// Claude as the in-page agent's model: the Messages API, called from the browser with Anthropic's SDK on the // person's own API key (from console.anthropic.com; a Claude plan covers Claude Code, not API calls, and // Claude Code drives this page through the MCP bridge instead). The conversation only ever grows: Claude's // thinking blocks go back as they came, so earlier turns are never edited. // agent.js loads this file (and the SDK with it) only when Claude is chosen. import Anthropic from "@anthropic-ai/sdk"; /** What is wrong with a value for a JSON schema (the subset specs.js uses), or null. */ function problem(schema, value) { if (!schema) return null; if (schema.enum && !schema.enum.includes(value)) return `one of ${schema.enum.join(", ")}`; switch (schema.type) { case "string": return typeof value === "string" ? null : "a string"; case "number": case "integer": return typeof value === "number" && Number.isFinite(value) ? null : "a number"; case "boolean": return typeof value === "boolean" ? null : "true or false"; case "array": { if (!Array.isArray(value)) return "a list"; for (const item of value) { const p = problem(schema.items, item); if (p) return `a list of items each ${p}`; } return null; } case "object": { if (!value || typeof value !== "object" || Array.isArray(value)) return "an object"; for (const k of schema.required ?? []) if (value[k] === undefined) return `missing ${k}`; for (const [k, v] of Object.entries(value)) { const p = problem(schema.properties?.[k], v); if (p) return `${k} should be ${p}`; } return null; } default: return null; } } /** The tool input's problem against its spec's parameters, or null (tool inputs stream unchecked). */ export const inputProblem = (spec, input) => problem(spec?.parameters ?? { type: "object" }, input); /** A data URL as an image block. */ function imageBlock(url) { const [, mediaType = "image/jpeg", data = ""] = /^data:([^;,]+)?(?:;base64)?,(.*)$/s.exec(url) ?? []; return { type: "image", source: { type: "base64", media_type: mediaType, data } }; } /** An API error as something to tell the person. */ function explain(error) { if (error instanceof Anthropic.AuthenticationError) return "The Anthropic API key was rejected (401): check it under “Model and endpoint”."; if (error instanceof Anthropic.PermissionDeniedError) return `The Anthropic API key may not use this (403): ${error.message}`; if (error instanceof Anthropic.RateLimitError) return "Rate-limited by the Anthropic API (429): wait a little and try again."; if (error instanceof Anthropic.APIConnectionError) return `Could not reach api.anthropic.com: ${error.message}`; if (error instanceof Anthropic.APIError) return `Anthropic API ${error.status ?? ""}: ${error.message}`.trim(); return error.message; } /** * One user turn with Claude: its tool calls run through `call(name, args)`, their results (and pictures) go * back, until it answers without a tool or `maxSteps` requests are used. `history` holds the Messages API * conversation and grows in place. `on` gets the agent's events (agent.js). */ export async function claudeTurn({ apiKey, model, effort, system, specs, history, text, call, on, signal, maxSteps }) { const client = new Anthropic({ apiKey, dangerouslyAllowBrowser: true }); const bySpec = new Map(specs.map((s) => [s.name, s])); const tools = specs.map((s) => ({ name: s.name, description: s.description, input_schema: s.parameters, eager_input_streaming: true })); history.push({ role: "user", content: text }); let unparsed = 0; // tool input that was not JSON at all, in a row for (let step = 0; step < maxSteps; ) { let message; try { const stream = client.messages.stream( { model, max_tokens: 16000, system, tools, messages: history, cache_control: { type: "ephemeral" }, // the conversation so far, for the next step's request ...(effort ? { output_config: { effort } } : {}), }, { signal }, ); message = await stream.finalMessage(); unparsed = 0; step++; } catch (error) { if (signal.aborted) throw new DOMException("stopped", "AbortError"); if (error instanceof Anthropic.APIError || ++unparsed > 2) throw new Error(explain(error)); continue; // the SDK could not parse a tool input: the same request again } history.push({ role: "assistant", content: message.content }); for (const block of message.content) if (block.type === "text" && block.text.trim()) on({ type: "assistant", text: block.text.trim() }); const uses = message.content.filter((b) => b.type === "tool_use"); if (!uses.length) { if (message.stop_reason === "refusal") on({ type: "error", message: "Claude declined to go on with this (refusal)." }); return; } // Every tool_use gets its tool_result, run or not, so that the conversation stays valid. const cut = message.stop_reason === "max_tokens" ? "its input was cut off (max_tokens)" : message.stop_reason === "refusal" ? "the turn ended in a refusal" : null; const results = []; for (const use of uses) { const bad = cut ?? (signal.aborted ? "stopped by the user" : inputProblem(bySpec.get(use.name), use.input)); if (bad) { results.push({ type: "tool_result", tool_use_id: use.id, is_error: true, content: JSON.stringify(cut || signal.aborted ? { not_run: bad } : { INVALID_JSON: JSON.stringify(use.input), problem: bad }) }); if (!signal.aborted) { on({ type: "tool", name: use.name, args: use.input }); on({ type: "result", name: use.name, result: { ok: false, message: `not run: ${bad}` } }); } continue; } on({ type: "tool", name: use.name, args: use.input }); const result = await call(use.name, use.input); const { image, ...rest } = result ?? {}; if (image) on({ type: "image", url: image }); on({ type: "result", name: use.name, result: rest }); results.push({ type: "tool_result", tool_use_id: use.id, content: [{ type: "text", text: JSON.stringify(rest) }, ...(image ? [imageBlock(image)] : [])], ...(rest.ok === false ? { is_error: true } : {}), }); } history.push({ role: "user", content: results }); if (signal.aborted) throw new DOMException("stopped", "AbortError"); if (cut) return on({ type: "error", message: `Claude's tool call was not run: ${cut}.` }); } on({ type: "assistant", text: `(stopped after ${maxSteps} steps)` }); }