Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit d9712d0d682f0ccd3515d6aa820fa9391ffd1bda
parent c721c02f1041b22a26054b6698bca74a61f7a624
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 10:47:35 -0400

Merge r27/llm: release 27 S1 — providers and the agent loop

Diffstat:
MENVIRONMENT.md | 1+
Mcommon/lib/envVars.ts | 1+
Acommon/lib/llm/agent.test.ts | 406+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/agent.ts | 509+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/anthropic.test.ts | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/anthropic.ts | 342+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/config.ts | 24++++++++++++++++++++++++
Acommon/lib/llm/index.ts | 12++++++++++++
Acommon/lib/llm/keyLeak.test.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/meter.test.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/meter.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/ollama.test.ts | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/ollama.ts | 215+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/prices.ts | 40++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/structured.test.ts | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/structured.ts | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/release-27.md | 48++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 2603 insertions(+), 0 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -57,6 +57,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | Variable | Default | What it does | Read by | |---|---|---|---| | `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs | +| `ANTHROPIC_API_KEY` | unset (the API key file is read instead) | The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript. | common/lib/llm/anthropic.ts | | `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts | | `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts | | `SYNC_TICK_TOKEN` | unset (no auth) | Bearer token for the tick endpoint; set on both the editor and the cron job. | common/bin/sync-tick.ts, editor/app/scheduler/auth.ts | diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -93,6 +93,7 @@ const DECLARED: EnvVarDecl[] = [ // ── runtime ──────────────────────────────────────────────────────────── { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." }, + { name: "ANTHROPIC_API_KEY", audience: "runtime", default: "unset (the API key file is read instead)", readBy: "common/lib/llm/anthropic.ts", doc: "The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript." }, { name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." }, { name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." }, { name: "SYNC_TICK_TOKEN", audience: "runtime", default: "unset (no auth)", readBy: "common/bin/sync-tick.ts, editor/app/scheduler/auth.ts", doc: "Bearer token for the tick endpoint; set on both the editor and the cron job." }, diff --git a/common/lib/llm/agent.test.ts b/common/lib/llm/agent.test.ts @@ -0,0 +1,406 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + errorTurn, + pauseTurn, + startFakeAnthropic, + textBlock, + textTurn, + thinkingBlock, + toolTurn, + toolUseBlock, + turn, + webSearchBlocks, +} from "../../testing/llm/fakeAnthropic.mjs"; +import { faultReply, reply, startFakeOllama, toolCallsReply } from "../../testing/llm/fakeOllama.mjs"; +import { runAgent, WRAP_UP_TEXT, type AgentEvent, type AgentTool } from "./agent"; +import { Meter } from "./meter"; +import { OllamaFaultError, promptEstimate, PromptTooLargeError } from "./ollama"; + +const lookup = (out: (q: string) => string = (q) => `found ${q}`): AgentTool => ({ + name: "lookup", + description: "Look a word up in the corpus.", + inputSchema: { type: "object", properties: { q: { type: "string" } }, required: ["q"] }, + run: async (input: { q: string }) => out(input.q), +}); + +const claude = (api: { url: string; key: string }, extra = {}) => ({ + anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: async () => {}, ...extra }, +}); + +test("Claude: a tool loop to end_turn, with the transcript and events", async () => { + const api = await startFakeAnthropic({ turns: [toolTurn("lookup", { q: "oven" }), textTurn("The oven came up once.")] }); + try { + const events: AgentEvent[] = []; + const meter = new Meter(); + const r = await runAgent({ + llm: claude(api), + model: "claude-sonnet-5", + system: "You research.", + user: "Ovens?", + tools: [lookup()], + meter, + onEvent: (e) => events.push(e), + }); + assert.equal(r.stopReason, "end_turn"); + assert.equal(r.text, "The oven came up once."); + const [first, second] = api.requests; + assert.deepEqual(first.cache_control, { type: "ephemeral" }); + assert.deepEqual(first.system, [{ type: "text", text: "You research.", cache_control: { type: "ephemeral" } }]); + assert.equal(first.tools[0].name, "lookup"); + assert.deepEqual(first.tools[0].input_schema, lookup().inputSchema); + const result = second.messages[2].content[0]; + assert.equal(result.type, "tool_result"); + assert.equal(result.tool_use_id, second.messages[1].content[0].id); + assert.equal(result.content, "found oven"); + assert.deepEqual( + r.transcript.map((t) => t.kind), + ["request", "response", "tool", "request", "response"], + ); + const req1 = r.transcript[3] as Extract<(typeof r.transcript)[number], { kind: "request" }>; + assert.equal(req1.messagesTotal, 3); + assert.equal((req1.request.messages as unknown[]).length, 1); // only what was added + assert.equal("system" in req1.request, false); + assert.ok(r.transcript.every((t) => t.kind !== "response" || typeof t.usage.output_tokens === "number")); + assert.deepEqual( + events.map((e) => e.type), + ["turn", "tool", "turn", "done"], + ); + assert.ok(meter.usd > 0); + JSON.parse(JSON.stringify(r.transcript)); + } finally { + await api.close(); + } +}); + +test("Claude: a tool error and an unknown tool come back as is_error results", async () => { + const api = await startFakeAnthropic({ + turns: [turn([toolUseBlock("lookup", { q: "x" }), toolUseBlock("nope", {})]), textTurn("done")], + }); + try { + const r = await runAgent({ + llm: claude(api), + model: "claude-sonnet-5", + system: "s", + user: "u", + tools: [lookup(() => { throw new Error("index offline"); })], + meter: new Meter(), + }); + assert.equal(r.stopReason, "end_turn"); + const results = api.requests[1].messages[2].content; + assert.deepEqual( + results.map((b: { content: string; is_error?: boolean }) => [b.content, b.is_error]), + [["error: index offline", true], ["error: no tool nope", true]], + ); + } finally { + await api.close(); + } +}); + +test("Claude: long tool results are cut for the model and clipped in the transcript", async () => { + const api = await startFakeAnthropic({ turns: [toolTurn("lookup", { q: "x" }), textTurn("ok")] }); + try { + const r = await runAgent({ + llm: claude(api), + model: "claude-sonnet-5", + system: "s", + user: "u", + tools: [lookup(() => "y".repeat(70_000))], + meter: new Meter(), + }); + const sent = api.requests[1].messages[2].content[0].content as string; + assert.ok(sent.startsWith("y".repeat(60_000)) && sent.includes("cut at 60000 chars")); + const tool = r.transcript.find((t) => t.kind === "tool") as { result: string; chars: number }; + assert.equal(tool.chars, 70_000); + assert.ok(tool.result.length < 4_100); + } finally { + await api.close(); + } +}); + +test("Claude: server web search in tools; pause_turn re-sent with the paused content and no user turn", async () => { + const blocks = webSearchBlocks("oven recall", [{ url: "https://example.org/a", title: "A" }]); + const api = await startFakeAnthropic({ + turns: [pauseTurn([textBlock("Searching."), ...blocks]), textTurn("Found it.")], + }); + try { + const events: AgentEvent[] = []; + const r = await runAgent({ + llm: claude(api), + model: "claude-sonnet-5", + system: "s", + user: "u", + tools: [lookup()], + meter: new Meter(), + serverWebSearch: { maxUses: 3 }, + onEvent: (e) => events.push(e), + }); + assert.equal(r.stopReason, "end_turn"); + assert.equal(r.text, "Found it."); + assert.deepEqual(api.requests[0].tools[1], { type: "web_search_20250305", name: "web_search", max_uses: 3 }); + const second = api.requests[1].messages; + assert.equal(second.length, 2); + assert.equal(second[1].role, "assistant"); + assert.deepEqual(second[1].content.slice(1), blocks); // the server blocks kept as they came + assert.ok(events.some((e) => e.type === "pause")); + } finally { + await api.close(); + } +}); + +test("Claude: a refused server web search falls back to the caller's own web_search tool", async () => { + const api = await startFakeAnthropic({ + turns: [errorTurn(400, "invalid_request_error", "tools.1: web_search is not enabled for this organization"), textTurn("ok")], + }); + try { + const web: AgentTool = { name: "web_search", description: "Search the web.", inputSchema: { type: "object", properties: {} }, run: async () => "" }; + const r = await runAgent({ + llm: claude(api), + model: "claude-sonnet-5", + system: "s", + user: "u", + tools: [lookup(), web], + meter: new Meter(), + serverWebSearch: { maxUses: 5 }, + }); + assert.equal(r.stopReason, "end_turn"); + assert.deepEqual(api.requests[0].tools.map((t: { name: string; type?: string }) => t.type ?? t.name), ["lookup", "web_search_20250305"]); + assert.deepEqual(api.requests[1].tools.map((t: { name: string; type?: string }) => t.type ?? t.name), ["lookup", "web_search"]); + assert.ok(r.transcript.some((t) => t.kind === "note" && /web search refused/.test(t.text))); + } finally { + await api.close(); + } +}); + +// Five tool turns then an answer; usage large enough to trip the prune. +const longRun = (withThinking: boolean) => { + const big = { usage: { input_tokens: 100_000, output_tokens: 10 } }; + return [ + turn([toolUseBlock("lookup", { q: "1" })], big), + turn([...(withThinking ? [thinkingBlock("plan")] : []), toolUseBlock("lookup", { q: "2" })], big), + turn([toolUseBlock("lookup", { q: "3" })], big), + turn([toolUseBlock("lookup", { q: "4" })], big), + turn([toolUseBlock("lookup", { q: "5" })], big), + textTurn("done", big), + ]; +}; + +test("Claude: a non-strict model prunes old tool results once the context is large", async () => { + const api = await startFakeAnthropic({ turns: longRun(false) }); + try { + const events: AgentEvent[] = []; + const r = await runAgent({ llm: claude(api), model: "claude-sonnet-5", system: "s", user: "u", tools: [lookup()], meter: new Meter(), onEvent: (e) => events.push(e) }); + assert.equal(r.stopReason, "end_turn"); + const last = api.requests[5].messages; + const results = last.filter((m: { role: string; content: unknown }) => m.role === "user" && Array.isArray(m.content)).map((m: { content: { content: string }[] }) => m.content[0].content); + assert.equal(results.length, 5); + assert.match(results[0], /dropped from context/); + assert.match(results[1], /dropped from context/); + assert.deepEqual(results.slice(2), ["found 3", "found 4", "found 5"]); + assert.ok(events.some((e) => e.type === "prune")); + } finally { + await api.close(); + } +}); + +test("Claude: append-only once a thinking block exists — no prune, the fake's signatures hold", async () => { + for (const model of ["claude-sonnet-5", "claude-sonnet-5-5"]) { + const api = await startFakeAnthropic({ turns: longRun(true), strictModels: ["claude-sonnet-5-5"] }); + try { + const r = await runAgent({ llm: claude(api), model, system: "s", user: "u", tools: [lookup()], meter: new Meter() }); + assert.equal(r.stopReason, "end_turn", model); + assert.equal(api.requests.length, 6); + assert.ok(!JSON.stringify(api.requests[5].messages).includes("dropped from context"), model); + if (model === "claude-sonnet-5-5") assert.deepEqual(api.requests[0].thinking, { type: "between_tools" }); + } finally { + await api.close(); + } + } +}); + +test("Claude, Sonnet 5.5: even without thinking blocks the history is never pruned", async () => { + const api = await startFakeAnthropic({ turns: longRun(false) }); + try { + await runAgent({ llm: claude(api), model: "claude-sonnet-5-5", system: "s", user: "u", tools: [lookup()], meter: new Meter() }); + assert.ok(!JSON.stringify(api.requests[5].messages).includes("dropped from context")); + } finally { + await api.close(); + } +}); + +test("Claude: one wrap-up message at 85% of the cap, then a budget stop at the cap", async () => { + // Sonnet 5: $10/M output, so 90k output tokens is $0.90 a turn. + const cost = { usage: { input_tokens: 0, output_tokens: 90_000 } }; + const api = await startFakeAnthropic({ + turns: [ + turn([toolUseBlock("lookup", { q: "1" })], cost), + turn([textBlock("Reading on."), toolUseBlock("lookup", { q: "2" })], cost), + turn([textBlock("Writing it up."), toolUseBlock("lookup", { q: "3" })], cost), + textTurn("never reached"), + ], + }); + try { + const events: AgentEvent[] = []; + const r = await runAgent({ + llm: claude(api), + model: "claude-sonnet-5", + system: "s", + user: "u", + tools: [lookup()], + meter: new Meter(), + maxUsd: 2, + onEvent: (e) => events.push(e), + }); + assert.equal(r.stopReason, "budget"); + assert.equal(r.text, "Writing it up."); + assert.equal(api.requests.length, 3); + const third = api.requests[2].messages; + const lastUser = third[third.length - 1].content; + assert.equal(lastUser[0].type, "tool_result"); + assert.deepEqual(lastUser[1], { type: "text", text: WRAP_UP_TEXT }); + assert.equal(events.filter((e) => e.type === "wrap-up").length, 1); + assert.ok(events.some((e) => e.type === "budget")); + } finally { + await api.close(); + } +}); + +test("Claude: the meter's own cap counts; a run already over it sends nothing", async () => { + const api = await startFakeAnthropic({ turns: [textTurn("x")] }); + try { + const meter = new Meter({ maxUsd: 0.5 }); + meter.add("claude-sonnet-5", { output_tokens: 60_000 }); // $0.60 spent before + const r = await runAgent({ llm: claude(api), model: "claude-sonnet-5", system: "s", user: "u", tools: [], meter }); + assert.equal(r.stopReason, "budget"); + assert.equal(api.requests.length, 0); + } finally { + await api.close(); + } +}); + +test("Claude: max_turns", async () => { + const api = await startFakeAnthropic({ turns: [toolTurn("lookup", { q: "1" }), toolTurn("lookup", { q: "2" })] }); + try { + const r = await runAgent({ llm: claude(api), model: "claude-sonnet-5", system: "s", user: "u", tools: [lookup()], meter: new Meter(), maxTurns: 2 }); + assert.equal(r.stopReason, "max_turns"); + } finally { + await api.close(); + } +}); + +test("Claude: the signal aborts the in-flight request and the loop", async () => { + const api = await startFakeAnthropic({ + turns: [toolTurn("lookup", { q: "1" }), async () => (await new Promise((r) => setTimeout(r, 400)), textTurn("late"))], + }); + try { + const ac = new AbortController(); + const tool = lookup((q) => { + setTimeout(() => ac.abort(), 50); // cancel while the next request is in flight + return `found ${q}`; + }); + const r = await runAgent({ llm: claude(api), model: "claude-sonnet-5", system: "s", user: "u", tools: [tool], meter: new Meter(), signal: ac.signal }); + assert.equal(r.stopReason, "cancelled"); + assert.equal(api.requests.length, 2); + } finally { + await new Promise((r) => setTimeout(r, 400)); + await api.close(); + } +}); + +test("Claude: a cancel during a tool stops before the next request", async () => { + const api = await startFakeAnthropic({ turns: [toolTurn("lookup", { q: "1" }), textTurn("never")] }); + try { + const ac = new AbortController(); + const r = await runAgent({ + llm: claude(api), + model: "claude-sonnet-5", + system: "s", + user: "u", + tools: [lookup(() => (ac.abort(), "x"))], + meter: new Meter(), + signal: ac.signal, + }); + assert.equal(r.stopReason, "cancelled"); + assert.equal(api.requests.length, 1); + } finally { + await api.close(); + } +}); + +// ─── ollama ─── + +test("ollama: a tool loop — functions out, tool_calls in, results as role tool; think false, num_ctx capped", async () => { + const ol = await startFakeOllama({ turns: [toolCallsReply([{ name: "lookup", arguments: { q: "oven" } }]), reply("One oven.")] }); + try { + const meter = new Meter(); + const r = await runAgent({ + llm: { ollama: { baseUrl: ol.url, numCtx: 65_536 } }, + model: "qwen3:8b", + system: "s", + user: "u", + tools: [lookup()], + meter, + serverWebSearch: { maxUses: 3 }, + }); + assert.equal(r.stopReason, "end_turn"); + assert.equal(r.text, "One oven."); + const [first, second] = ol.requests; + assert.equal(first.think, false); + assert.equal(first.options.num_ctx, 12_288); + assert.deepEqual(first.tools.map((t: { function: { name: string } }) => t.function.name), ["lookup"]); // no server search + assert.deepEqual(second.messages[3], { role: "tool", tool_name: "lookup", content: "found oven" }); + assert.equal(meter.usd, 0); + assert.deepEqual(r.transcript.map((t) => t.kind), ["request", "response", "tool", "request", "response"]); + } finally { + await ol.close(); + } +}); + +test("ollama: the context is fitted under the cap by dropping the oldest tool results first", async () => { + const ol = await startFakeOllama({ + turns: [ + toolCallsReply([{ name: "lookup", arguments: { q: "1" } }]), + toolCallsReply([{ name: "lookup", arguments: { q: "2" } }]), + toolCallsReply([{ name: "lookup", arguments: { q: "3" } }]), + reply("done"), + ], + }); + try { + const events: AgentEvent[] = []; + const cap = 1500; + const r = await runAgent({ + llm: { ollama: { baseUrl: ol.url, promptCapTokens: cap } }, + model: "qwen3:8b", + system: "s", + user: "u", + tools: [lookup((q) => `${q}:` + "z".repeat(3000))], // cut to 2500 for the model + meter: new Meter(), + onEvent: (e) => events.push(e), + }); + assert.equal(r.stopReason, "end_turn"); + for (const body of ol.requests) assert.ok(promptEstimate({ messages: body.messages, tools: body.tools }) <= cap); + const last = ol.requests[3].messages.filter((m: { role: string }) => m.role === "tool").map((m: { content: string }) => m.content); + assert.match(last[0], /dropped to fit/); + assert.match(last[last.length - 1], /^3:z/); + assert.ok(events.some((e) => e.type === "fit")); + } finally { + await ol.close(); + } +}); + +test("ollama: nothing left to drop and still too big is refused, never sent; done:false is a fault", async () => { + const ol = await startFakeOllama({ turns: [faultReply()] }); + try { + await assert.rejects( + runAgent({ llm: { ollama: { baseUrl: ol.url } }, model: "qwen3:8b", system: "s ".repeat(20_000), user: "u", tools: [], meter: new Meter() }), + PromptTooLargeError, + ); + assert.equal(ol.requests.length, 0); + await assert.rejects( + runAgent({ llm: { ollama: { baseUrl: ol.url } }, model: "qwen3:8b", system: "s", user: "u", tools: [], meter: new Meter() }), + OllamaFaultError, + ); + } finally { + await ol.close(); + } +}); diff --git a/common/lib/llm/agent.ts b/common/lib/llm/agent.ts @@ -0,0 +1,509 @@ +// The tool loop, on either provider (release 27; the stopgap's agentloop.py and +// api_sweep's loop, prune and budget). +// +// Claude: the tools as client tools, plus the API's own web search when asked +// (its blocks stay in the history); `pause_turn` re-sends the conversation with +// the paused content appended and no user turn. A non-strict model's old tool +// results are pruned once the context is large; a conversation holding a +// thinking block, or on a strict model, is append-only (the blocks are signed +// over the history before them). A refused server web search falls back to the +// caller's own `web_search` tool when there is one. +// ollama: the tools as functions; before each request the prompt is fitted +// under the cap by shrinking the OLDEST tool results first. +// Both: at `wrapUpAt` of the budget one wrap-up message; at the cap the loop +// stops (`budget`); `signal` aborts the in-flight request and the loop +// (`cancelled`). The transcript is what an iteration stores as its turns file. + +import { + AnthropicClient, + AnthropicError, + CancelledError, + cacheControl, + isStrictModel, + textOf, + toolUsesOf, + type ContentBlock, +} from "./anthropic"; +import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig, type Provider } from "./config"; +import type { Meter, Usage } from "./meter"; +import { + ollamaChat, + promptCapOf, + promptEstimate, + PromptTooLargeError, + toOllamaTools, + toolCallsOf, + type OllamaMessage, +} from "./ollama"; + +export type AgentTool = { + name: string; + description: string; + inputSchema: Record<string, unknown>; + run(input: any, ctx: { signal?: AbortSignal }): Promise<string>; +}; + +export type AgentStopReason = "end_turn" | "budget" | "max_turns" | "cancelled"; + +export type AgentEvent = + | { + type: "turn"; + turn: number; + provider: Provider; + stopReason: string | null; + calls: string[]; + text: string; + usage: Usage; + usd: number; + } + | { type: "tool"; turn: number; name: string; chars: number; error: boolean; ms: number } + | { type: "pause"; turn: number } + | { type: "prune"; turn: number; dropped: number } + | { type: "fit"; turn: number; dropped: number; estimate: number } + | { type: "wrap-up"; turn: number; usd: number } + | { type: "budget"; turn: number; usd: number } + | { type: "note"; turn: number; text: string } + | { type: "done"; turn: number; stopReason: AgentStopReason; usd: number }; + +export type TranscriptEntry = + | { + kind: "request"; + turn: number; + provider: Provider; + at: string; + // The request as sent, minus the history already in the transcript: + // `messages` holds only what was added since the previous request (all of + // it on turn 0); `system` and `tools` appear on turn 0 and when they change. + request: Record<string, unknown>; + messagesTotal: number; + } + | { + kind: "response"; + turn: number; + provider: Provider; + at: string; + stopReason: string | null; + content: unknown; + usage: Usage; + usd: number; + } + | { + kind: "tool"; + turn: number; + name: string; + id?: string; + input: unknown; + result: string; + chars: number; + error: boolean; + ms: number; + } + | { kind: "note"; turn: number; at: string; text: string }; + +export type AgentOptions = { + llm: LlmConfig; + model: string; + system: string; + user: string; + tools: AgentTool[]; + meter: Meter; + maxUsd?: number; + wrapUpAt?: number; + maxTurns?: number; + serverWebSearch?: { maxUses: number }; + signal?: AbortSignal; + onEvent?: (e: AgentEvent) => void; + // Additions (not in the brief's signature; defaults as noted): + maxTokens?: number; // per Claude response, 16000 + resultChars?: number; // one tool result the model sees: 60000 on Claude, 2500 local + transcriptResultChars?: number; // one tool result in the transcript, 4000 + wrapUpText?: string; +}; + +export type AgentResult = { text: string; stopReason: AgentStopReason; transcript: TranscriptEntry[] }; + +export const DEFAULT_WRAP_UP_AT = 0.85; +export const DEFAULT_MAX_TURNS = 40; +export const CLAUDE_RESULT_CHARS = 60_000; +export const LOCAL_RESULT_CHARS = 2_500; +export const TRANSCRIPT_RESULT_CHARS = 4_000; +// Past this context size a non-strict Claude conversation drops all but the +// last few tool results' text (what mattered is in the document being built). +export const PRUNE_OVER_TOKENS = 90_000; +export const KEEP_RECENT_RESULTS = 3; +export const WEB_SEARCH_TOOL_TYPE = "web_search_20250305"; + +export const WRAP_UP_TEXT = + "BUDGET: about 85% of this run's budget is spent. Stop reading or searching now. Finish with what you have — " + + "say plainly what you covered and what you did not — then stop."; +const PRUNED = "(dropped from context to save space — what mattered is in the document)"; +const FITTED = "(dropped to fit the context — what mattered is in the document)"; + +// ─── Helpers ─── + +const now = () => new Date().toISOString(); + +// Deep copy with every long string cut: what goes in the transcript. +export function clip(v: unknown, max = TRANSCRIPT_RESULT_CHARS): unknown { + if (typeof v === "string") return v.length > max ? `${v.slice(0, max)}… (${v.length} chars)` : v; + if (Array.isArray(v)) return v.map((x) => clip(x, max)); + if (v && typeof v === "object") { + const out: Record<string, unknown> = {}; + for (const [k, x] of Object.entries(v)) out[k] = clip(x, max); + return out; + } + return v; +} + +const cut = (s: string, max: number) => + s.length > max ? `${s.slice(0, max)}\n(cut at ${max} chars — narrow the call)` : s; + +function hasThinking(messages: { role: string; content: unknown }[]): boolean { + return messages.some( + (m) => + m.role === "assistant" && + Array.isArray(m.content) && + (m.content as ContentBlock[]).some((b) => b.type === "thinking" || b.type === "redacted_thinking"), + ); +} + +// api_sweep's prune: past PRUNE_OVER_TOKENS, all but the last few tool results +// are replaced. Never on a conversation holding thinking blocks. Returns how +// many it dropped. +export function pruneToolResults( + messages: { role: string; content: unknown }[], + contextTokens: number, + keep = KEEP_RECENT_RESULTS, +): number { + if (contextTokens < PRUNE_OVER_TOKENS || hasThinking(messages)) return 0; + let seen = 0; + let dropped = 0; + for (let i = messages.length - 1; i >= 0; i--) { + const m = messages[i]; + if (m.role !== "user" || !Array.isArray(m.content)) continue; + for (const b of m.content as ContentBlock[]) { + if (b.type !== "tool_result") continue; + seen++; + if (seen > keep && b.content !== PRUNED) { + b.content = PRUNED; + dropped++; + } + } + } + return dropped; +} + +// Shrink the oldest tool results until the request fits the local cap. +// Returns how many it dropped; throws PromptTooLargeError when nothing is left +// to drop and it still does not fit. +export function fitLocal(messages: OllamaMessage[], tools: object[], cap: number): number { + let dropped = 0; + let estimate = promptEstimate({ messages, tools }); + for (const m of messages) { + if (estimate <= cap) return dropped; + if (m.role === "tool" && m.content !== FITTED) { + m.content = FITTED; + dropped++; + estimate = promptEstimate({ messages, tools }); + } + } + if (estimate > cap) throw new PromptTooLargeError(estimate, cap); + return dropped; +} + +async function runTool( + tools: Map<string, AgentTool>, + name: string, + input: unknown, + signal?: AbortSignal, +): Promise<{ out: string; error: boolean; ms: number }> { + const t0 = Date.now(); + const tool = tools.get(name); + if (!tool) return { out: `error: no tool ${name}`, error: true, ms: 0 }; + try { + const out = await tool.run(input ?? {}, { signal }); + return { out: typeof out === "string" ? out : JSON.stringify(out), error: false, ms: Date.now() - t0 }; + } catch (err) { + return { out: `error: ${(err as Error)?.message ?? String(err)}`, error: true, ms: Date.now() - t0 }; + } +} + +// ─── The loop ─── + +export async function runAgent(o: AgentOptions): Promise<AgentResult> { + return providerOf(o.model) === "api" ? runClaude(o) : runLocal(o); +} + +class Run { + readonly transcript: TranscriptEntry[] = []; + readonly cap: number | undefined; + readonly wrapUpAt: number; + wrapped = false; + constructor(readonly o: AgentOptions) { + this.cap = o.maxUsd ?? o.meter.maxUsd; + this.wrapUpAt = o.wrapUpAt ?? DEFAULT_WRAP_UP_AT; + } + emit(e: AgentEvent) { + try { + this.o.onEvent?.(e); + } catch { + // a listener's failure never stops the run + } + } + note(turn: number, text: string) { + this.transcript.push({ kind: "note", turn, at: now(), text }); + this.emit({ type: "note", turn, text }); + } + spentOut(): boolean { + return this.cap !== undefined && this.o.meter.usd >= this.cap; + } + wrapUpDue(): boolean { + return !this.wrapped && this.cap !== undefined && this.o.meter.usd >= this.cap * this.wrapUpAt; + } + finish(turn: number, text: string, stopReason: AgentStopReason): AgentResult { + if (stopReason === "budget") this.emit({ type: "budget", turn, usd: this.o.meter.usd }); + this.emit({ type: "done", turn, stopReason, usd: this.o.meter.usd }); + return { text, stopReason, transcript: this.transcript }; + } +} + +const isCancel = (err: unknown, signal?: AbortSignal) => err instanceof CancelledError || !!signal?.aborted; + +async function runClaude(o: AgentOptions): Promise<AgentResult> { + const run = new Run(o); + const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); + const strict = isStrictModel(o.model); + const resultChars = o.resultChars ?? CLAUDE_RESULT_CHARS; + const maxTurns = o.maxTurns ?? DEFAULT_MAX_TURNS; + const byName = new Map(o.tools.map((t) => [t.name, t])); + let serverSearch = !!o.serverWebSearch; + const toolDefs = () => [ + ...o.tools + .filter((t) => !(serverSearch && t.name === "web_search")) + .map((t) => ({ name: t.name, description: t.description.slice(0, 1500), input_schema: t.inputSchema })), + ...(serverSearch + ? [{ type: WEB_SEARCH_TOOL_TYPE, name: "web_search", max_uses: o.serverWebSearch!.maxUses }] + : []), + ]; + const system = [{ type: "text", text: o.system, cache_control: cacheControl(client.cacheTtl) }]; + const messages: { role: string; content: string | ContentBlock[] }[] = [{ role: "user", content: o.user }]; + let recorded = 0; // messages already in the transcript + let lastTools = ""; + let lastInput = 0; + let lastText = ""; + + for (let turn = 0; turn < maxTurns; turn++) { + if (o.signal?.aborted) return run.finish(turn, lastText, "cancelled"); + if (run.spentOut()) return run.finish(turn, lastText, "budget"); + if (!strict) { + const dropped = pruneToolResults(messages, lastInput); + if (dropped) run.emit({ type: "prune", turn, dropped }); + } + const tools = toolDefs(); + const body: Record<string, unknown> = { + model: o.model, + max_tokens: o.maxTokens ?? 16_000, + system, + ...(tools.length ? { tools } : {}), + messages, + }; + const toolsJson = JSON.stringify(tools); + run.transcript.push({ + kind: "request", + turn, + provider: "api", + at: now(), + request: clip({ + model: o.model, + max_tokens: body.max_tokens, + ...(turn === 0 ? { system: o.system } : {}), + ...(toolsJson !== lastTools ? { tools } : {}), + messages: messages.slice(recorded), + }, o.transcriptResultChars) as Record<string, unknown>, + messagesTotal: messages.length, + }); + lastTools = toolsJson; + recorded = messages.length; + + let res; + const before = o.meter.usd; + try { + res = await client.messages(body, { meter: o.meter, signal: o.signal }); + } catch (err) { + if (isCancel(err, o.signal)) return run.finish(turn, lastText, "cancelled"); + if (serverSearch && err instanceof AnthropicError && err.status === 400 && /web_search/.test(err.message)) { + serverSearch = false; + run.note(turn, "server web search refused; going on without it"); + continue; + } + throw err; + } + const usd = o.meter.usd - before; + const u = res.usage ?? {}; + lastInput = + (Number(u.input_tokens) || 0) + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0); + messages.push({ role: "assistant", content: res.content }); + recorded = messages.length; + const calls = toolUsesOf(res); + const text = textOf(res); + if (text) lastText = text; + run.transcript.push({ + kind: "response", + turn, + provider: "api", + at: now(), + stopReason: res.stop_reason, + content: clip(res.content, o.transcriptResultChars), + usage: u, + usd, + }); + run.emit({ type: "turn", turn, provider: "api", stopReason: res.stop_reason, calls: calls.map((c) => c.name), text, usage: u, usd }); + + if (res.stop_reason === "pause_turn") { + // A server tool paused the turn: send it back as it is to carry on. + run.emit({ type: "pause", turn }); + continue; + } + if (!calls.length) return run.finish(turn, lastText, "end_turn"); + + const results = await Promise.all( + calls.map(async (c) => { + const r = await runTool(byName, c.name, c.input, o.signal); + run.transcript.push({ + kind: "tool", + turn, + name: c.name, + id: c.id, + input: clip(c.input, o.transcriptResultChars), + result: clip(r.out, o.transcriptResultChars) as string, + chars: r.out.length, + error: r.error, + ms: r.ms, + }); + run.emit({ type: "tool", turn, name: c.name, chars: r.out.length, error: r.error, ms: r.ms }); + return { + type: "tool_result", + tool_use_id: c.id, + content: cut(r.out, resultChars), + ...(r.error ? { is_error: true } : {}), + } as ContentBlock; + }), + ); + if (o.signal?.aborted) return run.finish(turn, lastText, "cancelled"); + if (run.spentOut()) { + messages.push({ role: "user", content: results }); + return run.finish(turn, lastText, "budget"); + } + if (run.wrapUpDue()) { + run.wrapped = true; + // After the tool results, in the same user turn: one message, append-only. + results.push({ type: "text", text: o.wrapUpText ?? WRAP_UP_TEXT }); + run.emit({ type: "wrap-up", turn, usd: o.meter.usd }); + } + messages.push({ role: "user", content: results }); + } + return run.finish(maxTurns, lastText, "max_turns"); +} + +async function runLocal(o: AgentOptions): Promise<AgentResult> { + const run = new Run(o); + const cfg = ollamaConfigOf(o.llm, o.model); + const cap = promptCapOf(cfg); + const resultChars = o.resultChars ?? LOCAL_RESULT_CHARS; + const maxTurns = o.maxTurns ?? DEFAULT_MAX_TURNS; + const byName = new Map(o.tools.map((t) => [t.name, t])); + const tools = toOllamaTools(o.tools); + const messages: OllamaMessage[] = [ + { role: "system", content: o.system }, + { role: "user", content: o.user }, + ]; + let recorded = 0; + let lastText = ""; + + for (let turn = 0; turn < maxTurns; turn++) { + if (o.signal?.aborted) return run.finish(turn, lastText, "cancelled"); + if (run.spentOut()) return run.finish(turn, lastText, "budget"); + const dropped = fitLocal(messages, tools, cap); + if (dropped) run.emit({ type: "fit", turn, dropped, estimate: promptEstimate({ messages, tools }) }); + run.transcript.push({ + kind: "request", + turn, + provider: "local", + at: now(), + request: clip({ + model: o.model, + ...(turn === 0 ? { tools } : {}), + messages: messages.slice(recorded), + ...(dropped ? { fitted: dropped } : {}), + }, o.transcriptResultChars) as Record<string, unknown>, + messagesTotal: messages.length, + }); + + let reply; + const before = o.meter.usd; + try { + reply = await ollamaChat(cfg, { model: o.model, messages, tools, signal: o.signal }); + } catch (err) { + if (isCancel(err, o.signal)) return run.finish(turn, lastText, "cancelled"); + throw err; + } + const usage: Usage = { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }; + o.meter.add(o.model, usage); + const usd = o.meter.usd - before; + const msg = reply.message; + messages.push({ + role: "assistant", + content: msg.content ?? "", + ...(msg.tool_calls?.length ? { tool_calls: msg.tool_calls } : {}), + }); + recorded = messages.length; + const calls = toolCallsOf(msg); + if (msg.content) lastText = msg.content; + run.transcript.push({ + kind: "response", + turn, + provider: "local", + at: now(), + stopReason: calls.length ? "tool_use" : "end_turn", + content: clip(msg, o.transcriptResultChars), + usage, + usd, + }); + run.emit({ + type: "turn", + turn, + provider: "local", + stopReason: calls.length ? "tool_use" : "end_turn", + calls: calls.map((c) => c.name), + text: msg.content ?? "", + usage, + usd, + }); + if (!calls.length) return run.finish(turn, lastText, "end_turn"); + + // One at a time: the local lane is one GPU, and the tools are paced. + for (const c of calls) { + const r = await runTool(byName, c.name, c.input, o.signal); + run.transcript.push({ + kind: "tool", + turn, + name: c.name, + input: clip(c.input, o.transcriptResultChars), + result: clip(r.out, o.transcriptResultChars) as string, + chars: r.out.length, + error: r.error, + ms: r.ms, + }); + run.emit({ type: "tool", turn, name: c.name, chars: r.out.length, error: r.error, ms: r.ms }); + messages.push({ role: "tool", tool_name: c.name, content: cut(r.out, resultChars) }); + if (o.signal?.aborted) return run.finish(turn, lastText, "cancelled"); + } + if (run.spentOut()) return run.finish(turn, lastText, "budget"); + if (run.wrapUpDue()) { + run.wrapped = true; + messages.push({ role: "user", content: o.wrapUpText ?? WRAP_UP_TEXT }); + run.emit({ type: "wrap-up", turn, usd: o.meter.usd }); + } + } + return run.finish(maxTurns, lastText, "max_turns"); +} diff --git a/common/lib/llm/anthropic.test.ts b/common/lib/llm/anthropic.test.ts @@ -0,0 +1,247 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + FAKE_KEY, + errorTurn, + startFakeAnthropic, + textTurn, + toolTurn, +} from "../../testing/llm/fakeAnthropic.mjs"; +import { + AnthropicClient, + AnthropicError, + ApiKeyError, + CancelledError, + backoffMs, + isClaudeModel, + isStrictModel, + prepareBody, + readApiKey, + redact, + textOf, +} from "./anthropic"; +import { Meter } from "./meter"; + +const noSleep = async () => {}; + +async function keyFile(content: string, mode: number) { + const dir = await mkdtemp(path.join(os.tmpdir(), "llm-key-")); + const file = path.join(dir, "anthropic.env"); + await writeFile(file, content); + await chmod(file, mode); + return { file, done: () => rm(dir, { recursive: true, force: true }) }; +} + +test("isClaudeModel / isStrictModel", () => { + assert.equal(isClaudeModel("claude-sonnet-5-5"), true); + assert.equal(isClaudeModel("qwen3:8b"), false); + assert.equal(isStrictModel("claude-sonnet-5-5"), true); + assert.equal(isStrictModel("claude-opus-5-5"), true); + assert.equal(isStrictModel("claude-sonnet-5"), false); + assert.equal(isStrictModel("claude-haiku-4-5"), false); +}); + +test("readApiKey: the environment first", () => { + assert.equal(readApiKey({ env: { ANTHROPIC_API_KEY: " k-from-env " }, apiKeyFile: "/nonexistent" }), "k-from-env"); +}); + +test("readApiKey: a mode-600 file, quotes and an export prefix tolerated", async () => { + const f = await keyFile(`# comment\nexport ANTHROPIC_API_KEY="${FAKE_KEY}"\n`, 0o600); + try { + assert.equal(readApiKey({ env: {}, apiKeyFile: f.file }), FAKE_KEY); + } finally { + await f.done(); + } +}); + +test("readApiKey: refused when group or others can read the file; missing file; no line; nothing configured", async () => { + const open = await keyFile(`ANTHROPIC_API_KEY=${FAKE_KEY}\n`, 0o644); + const noLine = await keyFile(`OTHER=1\n`, 0o600); + try { + assert.throws(() => readApiKey({ env: {}, apiKeyFile: open.file }), (e: Error) => { + assert.ok(e instanceof ApiKeyError); + assert.match(e.message, /chmod 600/); + assert.ok(!e.message.includes(FAKE_KEY)); + return true; + }); + assert.throws(() => readApiKey({ env: {}, apiKeyFile: noLine.file }), /has no ANTHROPIC_API_KEY= line/); + assert.throws(() => readApiKey({ env: {}, apiKeyFile: "/nonexistent/anthropic.env" }), /no API key/); + assert.throws(() => readApiKey({ env: {} }), /no API key/); + } finally { + await open.done(); + await noLine.done(); + } +}); + +test("redact: the key and any long run of it", () => { + assert.equal(redact(`bad key ${FAKE_KEY}!`, FAKE_KEY), "bad key [redacted]!"); + assert.ok(!redact(`echo ${FAKE_KEY.slice(4, 24)}`, FAKE_KEY).includes(FAKE_KEY.slice(8, 24))); +}); + +test("messages: the key only in x-api-key; top-level cache_control plus a system breakpoint", async () => { + const api = await startFakeAnthropic({ turns: [textTurn("hello")] }); + try { + const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); + const res = await client.messages({ model: "claude-sonnet-5", max_tokens: 100, system: "Be brief.", messages: [{ role: "user", content: "hi" }] }); + assert.equal(textOf(res), "hello"); + const h = api.requestHeaders[0]; + assert.equal(h["x-api-key"], api.key); + assert.equal(h["anthropic-version"], "2023-06-01"); + const body = api.requests[0]; + assert.deepEqual(body.cache_control, { type: "ephemeral" }); + assert.deepEqual(body.system, [{ type: "text", text: "Be brief.", cache_control: { type: "ephemeral" } }]); + assert.ok(!JSON.stringify(body).includes(api.key)); + } finally { + await api.close(); + } +}); + +test("messages: cacheTtl 1h on both breakpoints; the meter prices writes at 2x", async () => { + const api = await startFakeAnthropic({ + turns: [textTurn("a", { usage: { input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 1_000_000 } })], + }); + try { + const meter = new Meter(); + const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, cacheTtl: "1h" }); + await client.messages({ model: "claude-sonnet-5", max_tokens: 10, system: "S", messages: [{ role: "user", content: "x" }] }, { meter }); + assert.deepEqual(api.requests[0].cache_control, { type: "ephemeral", ttl: "1h" }); + assert.deepEqual(api.requests[0].system[0].cache_control, { type: "ephemeral", ttl: "1h" }); + assert.equal(meter.usd, 4); // $2/M × 2 + } finally { + await api.close(); + } +}); + +test("messages: a strict model loses temperature, gets thinking between_tools; a forced tool_choice is refused unsent", async () => { + const api = await startFakeAnthropic({ turns: [textTurn("ok")] }); + try { + const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); + await client.messages({ + model: "claude-sonnet-5-5", + max_tokens: 10, + temperature: 0.2, + thinking: { type: "disabled" }, + messages: [{ role: "user", content: "x" }], + }); + const body = api.requests[0]; + assert.equal("temperature" in body, false); + assert.deepEqual(body.thinking, { type: "between_tools" }); + await assert.rejects( + client.messages({ + model: "claude-sonnet-5-5", + max_tokens: 10, + tool_choice: { type: "tool", name: "answer" }, + messages: [{ role: "user", content: "x" }], + }), + /forced tool_choice/, + ); + assert.equal(api.requests.length, 1); + // Opus 5.5 keeps its own thinking default; a `disabled` it would refuse is dropped. + assert.equal("thinking" in prepareBody({ model: "claude-opus-5-5", thinking: { type: "disabled" } }, "5m"), false); + } finally { + await api.close(); + } +}); + +test("messages: 429 with retry-after, then 529 with backoff, then success", async () => { + const api = await startFakeAnthropic({ + turns: [ + errorTurn(429, "rate_limit_error", "slow down", { "retry-after": "7" }), + errorTurn(529, "overloaded_error", "overloaded"), + textTurn("third time"), + ], + }); + try { + const slept: number[] = []; + const client = new AnthropicClient({ + baseUrl: api.url, + env: { ANTHROPIC_API_KEY: api.key }, + sleep: async (ms) => void slept.push(ms), + }); + const res = await client.messages({ model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }); + assert.equal(textOf(res), "third time"); + assert.deepEqual(slept, [7000, backoffMs(1)]); + assert.equal(api.requests.length, 3); + } finally { + await api.close(); + } +}); + +test("messages: retries are bounded; a 400 is not retried", async () => { + const api = await startFakeAnthropic({ + turns: [ + errorTurn(503, "api_error", "down"), + errorTurn(503, "api_error", "down"), + errorTurn(503, "api_error", "down"), + errorTurn(400, "invalid_request_error", "messages: bad"), + ], + }); + try { + const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: noSleep, maxRetries: 2 }); + const body = { model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }; + await assert.rejects(client.messages(body), (e: AnthropicError) => { + assert.equal(e.status, 503); + assert.equal(e.retryable, true); + return true; + }); + assert.equal(api.requests.length, 3); + await assert.rejects(client.messages(body), (e: AnthropicError) => { + assert.equal(e.status, 400); + assert.equal(e.errorType, "invalid_request_error"); + assert.match(e.message, /messages: bad/); + return true; + }); + assert.equal(api.requests.length, 4); + } finally { + await api.close(); + } +}); + +test("messages: a model that refuses temperature is asked once more without it", async () => { + const api = await startFakeAnthropic({ + turns: [errorTurn(400, "invalid_request_error", "temperature: not supported on this model"), textTurn("fine")], + }); + try { + const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: noSleep }); + const res = await client.messages({ model: "claude-opus-5", max_tokens: 10, temperature: 0.2, messages: [{ role: "user", content: "x" }] }); + assert.equal(textOf(res), "fine"); + assert.equal(api.requests[0].temperature, 0.2); + assert.equal("temperature" in api.requests[1], false); + } finally { + await api.close(); + } +}); + +test("messages: the signal aborts the in-flight request", async () => { + const api = await startFakeAnthropic({ + turns: [async () => (await new Promise((r) => setTimeout(r, 400)), textTurn("late"))], + }); + try { + const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); + const ac = new AbortController(); + setTimeout(() => ac.abort(), 50); + await assert.rejects( + client.messages({ model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }, { signal: ac.signal }), + (e) => e instanceof CancelledError, + ); + } finally { + await new Promise((r) => setTimeout(r, 400)); + await api.close(); + } +}); + +test("messages: a tool turn comes back as content blocks", async () => { + const api = await startFakeAnthropic({ turns: [toolTurn("lookup", { q: "oven" })] }); + try { + const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); + const res = await client.messages({ model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }); + assert.equal(res.stop_reason, "tool_use"); + assert.equal(res.content[0].type, "tool_use"); + assert.deepEqual(client.describe(), { baseUrl: api.url, cacheTtl: "5m", maxRetries: 5 }); + } finally { + await api.close(); + } +}); diff --git a/common/lib/llm/anthropic.ts b/common/lib/llm/anthropic.ts @@ -0,0 +1,342 @@ +// The Claude Messages API over HTTPS with an API key (release 27; the stopgap's +// claude_api.py). Not a Claude Code session: billed to the Console account. +// +// The key: $ANTHROPIC_API_KEY, else `apiKeyFile` (a line ANTHROPIC_API_KEY=…, +// mode 600 — refused when group or others can read it). It is read here and +// sent only in the `x-api-key` header. It is never logged, put in an error, an +// event or a transcript: every message this module throws passes `redact`. +// +// Every request carries the top-level `cache_control` (the API moves that +// breakpoint forward each turn) plus one on the system prompt, both at the +// client's one TTL — a 1h breakpoint may not follow a 5m one. +// +// The strict models (Sonnet 5.5 first; see STRICT_MODELS) answer a 400 to a +// non-default `temperature`, a forced `tool_choice` and `thinking: disabled`, and +// sign their thinking blocks over the history before them, so their +// conversations stay append-only. This client drops `temperature` for them, +// refuses a forced `tool_choice` before sending, and asks Sonnet 5.5 for +// `thinking: {type: "between_tools"}`. + +import { readFileSync, statSync } from "node:fs"; +import os from "node:os"; +import type { CacheTtl } from "./prices"; +import type { Meter, Usage } from "./meter"; + +export type AnthropicConfig = { + apiKeyFile?: string; + baseUrl?: string; + cacheTtl?: CacheTtl; + fetch?: typeof fetch; + sleep?: (ms: number) => Promise<void>; + maxRetries?: number; + // Where ANTHROPIC_API_KEY is looked up (tests pass {}); default process.env. + env?: Record<string, string | undefined>; + // One request's timeout, retries apart (default 10 minutes). + timeoutMs?: number; +}; + +export type ContentBlock = { type: string; [k: string]: unknown }; +export type TextBlock = { type: "text"; text: string }; +export type ToolUseBlock = { type: "tool_use"; id: string; name: string; input: unknown }; + +export type MessagesResponse = { + id: string; + type: "message"; + role: "assistant"; + model: string; + content: ContentBlock[]; + stop_reason: string | null; + stop_sequence?: string | null; + usage: Usage; +}; + +export const DEFAULT_BASE_URL = "https://api.anthropic.com"; +export const ANTHROPIC_VERSION = "2023-06-01"; +export const DEFAULT_MAX_RETRIES = 5; + +// Models with Sonnet 5.5's rules: no sampling parameters, no forced tool use, +// preserved (signed) thinking. Opus 5.5 and Fable/Mythos 5.1 share the last two. +export const STRICT_MODELS = ["claude-sonnet-5-5", "claude-opus-5-5", "claude-fable-5-1", "claude-mythos-5-1"]; + +export function isClaudeModel(model: string): boolean { + return model.startsWith("claude-"); +} + +export function isStrictModel(model: string): boolean { + return STRICT_MODELS.some((m) => model.startsWith(m)); +} + +// The thinking setting a model is sent: Sonnet 5.5 refuses `disabled`, and +// `between_tools` is its lowest setting. Other models keep their default. +export function thinkingFor(model: string): { type: string } | undefined { + return model.startsWith("claude-sonnet-5-5") ? { type: "between_tools" } : undefined; +} + +export function cacheControl(ttl: CacheTtl = "5m"): { type: "ephemeral"; ttl?: "1h" } { + return ttl === "1h" ? { type: "ephemeral", ttl: "1h" } : { type: "ephemeral" }; +} + +export function textOf(res: { content?: ContentBlock[] }): string { + return (res.content ?? []) + .filter((b) => b.type === "text" && typeof b.text === "string") + .map((b) => b.text as string) + .join(""); +} + +export function toolUsesOf(res: { content?: ContentBlock[] }): ToolUseBlock[] { + return (res.content ?? []).filter((b): b is ToolUseBlock & ContentBlock => b.type === "tool_use"); +} + +// ─── The key ─── + +export class ApiKeyError extends Error { + constructor(message: string) { + super(message); + this.name = "ApiKeyError"; + } +} + +const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p); + +export function readApiKey(cfg: AnthropicConfig): string { + const env = cfg.env ?? process.env; + const fromEnv = (env.ANTHROPIC_API_KEY ?? "").trim(); + if (fromEnv) return fromEnv; + if (!cfg.apiKeyFile) + throw new ApiKeyError("no API key: set ANTHROPIC_API_KEY, or configure the API key file"); + const file = expandHome(cfg.apiKeyFile); + let mode: number; + try { + mode = statSync(file).mode; + } catch { + throw new ApiKeyError( + `no API key: set ANTHROPIC_API_KEY, or put a line ANTHROPIC_API_KEY=… in ${file} (chmod 600)`, + ); + } + if (mode & 0o077) throw new ApiKeyError(`${file} is readable by others — chmod 600 it first`); + let text: string; + try { + text = readFileSync(file, "utf8"); + } catch { + throw new ApiKeyError(`${file} could not be read`); + } + for (const raw of text.split("\n")) { + const line = raw.trim().replace(/^export\s+/, ""); + if (!line.startsWith("ANTHROPIC_API_KEY=")) continue; + const key = line + .slice("ANTHROPIC_API_KEY=".length) + .trim() + .replace(/^(["'])(.*)\1$/, "$2") + .trim(); + if (key) return key; + } + throw new ApiKeyError(`${file} has no ANTHROPIC_API_KEY= line`); +} + +// Replace every occurrence of the key (and of a long-enough piece of it) in a +// text: the last line of defence for anything that leaves this module. +export function redact(text: string, key: string | undefined): string { + if (!key || key.length < 8) return text; + let out = text.split(key).join("[redacted]"); + // A server or a proxy may echo a truncated key; hide any 16-char run of it. + if (key.length >= 24) + for (let i = 0; i + 16 <= key.length; i += 8) out = out.split(key.slice(i, i + 16)).join("[redacted]"); + return out; +} + +// ─── Errors ─── + +export class AnthropicError extends Error { + readonly status: number | undefined; + readonly errorType: string | undefined; + readonly retryable: boolean; + constructor(message: string, o: { status?: number; errorType?: string; retryable?: boolean } = {}) { + super(message); + this.name = "AnthropicError"; + this.status = o.status; + this.errorType = o.errorType; + this.retryable = o.retryable ?? false; + } +} + +export class CancelledError extends Error { + constructor() { + super("cancelled"); + this.name = "CancelledError"; + } +} + +const RETRY_STATUSES = new Set([408, 429, 500, 502, 503, 504, 529]); +const isRetryStatus = (s: number) => RETRY_STATUSES.has(s) || s >= 500; + +// retry-after: seconds (possibly fractional) or an HTTP date; capped at 2 min. +function retryAfterMs(value: string | null): number | undefined { + if (!value) return undefined; + const secs = Number(value); + let ms = Number.isFinite(secs) ? secs * 1000 : Date.parse(value) - Date.now(); + if (!Number.isFinite(ms) || ms < 0) return undefined; + ms = Math.min(ms, 120_000); + return ms; +} + +export const backoffMs = (attempt: number) => Math.min(60_000, 5_000 * 2 ** attempt); + +function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { + return new Promise((resolve, reject) => { + if (signal?.aborted) return reject(new CancelledError()); + const t = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(t); + reject(new CancelledError()); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +// ─── The request body ─── + +// The body as sent: top-level cache_control, the system prompt as a block with +// its own breakpoint, and the strict models' rules. Exported for tests. +export function prepareBody(body: Record<string, unknown>, ttl: CacheTtl): Record<string, unknown> { + const model = String(body.model ?? ""); + const cc = cacheControl(ttl); + const out: Record<string, unknown> = { cache_control: cc, ...body }; + if (typeof out.system === "string" && out.system) + out.system = [{ type: "text", text: out.system, cache_control: cc }]; + if (isStrictModel(model)) { + delete out.temperature; + const tc = out.tool_choice as { type?: string } | undefined; + if (tc && (tc.type === "tool" || tc.type === "any")) + throw new AnthropicError( + `${model} refuses a forced tool_choice; use a strict tool with tool_choice auto`, + { status: 400, errorType: "client_refused" }, + ); + const thinking = thinkingFor(model); + const asked = out.thinking as { type?: string } | undefined; + if (thinking && (!asked || asked.type === "disabled")) out.thinking = thinking; + else if (asked?.type === "disabled") delete out.thinking; + } + return out; +} + +// ─── The client ─── + +export class AnthropicClient { + readonly cacheTtl: CacheTtl; + readonly maxRetries: number; + private readonly url: string; + // Private (#) so neither inspect() nor JSON shows the config: its `env` may + // hold the key. + readonly #cfg: AnthropicConfig; + #key: string | undefined; + + constructor(cfg: AnthropicConfig) { + this.#cfg = cfg; + this.cacheTtl = cfg.cacheTtl ?? "5m"; + this.maxRetries = cfg.maxRetries ?? DEFAULT_MAX_RETRIES; + this.url = (cfg.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "") + "/v1/messages"; + } + + // The config without anything secret, for logs and records. + describe(): { baseUrl: string; cacheTtl: CacheTtl; maxRetries: number } { + return { baseUrl: this.url.replace(/\/v1\/messages$/, ""), cacheTtl: this.cacheTtl, maxRetries: this.maxRetries }; + } + + toJSON() { + return this.describe(); + } + + private key(): string { + this.#key ??= readApiKey(this.#cfg); + return this.#key; + } + + private fail(message: string, o: ConstructorParameters<typeof AnthropicError>[1] = {}): AnthropicError { + return new AnthropicError(redact(message, this.#key), o); + } + + // POST /v1/messages with retries on 429/5xx/529 (retry-after, else backoff). + // A 400 is not retried, except once without `temperature` when the model + // refuses one. `signal` aborts the in-flight request and any wait. + async messages( + body: Record<string, unknown>, + o: { meter?: Meter; signal?: AbortSignal } = {}, + ): Promise<MessagesResponse> { + const key = this.key(); + let sent = prepareBody(body, this.cacheTtl); + const doFetch = this.#cfg.fetch ?? fetch; + const sleep = this.#cfg.sleep; + const wait = async (ms: number) => { + if (sleep) await sleep(ms); + else await abortableSleep(ms, o.signal); + if (o.signal?.aborted) throw new CancelledError(); + }; + let last = ""; + let retries = 0; + for (;;) { + if (o.signal?.aborted) throw new CancelledError(); + const timeout = AbortSignal.timeout(this.#cfg.timeoutMs ?? 600_000); + const signal = o.signal ? AbortSignal.any([o.signal, timeout]) : timeout; + let res: Response; + try { + res = await doFetch(this.url, { + method: "POST", + headers: { + "x-api-key": key, + "anthropic-version": ANTHROPIC_VERSION, + "content-type": "application/json", + }, + body: JSON.stringify(sent), + signal, + }); + } catch (err) { + if (o.signal?.aborted) throw new CancelledError(); + last = `request failed: ${(err as Error)?.message ?? String(err)}`; + if (retries >= this.maxRetries) break; + await wait(backoffMs(retries++)); + continue; + } + if (res.ok) { + let parsed: MessagesResponse; + try { + parsed = (await res.json()) as MessagesResponse; + } catch { + throw this.fail("Claude API: the response is not JSON", { status: res.status }); + } + if (o.meter) o.meter.add(String(sent.model), parsed.usage ?? {}, { cacheTtl: this.cacheTtl }); + return parsed; + } + const raw = await res.text().catch(() => ""); + let errorType: string | undefined; + let detail = raw; + try { + const j = JSON.parse(raw) as { error?: { type?: string; message?: string } }; + errorType = j.error?.type; + detail = j.error?.message ?? raw; + } catch { + // not JSON: keep the text + } + detail = detail.slice(0, 600); + last = `HTTP ${res.status}${errorType ? ` ${errorType}` : ""}: ${detail}`; + if (res.status === 400 && /temperature/.test(detail) && "temperature" in sent) { + const { temperature: _dropped, ...rest } = sent; + sent = rest; // a model that fixes its own sampling + continue; + } + if (isRetryStatus(res.status) && retries < this.maxRetries) { + await wait(retryAfterMs(res.headers.get("retry-after")) ?? backoffMs(retries)); + retries++; + continue; + } + throw this.fail(`Claude API ${last}`, { + status: res.status, + errorType, + retryable: isRetryStatus(res.status), + }); + } + throw this.fail(`Claude API: gave up after ${retries} retries (${last})`, { retryable: true }); + } +} diff --git a/common/lib/llm/config.ts b/common/lib/llm/config.ts @@ -0,0 +1,24 @@ +// Which provider a model runs on, and the config for both (release 27). This +// module reads no settings: the caller (an editor job, S6) passes everything in. + +import { isClaudeModel, type AnthropicConfig } from "./anthropic"; +import type { OllamaConfig } from "./ollama"; + +export type LlmConfig = { anthropic?: AnthropicConfig; ollama?: OllamaConfig }; + +export type Provider = "api" | "local"; + +// A Claude model goes to the API; anything else is a local model on ollama. +export function providerOf(model: string): Provider { + return isClaudeModel(model) ? "api" : "local"; +} + +export function anthropicConfigOf(llm: LlmConfig, model: string): AnthropicConfig { + if (!llm.anthropic) throw new Error(`${model} runs on the Claude API, and no API config was given`); + return llm.anthropic; +} + +export function ollamaConfigOf(llm: LlmConfig, model: string): OllamaConfig { + if (!llm.ollama?.baseUrl) throw new Error(`${model} runs on ollama, and no ollama URL was given`); + return llm.ollama; +} diff --git a/common/lib/llm/index.ts b/common/lib/llm/index.ts @@ -0,0 +1,12 @@ +// The LLM providers and the agent loop (release 27, S1): the Claude Messages +// API with an API key, a local model on ollama, one structured answer on +// either, and the tool loop. Nothing here reads settings; the caller passes the +// config in (S6 builds it from `settings.generation`). + +export * from "./prices"; +export * from "./meter"; +export * from "./anthropic"; +export * from "./ollama"; +export * from "./config"; +export * from "./structured"; +export * from "./agent"; diff --git a/common/lib/llm/keyLeak.test.ts b/common/lib/llm/keyLeak.test.ts @@ -0,0 +1,145 @@ +// The API key never leaves the x-api-key header: not in a log, an error, an +// event, a transcript or a request body — on success, a 401, a 400, retry +// exhaustion, a network failure, a tool error and a bad key file. The key is +// recognisable, and the servers below echo it back in their errors (worse than +// the real API does) to prove the redaction. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { inspect } from "node:util"; +import { FAKE_KEY, errorTurn, startFakeAnthropic, textTurn, toolTurn, turn, toolUseBlock } from "../../testing/llm/fakeAnthropic.mjs"; +import { AnthropicClient, type AnthropicConfig } from "./anthropic"; +import { runAgent, type AgentEvent, type AgentTool } from "./agent"; +import { Meter } from "./meter"; +import { structuredAnswer } from "./structured"; + +const KEY = FAKE_KEY; + +function capture(seen: string[], v: unknown) { + if (v instanceof Error) { + seen.push(v.message, String(v.stack), String(v), inspect(v, { depth: 5 }), JSON.stringify({ ...v })); + if (v.cause) capture(seen, v.cause); + } else seen.push(typeof v === "string" ? v : (JSON.stringify(v) ?? String(v)), inspect(v, { depth: 8 })); +} + +test("the key appears in no log, error, event, transcript or request body", async () => { + const seen: string[] = []; + const methods = ["log", "info", "warn", "error", "debug"] as const; + const saved = methods.map((m) => console[m]); + for (const m of methods) console[m] = (...args: unknown[]) => void seen.push(args.map((a) => inspect(a)).join(" ")); + const echo = `invalid request (key ${KEY})`; + const api = await startFakeAnthropic({ + turns: [ + // 1. success: a tool loop with a tool that errors, then an answer + toolTurn("lookup", { q: "oven" }), + textTurn("done"), + // 2. structured answer, success + turn([toolUseBlock("answer", { ok: true })]), + // 3. a 400 that echoes the key + errorTurn(400, "invalid_request_error", echo), + // 4. retry exhaustion, every attempt echoing the key + errorTurn(529, "overloaded_error", echo), + errorTurn(529, "overloaded_error", echo), + errorTurn(529, "overloaded_error", echo), + ], + }); + const wrong = await startFakeAnthropic({ key: "another-key-for-the-401", turns: [] }); + const dir = await mkdtemp(path.join(os.tmpdir(), "llm-leak-")); + try { + const env = { ANTHROPIC_API_KEY: KEY }; + const cfg: AnthropicConfig = { baseUrl: api.url, env, sleep: async () => {}, maxRetries: 2 }; + const events: AgentEvent[] = []; + const failing: AgentTool = { + name: "lookup", + description: "d", + inputSchema: { type: "object", properties: {} }, + run: async () => { + throw new Error("the index is offline"); + }, + }; + + // 1. + const r = await runAgent({ + llm: { anthropic: cfg }, + model: "claude-sonnet-5-5", + system: "s", + user: "u", + tools: [failing], + meter: new Meter(), + onEvent: (e) => events.push(e), + }); + assert.equal(r.stopReason, "end_turn"); + capture(seen, r); + capture(seen, events); + // 2. + capture(seen, await structuredAnswer({ llm: { anthropic: cfg }, model: "claude-sonnet-5", system: "s", user: "u", schema: { type: "object", properties: { ok: { type: "boolean" } } } })); + // 3. + 4. + const client = new AnthropicClient(cfg); + const body = { model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }; + for (let i = 0; i < 2; i++) { + const err = await client.messages(body).then( + () => assert.fail("expected an error"), + (e: unknown) => e, + ); + capture(seen, err); + } + capture(seen, client); + // 5. a 401 (the server knows another key) — through the agent, so its events too + const err401 = await runAgent({ + llm: { anthropic: { ...cfg, baseUrl: wrong.url } }, + model: "claude-sonnet-5", + system: "s", + user: "u", + tools: [], + meter: new Meter(), + onEvent: (e) => events.push(e), + }).then( + () => assert.fail("expected a 401"), + (e: unknown) => e, + ); + assert.match(String(err401), /401/); + capture(seen, err401); + // 6. a network failure (nothing listens there) + const closed = await startFakeAnthropic(); + const closedUrl = closed.url; + await closed.close(); + capture( + seen, + await new AnthropicClient({ ...cfg, baseUrl: closedUrl }).messages(body).catch((e: unknown) => e), + ); + // 7. bad key files: readable by others, and no key line + const open = path.join(dir, "open.env"); + await writeFile(open, `ANTHROPIC_API_KEY=${KEY}\n`); + await chmod(open, 0o644); + const noLine = path.join(dir, "noline.env"); + await writeFile(noLine, `ANTHROPIC_KEY=${KEY}\n`); + await chmod(noLine, 0o600); + for (const file of [open, noLine]) { + const e = await new AnthropicClient({ baseUrl: api.url, env: {}, apiKeyFile: file }).messages(body).catch((x: unknown) => x); + assert.ok(e instanceof Error); + capture(seen, e); + } + + // The key was used — and only in the header. + assert.ok(api.requestHeaders.length >= 6); + for (const h of api.requestHeaders) assert.equal(h["x-api-key"], KEY); + capture(seen, api.requests); + capture(seen, wrong.requests); + + const all = seen.join("\n"); + assert.ok(all.length > 1000, "captured something"); + assert.ok(all.includes("[redacted]"), "the echoed key was redacted"); + assert.ok(all.includes("the index is offline"), "the tool error was captured"); + assert.equal(all.includes(KEY), false, "the key leaked"); + for (let i = 0; i + 16 <= KEY.length; i += 4) + assert.equal(all.includes(KEY.slice(i, i + 16)), false, `a piece of the key leaked: ${i}`); + } finally { + methods.forEach((m, i) => (console[m] = saved[i])); + await api.close(); + await wrong.close(); + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/llm/meter.test.ts b/common/lib/llm/meter.test.ts @@ -0,0 +1,73 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { priceOf, PRICES } from "./prices"; +import { Meter } from "./meter"; + +const close = (a: number, b: number) => assert.ok(Math.abs(a - b) < 1e-9, `${a} ≈ ${b}`); + +test("priceOf: the longest prefix wins", () => { + assert.deepEqual(priceOf("claude-opus-5-5"), PRICES["claude-opus-5-5"]); + assert.deepEqual(priceOf("claude-opus-5"), PRICES["claude-opus-5"]); + assert.deepEqual(priceOf("claude-sonnet-5-5-20261001"), PRICES["claude-sonnet-5-5"]); + assert.deepEqual(priceOf("claude-fable-5-1"), PRICES["claude-fable-5-1"]); + assert.deepEqual(priceOf("claude-fable-5"), PRICES["claude-fable-5"]); +}); + +test("priceOf: an unknown Claude model is priced as Opus 5; a local model is free", () => { + assert.deepEqual(priceOf("claude-unheard-of-9"), PRICES["claude-opus-5"]); + assert.deepEqual(priceOf("qwen3:8b"), { input: 0, output: 0, cacheReadMult: 0 }); +}); + +test("Meter: input, output, cache writes at 1.25x (5m) and reads at the model's multiplier", () => { + const m = new Meter(); + // Sonnet 5.5: $2 in, $10 out, reads 0.05x. + const usd = m.add("claude-sonnet-5-5", { + input_tokens: 1_000_000, + output_tokens: 100_000, + cache_creation_input_tokens: 1_000_000, + cache_read_input_tokens: 1_000_000, + }); + close(usd, 2 + 1 + 2 * 1.25 + 2 * 0.05); + close(m.usd, usd); +}); + +test("Meter: writes at 2x when the run's TTL is 1h, or by the API's split when it reports one", () => { + const m = new Meter(); + close(m.add("claude-sonnet-5", { cache_creation_input_tokens: 1_000_000 }, { cacheTtl: "1h" }), 4); + close(m.add("claude-sonnet-5", { cache_creation_input_tokens: 1_000_000 }), 2.5); + // The split wins over the TTL hint. + close( + m.add( + "claude-sonnet-5", + { + cache_creation_input_tokens: 1_000_000, + cache_creation: { ephemeral_5m_input_tokens: 500_000, ephemeral_1h_input_tokens: 500_000 }, + }, + { cacheTtl: "1h" }, + ), + 0.5 * 2 * 1.25 + 0.5 * 2 * 2, + ); +}); + +test("Meter: over() against the cap, never without one; summary per model", () => { + const capped = new Meter({ maxUsd: 1 }); + capped.add("claude-sonnet-5", { output_tokens: 85_000 }); // $0.85 + assert.equal(capped.over(0.85), true); + assert.equal(capped.over(), false); + capped.add("claude-sonnet-5", { output_tokens: 15_000 }); + assert.equal(capped.over(), true); + const free = new Meter(); + free.add("claude-opus-5", { output_tokens: 1_000_000 }); + assert.equal(free.over(), false); + + const m = new Meter(); + m.add("qwen3:8b", { input_tokens: 5000, output_tokens: 200 }); + m.add("claude-sonnet-5", { input_tokens: 100, cache_read_input_tokens: 300, output_tokens: 10 }); + const s = m.summary(); + assert.equal(s.byModel["qwen3:8b"].usd, 0); + assert.equal(s.byModel["qwen3:8b"].calls, 1); + assert.equal(s.byModel["claude-sonnet-5"].cacheHit, 0.75); + // The summary is a copy. + s.byModel["qwen3:8b"].calls = 99; + assert.equal(m.summary().byModel["qwen3:8b"].calls, 1); +}); diff --git a/common/lib/llm/meter.ts b/common/lib/llm/meter.ts @@ -0,0 +1,98 @@ +// A running token and estimated-USD tally across every call of a run (release +// 27), on either provider: a local model's calls are counted and cost nothing. + +import { CACHE_WRITE_MULT, priceOf, type CacheTtl } from "./prices"; + +// The Messages API's `usage`; ollama's counts map onto input/output. +export type Usage = { + input_tokens?: number; + output_tokens?: number; + cache_creation_input_tokens?: number | null; + cache_read_input_tokens?: number | null; + // The write split by TTL, when the API reports it. + cache_creation?: { ephemeral_5m_input_tokens?: number; ephemeral_1h_input_tokens?: number } | null; + [k: string]: unknown; +}; + +export type ModelTally = { + calls: number; + input: number; + cacheWrite: number; + cacheRead: number; + output: number; + usd: number; + // cache reads over all input (input + writes + reads), 0..1 + cacheHit: number; +}; + +const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0); +const round = (v: number, places = 6) => Math.round(v * 10 ** places) / 10 ** places; + +export class Meter { + // The cap `over()` measures against; mutable, so a caller may extend a run + // (a bounded repair round) without a second meter. + maxUsd: number | undefined; + private total = 0; + private readonly byModel: Record<string, ModelTally> = {}; + + constructor(o: { maxUsd?: number } = {}) { + this.maxUsd = o.maxUsd; + } + + get usd(): number { + return this.total; + } + + // Adds one call's usage and returns its USD. Cache writes the API does not + // split by TTL are priced at `cacheTtl` (the run's one TTL; default 5m). + add(model: string, usage: Usage, o: { cacheTtl?: CacheTtl } = {}): number { + const p = priceOf(model); + const input = n(usage.input_tokens); + const output = n(usage.output_tokens); + const write = n(usage.cache_creation_input_tokens); + const read = n(usage.cache_read_input_tokens); + const split = usage.cache_creation ?? null; + let write1h: number; + if (split && (split.ephemeral_1h_input_tokens !== undefined || split.ephemeral_5m_input_tokens !== undefined)) + write1h = Math.min(write, n(split.ephemeral_1h_input_tokens)); + else write1h = o.cacheTtl === "1h" ? write : 0; + const write5m = write - write1h; + const usd = + (input * p.input + + write5m * p.input * CACHE_WRITE_MULT["5m"] + + write1h * p.input * CACHE_WRITE_MULT["1h"] + + read * p.input * p.cacheReadMult + + output * p.output) / + 1e6; + this.total += usd; + const m = (this.byModel[model] ??= { + calls: 0, + input: 0, + cacheWrite: 0, + cacheRead: 0, + output: 0, + usd: 0, + cacheHit: 0, + }); + m.calls += 1; + m.input += input; + m.cacheWrite += write; + m.cacheRead += read; + m.output += output; + m.usd = round(m.usd + usd); + const all = m.input + m.cacheWrite + m.cacheRead; + m.cacheHit = all ? round(m.cacheRead / all, 3) : 0; + return usd; + } + + // True once the spend reaches `frac` of the cap; never without a cap. + over(frac = 1): boolean { + return this.maxUsd !== undefined && this.total >= this.maxUsd * frac; + } + + summary(): { usd: number; byModel: Record<string, ModelTally> } { + const byModel: Record<string, ModelTally> = {}; + for (const [k, v] of Object.entries(this.byModel)) byModel[k] = { ...v }; + return { usd: round(this.total), byModel }; + } +} diff --git a/common/lib/llm/ollama.test.ts b/common/lib/llm/ollama.test.ts @@ -0,0 +1,134 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + faultReply, + jsonReply, + reply, + startFakeOllama, + toolCallsReply, +} from "../../testing/llm/fakeOllama.mjs"; +import { + estimateTokens, + NUM_CTX_MAX, + ollamaChat, + OllamaError, + OllamaFaultError, + promptEstimate, + PromptTooLargeError, + toOllamaTools, + toolCallsOf, + unloadOllama, +} from "./ollama"; + +test("estimateTokens: 3.5 characters a token, over a string or the JSON of a value", () => { + assert.equal(estimateTokens("x".repeat(35)), 10); + assert.equal(estimateTokens({ a: 1 }), Math.ceil(JSON.stringify({ a: 1 }).length / 3.5)); +}); + +test("ollamaChat: stream false, think false on a thinking model, num_ctx clamped to 12k, the format passed", async () => { + const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] }), reply("plain")] }); + try { + const cfg = { baseUrl: ol.url + "/", numCtx: 32_768, temperature: 0.2 }; + const schema = { type: "object", properties: { terms: { type: "array" } } }; + const r = await ollamaChat(cfg, { model: "qwen3:8b", messages: [{ role: "user", content: "hi" }], format: schema }); + assert.deepEqual(JSON.parse(r.message.content), { terms: ["oven"] }); + assert.ok(r.promptTokens > 0 && r.evalTokens > 0); + const body = ol.requests[0]; + assert.equal(body.stream, false); + assert.equal(body.think, false); + assert.equal(body.options.num_ctx, NUM_CTX_MAX); + assert.equal(body.options.temperature, 0.2); + assert.deepEqual(body.format, schema); + // A model with no reasoning mode is not sent `think` at all. + await ollamaChat(cfg, { model: "qwen2.5:7b", messages: [{ role: "user", content: "hi" }] }); + assert.equal("think" in ol.requests[1], false); + } finally { + await ol.close(); + } +}); + +test("ollamaChat: a prompt over the cap is refused BEFORE it is sent", async () => { + const ol = await startFakeOllama({ turns: [reply("never")] }); + try { + const big = "word ".repeat(8000); // ~11.4k tokens at 3.5 chars + await assert.rejects( + ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: big }] }), + (e) => e instanceof PromptTooLargeError && e.estimate > 8000, + ); + // A lower cap from the caller is honoured; a higher one is clamped to 8k. + await assert.rejects( + ollamaChat({ baseUrl: ol.url, promptCapTokens: 300 }, { model: "qwen3:8b", messages: [{ role: "user", content: "x".repeat(2000) }] }), + PromptTooLargeError, + ); + await assert.rejects( + ollamaChat({ baseUrl: ol.url, promptCapTokens: 50_000 }, { model: "qwen3:8b", messages: [{ role: "user", content: big }] }), + PromptTooLargeError, + ); + assert.equal(ol.requests.length, 0); + } finally { + await ol.close(); + } +}); + +test("ollamaChat: done:false is a GPU fault, an HTTP error is an error", async () => { + const ol = await startFakeOllama({ turns: [faultReply()] }); + try { + await assert.rejects( + ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }] }), + (e) => e instanceof OllamaFaultError && /GPU fault/.test(e.message), + ); + await assert.rejects( + ollamaChat({ baseUrl: ol.url }, { model: "llama-none", messages: [{ role: "user", content: "x" }] }), + (e) => e instanceof OllamaError && e.status === 404, + ); + } finally { + await ol.close(); + } +}); + +test("tools both ways: AgentTool → function; tool_calls (object or string arguments) → name + input", async () => { + const ol = await startFakeOllama({ + turns: [ + toolCallsReply([{ name: "lookup", arguments: { q: "oven" } }]), + () => ({ + message: { role: "assistant", content: "", tool_calls: [{ function: { name: "lookup", arguments: '{"q":"tile"}' } }] }, + done: true, + }), + ], + }); + try { + const tools = toOllamaTools([ + { name: "lookup", description: "Look it up.", inputSchema: { type: "object", properties: { q: { type: "string" } } } }, + ]); + assert.deepEqual(tools[0], { + type: "function", + function: { name: "lookup", description: "Look it up.", parameters: { type: "object", properties: { q: { type: "string" } } } }, + }); + const a = await ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }], tools }); + assert.deepEqual(toolCallsOf(a.message), [{ name: "lookup", input: { q: "oven" } }]); + assert.deepEqual(ol.requests[0].tools, tools); + const b = await ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }], tools }); + assert.deepEqual(toolCallsOf(b.message), [{ name: "lookup", input: { q: "tile" } }]); + } finally { + await ol.close(); + } +}); + +test("unloadOllama: keep_alive 0", async () => { + const ol = await startFakeOllama({ turns: [reply("x")] }); + try { + await ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }] }); + assert.deepEqual(ol.loaded(), ["qwen3:8b"]); + await unloadOllama({ baseUrl: ol.url }, "qwen3:8b"); + assert.deepEqual(ol.unloads, ["qwen3:8b"]); + assert.deepEqual(ol.loaded(), []); + await assert.rejects(unloadOllama({ baseUrl: ol.url }, "nope:1b"), /404/); + } finally { + await ol.close(); + } +}); + +test("promptEstimate counts messages, tools and format", () => { + const m = [{ role: "user", content: "x".repeat(350) }]; + assert.ok(promptEstimate({ messages: m, tools: [{ a: "y".repeat(350) }] }) > promptEstimate({ messages: m })); +}); diff --git a/common/lib/llm/ollama.ts b/common/lib/llm/ollama.ts @@ -0,0 +1,215 @@ +// A local model on ollama (release 27): `/api/chat` with tools or a `format` +// schema, and the unload. The stopgap's local_sweep.chat and agentloop's local +// loop, with Q0's limits for the 8 GB card (2026-10-11): +// - `num_ctx` is clamped to 12k; +// - the prompt is estimated and REFUSED over 8k tokens before it is sent (a +// 13.8k prompt hung the GPU); +// - `done: false` is a GPU fault, never an answer; +// - one JSON answer (`stream: false`), `think: false` on thinking models +// unless the caller asks for thinking. +// `digestApps.ts`'s `ollamaDirect` is the digest's own call and is left as it is. + +export type OllamaConfig = { + baseUrl: string; + numCtx?: number; + promptCapTokens?: number; + fetch?: typeof fetch; + temperature?: number; + // One request's timeout (default 15 minutes: a cold load plus a long answer). + timeoutMs?: number; +}; + +export type OllamaToolCall = { function: { name: string; arguments: Record<string, unknown> } }; + +export type OllamaMessage = { + role: string; + content: string; + tool_calls?: OllamaToolCall[]; + tool_name?: string; + thinking?: string; + [k: string]: unknown; +}; + +export type OllamaTool = { + type: "function"; + function: { name: string; description: string; parameters: Record<string, unknown> }; +}; + +export const NUM_CTX_MAX = 12_288; +export const PROMPT_CAP_TOKENS = 8_000; +// Q0's estimate: 3.5 characters a token, over the JSON of what is sent — on the +// safe side of ollama's own count for English transcripts. +export const CHARS_PER_TOKEN = 3.5; + +export function estimateTokens(v: unknown): number { + const s = typeof v === "string" ? v : (JSON.stringify(v ?? "") ?? ""); + return Math.ceil(s.length / CHARS_PER_TOKEN); +} + +// What a chat request is estimated at: its messages, tools and format. +export function promptEstimate(req: { messages: unknown[]; tools?: unknown[]; format?: unknown }): number { + return estimateTokens([req.messages, req.tools ?? null, req.format ?? null]); +} + +export function numCtxOf(cfg: OllamaConfig): number { + const v = cfg.numCtx ?? NUM_CTX_MAX; + return Math.max(512, Math.min(NUM_CTX_MAX, Math.floor(v))); +} + +export function promptCapOf(cfg: OllamaConfig): number { + const v = cfg.promptCapTokens ?? PROMPT_CAP_TOKENS; + return Math.max(256, Math.min(PROMPT_CAP_TOKENS, Math.floor(v))); +} + +// Models with a reasoning mode, which take `think`; ollama refuses `think` on +// the others, so it is sent only to these unless the caller sets it. +const THINKING_MODELS = /^(qwen3|qwq|deepseek-r1|gpt-oss|magistral|cogito)/; + +export class OllamaError extends Error { + readonly status: number | undefined; + constructor(message: string, status?: number) { + super(message); + this.name = "OllamaError"; + this.status = status; + } +} + +export class OllamaFaultError extends OllamaError { + constructor(model: string) { + super(`${model} answered done:false (a GPU fault) — not an answer`); + this.name = "OllamaFaultError"; + } +} + +export class PromptTooLargeError extends OllamaError { + readonly estimate: number; + readonly cap: number; + constructor(estimate: number, cap: number) { + super(`prompt ~${estimate} tokens is over the ${cap}-token cap — not sent`); + this.name = "PromptTooLargeError"; + this.estimate = estimate; + this.cap = cap; + } +} + +const base = (cfg: OllamaConfig) => cfg.baseUrl.replace(/\/+$/, ""); + +// ollama returns tool-call arguments as an object; some models send a string. +function normalizeMessage(m: Partial<OllamaMessage> | undefined): OllamaMessage { + const out: OllamaMessage = { ...(m ?? {}), role: m?.role ?? "assistant", content: m?.content ?? "" }; + if (Array.isArray(m?.tool_calls) && m.tool_calls.length) { + out.tool_calls = m.tool_calls.map((c) => { + let args: unknown = c?.function?.arguments ?? {}; + if (typeof args === "string") { + try { + args = JSON.parse(args); + } catch { + args = {}; + } + } + return { + function: { + name: String(c?.function?.name ?? ""), + arguments: args && typeof args === "object" && !Array.isArray(args) ? (args as Record<string, unknown>) : {}, + }, + }; + }); + } else delete out.tool_calls; + return out; +} + +export async function ollamaChat( + cfg: OllamaConfig, + req: { + model: string; + messages: object[]; + tools?: object[]; + format?: object; + think?: boolean; + signal?: AbortSignal; + }, +): Promise<{ message: OllamaMessage; promptTokens: number; evalTokens: number }> { + const cap = promptCapOf(cfg); + const estimate = promptEstimate(req); + if (estimate > cap) throw new PromptTooLargeError(estimate, cap); + const think = req.think ?? (THINKING_MODELS.test(req.model) ? false : undefined); + const body = { + model: req.model, + stream: false, + ...(think !== undefined ? { think } : {}), + messages: req.messages, + ...(req.tools?.length ? { tools: req.tools } : {}), + ...(req.format ? { format: req.format } : {}), + options: { + num_ctx: numCtxOf(cfg), + ...(cfg.temperature !== undefined ? { temperature: cfg.temperature } : {}), + }, + }; + const timeout = AbortSignal.timeout(cfg.timeoutMs ?? 900_000); + const signal = req.signal ? AbortSignal.any([req.signal, timeout]) : timeout; + let res: Response; + try { + res = await (cfg.fetch ?? fetch)(`${base(cfg)}/api/chat`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + signal, + }); + } catch (err) { + if (req.signal?.aborted) throw err; + throw new OllamaError(`ollama request failed (${base(cfg)}): ${(err as Error)?.message ?? String(err)}`); + } + if (!res.ok) { + const text = await res.text().catch(() => ""); + let detail = text; + try { + detail = (JSON.parse(text) as { error?: string }).error ?? text; + } catch { + // keep the text + } + throw new OllamaError(`ollama returned ${res.status}: ${detail.slice(0, 300) || res.statusText}`, res.status); + } + const out = (await res.json()) as { + message?: Partial<OllamaMessage>; + done?: boolean; + prompt_eval_count?: number; + eval_count?: number; + }; + if (!out.done) throw new OllamaFaultError(req.model); + return { + message: normalizeMessage(out.message), + promptTokens: typeof out.prompt_eval_count === "number" ? out.prompt_eval_count : estimate, + evalTokens: typeof out.eval_count === "number" ? out.eval_count : 0, + }; +} + +// Frees the card: `keep_alive: 0` with nothing to answer. +export async function unloadOllama(cfg: OllamaConfig, model: string): Promise<void> { + const res = await (cfg.fetch ?? fetch)(`${base(cfg)}/api/generate`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model, keep_alive: 0 }), + signal: AbortSignal.timeout(30_000), + }); + if (!res.ok) { + const text = await res.text().catch(() => ""); + throw new OllamaError(`ollama unload of ${model} returned ${res.status}: ${text.slice(0, 300)}`, res.status); + } + await res.body?.cancel().catch(() => {}); +} + +// ─── Tools, both ways ─── + +export function toOllamaTools( + tools: { name: string; description: string; inputSchema: Record<string, unknown> }[], + descriptionChars = 600, +): OllamaTool[] { + return tools.map((t) => ({ + type: "function", + function: { name: t.name, description: t.description.slice(0, descriptionChars), parameters: t.inputSchema }, + })); +} + +export function toolCallsOf(message: OllamaMessage): { name: string; input: Record<string, unknown> }[] { + return (message.tool_calls ?? []).map((c) => ({ name: c.function.name, input: c.function.arguments })); +} diff --git a/common/lib/llm/prices.ts b/common/lib/llm/prices.ts @@ -0,0 +1,40 @@ +// What a Claude model costs, for the USD meter (release 27). An ESTIMATE: the +// Console's usage page is the truth. +// +// USD per million tokens: input, output, and the cache-read multiplier of the +// input price, from the prompt-caching page's table (2026-10-12). Cache writes +// bill 1.25x input (5-minute TTL) or 2x (1-hour). The longest matching prefix +// wins; an unknown Claude model is priced as Opus 5 (the dearer guess), and a +// model that is not Claude (a local one on ollama) costs nothing. + +export type Price = { input: number; output: number; cacheReadMult: number }; + +export type CacheTtl = "5m" | "1h"; + +// The cache-WRITE multiplier of the input price, per TTL. +export const CACHE_WRITE_MULT: Record<CacheTtl, number> = { "5m": 1.25, "1h": 2 }; + +export const PRICES: Readonly<Record<string, Price>> = { + "claude-fable-5-1": { input: 10, output: 50, cacheReadMult: 0.025 }, + "claude-mythos-5-1": { input: 10, output: 50, cacheReadMult: 0.025 }, + "claude-fable-5": { input: 10, output: 50, cacheReadMult: 0.1 }, + "claude-mythos-5": { input: 10, output: 50, cacheReadMult: 0.1 }, + "claude-opus-5-5": { input: 4, output: 20, cacheReadMult: 0.05 }, + "claude-opus-5": { input: 5, output: 25, cacheReadMult: 0.1 }, + "claude-opus-4": { input: 5, output: 25, cacheReadMult: 0.1 }, + "claude-sonnet-5-5": { input: 2, output: 10, cacheReadMult: 0.05 }, + "claude-sonnet-5": { input: 2, output: 10, cacheReadMult: 0.1 }, + "claude-sonnet-4": { input: 3, output: 15, cacheReadMult: 0.1 }, + // Up to 100k input tokens a request; more bills 5x (not modelled here). + "claude-haiku-5-5": { input: 0.1, output: 0.5, cacheReadMult: 0.1 }, + "claude-haiku-4-5": { input: 1, output: 5, cacheReadMult: 0.1 }, +}; + +const FREE: Price = { input: 0, output: 0, cacheReadMult: 0 }; +const BY_LENGTH = Object.keys(PRICES).sort((a, b) => b.length - a.length); + +export function priceOf(model: string): Price { + if (!model.startsWith("claude-")) return FREE; + for (const prefix of BY_LENGTH) if (model.startsWith(prefix)) return PRICES[prefix]; + return PRICES["claude-opus-5"]; +} diff --git a/common/lib/llm/structured.test.ts b/common/lib/llm/structured.test.ts @@ -0,0 +1,172 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + startFakeAnthropic, + textTurn, + thinkingBlock, + toolUseBlock, + turn, + textBlock, +} from "../../testing/llm/fakeAnthropic.mjs"; +import { faultReply, jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs"; +import { closeSchema, structuredAnswer, StructuredAnswerError } from "./structured"; +import { PromptTooLargeError } from "./ollama"; +import { Meter } from "./meter"; +import { providerOf } from "./config"; + +const schema = { + type: "object", + properties: { terms: { type: "array", items: { type: "string" } }, note: { type: "object", properties: { why: { type: "string" } } } }, + required: ["terms"], +}; + +test("providerOf: Claude → api, anything else → local", () => { + assert.equal(providerOf("claude-sonnet-5-5"), "api"); + assert.equal(providerOf("qwen3:8b"), "local"); +}); + +test("closeSchema: additionalProperties false and every property required, nested", () => { + const c = closeSchema(schema) as any; + assert.equal(c.additionalProperties, false); + assert.deepEqual(c.required, ["terms", "note"]); + assert.equal(c.properties.note.additionalProperties, false); + assert.deepEqual(c.properties.note.required, ["why"]); + assert.equal((schema as any).additionalProperties, undefined); // not mutated +}); + +test("Claude, a non-strict model: the answer tool forced", async () => { + const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["oven"] })])] }); + try { + const meter = new Meter(); + const out = await structuredAnswer<{ terms: string[] }>({ + llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, + model: "claude-haiku-4-5", + system: "Plan searches.", + user: "Ovens?", + schema, + meter, + }); + assert.deepEqual(out, { terms: ["oven"] }); + const body = api.requests[0]; + assert.deepEqual(body.tool_choice, { type: "tool", name: "answer" }); + assert.equal(body.tools[0].strict, undefined); + assert.equal("temperature" in body, false); + assert.ok(meter.usd > 0); + } finally { + await api.close(); + } +}); + +test("Claude, Sonnet 5.5: a strict tool with tool_choice auto; one re-ask, append-only after a thinking block", async () => { + const api = await startFakeAnthropic({ + turns: [ + turn([thinkingBlock("hmm"), textBlock("I think ovens.")]), + turn([toolUseBlock("answer", { terms: ["oven"], note: { why: "asked" } })]), + ], + }); + try { + const out = await structuredAnswer({ + llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, + model: "claude-sonnet-5-5", + system: "Plan searches.", + user: "Ovens?", + schema, + }); + assert.deepEqual(out, { terms: ["oven"], note: { why: "asked" } }); + const [first, second] = api.requests; + assert.deepEqual(first.tool_choice, { type: "auto" }); + assert.equal(first.tools[0].strict, true); + assert.equal(first.tools[0].input_schema.additionalProperties, false); + assert.deepEqual(first.thinking, { type: "between_tools" }); + assert.match(first.messages[0].content, /calling the `answer` tool/); + // The re-ask appends the answer as it came (the fake checks the signature). + assert.equal(second.messages.length, 3); + assert.equal(second.messages[1].content[0].type, "thinking"); + assert.match(second.messages[2].content, /Call the `answer` tool/); + } finally { + await api.close(); + } +}); + +test("Claude, Sonnet 5.5: no answer after the re-ask is an error", async () => { + const api = await startFakeAnthropic({ turns: [textTurn("no"), textTurn("still no")] }); + try { + await assert.rejects( + structuredAnswer({ + llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, + model: "claude-sonnet-5-5", + system: "s", + user: "u", + schema, + }), + StructuredAnswerError, + ); + assert.equal(api.requests.length, 2); + } finally { + await api.close(); + } +}); + +test("Claude: a model that refuses the forced tool_choice falls back to the strict way", async () => { + const api = await startFakeAnthropic({ + strictModels: ["claude-opus-5"], + turns: [turn([toolUseBlock("answer", { terms: ["tile"] })])], + }); + try { + const out = await structuredAnswer({ + llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: async () => {} } }, + model: "claude-opus-5", + system: "s", + user: "u", + schema, + }); + assert.deepEqual(out, { terms: ["tile"] }); + assert.equal(api.requests.length, 2); + assert.deepEqual(api.requests[1].tool_choice, { type: "auto" }); + } finally { + await api.close(); + } +}); + +test("ollama: format-constrained JSON; a GPU fault retried once; the meter counts tokens at $0", async () => { + const ol = await startFakeOllama({ turns: [faultReply(), jsonReply({ terms: ["oven"] })] }); + try { + const meter = new Meter(); + const out = await structuredAnswer({ + llm: { ollama: { baseUrl: ol.url } }, + model: "qwen3:8b", + system: "s", + user: "u", + schema, + meter, + }); + assert.deepEqual(out, { terms: ["oven"] }); + assert.equal(ol.requests.length, 2); + assert.deepEqual(ol.requests[1].format, schema); + assert.equal(ol.requests[1].think, false); + assert.equal(meter.usd, 0); + assert.equal(meter.summary().byModel["qwen3:8b"].calls, 1); + } finally { + await ol.close(); + } +}); + +test("ollama: an answer that is not JSON twice is an error; an oversized prompt is never sent", async () => { + const ol = await startFakeOllama({ turns: [reply("prose"), reply("more prose")] }); + try { + const llm = { ollama: { baseUrl: ol.url } }; + await assert.rejects(structuredAnswer({ llm, model: "qwen3:8b", system: "s", user: "u", schema }), /not JSON/); + await assert.rejects( + structuredAnswer({ llm, model: "qwen3:8b", system: "s", user: "w ".repeat(20_000), schema }), + PromptTooLargeError, + ); + assert.equal(ol.requests.length, 2); + } finally { + await ol.close(); + } +}); + +test("a provider without its config is a clear error", async () => { + await assert.rejects(structuredAnswer({ llm: {}, model: "qwen3:8b", system: "s", user: "u", schema }), /no ollama URL/); + await assert.rejects(structuredAnswer({ llm: {}, model: "claude-sonnet-5", system: "s", user: "u", schema }), /no API config/); +}); diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -0,0 +1,136 @@ +// One JSON answer matching a schema, on either provider (release 27; the +// stopgap's claude_api.chat_json and local_sweep.chat). +// +// Claude: a single tool `answer` carries the schema. Most models are forced to +// call it. A strict model (no forced tool_choice) gets a STRICT tool with a +// closed schema and tool_choice auto plus an instruction, and is re-asked once +// if it answers without calling it. A non-strict model whose forced call is +// refused (a 400 naming tool_choice) falls back to the strict way. +// ollama: constrained decoding through `format`, retried once on a GPU fault or +// an answer that is not JSON. A prompt over the cap is refused, never sent. + +import { extractJsonObject } from "../parseStdoutJson"; +import { + AnthropicClient, + AnthropicError, + isStrictModel, + toolUsesOf, + type ContentBlock, + type MessagesResponse, +} from "./anthropic"; +import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; +import type { Meter } from "./meter"; +import { ollamaChat, OllamaError, PromptTooLargeError } from "./ollama"; + +export const ANSWER_TOOL = "answer"; +const ASK = "Answer by calling the `answer` tool."; +const REASK = "Call the `answer` tool with your answer now."; + +export class StructuredAnswerError extends Error { + constructor(message: string) { + super(message); + this.name = "StructuredAnswerError"; + } +} + +// Strict tool use: `additionalProperties: false` on every object and every +// property required. +export function closeSchema<T>(schema: T): T { + if (Array.isArray(schema)) return schema.map((s) => closeSchema(s)) as T; + if (!schema || typeof schema !== "object") return schema; + const out: Record<string, unknown> = {}; + for (const [k, v] of Object.entries(schema as Record<string, unknown>)) out[k] = closeSchema(v); + if (out.type === "object") { + out.additionalProperties = false; + out.required = Object.keys((out.properties as Record<string, unknown>) ?? {}); + } + return out as T; +} + +type Opts = { + llm: LlmConfig; + model: string; + system: string; + user: string; + schema: object; + meter?: Meter; + signal?: AbortSignal; + maxTokens?: number; +}; + +export async function structuredAnswer<T>(o: Opts): Promise<T> { + return providerOf(o.model) === "api" ? claudeAnswer<T>(o) : localAnswer<T>(o); +} + +async function claudeAnswer<T>(o: Opts): Promise<T> { + const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); + const strict = isStrictModel(o.model); + try { + return await claudeTry<T>(client, o, strict); + } catch (err) { + if (!strict && err instanceof AnthropicError && err.status === 400 && /tool_choice/.test(err.message)) + return claudeTry<T>(client, o, true); + throw err; + } +} + +async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): Promise<T> { + const tool = { + name: ANSWER_TOOL, + description: "Give the answer.", + input_schema: strict ? closeSchema(o.schema) : o.schema, + ...(strict ? { strict: true } : {}), + }; + let messages: { role: string; content: string | ContentBlock[] }[] = [ + { role: "user", content: strict ? `${o.user}\n\n${ASK}` : o.user }, + ]; + let res: MessagesResponse | undefined; + for (let attempt = 0; attempt < (strict ? 2 : 1); attempt++) { + res = await client.messages( + { + model: o.model, + max_tokens: o.maxTokens ?? 4096, + system: o.system, + messages, + tools: [tool], + tool_choice: strict ? { type: "auto" } : { type: "tool", name: ANSWER_TOOL }, + }, + { meter: o.meter, signal: o.signal }, + ); + const call = toolUsesOf(res).find((b) => b.name === ANSWER_TOOL); + if (call && call.input && typeof call.input === "object") return call.input as T; + // Append-only: the re-ask follows the answer as it came. + messages = [...messages, { role: "assistant", content: res.content }, { role: "user", content: REASK }]; + } + throw new StructuredAnswerError(`${o.model}: no structured answer (stop_reason ${res?.stop_reason ?? "none"})`); +} + +async function localAnswer<T>(o: Opts): Promise<T> { + const cfg = ollamaConfigOf(o.llm, o.model); + let last = ""; + for (let attempt = 0; attempt < 2; attempt++) { + let reply: Awaited<ReturnType<typeof ollamaChat>>; + try { + reply = await ollamaChat(cfg, { + model: o.model, + messages: [ + { role: "system", content: o.system }, + { role: "user", content: o.user }, + ], + format: o.schema, + signal: o.signal, + }); + } catch (err) { + if (err instanceof PromptTooLargeError || o.signal?.aborted) throw err; + if (!(err instanceof OllamaError) || (err.status !== undefined && err.status < 500)) throw err; + last = err.message; + continue; + } + o.meter?.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); + const content = reply.message.content ?? ""; + const value = content.trim() ? extractJsonObject(content) : null; + if (value !== null && typeof value === "object") return value as T; + last = content.trim() ? "the answer is not JSON" : "an empty answer"; + } + throw new StructuredAnswerError(`${o.model}: no structured answer (${last})`); +} diff --git a/plans/release-27.md b/plans/release-27.md @@ -258,6 +258,54 @@ Gates: common tsc clean; common tests 3827/3827 (9 new, `testing/fakes.test.ts`) Found: as committed, the `paragraphs` fixture manifest shows two of the owed bugs (no title `foot`; Coverage a bare chapter card). S7 fixes them and regenerates it. +### S1, as shipped (2026-10-13, lane A, `r27/llm`) + +`common/lib/llm/`: the providers and the agent loop, with no settings read (everything comes in as options; S6 builds +them from `settings.generation`). Raw `fetch`, no SDK; `fetch` and `sleep` are injectable. + +| Commit | What | +| --- | --- | +| `e664e9cc` | `prices.ts` (longest prefix; unknown Claude = Opus 5, local = free), `meter.ts` (`Meter`; writes 1.25x/2x by the API's split, else the run's TTL), `anthropic.ts` (`AnthropicClient`, `readApiKey`, `redact`; caching; the strict models' rules; retries), `ollama.ts` (`ollamaChat`, `unloadOllama`, `estimateTokens`, tools both ways), `config.ts` (`LlmConfig`, `providerOf`), `structured.ts` (`structuredAnswer`); tests | +| `1beab231` | `agent.ts` (`runAgent`, `AgentTool`, `AgentEvent`, `TranscriptEntry`), `index.ts`; the agent tests and the key-leak test; the client's config made a `#private` field | +| `8d1f2ed4` | `envVars.ts` declares `ANTHROPIC_API_KEY`; ENVIRONMENT.md regenerated | +| `65a81a88` | the key-leak test's second key is not key-shaped | + +Rulings in the code: +- **The key** is read from env `ANTHROPIC_API_KEY`, else `apiKeyFile` (`~` expanded; refused when group or others have any bit; `export` and quotes tolerated). + - It is sent only in `x-api-key`. + - Every message the client throws passes `redact` (the key and any 16-character run of it). + - The config and the key are `#private`, so neither `inspect()` nor `JSON.stringify` shows them. + - `env` is an option (tests pass `{}`). +- **Strict models** are `claude-sonnet-5-5`, `claude-opus-5-5` and `claude-fable-5-1` / `claude-mythos-5-1`: + - no `temperature`; + - a forced `tool_choice` is refused before sending; + - append-only history (no prune). + - Only Sonnet 5.5 is sent `thinking: {type: "between_tools"}`; the others keep their default, and a `disabled` is dropped. +- **Caching:** the top-level `cache_control` plus a system breakpoint, at the client's one TTL. +- **Retries:** 408/429/5xx/529, `retry-after` (capped at 2 min) else 5 s × 2ⁿ (≤ 60 s), 5 by default. A 400 is not retried, except once without `temperature` when the model names it. +- **`structuredAnswer`:** + - A non-strict Claude model is forced to the `answer` tool. A 400 naming `tool_choice` falls back to the strict way. + - A strict model gets `strict: true`, a closed schema, `tool_choice: auto` and one re-ask. + - ollama uses `format`, retried once on a fault or a non-JSON answer. A prompt over the cap is never sent or retried. +- **ollama:** the estimate is 3.5 chars a token over messages + tools + format (safer than the fake's 4). The cap is ≤ 8000 and `num_ctx` ≤ 12288, both clamped. `think: false` is sent only to thinking models (qwen3, qwq, deepseek-r1, gpt-oss, magistral, cogito) unless asked. +- **`runAgent`:** + - Claude's server web search is `web_search_20250305` (the stopgap's, proven live). A 400 naming `web_search` drops it, and the caller's own `web_search` tool, hidden while the server one is on, comes back. + - Tool results are cut at 60 000 chars for Claude and 2 500 local. + - A non-strict conversation is pruned past 90k context tokens (keeping 3), never once a thinking block exists. + - The wrap-up is one text block after the tool results at `wrapUpAt` (0.85) of `maxUsd ?? meter.maxUsd`. + - The budget is checked before each request and after tools. The local loop runs its tools one at a time. +- **The transcript:** + - Request entries carry only the messages added since the previous request, with `system`/`tools` on turn 0 and when they change. + - Response entries carry the content, usage and USD. + - Tool entries carry the input, the result clipped to 4 000 chars, the full length, the error flag and the ms. + - Every string is clipped. +- `digestApps.ts`'s `ollamaDirect` is unchanged (not required; its error and option semantics differ). + +Gates: tsc clean (all packages); common 3878/3878 (51 new in `lib/llm/`); mcp 306/306; `docs env --check` clean. +No builds (no app code). + +Found and fixed: `inspect(client)` showed the config's `env`, key included (the key-leak test caught it). + ## Rollout - Fast-forward `main`.