Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314// Claude Code as the assistant. Two roads: the writer's own, run by the host// (the desktop app's sidecar starts `claude -p` in the folder of the// document, stored there as a .nat file so Claude Code can read it and// whatever the writer keeps beside it), or another Natural's on the network,// which lends its Claude Code behind a password. The protocol is the same as// for any assistant: the instructions as the system prompt, the document and// the ask as the prompt, the answer parsed into a note and suggestions. Both// roads stream what Claude Code does as it does it (the files it reads, the// words as they come), as lines of JSON the host or the lending Natural// forwards from `claude -p --output-format stream-json`.import type { Assistant, AssistantEvent, AssistantReply, AssistantRequest } from './types.ts';import { ASSISTANT_INSTRUCTIONS, contextForAssistant, parseReply } from '../suggestions/protocol.ts';import { describeError, type ProbeResult } from './openai.ts';import { countOf, readLines } from './stream.ts';
/** The document as a file: its path when it has one (the host has saved it), else its name and text for the runner to store. */export type CodeFile = { path?: string; name: string; text: string };/** What the runner is given: the prompts, the document, and the writer's choices. */export type CodeJob = { system: string; prompt: string; model?: string; command?: string; file?: CodeFile | null };export type CodeResult = { text: string; duration?: number; cost?: number; file?: string };/** What a run reports as it goes, and how it is stopped. */export type CodeHooks = { onEvent?: (event: AssistantEvent) => void; signal?: AbortSignal };/** The host's way of running Claude Code (the sidecar, in the app). */export type CodeRunner = (job: CodeJob, hooks?: CodeHooks) => Promise<CodeResult>;/** The host's way of finding it: where the command resolves and its version. */export type CodeCheck = (command: string) => Promise<{ version: string; path: string }>;
export const DEFAULT_CODE_COMMAND = 'claude';export const DEFAULT_PEER_PORT = 7474;
/** What Claude Code is told beyond the protocol: that the document is on disk beside it, that it reads only, that it answers in JSON alone. */export const CODE_NOTE = `You are running as Claude Code. The document is also stored as a .nat file (JSON) in your working directory, with whatever related material the writer keeps in that folder: read what helps ground your suggestions, change nothing on disk, and answer with the JSON object only, no prose around it.`;
/** The two prompts for a request: the protocol (and the style) as the system prompt; the conversation so far, the context, the document and the ask as the prompt. */export function codePrompt(req: AssistantRequest): { system: string; prompt: string } { const system = [ASSISTANT_INSTRUCTIONS, req.style, CODE_NOTE].filter(Boolean).join('\n\n'); const earlier = req.history.length ? `Earlier in this conversation:\n\n${req.history.map((h) => `${h.role === 'user' ? 'The writer' : 'You'}: ${h.text}`).join('\n\n')}\n\n---\n\n` : ''; const prompt = `${earlier}${req.context?.length ? `${contextForAssistant(req.context)}\n\n---\n\n` : ''}The document:\n\n${req.document}\n\n${req.selection ? `The writer has selected: "${req.selection}"\n\n` : ''}The writer asks: ${req.instruction}`; return { system, prompt };}
function finish(text: string): AssistantReply { const { reply, errors } = parseReply(text); if (errors.length) reply.message += `\n\n(${errors.length} malformed suggestion${errors.length === 1 ? '' : 's'} ignored: ${errors.join('; ')})`; return reply;}
const hostOf = (url: string): string => { try { return new URL(url).host; } catch { return url; }};
// --- what Claude Code says as it works, as the pane shows it ---------------------------------------
const shortPath = (p: string): string => p.split('/').filter(Boolean).slice(-2).join('/');const clip = (s: string, n: number): string => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
/** A tool's input as a phrase: the file for Read, the pattern for Glob and Grep, the input as JSON otherwise. */export function describeToolInput(name: string, input: unknown): string { const i = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>; const str = (k: string): string | null => (typeof i[k] === 'string' && i[k] ? (i[k] as string) : null); switch (name) { case 'Read': return shortPath(str('file_path') ?? '') + (typeof i.offset === 'number' ? ` from line ${i.offset}` : ''); case 'Glob': case 'Grep': { const where = str('path'); return `${name === 'Grep' ? `"${str('pattern') ?? ''}"` : (str('pattern') ?? '')}${where ? ` in ${shortPath(where)}` : ''}`; } default: { const text = str('description') ?? str('prompt') ?? str('query') ?? str('command') ?? str('url'); return clip(text ?? JSON.stringify(i), 120); } }}
/** A tool's answer in a line: how many lines, and the first of them. */export function shortResult(text: string): string { // Read numbers its lines ("12\tthe text"): the numbers are not the text const lines = text .split('\n') .map((l) => l.replace(/^\d+\t/, '').trim()) .filter(Boolean); const first = lines[0] ?? ''; if (lines.length <= 1) return clip(first, 120); return `${lines.length} lines — ${clip(first, 80)}`;}
/** The text a tool result carries: a string, or blocks of text. */const resultText = (content: unknown): string => (typeof content === 'string' ? content : Array.isArray(content) ? content.map((c) => (c && typeof c === 'object' && typeof (c as { text?: unknown }).text === 'string' ? (c as { text: string }).text : '')).join('\n') : '');
type RawBlock = { type?: string; id?: string; name?: string; input?: unknown; text?: string; tool_use_id?: string; content?: unknown; is_error?: boolean };type Raw = { type?: string; subtype?: string; status?: string; model?: string; cwd?: string; claude_code_version?: string; message?: { content?: RawBlock[] }; event?: { type?: string; delta?: { type?: string; text?: string; thinking?: string } }; duration_ms?: number; total_cost_usd?: number; usage?: { input_tokens?: number; output_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number };};
/** * Turn the lines Claude Code prints (`--output-format stream-json --verbose * --include-partial-messages`) into the assistant's events, one line at a * time: the start as a status, each tool used and what it answered, the * thinking and the words as they stream, what the run cost at the end. The * mapper keeps what it has seen, so a message's text streamed piece by piece * is not told again when the whole message follows. */export function codeEventMapper(): (raw: unknown) => AssistantEvent[] { let streamed = ''; let turns = 0; return (raw) => { const o = (raw && typeof raw === 'object' ? raw : {}) as Raw; switch (o.type) { case 'system': if (o.subtype === 'init') return [{ kind: 'status', text: `Claude Code${o.claude_code_version ? ` ${o.claude_code_version}` : ''}${o.model ? ` with ${o.model}` : ''}, in ${o.cwd ? shortPath(o.cwd) : 'its folder'}` }]; if (o.subtype === 'status' && o.status === 'requesting') { turns++; return [{ kind: 'status', text: turns === 1 ? 'Asking the model' : `Asking the model again (turn ${turns})` }]; } return []; case 'stream_event': { const ev = o.event; if (ev?.type === 'message_start') streamed = ''; if (ev?.type === 'content_block_delta') { if (ev.delta?.type === 'text_delta' && ev.delta.text) { streamed += ev.delta.text; return [{ kind: 'text', delta: ev.delta.text }]; } if (ev.delta?.type === 'thinking_delta' && ev.delta.thinking) return [{ kind: 'thinking', delta: ev.delta.thinking }]; } return []; } case 'assistant': { const out: AssistantEvent[] = []; for (const b of o.message?.content ?? []) { if (b.type === 'tool_use' && b.name) out.push({ kind: 'tool', name: b.name, input: describeToolInput(b.name, b.input), ...(b.id ? { id: b.id } : {}) }); else if (b.type === 'text' && b.text) { // without partial messages the text comes here whole; with them, only what was not streamed is new const rest = b.text.startsWith(streamed) ? b.text.slice(streamed.length) : b.text; if (rest) out.push({ kind: 'text', delta: rest }); streamed = b.text; } } return out; } case 'user': { const out: AssistantEvent[] = []; for (const b of o.message?.content ?? []) { if (b.type === 'tool_result') out.push({ kind: 'tool-result', text: shortResult(resultText(b.content)), ...(b.tool_use_id ? { id: b.tool_use_id } : {}), ...(b.is_error ? { error: true } : {}) }); } return out; } case 'result': { const u = o.usage; const input = u ? (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) : 0; return [{ kind: 'usage', ...(input ? { input } : {}), ...(u?.output_tokens ? { output: u.output_tokens } : {}), ...(typeof o.total_cost_usd === 'number' ? { cost: o.total_cost_usd } : {}), ...(typeof o.duration_ms === 'number' ? { duration: o.duration_ms } : {}) }]; } default: return []; } };}
/** * Read a run as the sidecar (or a lending Natural) streams it: one JSON * object per line, `{ event }` for each line Claude Code printed, then * `{ result }` with its answer, or `{ error, name }`. */export async function readCodeStream(res: Response, hooks: CodeHooks = {}): Promise<CodeResult> { const map = codeEventMapper(); let result: CodeResult | null = null; let failure: Error | null = null; await readLines( res, (line) => { let o: { event?: unknown; result?: CodeResult; error?: string; name?: string }; try { o = JSON.parse(line) as typeof o; } catch { return; // not one of ours } if (o.event !== undefined) for (const e of map(o.event)) hooks.onEvent?.(e); else if (o.result) result = o.result; else if (o.error) { failure = new Error(o.error); if (o.name) failure.name = o.name; } }, hooks.signal, ); if (hooks.signal?.aborted) throw new DOMException('stopped', 'AbortError'); if (failure) throw failure; if (!result) throw new Error('Claude Code: the run ended without an answer'); return result;}
export type CodeAssistantOptions = { run: CodeRunner; /** The document as a file, asked for at each request (the host knows which document is asking). */ file?: () => CodeFile | null; model?: string; command?: string; prompts?: string[];};
/** Claude Code on this machine, run by the host. */export class CodeAssistant implements Assistant { readonly name: string; readonly prompts: string[] | undefined; #o: CodeAssistantOptions;
constructor(o: CodeAssistantOptions) { this.#o = o; this.name = o.model ? `Claude Code (${o.model})` : 'Claude Code'; this.prompts = o.prompts; }
async suggest(req: AssistantRequest): Promise<AssistantReply> { const { system, prompt } = codePrompt(req); const file = this.#o.file?.() ?? null; req.onEvent?.({ kind: 'status', text: `Running ${this.#o.command ?? DEFAULT_CODE_COMMAND}${this.#o.model ? ` with ${this.#o.model}` : ''} beside ${file?.name ?? 'the document'}: ${countOf(prompt.length, 'character')}` }); const r = await this.#o.run({ system, prompt, ...(this.#o.model ? { model: this.#o.model } : {}), ...(this.#o.command ? { command: this.#o.command } : {}), file }, { ...(req.onEvent ? { onEvent: req.onEvent } : {}), ...(req.signal ? { signal: req.signal } : {}) }); return finish(r.text); }}
export type PeerAssistantOptions = { /** The lending Natural's address, e.g. http://name.local:7474. */ url: string; password: string; file?: () => CodeFile | null; prompts?: string[]; fetch?: typeof fetch;};
/** Claude Code on another Natural on the network, which lends it behind a password. */export class PeerAssistant implements Assistant { readonly name: string; readonly prompts: string[] | undefined; #o: PeerAssistantOptions;
constructor(o: PeerAssistantOptions) { if (!o.url) throw new Error('the lending Natural needs an address'); this.#o = o; this.name = `Claude Code (${hostOf(o.url)})`; this.prompts = o.prompts; }
async #post(path: string, body: string, signal?: AbortSignal): Promise<Response> { const f = this.#o.fetch ?? fetch; try { return await f(`${this.#o.url.replace(/\/$/, '')}${path}`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${this.#o.password}` }, body, ...(signal ? { signal } : {}), }); } catch (err) { if (signal?.aborted) throw err; throw new Error(`${this.name}: unreachable (${describeError(err)})`); } }
async suggest(req: AssistantRequest): Promise<AssistantReply> { const { system, prompt } = codePrompt(req); const file = this.#o.file?.(); const body = JSON.stringify({ system, prompt, ...(file ? { name: file.name, text: file.text } : {}) }); req.onEvent?.({ kind: 'status', text: `Asking ${hostOf(this.#o.url)} to run its Claude Code beside ${file?.name ?? 'the document'}: ${countOf(prompt.length, 'character')}` }); // the lending Natural streams the run (/stream); an older one answers whole (/ask) let res = await this.#post('/stream', body, req.signal); if (res.status === 404) res = await this.#post('/ask', body, req.signal); if (res.status === 401 || res.status === 403) throw new Error(`${this.name}: ${this.#o.password ? 'the password is wrong' : 'it needs the password'}`); if (res.status === 429) throw new Error(`${this.name}: too many wrong passwords from here; it will listen again later`); if ((res.headers.get('content-type') ?? '').includes('x-ndjson')) { try { const r = await readCodeStream(res, { ...(req.onEvent ? { onEvent: req.onEvent } : {}), ...(req.signal ? { signal: req.signal } : {}) }); return finish(r.text); } catch (err) { if (req.signal?.aborted) throw err; throw new Error(`${this.name}: ${err instanceof Error ? err.message : String(err)}`); } } const data = (await res.json().catch(() => ({}))) as { text?: string; error?: string }; if (!res.ok || data.error) throw new Error(`${this.name}: ${data.error ?? `answered ${res.status}`}`); if (data.text) req.onEvent?.({ kind: 'text', delta: data.text }); return finish(data.text ?? ''); }}
/** Ask a lending Natural whether it is there and the password is right; what it answered, the way a road is reported. */export async function probePeer(url: string, password: string, { fetch: f = fetch, timeout = 10_000 }: { fetch?: typeof fetch; timeout?: number } = {}): Promise<ProbeResult> { const base = { label: hostOf(url), baseUrl: url }; try { const res = await f(`${url.replace(/\/$/, '')}/check`, { method: 'POST', headers: { authorization: `Bearer ${password}` }, signal: AbortSignal.timeout(timeout) }); if (res.status === 401 || res.status === 403) return { ...base, ok: false, status: res.status, error: password ? 'refused: the password is wrong' : 'refused: it needs the password' }; if (res.status === 429) return { ...base, ok: false, status: res.status, error: 'refused: too many wrong passwords from here; it will listen again later' }; if (!res.ok) return { ...base, ok: false, status: res.status, error: `answered ${res.status} ${(await res.text()).slice(0, 120)}`.trim() }; const data = (await res.json().catch(() => ({}))) as { version?: string; name?: string }; return { ...base, ok: true, status: res.status, detail: `lends Claude Code${data.version ? ` ${data.version}` : ''}${data.name ? ` (${data.name})` : ''}` }; } catch (err) { return { ...base, ok: false, error: `unreachable: ${describeError(err)}` }; }}