// ModelClient backed by the Anthropic API (TypeScript SDK, beta Messages endpoint). // // Why the beta endpoint: refusal fallbacks (lab 01), server-side compaction and context editing // (lab 07) are beta features. Using one endpoint from the start keeps one set of message types // for the whole lab. import Anthropic from '@anthropic-ai/sdk'; import type { AnthropicBeta } from '@anthropic-ai/sdk/resources/beta/beta'; import type { BetaContextManagementConfig, BetaMessage, MessageCreateParamsNonStreaming, } from '@anthropic-ai/sdk/resources/beta/messages/messages'; import type { StewardConfig } from '../config/config.ts'; import { attachPartialMessage } from './model.ts'; import type { ModelCallOptions, ModelClient, ModelRequest } from './model.ts'; /** How many times to re-send a request whose stream broke before it finished. */ const STREAM_RETRIES = 2; export interface AnthropicModelOptions { model: string; effort: StewardConfig['model']['effort']; maxTokens: number; refusalFallbacks: boolean; /** Server-side context management (lab 07). Omit to send none. */ context?: StewardConfig['context']; /** Token budget the model paces a whole task against (sub-agents, lab 10). */ taskBudgetTokens?: number; /** Injected for tests or custom setups; defaults to `new Anthropic()`. */ client?: Anthropic; } type RequestParams = Omit; /** * Builds the request body. A pure function, so tests can check exactly what would be sent. */ export function buildRequestParams( request: ModelRequest, options: AnthropicModelOptions, ): RequestParams { const betas: AnthropicBeta[] = []; const params: RequestParams = { model: options.model, max_tokens: options.maxTokens, system: request.system, messages: request.messages, // Our own tools stream their input as it is generated. The server then skips input // validation, so the turn loop validates every input with Zod before running a tool. // Anthropic-defined tools (type set, for example the memory tool) are sent as they are. tools: request.tools.map((tool) => 'input_schema' in tool ? { ...tool, eager_input_streaming: true } : tool, ), // Thinking is adaptive by default on current models; effort sets how hard it works. output_config: { effort: options.effort, ...(options.taskBudgetTokens ? { task_budget: { type: 'tokens' as const, total: options.taskBudgetTokens } } : {}), }, // Cache the longest stable prefix automatically (lab 03 explains what breaks it). cache_control: { type: 'ephemeral' }, }; if (options.refusalFallbacks) { // If the model declines, the API re-runs the request on a fallback model in the same call. params.fallbacks = 'default'; betas.push('server-side-fallback-2026-07-01'); } if (options.taskBudgetTokens) betas.push('task-budgets-2026-03-13'); const edits: NonNullable = []; if (options.context?.clearToolResults.enabled) { // Context editing: drop old tool results from what the model sees (lab 07). // The memory tool is excluded: its results are small and worth keeping. edits.push({ type: 'clear_tool_uses_20250919', trigger: { type: 'input_tokens', value: options.context.clearToolResults.triggerTokens }, keep: { type: 'tool_uses', value: options.context.clearToolResults.keepRecent }, exclude_tools: ['memory'], }); betas.push('context-management-2025-06-27'); } if (options.context?.compaction.enabled) { // Server-side compaction: summarize earlier turns when the request gets large (lab 07). const { triggerTokens, instructions } = options.context.compaction; edits.push({ type: 'compact_20260112', trigger: { type: 'input_tokens', value: triggerTokens }, ...(instructions ? { instructions } : {}), }); betas.push('compact-2026-01-12'); } if (edits.length > 0) params.context_management = { edits }; if (betas.length > 0) params.betas = betas; return params; } export class AnthropicModel implements ModelClient { readonly model: string; private readonly client: Anthropic; private readonly options: AnthropicModelOptions; constructor(options: AnthropicModelOptions) { this.options = options; this.model = options.model; // No key argument: the SDK finds ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or an // `ant auth login` profile on its own. this.client = options.client ?? new Anthropic(); } static fromConfig(config: StewardConfig, which: 'main' | 'subagent' = 'main'): AnthropicModel { const main = which === 'main'; return new AnthropicModel({ model: config.model[which], effort: main ? config.model.effort : 'low', maxTokens: config.model.maxTokens, // Server-side fallbacks are set up for the main model (see lab 01); sub-agents skip them. refusalFallbacks: main && config.model.refusalFallbacks, ...(main ? { context: config.context } : { taskBudgetTokens: config.subagents.taskBudgetTokens }), }); } async complete(request: ModelRequest, options: ModelCallOptions = {}): Promise { const params = buildRequestParams(request, this.options); let attempt = 0; for (;;) { const stream = this.client.beta.messages.stream(params, { signal: options.signal }); if (options.onText) stream.on('text', options.onText); try { return await stream.finalMessage(); } catch (err) { // API errors (bad request, auth, rate limit) carry a status and are not retried here: // the SDK already retried the retryable ones. A broken stream or an unparseable streamed // tool input is not an APIError; re-send the same request a couple of times. (Text that // already streamed is shown again in that case.) // Cancelled: the usage reported so far is still billed, so pass it on with the error. if (options.signal?.aborted) throw attachPartialMessage(err, stream.currentMessage); if (err instanceof Anthropic.APIError) throw err; if (attempt++ >= STREAM_RETRIES) throw err; } } } }