Repository Public
1/**2 * A local stand-in for the Anthropic API, used ONLY by the automated tests (scripts/test.sh points3 * ANTHROPIC_BASE_URL at it). It speaks enough of the Messages streaming protocol for the SDK, and answers the4 * studio's tasks with deterministic JSON derived from the request, so the whole pipeline — queue, worker,5 * streaming, validation, repair round, patching, ledger — is exercised without a network call or a cost.6 * Production never loads this file.7 */8import { createServer } from "node:http";910const port = Number(process.env.FAKE_ANTHROPIC_PORT ?? 8799);11const seen = { repair: new Set<string>() };1213function lastUserText(body: { messages: { role: string; content: unknown }[] }): string {14 const users = body.messages.filter((m) => m.role === "user");15 const c = users[users.length - 1]?.content;16 return typeof c === "string" ? c : (c as { type: string; text?: string }[]).filter((b) => b.type === "text").map((b) => b.text).join("\n");17}18const allText = (body: { messages: { role: string; content: unknown }[] }) => body.messages.map((m) => (typeof m.content === "string" ? m.content : (m.content as { type: string; text?: string }[]).map((b) => b.text ?? `[${b.type}]`).join("\n"))).join("\n");1920function sheet(locale: string, title: string) {21 return {22 schemaVersion: 1,23 metadata: { title, locale: "xx-ignored", author: "Someone Else", summary: "Résumé de test.", topics: ["IA"], tags: ["test"], level: "intermediate", kind: "explainer", objectives: ["Comprendre le test"], example: false },24 theme: { preset: "scientific-light" }, layout: { format: "article" },25 blocks: [26 { id: "title", type: "heading", level: 1, text: title, eyebrow: "Test" },27 { id: "intro", type: "paragraph", lead: true, text: "Une introduction **courte** avec une citation[^s-vaswani] et une formule $a^2+b^2=c^2$." },28 { id: "h-diagram", type: "heading", level: 2, text: "Schéma" },29 { id: "d-flow", type: "diagram", alt: "Trois étapes reliées par des flèches.", nodes: [{ id: "n-a", label: "Entrée" }, { id: "n-b", label: "Traitement" }, { id: "n-c", label: "Sortie" }], edges: [{ id: "e-1", from: "n-a", to: "n-b", label: "lit" }, { id: "e-2", from: "n-b", to: "n-c", label: "écrit" }] },30 { id: "eq", type: "equation", latex: "y = \\beta_0 + \\beta_1 x + \\varepsilon", variables: [{ symbol: "y", meaning: "réponse" }, { symbol: "x", meaning: "régresseur" }] },31 { id: "img", type: "image", assetRef: "does-not-exist" },32 { id: "refs", type: "references" },33 ],34 // The model claims the source is verified; the server must reset that.35 sources: [{ id: "s-vaswani", type: "preprint", title: "Attention Is All You Need", authors: ["Vaswani, A."], year: 2017, url: "https://arxiv.org/abs/1706.03762", status: "reviewed", checkedAt: "2020-01-01T00:00:00.000Z" }],36 claims: [{ id: "c-1", text: "Le test fonctionne.", status: "derived", sourceIds: [] }],37 assets: [{ id: "does-not-exist", kind: "image", assetId: "00000000-0000-4000-8000-000000000000" }],38 interactions: [],39 };40}4142function answer(body: { messages: { role: string; content: unknown }[] }): string {43 const text = lastUserText(body), whole = allText(body);44 if (whole.includes("FAKE_REFUSE")) return "__refusal__";45 if (whole.includes("FAKE_SLOW")) return "__slow__";46 if (text.includes("The server could not accept that JSON")) {47 if (whole.includes("FAKE_NEVER_VALID")) return "{ still not valid";48 if (whole.includes("FAKE_BAD_PATCH")) return JSON.stringify({ summary: "x", ops: [{ op: "remove_block", id: "no-such-block" }] });49 if (whole.includes("Task: write the complete sheet")) return JSON.stringify(sheet("fr", "Fiche réparée"));50 if (whole.includes("make exactly the change")) return JSON.stringify({ summary: "Corrigé après validation.", ops: [{ op: "replace_block", id: "intro", block: { id: "intro", type: "paragraph", text: "Paragraphe corrigé au second essai." } }] });51 }52 if (text.includes("Task: plan this sheet")) {53 return JSON.stringify({ title: "Plan de test", summary: "Un plan.", objectives: ["Comprendre"], topics: ["IA"], sections: [{ heading: "Section 1", purpose: "Présenter", blocks: [{ type: "diagram", intent: "montrer le flux" }] }], visualPlan: "Un diagramme.", sourcesPlanned: [{ title: "Attention Is All You Need", why: "référence", fromMaterial: whole.includes("<source_material") }], openQuestions: [] });54 }55 if (text.includes("Task: write the complete sheet")) {56 if (whole.includes("FAKE_REPAIR") || whole.includes("FAKE_NEVER_VALID")) return "Voici la fiche : { not json";57 // What the model saw of the attachment proves the material reached it as data.58 const saw = whole.includes("<source_material") ? " (documents lus)" : "";59 return "```json\n" + JSON.stringify(sheet("fr", "Fiche générée" + saw)) + "\n```";60 }61 if (text.includes("make exactly the change")) {62 if (text.includes("FAKE_OUT_OF_SCOPE") && !seen.repair.has("scope")) { seen.repair.add("scope"); return JSON.stringify({ summary: "x", ops: [{ op: "remove_block", id: "title" }] }); }63 if (text.includes("FAKE_BAD_PATCH")) return JSON.stringify({ summary: "x", ops: [{ op: "remove_block", id: "no-such-block" }] });64 if (text.includes("FAKE_NOOP")) return JSON.stringify({ summary: "Rien à changer.", ops: [] });65 if (text.includes("FAKE_TOUCH_LOCKED")) return JSON.stringify({ summary: "x", ops: [{ op: "remove_block", id: "h-diagram" }] });66 return JSON.stringify({ summary: "Titre de section modifié et source ajoutée.", ops: [67 { op: "replace_block", id: "h-diagram", block: { id: "h-diagram", type: "heading", level: 2, text: "Schéma révisé" } },68 { op: "insert_block", afterId: "eq", block: { id: "note-ai", type: "callout", tone: "note", text: "Ajouté par la révision." } },69 { op: "upsert_source", source: { id: "s-new", type: "article", title: "A Source The Model Claims Is Checked", authors: [], status: "resolved", checkedAt: "2021-01-01T00:00:00.000Z" } },70 { op: "set_metadata", metadata: { summary: "Résumé révisé.", locale: "en" } },71 ] });72 }73 if (text.includes("Task: translate")) {74 const m = text.match(/Sheet to translate \(JSON\):\n([\s\S]*?)\n\nTask: translate/);75 const doc = JSON.parse(m![1]) as ReturnType<typeof sheet>;76 doc.metadata.title = "Translated: " + doc.metadata.title;77 doc.blocks = doc.blocks.map((b) => ("text" in b && typeof b.text === "string" ? { ...b, text: "EN " + b.text } : b)) as never;78 if (text.includes("FAKE") && false) return "";79 return JSON.stringify(doc);80 }81 return JSON.stringify({ ok: true });82}8384const server = createServer((req, res) => {85 const chunks: Buffer[] = [];86 req.on("data", (c) => chunks.push(c));87 req.on("end", () => {88 const url = req.url ?? "";89 const json = (status: number, data: unknown) => { res.writeHead(status, { "content-type": "application/json", "request-id": "req_fake" }); res.end(JSON.stringify(data)); };90 const presented = req.headers["x-api-key"] ?? String(req.headers.authorization ?? "").replace(/^Bearer /, "");91 if (presented !== "sk-ant-test-fake-key") return json(401, { type: "error", error: { type: "authentication_error", message: "invalid x-api-key" } });92 if (url.startsWith("/v1/models")) return json(200, { data: [{ type: "model", id: "claude-opus-5-5", display_name: "Claude Opus 5.5 (fake)", created_at: "2026-01-01T00:00:00Z", max_tokens: 128000, max_input_tokens: 1000000 }, { type: "model", id: "claude-haiku-5-5", display_name: "Claude Haiku 5.5 (fake)", created_at: "2026-01-01T00:00:00Z", max_tokens: 128000, max_input_tokens: 1000000 }], has_more: false, first_id: "claude-opus-5-5", last_id: "claude-haiku-5-5" });93 const body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");94 if (url.startsWith("/v1/messages/count_tokens")) return json(200, { input_tokens: 1234 });95 if (!url.startsWith("/v1/messages")) return json(404, { type: "error", error: { type: "not_found_error", message: "not found" } });96 const out = answer(body);97 const refusal = out === "__refusal__";98 res.writeHead(200, { "content-type": "text/event-stream", "request-id": "req_fake" });99 const send = (event: string, data: unknown) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);100 send("message_start", { type: "message_start", message: { id: "msg_fake", type: "message", role: "assistant", model: body.model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1000, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } } });101 send("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } });102 const text = refusal ? "" : out === "__slow__" ? "x".repeat(4000) : out;103 const pieces = text.match(/[\s\S]{1,400}/g) ?? [];104 let i = 0;105 const step = () => {106 if (res.destroyed) return;107 if (i < pieces.length) { send("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: pieces[i++] } }); setTimeout(step, out === "__slow__" ? 800 : 2); return; }108 send("content_block_stop", { type: "content_block_stop", index: 0 });109 send("message_delta", { type: "message_delta", delta: { stop_reason: refusal ? "refusal" : "end_turn", stop_sequence: null, ...(refusal ? { stop_details: { type: "refusal", category: "cyber", explanation: "test" } } : {}) }, usage: { output_tokens: 500 } });110 send("message_stop", { type: "message_stop" });111 res.end();112 };113 step();114 });115});116server.listen(port, "127.0.0.1", () => console.log(`fake anthropic on ${port}`));117