// Claude Code as the assistant: the prompts it is given, the writer's own run // by the host, another Natural's reached with a password, and the probe that // tells "there" from "wrong password" from "unreachable". import { test } from 'node:test'; import assert from 'node:assert/strict'; import { CODE_NOTE, CodeAssistant, PeerAssistant, codePrompt, probePeer, type CodeJob } from '../src/assistant/code.ts'; import { ASSISTANT_INSTRUCTIONS } from '../src/suggestions/protocol.ts'; import { DEFAULT_ASSISTANT_SETTINGS, assistantFromSettings, shortName } from '../src/assistant/settings.ts'; import { FakeAssistant } from '../src/assistant/fake.ts'; const REPLY = JSON.stringify({ message: 'Fine.', ops: [{ op: 'replace', block: 'p1', find: 'teh', with: 'the' }] }); const req = { document: '[p1] teh text', instruction: 'Proofread', selection: 'teh', style: 'Plain and short.', context: [{ label: 'Chapter 2', text: 'Later on.' }], history: [{ role: 'user' as const, text: 'Hello' }, { role: 'assistant' as const, text: 'Yes?' }] }; test('the prompts: the protocol, the style and the note as the system prompt; the conversation, the context, the document and the ask as the prompt', () => { const { system, prompt } = codePrompt(req); assert.ok(system.startsWith(ASSISTANT_INSTRUCTIONS)); assert.ok(system.includes('\n\nPlain and short.\n\n')); assert.ok(system.endsWith(CODE_NOTE)); assert.match(prompt, /^Earlier in this conversation:\n\nThe writer: Hello\n\nYou: Yes\?\n\n---\n\n/); assert.ok(prompt.includes('Chapter 2')); assert.ok(prompt.includes('The document:\n\n[p1] teh text\n\n')); assert.ok(prompt.includes('The writer has selected: "teh"')); assert.ok(prompt.endsWith('The writer asks: Proofread')); const bare = codePrompt({ document: 'd', instruction: 'Go', history: [] }); assert.equal(bare.system, `${ASSISTANT_INSTRUCTIONS}\n\n${CODE_NOTE}`); assert.equal(bare.prompt, 'The document:\n\nd\n\nThe writer asks: Go'); }); test('Claude Code on this machine: the host runs it with the prompts, the model, the command and the document as a file', async () => { const jobs: CodeJob[] = []; const a = new CodeAssistant({ run: async (job) => { jobs.push(job); return { text: `Here you go:\n\`\`\`json\n${REPLY}\n\`\`\`` }; }, file: () => ({ path: '/Users/me/Essay.nat', name: 'Essay.nat', text: '{}' }), model: 'opus', command: '/opt/claude', }); assert.equal(a.name, 'Claude Code (opus)'); const reply = await a.suggest(req); assert.equal(reply.message, 'Fine.'); assert.equal(reply.ops.length, 1); assert.equal(jobs.length, 1); assert.equal(jobs[0]!.model, 'opus'); assert.equal(jobs[0]!.command, '/opt/claude'); assert.deepEqual(jobs[0]!.file, { path: '/Users/me/Essay.nat', name: 'Essay.nat', text: '{}' }); assert.equal(jobs[0]!.system, codePrompt(req).system); assert.equal(new CodeAssistant({ run: async () => ({ text: '' }) }).name, 'Claude Code'); }); type Call = { url: string; method: string; headers: Record; body: string }; function fakeFetch(answer: (c: Call) => Response | Promise): { fetch: typeof fetch; calls: Call[] } { const calls: Call[] = []; const f = (async (input: RequestInfo | URL, init?: RequestInit) => { const r = new Request(input, init); const headers: Record = {}; r.headers.forEach((v, k) => (headers[k] = v)); const c = { url: r.url, method: r.method, headers, body: r.method === 'POST' ? await r.text() : '' }; calls.push(c); return answer(c); }) as typeof fetch; return { fetch: f, calls }; } const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); const peer = (c: Call) => (c.headers.authorization !== 'Bearer open sesame' ? json(401, { error: 'wrong password' }) : c.url.endsWith('/check') ? json(200, { ok: true, name: 'study.local', version: '9.9.9' }) : json(200, { text: REPLY, duration: 12 })); test('Claude Code on another Natural: the prompts and the document go to it with the password, and its answer is parsed', async () => { const { fetch, calls } = fakeFetch(peer); const a = new PeerAssistant({ url: 'http://study.local:7474/', password: 'open sesame', file: () => ({ name: 'Essay.nat', text: '{"t":1}' }), fetch }); assert.equal(a.name, 'Claude Code (study.local:7474)'); const reply = await a.suggest(req); assert.equal(reply.message, 'Fine.'); // the run is asked for as a stream; a lender that answers whole (as this one does) is read whole assert.equal(calls[0]!.url, 'http://study.local:7474/stream'); assert.equal(calls[0]!.headers.authorization, 'Bearer open sesame'); const sent = JSON.parse(calls[0]!.body) as { system: string; prompt: string; name: string; text: string; path?: string }; assert.equal(sent.name, 'Essay.nat'); assert.equal(sent.text, '{"t":1}'); assert.equal(sent.path, undefined, 'a path means nothing on another machine'); assert.equal(sent.system, codePrompt(req).system); const wrong = new PeerAssistant({ url: 'http://study.local:7474', password: 'nope', fetch }); await assert.rejects(wrong.suggest(req), /^Error: Claude Code \(study\.local:7474\): the password is wrong$/); const none = new PeerAssistant({ url: 'http://study.local:7474', password: '', fetch }); await assert.rejects(none.suggest(req), /it needs the password/); const gone = new PeerAssistant({ url: 'http://away.local:7474', password: 'x', fetch: (async () => { throw new TypeError('fetch failed', { cause: { code: 'ECONNREFUSED' } }); }) as typeof fetch, }); await assert.rejects(gone.suggest(req), /unreachable \(fetch failed \(ECONNREFUSED\)\)/); const locked = new PeerAssistant({ url: 'http://study.local:7474', password: 'x', fetch: (async () => json(429, { error: 'later' })) as typeof fetch }); await assert.rejects(locked.suggest(req), /too many wrong passwords/); }); test('the probe tells there, wrong password and unreachable apart', async () => { const { fetch } = fakeFetch(peer); const ok = await probePeer('http://study.local:7474', 'open sesame', { fetch }); assert.equal(ok.ok, true); assert.equal(ok.label, 'study.local:7474'); assert.equal(ok.detail, 'lends Claude Code 9.9.9 (study.local)'); const wrong = await probePeer('http://study.local:7474', 'nope', { fetch }); assert.equal(wrong.ok, false); assert.equal(wrong.error, 'refused: the password is wrong'); assert.equal((await probePeer('http://study.local:7474', '', { fetch })).error, 'refused: it needs the password'); const gone = await probePeer('http://away.local:7474', 'x', { fetch: (async () => { throw new TypeError('fetch failed', { cause: { code: 'ENOTFOUND' } }); }) as typeof fetch, }); assert.match(gone.error!, /^unreachable: fetch failed \(ENOTFOUND\)$/); }); test('the settings: Claude Code needs the host to run it, a peer needs an address; both are named Claude Code for short', () => { const run = async () => ({ text: '' }); const code = assistantFromSettings({ ...DEFAULT_ASSISTANT_SETTINGS, kind: 'code', codeModel: 'sonnet' }, undefined, { code: run }); assert.ok(code instanceof CodeAssistant); assert.equal(code.name, 'Claude Code (sonnet)'); assert.equal(shortName(code), 'Claude Code'); assert.ok(assistantFromSettings({ ...DEFAULT_ASSISTANT_SETTINGS, kind: 'code' }) instanceof FakeAssistant, 'a page cannot run it'); const p = assistantFromSettings({ ...DEFAULT_ASSISTANT_SETTINGS, kind: 'peer', peerUrl: 'http://study.local:7474', peerPassword: 'x' }); assert.ok(p instanceof PeerAssistant); assert.equal(p.name, 'Claude Code (study.local:7474)'); assert.ok(assistantFromSettings({ ...DEFAULT_ASSISTANT_SETTINGS, kind: 'peer' }) instanceof FakeAssistant, 'no address, no peer'); assert.equal(DEFAULT_ASSISTANT_SETTINGS.codeCommand, 'claude'); });