// 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 { lazyKeyRedactor, recordModelCall } from "./callLog-server"; 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; run(input: any, ctx: { signal?: AbortSignal }): Promise; }; 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; 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 = {}; 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; // A turn's new messages as the model log keeps them: the text sent, each tool // result under the call it answers; an image or a server block by its kind. export function messagesText(msgs: readonly { role: string; content?: unknown; tool_name?: unknown }[]): string { const out: string[] = []; for (const m of msgs) { const c = m.content; if (typeof c === "string") { if (c.trim()) out.push(m.role === "tool" ? `[tool result: ${String(m.tool_name ?? "")}]\n${c}` : m.role === "user" ? c : `[${m.role}]\n${c}`); continue; } if (!Array.isArray(c)) continue; for (const b of c as ContentBlock[]) { if (b.type === "text" && typeof b.text === "string") out.push(b.text); else if (b.type === "tool_result") { const inner = typeof b.content === "string" ? b.content : Array.isArray(b.content) ? (b.content as ContentBlock[]).map((x) => (typeof x.text === "string" ? x.text : `[${x.type}]`)).join("\n") : ""; out.push(`[tool result]\n${inner}`); } else out.push(`[${b.type}]`); } } return out.join("\n\n"); } // A turn's answer as the model log keeps it: its text, then each tool call. function answerOf(text: string, calls: { name: string; input: unknown }[]): string { return [text, ...calls.map((c) => `→ ${c.name} ${JSON.stringify(c.input ?? {})}`)].filter((x) => x && x.trim()).join("\n"); } 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, 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 { 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 { 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 = { 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, messagesTotal: messages.length, }); lastTools = toolsJson; const fresh = messagesText(messages.slice(recorded)); recorded = messages.length; let res; const before = o.meter.usd; const t0 = Date.now(); const turnRecord = (answer: string, extra: { tokensIn?: number; tokensOut?: number; error?: string }) => recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "api", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra, redact: (s) => client.redactText(s) }); try { res = await client.messages(body, { meter: o.meter, signal: o.signal }); } catch (err) { turnRecord("", { error: (err as Error)?.message ?? String(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; turnRecord(answerOf(text, calls), { tokensIn: lastInput, tokensOut: Number(u.output_tokens) || 0 }); 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 { 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])); // One redactor for the run's turns, its key read only if a turn is recorded. const localRedact = lazyKeyRedactor(o.llm.anthropic); 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, messagesTotal: messages.length, }); let reply; const before = o.meter.usd; const fresh = messagesText(messages.slice(turn === 0 ? 1 : recorded)); const t0 = Date.now(); const turnRecord = (answer: string, extra: { tokensIn?: number; tokensOut?: number; error?: string }) => recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "local", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra, redact: localRedact }); try { reply = await ollamaChat(cfg, { model: o.model, messages, tools, signal: o.signal }); } catch (err) { turnRecord("", { error: (err as Error)?.message ?? String(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; turnRecord(answerOf(msg.content ?? "", calls), { tokensIn: reply.promptTokens, tokensOut: reply.evalTokens }); 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"); }