// The turn loop: one user message in, one finished answer out. // // A "turn" can take several model calls. Each call either ends the turn (the model is done, was // cut off, or declined) or asks for tools. When it asks for tools, we check each call against // the policy, run the allowed ones, and call the model again with the results. Three rules keep // the conversation valid: // // 1. Append the model's content exactly as it came back (text, thinking, tool_use, fallback, // compaction blocks). Never rebuild it from the text. Current models check that earlier // turns are unchanged, and server features store state in those blocks. // 2. Every tool_use gets exactly one tool_result, and all results for one assistant message go // back together in ONE user message. // 3. Never run tools from a response that was cut off (max_tokens) or declined (refusal): the // input may be incomplete. Answer those tool calls with error results instead, so the // history stays valid for the next turn. // // Lab 05 adds approvals: if any call in a batch needs the owner's approval, NOTHING in that batch // runs yet. The turn ends with stop "awaiting_approval". When the owner answers, the loop is // started again in "resume" mode: no new user message, just the decisions, and it carries on // from the waiting tool calls. import type { BetaContentBlock, BetaMessage, BetaMessageParam, BetaToolResultBlockParam, BetaToolUseBlock, } from '@anthropic-ai/sdk/resources/beta/messages/messages'; import { describeCall, execute, parseCall, toApiTool, type Tool, type ToolContext, } from '../tools/tool.ts'; import { mergeConsecutiveUserMessages } from './messages.ts'; import { partialMessageOf } from './model.ts'; import type { BetaTextBlockParam, ModelClient, ModelRequest } from './model.ts'; export type TurnStop = | 'end_turn' // the model finished | 'awaiting_approval' // a tool call waits for the owner (lab 05) | 'refusal' // the model (and any fallback) declined | 'max_tokens' // the answer hit the output limit | 'max_steps' // our own safety limit on model calls per turn | 'context_window' // the conversation no longer fits (lab 07 prevents this) | 'budget' // the daily spending limit was reached before the turn started (lab 12) | 'other'; /** Tokens of one billed request, and the model that served it (lab 12: pricing). */ export interface RequestUsage { model: string; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; } export interface TurnUsage { modelCalls: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; /** Size of the last request in tokens (all input, cached or not): how full the context is. */ contextTokens?: number; /** * The same tokens, one entry per billed request. Prices can differ per request: a fallback * model may answer (lab 01), compaction is its own request (lab 07), and some models charge * more for long prompts. Older session logs have no list; cost then uses the turn's model. */ requests?: RequestUsage[]; } export interface Authorization { decision: 'allow' | 'ask' | 'deny'; reason: string; } export interface PendingApproval { toolUseId: string; tool: string; summary: string; reason: string; } /** Reported once per tool call, after the decision (and after running, when it ran). */ export interface ToolReport { toolUseId: string; tool: string; summary: string; decision: Authorization['decision'] | 'approved' | 'denied-by-owner' | 'invalid'; reason: string; outcome: 'ok' | 'error' | 'not-run' | 'pending'; ms?: number; } export interface TurnInput { model: ModelClient; system: BetaTextBlockParam[]; tools: readonly Tool[]; toolContext: ToolContext; /** Conversation so far. Not modified: new messages are reported through onMessage. */ history: readonly BetaMessageParam[]; /** The new user message. Leave it out to resume after approvals. */ userMessage?: BetaMessageParam; /** The owner's answers, by tool_use id, when resuming after approvals. */ approvals?: ReadonlyMap; /** Decides whether a call may run. Without it, every valid call runs. */ authorize?: (tool: Tool, input: unknown) => Authorization; maxSteps: number; onText?: (delta: string) => void; /** Called for every message added to the conversation, in order. Lab 02 persists these. */ onMessage?: (message: BetaMessageParam) => Promise | void; /** Called when a tool starts and ends, for progress display. */ onTool?: (event: { name: string; phase: 'start' | 'end'; isError?: boolean }) => void; /** Called once per tool call with its decision and outcome (the audit log, lab 05). */ onToolReport?: (report: ToolReport) => Promise | void; /** Called after every model call with the turn's running totals, so a turn that later fails * or is cancelled still accounts for what it spent (the ledger, lab 12). */ onUsage?: (usage: Readonly) => void; signal?: AbortSignal; } export interface TurnResult { /** The visible answer: all text blocks of the final assistant message. */ text: string; stop: TurnStop; /** Messages this turn added, in order. */ added: BetaMessageParam[]; usage: TurnUsage; /** Tool calls waiting for the owner, when stop is "awaiting_approval". */ pending?: PendingApproval[]; } type BatchResult = { results: BetaToolResultBlockParam[] } | { pending: PendingApproval[] }; export async function runTurn(input: TurnInput): Promise { const conversation: BetaMessageParam[] = [...input.history]; const added: BetaMessageParam[] = []; const usage: TurnUsage = { modelCalls: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, contextTokens: 0, }; const apiTools = input.tools.map(toApiTool); const append = async (message: BetaMessageParam) => { conversation.push(message); added.push(message); await input.onMessage?.(message); }; if (input.userMessage) { await append(input.userMessage); } else { // Resume: the last message must be an assistant message whose tool calls wait for answers. const last = conversation.at(-1); const waiting = last?.role === 'assistant' && Array.isArray(last.content) ? last.content.filter((b): b is BetaToolUseBlock => b.type === 'tool_use') : []; if (waiting.length === 0) throw new Error('nothing to resume: no tool calls are waiting'); const batch = await runBatch(input, waiting); if ('pending' in batch) { return { text: '', stop: 'awaiting_approval', added, usage, pending: batch.pending }; } await append({ role: 'user', content: batch.results }); } for (let step = 0; step < input.maxSteps; step++) { const request: ModelRequest = { system: input.system, messages: mergeConsecutiveUserMessages(conversation), tools: apiTools, }; let response; try { response = await input.model.complete(request, { onText: input.onText, signal: input.signal, }); } catch (err) { // A cancelled call is still billed for what the API already processed: count it. const partial = partialMessageOf(err); if (partial) { addUsage(usage, partial, input.model.model); input.onUsage?.(usage); } throw err; } addUsage(usage, response, input.model.model); input.onUsage?.(usage); // Rule 1: store the content exactly as returned. (A declined request can come back with no // content at all; an empty assistant message is not valid, so nothing is stored then.) if (response.content.length > 0) { await append({ role: 'assistant', content: response.content }); } const toolUses = response.content.filter(isToolUse); switch (response.stop_reason) { case 'tool_use': { // Rule 2: decide every call, run the allowed ones, send all results in one message. const batch = await runBatch(input, toolUses); if ('pending' in batch) { return { text: textOf(response.content), stop: 'awaiting_approval', added, usage, pending: batch.pending, }; } await append({ role: 'user', content: batch.results }); continue; } case 'pause_turn': case 'compaction': // A server-side tool paused a long turn, or the server paused after compacting the // conversation (lab 07). Send the conversation back to let it continue. continue; case 'end_turn': case 'stop_sequence': return { text: textOf(response.content), stop: 'end_turn', added, usage }; case 'max_tokens': case 'refusal': case 'model_context_window_exceeded': { // Rule 3: do not run tools from a cut-off or declined response. if (toolUses.length > 0) { await append({ role: 'user', content: toolUses.map((call) => notRun(call, response.stop_reason ?? 'unknown')), }); } const stop: TurnStop = response.stop_reason === 'max_tokens' ? 'max_tokens' : response.stop_reason === 'refusal' ? 'refusal' : 'context_window'; return { text: textOf(response.content), stop, added, usage }; } default: // Close any open tool calls first, so the history stays valid. if (toolUses.length > 0) { await append({ role: 'user', content: toolUses.map((c) => notRun(c, 'turn ended')) }); } return { text: textOf(response.content), stop: 'other', added, usage }; } } return { text: '', stop: 'max_steps', added, usage }; } interface Planned { call: BetaToolUseBlock; parsed: ReturnType; summary: string; auth?: Authorization; byOwner: boolean; } /** * Decides every call in one assistant message, then runs them. If any call needs approval, * nothing runs and the calls that need approval are returned. */ async function runBatch(input: TurnInput, calls: BetaToolUseBlock[]): Promise { const planned: Planned[] = calls.map((call) => { const parsed = parseCall(input.tools, call.name, call.input); if (!parsed.ok) return { call, parsed, summary: call.name, byOwner: false }; const summary = describeCall(parsed.tool, parsed.input); const answer = input.approvals?.get(call.id); if (answer === 'approved') { return { call, parsed, summary, byOwner: true, auth: { decision: 'allow', reason: 'approved by the owner' }, }; } if (answer === 'denied') { return { call, parsed, summary, byOwner: true, auth: { decision: 'deny', reason: 'denied by the owner' }, }; } const auth = input.authorize?.(parsed.tool, parsed.input) ?? { decision: 'allow', reason: 'no policy', }; return { call, parsed, summary, byOwner: false, auth }; }); const pending: PendingApproval[] = planned.flatMap((p) => p.auth?.decision === 'ask' ? [{ toolUseId: p.call.id, tool: p.call.name, summary: p.summary, reason: p.auth.reason }] : [], ); if (pending.length > 0) { for (const p of pending) { await input.onToolReport?.({ ...p, decision: 'ask', outcome: 'pending' }); } return { pending }; } const results = await Promise.all(planned.map((p) => runPlanned(input, p))); return { results }; } async function runPlanned(input: TurnInput, p: Planned): Promise { const { call, parsed, summary, auth, byOwner } = p; const report = (r: Pick) => input.onToolReport?.({ toolUseId: call.id, tool: call.name, summary, ...r }); if (!parsed.ok) { await report({ decision: 'invalid', reason: parsed.outcome.content, outcome: 'not-run' }); return result(call.id, parsed.outcome.content, true); } if (auth?.decision === 'deny') { await report({ decision: byOwner ? 'denied-by-owner' : 'deny', reason: auth.reason, outcome: 'not-run', }); const why = byOwner ? 'The owner denied this call.' : `Not allowed: ${auth.reason}.`; return result(call.id, `${why} It did not run.`, true); } input.onTool?.({ name: call.name, phase: 'start' }); const started = Date.now(); const outcome = await execute(parsed.tool, parsed.input, { ...input.toolContext, ...(input.signal ? { signal: input.signal } : {}), }); input.onTool?.({ name: call.name, phase: 'end', isError: outcome.isError }); await report({ decision: byOwner ? 'approved' : 'allow', reason: auth?.reason ?? 'no policy', outcome: outcome.isError ? 'error' : 'ok', ms: Date.now() - started, }); return result(call.id, outcome.content, outcome.isError); } function result(toolUseId: string, content: string, isError: boolean): BetaToolResultBlockParam { return { type: 'tool_result', tool_use_id: toolUseId, content, ...(isError ? { is_error: true } : {}), }; } function isToolUse(block: BetaContentBlock): block is BetaToolUseBlock { return block.type === 'tool_use'; } function notRun(call: BetaToolUseBlock, reason: string): BetaToolResultBlockParam { return result( call.id, `Not run: the response ended early (${reason}), so the input may be incomplete.`, true, ); } /** Joins the text blocks of a response. Thinking and tool blocks are not shown to the owner. */ export function textOf(content: BetaContentBlock[]): string { return content .filter((block) => block.type === 'text') .map((block) => block.text) .join(''); } function addUsage(total: TurnUsage, response: BetaMessage, requestedModel: string): void { const { usage } = response; total.requests = [...(total.requests ?? []), ...requestsOf(response, requestedModel)]; const cacheRead = usage.cache_read_input_tokens ?? 0; const cacheWrite = usage.cache_creation_input_tokens ?? 0; total.modelCalls += 1; total.inputTokens += usage.input_tokens; total.outputTokens += usage.output_tokens; total.cacheReadTokens += cacheRead; total.cacheWriteTokens += cacheWrite; total.contextTokens = usage.input_tokens + cacheRead + cacheWrite; // Server-side compaction (lab 07) runs an extra summarizing step that is billed but NOT // included in the top-level counts above; it is reported only in usage.iterations. Add it, so // the cost and the daily limit (lab 12) see it. It does not change contextTokens. for (const step of usage.iterations ?? []) { if (step.type !== 'compaction') continue; total.inputTokens += step.input_tokens; total.outputTokens += step.output_tokens; total.cacheReadTokens += step.cache_read_input_tokens; total.cacheWriteTokens += step.cache_creation_input_tokens; } } /** * One entry per billed request. The API lists them in usage.iterations: the model's own steps * ("message", model null = the requested model), the step a fallback model answered * ("fallback_message"), and compaction. Without that list, the whole call is one request. */ function requestsOf(response: BetaMessage, requestedModel: string): RequestUsage[] { const { usage } = response; const entry = ( model: string | null | undefined, u: { input_tokens: number | null; output_tokens: number | null; cache_read_input_tokens: number | null; cache_creation_input_tokens: number | null; }, ): RequestUsage => ({ model: model || requestedModel, inputTokens: u.input_tokens ?? 0, outputTokens: u.output_tokens ?? 0, cacheReadTokens: u.cache_read_input_tokens ?? 0, cacheWriteTokens: u.cache_creation_input_tokens ?? 0, }); const steps = usage.iterations ?? []; if (steps.length === 0) return [entry(requestedModel, usage)]; return steps.map((step) => entry('model' in step ? step.model : null, step)); }