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(); } });