Archilyzer · Source

archilyzer

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

commit 4b3eb3aaf91efdf8a57b91522e5e21ae76f3c7e5
parent 43b21d3c37d16d6c8b9a5063aac06f12e48acf1a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 10:38:42 -0400

common: release 27 S1 — the agent loop on either provider, and the key-leak test

runAgent: Claude with the caller's tools plus the API's web search
(max_uses; a refusal falls back to the caller's web_search), pause_turn
re-sent with no user turn, old tool results pruned on non-strict models
only while no thinking block exists, append-only otherwise; ollama with
the prompt fitted under the cap by dropping the oldest tool results first.
One wrap-up message at wrapUpAt of the cap, a budget stop at the cap,
max_turns, and an abort signal that cancels the in-flight request. The
transcript is request deltas, responses, tool calls and clipped results,
with usage per turn. The client's config is now a private field: inspect()
showed its env, key included.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/lib/llm/agent.test.ts | 406+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/agent.ts | 509+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/llm/anthropic.ts | 14++++++++------
Acommon/lib/llm/index.ts | 12++++++++++++
Acommon/lib/llm/keyLeak.test.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 1080 insertions(+), 6 deletions(-)

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.ts b/common/lib/llm/anthropic.ts @@ -228,11 +228,13 @@ export class AnthropicClient { readonly cacheTtl: CacheTtl; readonly maxRetries: number; private readonly url: string; - private readonly cfg: AnthropicConfig; + // 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.#cfg = cfg; this.cacheTtl = cfg.cacheTtl ?? "5m"; this.maxRetries = cfg.maxRetries ?? DEFAULT_MAX_RETRIES; this.url = (cfg.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "") + "/v1/messages"; @@ -248,7 +250,7 @@ export class AnthropicClient { } private key(): string { - this.#key ??= readApiKey(this.cfg); + this.#key ??= readApiKey(this.#cfg); return this.#key; } @@ -265,8 +267,8 @@ export class AnthropicClient { ): Promise<MessagesResponse> { const key = this.key(); let sent = prepareBody(body, this.cacheTtl); - const doFetch = this.cfg.fetch ?? fetch; - const sleep = this.cfg.sleep; + 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); @@ -276,7 +278,7 @@ export class AnthropicClient { let retries = 0; for (;;) { if (o.signal?.aborted) throw new CancelledError(); - const timeout = AbortSignal.timeout(this.cfg.timeoutMs ?? 600_000); + const timeout = AbortSignal.timeout(this.#cfg.timeoutMs ?? 600_000); const signal = o.signal ? AbortSignal.any([o.signal, timeout]) : timeout; let res: Response; try { 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: "sk-ant-some-other-key-entirely", 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 }); + } +});