// A fake Anthropic Messages API for the generation tests (release 27). No test // ever calls the real API; the live smoke is the only place a real key is used. // // const api = await startFakeAnthropic({ turns: [textTurn("hi")] }); // … point the client at api.url (the base, like ANTHROPIC_BASE_URL) with api.key … // api.requests every request body, in order (headers in api.requestHeaders) // api.push(…) more scripted turns // await api.close() // // What it enforces, because the real API does (each is a 400 invalid_request_error): // - a STRICT model (Sonnet 5.5 by default) refuses a non-default `temperature`, // a forced `tool_choice` ({type:"tool"} or {type:"any"}) and `thinking: {type:"disabled"}`; // - a thinking block is signed over the conversation before it: an assistant // turn carrying thinking whose history was edited (or whose block was) is refused, // so a client must keep history append-only once a thinking block appears; // - `max_tokens` is required, and `model`, and a non-empty `messages`. // - an image block (release 30) is base64 of a JPEG/PNG/GIF/WebP whose bytes // match its media type, in a user turn; its usage is (w·h)/750 tokens. // A missing or wrong `x-api-key` is a 401 authentication_error. // // A scripted turn is a response (helpers below), an error (`errorTurn`), or a // function (body, ctx) → either, for a turn that depends on the request. When // the script runs out, the server answers 500 "fake: script exhausted" so the // test fails where it should. // // Usage: a turn's `usage` is used as given; otherwise it is estimated (4 chars a // token). A request carrying `cache_control` (top level or on a block) caches its // prefix: the first time a prefix is seen it is a cache write, after that a read. import http from "node:http"; import { createHash } from "node:crypto"; export const FAKE_KEY = "fake-anthropic-0000-TESTKEY-never-a-real-key"; export const DEFAULT_STRICT_MODELS = ["claude-sonnet-5-5"]; const tok = (v) => Math.max(1, Math.ceil(JSON.stringify(v ?? "").length / 4)); let idSeq = 0; const nextId = (p) => `${p}_fake${String(++idSeq).padStart(6, "0")}`; // ─── Turn builders ─── export const textBlock = (text) => ({ type: "text", text }); export const toolUseBlock = (name, input, id = nextId("toolu")) => ({ type: "tool_use", id, name, input }); // A thinking block; the server signs it over the request it answers. export const thinkingBlock = (thinking) => ({ type: "thinking", thinking }); // The server-side web search (`web_search_20250305`-style): a server_tool_use // block and its result block, both in the assistant's content. export function webSearchBlocks(query, results) { const id = nextId("srvtoolu"); return [ { type: "server_tool_use", id, name: "web_search", input: { query } }, { type: "web_search_tool_result", tool_use_id: id, content: results.map((r) => ({ type: "web_search_result", url: r.url, title: r.title, encrypted_content: Buffer.from(r.text ?? r.title).toString("base64"), page_age: r.page_age ?? null, })), }, ]; } // A whole response. `stop_reason` defaults from the content: tool_use when it // asks for a client tool, else end_turn. export function turn(content, opts = {}) { const blocks = Array.isArray(content) ? content : [content]; return { content: blocks, stop_reason: opts.stop_reason ?? (blocks.some((b) => b.type === "tool_use") ? "tool_use" : "end_turn"), ...(opts.usage ? { usage: opts.usage } : {}), }; } export const textTurn = (text, opts) => turn([textBlock(text)], opts); export const toolTurn = (name, input, opts) => turn([toolUseBlock(name, input)], opts); // A long server-tool turn the API pauses: the client sends the conversation back // as is (the paused assistant content appended) and the API continues it. export const pauseTurn = (content) => turn(content, { stop_reason: "pause_turn" }); export const errorTurn = (status, type, message, headers = {}) => ({ __error: { status, type, message, headers } }); // ─── The rules the real API enforces ─── export function strictModelProblem(body, strictModels = DEFAULT_STRICT_MODELS) { const model = String(body.model ?? ""); if (!strictModels.some((m) => model.startsWith(m))) return null; if (body.temperature !== undefined && body.temperature !== 1) return `temperature: ${model} does not support a non-default temperature`; const tc = body.tool_choice; if (tc && (tc.type === "tool" || tc.type === "any")) return `tool_choice: ${model} does not support forced tool use; use a strict tool with tool_choice auto`; if (body.thinking && body.thinking.type === "disabled") return `thinking: ${model} does not support thinking.type "disabled"; use "between_tools"`; return null; } const sign = (history, thinking) => createHash("sha256").update(JSON.stringify(history)).update("\u0000").update(thinking).digest("base64url"); // Every assistant turn's thinking blocks must carry the signature they were // issued with over the messages before them, unedited. export function signatureProblem(body) { const msgs = Array.isArray(body.messages) ? body.messages : []; for (let i = 0; i < msgs.length; i++) { const m = msgs[i]; if (m.role !== "assistant" || !Array.isArray(m.content)) continue; for (const b of m.content) { if (b.type !== "thinking") continue; if (!b.signature || b.signature !== sign(msgs.slice(0, i), b.thinking ?? "")) return `messages.${i}.content: thinking block signature is invalid (the history before it was edited)`; } } return null; } // ─── Images (release 30, the frame scan) ─── // A base64 image's size from its bytes (JPEG SOF, PNG IHDR), or null. export function imageSize(buf) { if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504e47) return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }; if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null; let i = 2; while (i + 9 < buf.length) { if (buf[i] !== 0xff) return null; const m = buf[i + 1]; const len = buf.readUInt16BE(i + 2); if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) }; i += 2 + len; } return null; } // What an image costs in input tokens: (w·h)/750 after the API's downscale // (long edge ≤ 1568, ≤ ~1.15 MP). export function imageTokens(width, height) { let s = 1; if (Math.max(width, height) > 1568) s = 1568 / Math.max(width, height); if (width * height * s * s > 1_150_000) s = Math.sqrt(1_150_000 / (width * height)); return Math.ceil((width * s * height * s) / 750); } const IMAGE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"]; // Every image block of a request's messages, decoded: {mediaType, bytes, width, height}. export function imagesOf(body) { const out = []; for (const m of Array.isArray(body?.messages) ? body.messages : []) { if (!Array.isArray(m.content)) continue; for (const b of m.content) { if (b?.type !== "image") continue; const bytes = Buffer.from(String(b.source?.data ?? ""), "base64"); out.push({ mediaType: b.source?.media_type, bytes, ...(imageSize(bytes) ?? { width: 0, height: 0 }) }); } } return out; } // An image block the real API refuses: not base64, an unknown media type, no // data, bytes that are not the image type named, or an image in an assistant turn. export function imageProblem(body) { const msgs = Array.isArray(body.messages) ? body.messages : []; for (let i = 0; i < msgs.length; i++) { const m = msgs[i]; if (!Array.isArray(m.content)) continue; for (let j = 0; j < m.content.length; j++) { const b = m.content[j]; if (b?.type !== "image") continue; const at = `messages.${i}.content.${j}`; if (m.role !== "user") return `${at}: an image is only allowed in a user turn`; const src = b.source ?? {}; if (src.type !== "base64") return `${at}.source.type: the fake takes base64 images only`; if (!IMAGE_TYPES.includes(src.media_type)) return `${at}.source.media_type: ${src.media_type} is not an image type`; if (typeof src.data !== "string" || !src.data || /[^A-Za-z0-9+/=]/.test(src.data)) return `${at}.source.data: not base64`; const bytes = Buffer.from(src.data, "base64"); const size = imageSize(bytes); const isPng = bytes.length > 4 && bytes.readUInt32BE(0) === 0x89504e47; const isJpeg = bytes.length > 2 && bytes[0] === 0xff && bytes[1] === 0xd8; if ((src.media_type === "image/jpeg" && !isJpeg) || (src.media_type === "image/png" && !isPng) || !size) return `${at}: the image bytes are not a ${src.media_type}`; } } return null; } // A request's messages with every image's data replaced by its token cost, for the usage estimate. function withoutImageData(messages) { let tokens = 0; const stripped = (messages ?? []).map((m) => Array.isArray(m.content) ? { ...m, content: m.content.map((b) => { if (b?.type !== "image") return b; const size = imageSize(Buffer.from(String(b.source?.data ?? ""), "base64")); tokens += size ? imageTokens(size.width, size.height) : 1600; return { type: "image" }; }), } : m, ); return { stripped, tokens }; } function requestProblem(body) { if (!body || typeof body !== "object") return "body: not JSON"; if (!body.model) return "model: required"; if (typeof body.max_tokens !== "number") return "max_tokens: required"; if (!Array.isArray(body.messages) || body.messages.length === 0) return "messages: required"; return null; } const hasCacheControl = (body) => !!body.cache_control || JSON.stringify([body.system, body.tools, body.messages]).includes('"cache_control"'); // ─── The server ─── export async function startFakeAnthropic(opts = {}) { const key = opts.key ?? FAKE_KEY; const strictModels = opts.strictModels ?? DEFAULT_STRICT_MODELS; const script = [...(opts.turns ?? [])]; const requests = []; const requestHeaders = []; const seenPrefixes = new Set(); const send = (res, status, payload, headers = {}) => { res.writeHead(status, { "content-type": "application/json", ...headers }); res.end(JSON.stringify(payload)); }; const apiError = (res, status, type, message, headers) => send(res, status, { type: "error", error: { type, message } }, headers); const server = http.createServer((req, res) => { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", async () => { if (req.method !== "POST" || req.url !== "/v1/messages") return apiError(res, 404, "not_found_error", `fake: no route ${req.method} ${req.url}`); let body; try { body = JSON.parse(raw); } catch { return apiError(res, 400, "invalid_request_error", "body: not JSON"); } requests.push(body); requestHeaders.push({ ...req.headers }); if (req.headers["x-api-key"] !== key) return apiError(res, 401, "authentication_error", "invalid x-api-key"); if (!req.headers["anthropic-version"]) return apiError(res, 400, "invalid_request_error", "anthropic-version: header required"); const problem = requestProblem(body) ?? strictModelProblem(body, strictModels) ?? signatureProblem(body) ?? imageProblem(body); if (problem) return apiError(res, 400, "invalid_request_error", problem); let next = script.shift(); if (next === undefined) return apiError(res, 500, "api_error", "fake: script exhausted"); if (typeof next === "function") next = await next(body, { requests }); if (next.__error) { const e = next.__error; return apiError(res, e.status, e.type, e.message, e.headers); } // Sign each thinking block over the conversation it answers. const content = next.content.map((b) => b.type === "thinking" ? { ...b, signature: sign(body.messages, b.thinking ?? "") } : b, ); let usage = next.usage; if (!usage) { // A cached request reads the longest conversation cached before it // (same system and tools, its messages a prefix of these) and writes the // rest up to its last message. const head = JSON.stringify([body.system ?? null, body.tools ?? null]); // An image counts at its token cost, not its base64. const { stripped, tokens: imgTokens } = withoutImageData(body.messages); const total = tok([body.system ?? null, body.tools ?? null, stripped]) + imgTokens; const last = tok(stripped[stripped.length - 1]) + withoutImageData(body.messages.slice(-1)).tokens; const cached = hasCacheControl(body); let read = 0; if (cached) { for (let k = body.messages.length; k >= 1 && !read; k--) if (seenPrefixes.has(head + JSON.stringify(body.messages.slice(0, k)))) read = tok([body.system ?? null, body.tools ?? null, body.messages.slice(0, k)]); seenPrefixes.add(head + JSON.stringify(body.messages)); } usage = { input_tokens: cached ? last : total, cache_creation_input_tokens: cached ? Math.max(0, total - read - last) : 0, cache_read_input_tokens: read, output_tokens: tok(content), }; } send(res, 200, { id: nextId("msg"), type: "message", role: "assistant", model: body.model, content, stop_reason: next.stop_reason, stop_sequence: null, usage, }); }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const { port } = server.address(); return { url: `http://127.0.0.1:${port}`, key, requests, requestHeaders, push: (...turns) => script.push(...turns), remaining: () => script.length, close: () => new Promise((r) => server.close(() => r())), }; }