Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

global-setup.ts

1,463 lines51.8 KB

1import { LLMock } from '@copilotkit/aimock'
2import fs from 'fs'
3import http from 'http'
4import path from 'path'
5import { fileURLToPath } from 'url'
6import type { Mountable } from '@copilotkit/aimock'
7​
8const __filename = fileURLToPath(import.meta.url)
9const __dirname = path.dirname(__filename)
10​
11/**
12 * Directories to skip when loading JSON fixtures.
13 * - 'recorded' is for record-mode output
14 * - 'video-gen' uses programmatic registration (needs match.endpoint)
15 */
16const SKIP_FIXTURE_DIRS = new Set(['recorded', 'video-gen'])
17​
18export default async function globalSetup() {
19 const mock = new LLMock({ port: 4010, host: '127.0.0.1', logLevel: 'info' })
20​
21 // Load all JSON fixture directories (except skipped ones)
22 const fixturesDir = path.resolve(__dirname, 'fixtures')
23 const entries = fs.readdirSync(fixturesDir, { withFileTypes: true })
24 for (const entry of entries) {
25 if (entry.isDirectory() && !SKIP_FIXTURE_DIRS.has(entry.name)) {
26 await mock.loadFixtureDir(path.join(fixturesDir, entry.name))
27 }
28 }
29​
30 // Register media fixtures programmatically (require match.endpoint)
31 registerMediaFixtures(mock)
32​
33 // Mount xAI-shaped audio routes (/v1/tts, /v1/stt) — these are NOT
34 // OpenAI-compatible so aimock's onSpeech/onTranscription helpers don't cover
35 // them. Use mock.mount() to handle the paths directly.
36 mock.mount('/v1/tts', grokTTSMount())
37 mock.mount('/v1/stt', grokSTTMount())
38​
39 // ElevenLabs TTS (/v1/text-to-speech/{voiceId}) and STT (/v1/speech-to-text)
40 // are not yet covered by aimock helpers (1.17 added /v1/sound-generation
41 // and /v1/music/* but not these). Mount them here following the grok
42 // pattern above.
43 mock.mount('/v1/text-to-speech', elevenLabsTTSMount())
44 mock.mount('/v1/speech-to-text', elevenLabsSTTMount())
45​
46 // Gemini TTS hits the standard Gemini generateContent endpoint
47 // (POST /v1beta/models/{model}:generateContent) with
48 // responseModalities: ['AUDIO']. aimock's native Gemini audio helper derives
49 // the mime type from the fixture's `format`/`contentType`, so it can't emit
50 // the raw `audio/L16;codec=pcm;rate=24000` PCM that real Gemini TTS returns.
51 // Mount the TTS model's generateContent path directly so we can hand back
52 // PCM and exercise the adapter's PCM→WAV normalization. The path is specific
53 // to the TTS model, so it doesn't intercept Gemini chat/summarize requests.
54 mock.mount(
55 '/v1beta/models/gemini-3.1-flash-tts-preview:generateContent',
56 geminiTTSMount(),
57 )
58 // Gemini Veo video generation. aimock 1.29 mocks Gemini's `:predict`
59 // (Imagen) endpoint but not the long-running `:predictLongRunning` +
60 // operations-polling pair Veo uses, so mount both here. Non-Veo paths
61 // under /v1beta/models (chat, images) return false and fall through to
62 // aimock's native Gemini handlers.
63 mock.mount('/v1beta/models', geminiVeoMount())
64​
65 // Embedding endpoints aimock doesn't cover natively. OpenAI's
66 // /v1/embeddings IS covered natively (JSON fixture in fixtures/embedding/),
67 // but the other embedding providers need custom mounts:
68 //
69 // - Gemini: @google/genai posts to `{model}:batchEmbedContents` on the
70 // MLDev (API-key) surface; aimock 1.34 only handles `:embedContent`.
71 // Mounted on the same '/v1beta/models' prefix as the Veo mount above —
72 // mounts are tried in order and each returns false for paths it doesn't
73 // own, so both coexist and non-matching paths still fall through to
74 // aimock's native Gemini handlers.
75 // - Ollama: the ollama SDK's `embed()` (POST /api/embed) expects the batch
76 // `embeddings: number[][]` shape; aimock's native handler responds with
77 // the legacy singular `embedding` field, which crashes the adapter.
78 // - Mistral: the Mistral SDK Zod-validates the /v1/embeddings response and
79 // requires an `id` field aimock's OpenAI-format response builder omits.
80 // The adapter under test points its serverURL at the '/mistral' prefix.
81 mock.mount('/v1beta/models', geminiBatchEmbedMount())
82 mock.mount('/api/embed', ollamaEmbedMount())
83 mock.mount('/mistral', mistralEmbeddingsMount())
84​
85 // Gemini Omni Flash video generation (Interactions API). aimock handles
86 // synchronous text interactions natively, but not background video jobs
87 // (POST /v1beta/interactions with background:true → poll
88 // GET /v1beta/interactions/{id} → inline base64 mp4). The adapter under
89 // test points its baseUrl at this dedicated prefix so aimock's native
90 // interactions handling stays untouched for the stateful-interactions
91 // text tests.
92 mock.mount('/omni-video', geminiOmniVideoMount())
93​
94 // Anthropic server_tool_use bug reproduction (issue #604). aimock can't
95 // natively synthesize `server_tool_use` / `web_fetch_tool_result` content
96 // blocks, so this mount hand-crafts the raw SSE Claude would emit when a
97 // client `tool_use` is followed by a `web_fetch` `server_tool_use` in the
98 // same response. The corresponding api.anthropic-bug-test.ts route points
99 // the Anthropic adapter here.
100 mock.mount('/anthropic-bug-test', anthropicServerToolBugMount())
101​
102 // OpenRouter per-request cost capture. aimock's OpenAI-compatible chat
103 // helper doesn't synthesize OpenRouter's `usage.cost` / `usage.cost_details`,
104 // and crucially those land on a trailing usage-only chunk (choices: []) that
105 // arrives AFTER the finish_reason chunk. This mount hand-crafts that exact
106 // wire shape so the companion spec can assert cost reaches RUN_FINISHED.usage.
107 mock.mount('/openrouter-cost', openRouterCostMount())
108​
109 // OpenAI-compatible detailed usage capture. aimock's chat helper doesn't
110 // synthesize `prompt_tokens_details` / `completion_tokens_details`, so this
111 // mount hand-crafts a chat-completion stream whose trailing usage chunk
112 // carries cached prompt tokens and reasoning completion tokens. The companion
113 // spec asserts those reach `RUN_FINISHED.usage` as the canonical
114 // `promptTokensDetails.cachedTokens` / `completionTokensDetails.reasoningTokens`.
115 mock.mount('/openai-usage-details', openaiUsageDetailsMount())
116​
117 // Anthropic structured-output fallback usage (#758). The Anthropic text
118 // adapter has no native `structuredOutputStream`, so streaming structured
119 // output runs through the activity layer's `fallbackStructuredOutputStream`,
120 // which wraps the non-streaming `structuredOutput()`. aimock's native
121 // Anthropic helper doesn't synthesize a tool-forced `structured_output`
122 // response with usage, so this mount hand-crafts the non-streaming
123 // `/v1/messages` JSON the adapter expects. The companion spec asserts the
124 // `usage` survives onto `RUN_FINISHED.usage` on the fallback path.
125 mock.mount('/anthropic-structured-usage', anthropicStructuredUsageMount())
126​
127 // BytePlus. Ark (chat, Seedream image, Seedance video) serves its whole data
128 // plane under /api/v3, and Seed Speech (TTS/ASR) mounts its own endpoints at
129 // the same prefix on a different host — which collapses onto one prefix here
130 // because every adapter points at this single mock. Chat and image are NOT
131 // handled by these mounts: aimock's compat-path normalizer rewrites
132 // `/api/v3/chat/completions` and `/api/v3/images/generations` to their /v1
133 // equivalents, so each mount returns false for anything it doesn't own and
134 // those two fall through to the native handlers. Mounts are matched by raw
135 // pathname *before* that normalization, so ordering here is safe.
136 mock.mount('/api/v3', byteplusSeedanceMount())
137 mock.mount('/api/v3', byteplusTTSMount())
138 mock.mount('/api/v3', byteplusASRMount())
139​
140 await mock.start()
141 console.log(`[aimock] started on port 4010`)
142 ;(globalThis as any).__aimock = mock
144​
145function registerMediaFixtures(mock: LLMock) {
146 // Transcription: onTranscription sets match.endpoint = "transcription"
147 mock.onTranscription({
148 transcription: {
149 text: 'I would like to buy a Fender Stratocaster please',
150 },
151 })
152​
153 // Video: onVideo sets match.endpoint = "video"
154 // id + status are required for the OpenAI SDK's videos API to work:
155 // - POST /v1/videos reads response.id for the job ID
156 // - GET /v1/videos/{id} reads response.status to determine completion
157 mock.onVideo('a guitar being played in a store', {
158 video: {
159 url: 'https://example.com/guitar-store.mp4',
160 duration: 10,
161 id: 'video-job-e2e',
162 status: 'completed',
163 },
164 })
165​
166 // Image-to-video: the Sora adapter uploads the image part as
167 // `input_reference`, which makes the OpenAI SDK switch to a multipart
168 // POST /v1/videos. aimock 1.29 extracts the `prompt` form field from
169 // multipart bodies, so matching works the same as the JSON case above.
170 mock.onVideo('animate this product photo', {
171 video: {
172 url: 'https://example.com/product-animated.mp4',
173 duration: 5,
174 id: 'video-job-i2v-e2e',
175 status: 'completed',
176 },
177 })
178​
179 // ElevenLabs music (/v1/music/*) and SFX (/v1/sound-generation) are
180 // covered natively by aimock 1.17 — fixtures live under
181 // fixtures/audio-gen/ and fixtures/sound-effects/ and are loaded by the
182 // generic loadFixtureDir() loop above.
184​
185/**
186 * Minimal MP3 bytes — just enough for the <audio> element to consider it a
187 * valid media resource in tests. The e2e specs only check visibility of the
188 * `generated-audio` element, not playback fidelity.
189 */
190const FAKE_MP3_BYTES = Buffer.from([
191 0xff, 0xfb, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
192])
193​
194/**
195 * Raw 16-bit little-endian PCM bytes. Gemini TTS returns audio as
196 * `audio/L16;codec=pcm;rate=24000` inlineData, which the adapter wraps in a
197 * RIFF/WAV header before handing it to the browser. The samples are arbitrary
198 * silence — the spec only asserts the `<audio>` element becomes visible.
199 */
200const FAKE_PCM_BYTES = Buffer.alloc(32)
201​
202function grokTTSMount(): Mountable {
203 return {
204 async handleRequest(
205 req: http.IncomingMessage,
206 res: http.ServerResponse,
207 // aimock strips the mount prefix — pathname will be "/" for an exact match.
208 pathname: string,
209 ): Promise<boolean> {
210 if (pathname !== '/' || req.method !== 'POST') return false
211 // Drain the request body (we don't need to inspect it for tests).
212 await drainBody(req)
213 res.statusCode = 200
214 res.setHeader('Content-Type', 'audio/mpeg')
215 res.setHeader('Content-Length', String(FAKE_MP3_BYTES.length))
216 res.end(FAKE_MP3_BYTES)
217 return true
218 },
219 }
221​
222function geminiTTSMount(): Mountable {
223 return {
224 async handleRequest(
225 req: http.IncomingMessage,
226 res: http.ServerResponse,
227 // aimock strips the mount prefix — pathname will be "/" for an exact match.
228 pathname: string,
229 ): Promise<boolean> {
230 if (pathname !== '/' || req.method !== 'POST') return false
231 await drainBody(req)
232 res.statusCode = 200
233 res.setHeader('Content-Type', 'application/json')
234 // Mirror the Gemini generateContent audio response shape: audio lands as
235 // a single `candidates[0].content.parts[0].inlineData` entry. The PCM
236 // mime type forces the adapter down its PCM→WAV wrapping path.
237 res.end(
238 JSON.stringify({
239 candidates: [
240 {
241 content: {
242 role: 'model',
243 parts: [
244 {
245 inlineData: {
246 mimeType: 'audio/L16;codec=pcm;rate=24000',
247 data: FAKE_PCM_BYTES.toString('base64'),
248 },
249 },
250 ],
251 },
252 finishReason: 'STOP',
253 index: 0,
254 },
255 ],
256 usageMetadata: {
257 promptTokenCount: 5,
258 candidatesTokenCount: 15,
259 totalTokenCount: 20,
260 },
261 }),
262 )
263 return true
264 },
265 }
267​
268function grokSTTMount(): Mountable {
269 return {
270 async handleRequest(
271 req: http.IncomingMessage,
272 res: http.ServerResponse,
273 pathname: string,
274 ): Promise<boolean> {
275 if (pathname !== '/' || req.method !== 'POST') return false
276 await drainBody(req)
277 res.statusCode = 200
278 res.setHeader('Content-Type', 'application/json')
279 res.end(
280 JSON.stringify({
281 text: 'I would like to buy a Fender Stratocaster please',
282 language: 'en',
283 duration: 3.0,
284 words: [
285 { text: 'I', start: 0, end: 0.1, confidence: 0.99 },
286 { text: 'would', start: 0.1, end: 0.3, confidence: 0.98 },
287 { text: 'like', start: 0.3, end: 0.5, confidence: 0.97 },
288 { text: 'to', start: 0.5, end: 0.6, confidence: 0.99 },
289 { text: 'buy', start: 0.6, end: 0.8, confidence: 0.98 },
290 { text: 'a', start: 0.8, end: 0.9, confidence: 0.99 },
291 { text: 'Fender', start: 0.9, end: 1.3, confidence: 0.96 },
292 { text: 'Stratocaster', start: 1.3, end: 2.0, confidence: 0.94 },
293 { text: 'please', start: 2.0, end: 2.4, confidence: 0.97 },
294 ],
295 }),
296 )
297 return true
298 },
299 }
301​
302function elevenLabsTTSMount(): Mountable {
303 return {
304 async handleRequest(
305 req: http.IncomingMessage,
306 res: http.ServerResponse,
307 pathname: string,
308 ): Promise<boolean> {
309 // ElevenLabs TTS hits POST /v1/text-to-speech/{voiceId} or
310 // /v1/text-to-speech/{voiceId}/stream. After mount-prefix stripping
311 // pathname will be /{voiceId} or /{voiceId}/stream — accept any
312 // sub-path so we don't have to enumerate voice IDs.
313 if (req.method !== 'POST' || pathname === '/' || pathname === '')
314 return false
315 await drainBody(req)
316 res.statusCode = 200
317 res.setHeader('Content-Type', 'audio/mpeg')
318 res.setHeader('Content-Length', String(FAKE_MP3_BYTES.length))
319 res.end(FAKE_MP3_BYTES)
320 return true
321 },
322 }
324​
325function elevenLabsSTTMount(): Mountable {
326 return {
327 async handleRequest(
328 req: http.IncomingMessage,
329 res: http.ServerResponse,
330 pathname: string,
331 ): Promise<boolean> {
332 if (pathname !== '/' || req.method !== 'POST') return false
333 await drainBody(req)
334 res.statusCode = 200
335 res.setHeader('Content-Type', 'application/json')
336 // Scribe wire format is snake_case (the SDK converts to camelCase
337 // before handing the response to user code). Each word needs a
338 // `logprob` field per the SDK's runtime validation. Keep "Fender
339 // Stratocaster" so the existing transcription.spec.ts assertion
340 // passes for elevenlabs too.
341 res.end(
342 JSON.stringify({
343 language_code: 'en',
344 language_probability: 0.99,
345 text: 'I would like to buy a Fender Stratocaster please',
346 audio_duration_secs: 2.4,
347 words: [
348 { text: 'I', start: 0, end: 0.1, type: 'word', logprob: -0.01 },
349 {
350 text: 'would',
351 start: 0.1,
352 end: 0.3,
353 type: 'word',
354 logprob: -0.02,
355 },
356 {
357 text: 'like',
358 start: 0.3,
359 end: 0.5,
360 type: 'word',
361 logprob: -0.03,
362 },
363 { text: 'to', start: 0.5, end: 0.6, type: 'word', logprob: -0.01 },
364 { text: 'buy', start: 0.6, end: 0.8, type: 'word', logprob: -0.02 },
365 { text: 'a', start: 0.8, end: 0.9, type: 'word', logprob: -0.01 },
366 {
367 text: 'Fender',
368 start: 0.9,
369 end: 1.3,
370 type: 'word',
371 logprob: -0.04,
372 },
373 {
374 text: 'Stratocaster',
375 start: 1.3,
376 end: 2.0,
377 type: 'word',
378 logprob: -0.06,
379 },
380 {
381 text: 'please',
382 start: 2.0,
383 end: 2.4,
384 type: 'word',
385 logprob: -0.03,
386 },
387 ],
388 }),
389 )
390 return true
391 },
392 }
394​
395/**
396 * Mounts Gemini Veo's long-running video generation endpoints:
397 *
398 * - `POST /v1beta/models/{model}:predictLongRunning` — starts the job and
399 * returns the operation name.
400 * - `GET /v1beta/models/{model}/operations/{id}` — polls the operation. The
401 * mock completes immediately with the raw MLDev wire shape
402 * (`response.generateVideoResponse.generatedSamples[0].video.uri`), which
403 * the `@google/genai` SDK maps to `response.generatedVideos[0].video.uri`.
404 *
405 * Mirrors the openai `onVideo` fixture: same prompt-agnostic completed job,
406 * same target video URL.
407 */
408function geminiVeoMount(): Mountable {
409 const VIDEO_URL = 'https://example.com/guitar-store.mp4'
410 return {
411 async handleRequest(
412 req: http.IncomingMessage,
413 res: http.ServerResponse,
414 // aimock strips the mount prefix ('/v1beta/models') and any query
415 // string, so pathname looks like '/{model}:predictLongRunning' or
416 // '/{model}/operations/{id}'.
417 pathname: string,
418 ): Promise<boolean> {
419 const createMatch = pathname.match(/^\/([^/:]+):predictLongRunning$/)
420 if (createMatch && req.method === 'POST') {
421 await drainBody(req)
422 res.statusCode = 200
423 res.setHeader('Content-Type', 'application/json')
424 res.end(
425 JSON.stringify({
426 name: `models/${createMatch[1]}/operations/veo-job-e2e`,
427 }),
428 )
429 return true
430 }
431​
432 const pollMatch = pathname.match(/^\/([^/:]+)\/operations\/([^/]+)$/)
433 if (pollMatch && req.method === 'GET') {
434 res.statusCode = 200
435 res.setHeader('Content-Type', 'application/json')
436 res.end(
437 JSON.stringify({
438 name: `models/${pollMatch[1]}/operations/${pollMatch[2]}`,
439 done: true,
440 response: {
441 generateVideoResponse: {
442 generatedSamples: [{ video: { uri: VIDEO_URL } }],
443 },
444 },
445 }),
446 )
447 return true
448 }
449​
450 // Not a Veo path — fall through to aimock's native Gemini handlers.
451 return false
452 },
453 }
455​
456/**
457 * Deterministic 8-dimension embedding vector shared by the embedding mounts
458 * below and mirrored by the OpenAI JSON fixture in
459 * `fixtures/embedding/basic.json`. The embedding spec asserts each rendered
460 * vector reports exactly this dimension count.
461 */
462const EMBED_VECTOR = [0.1, -0.2, 0.3, -0.4, 0.5, -0.6, 0.7, -0.8]
463​
464/**
465 * Mounts Gemini's `{model}:batchEmbedContents` endpoint. The @google/genai
466 * SDK's `models.embedContent()` posts to `:batchEmbedContents` on the MLDev
467 * (API-key) surface — even for a single input — but aimock 1.34 only models
468 * `:embedContent`. Returns one deterministic vector per request entry, in
469 * the raw MLDev wire shape (`embeddings[].values`) the SDK maps to
470 * `EmbedContentResponse.embeddings`.
471 *
472 * Shares the '/v1beta/models' mount prefix with geminiVeoMount; non-embed
473 * paths return false and fall through to the Veo mount / native handlers.
474 */
475function geminiBatchEmbedMount(): Mountable {
476 return {
477 async handleRequest(
478 req: http.IncomingMessage,
479 res: http.ServerResponse,
480 // aimock strips the mount prefix ('/v1beta/models') and any query
481 // string, so pathname looks like '/{model}:batchEmbedContents'.
482 pathname: string,
483 ): Promise<boolean> {
484 const match = pathname.match(/^\/([^/:]+):batchEmbedContents$/)
485 if (!match || req.method !== 'POST') return false
486 const bodyText = await readBody(req)
487 let count = 1
488 try {
489 const body = JSON.parse(bodyText) as { requests?: Array<unknown> }
490 if (Array.isArray(body.requests)) count = body.requests.length
491 } catch {
492 // Malformed body — respond with a single vector anyway.
493 }
494 res.statusCode = 200
495 res.setHeader('Content-Type', 'application/json')
496 res.end(
497 JSON.stringify({
498 embeddings: Array.from({ length: count }, () => ({
499 values: [...EMBED_VECTOR],
500 })),
501 }),
502 )
503 return true
504 },
505 }
507​
508/**
509 * Mounts Ollama's batch embed endpoint (POST /api/embed). aimock's native
510 * handler answers with the legacy /api/embeddings shape (singular
511 * `embedding: number[]`), but the ollama SDK's `embed()` — which the
512 * @tanstack/ai-ollama embedding adapter uses — expects
513 * `embeddings: number[][]` with one vector per input.
514 */
515function ollamaEmbedMount(): Mountable {
516 return {
517 async handleRequest(
518 req: http.IncomingMessage,
519 res: http.ServerResponse,
520 // aimock strips the mount prefix — pathname will be "/" for an exact match.
521 pathname: string,
522 ): Promise<boolean> {
523 if (pathname !== '/' || req.method !== 'POST') return false
524 const bodyText = await readBody(req)
525 let model = 'nomic-embed-text'
526 let inputs: Array<string> = ['']
527 try {
528 const body = JSON.parse(bodyText) as {
529 model?: string
530 input?: string | Array<string>
531 }
532 if (body.model) model = body.model
533 inputs = Array.isArray(body.input) ? body.input : [body.input ?? '']
534 } catch {
535 // Malformed body — respond with a single vector anyway.
536 }
537 res.statusCode = 200
538 res.setHeader('Content-Type', 'application/json')
539 res.end(
540 JSON.stringify({
541 model,
542 embeddings: inputs.map(() => [...EMBED_VECTOR]),
543 prompt_eval_count: inputs.length * 3,
544 }),
545 )
546 return true
547 },
548 }
550​
551/**
552 * Mounts a Mistral-shaped embeddings endpoint under the '/mistral' prefix
553 * (the adapter under test sets serverURL to `<aimock>/mistral`, so the SDK
554 * posts to '/mistral/v1/embeddings'). aimock's native /v1/embeddings handler
555 * builds an OpenAI-format response without an `id`, which fails the Mistral
556 * SDK's Zod response validation (`EmbeddingResponse` requires `id`).
557 */
558function mistralEmbeddingsMount(): Mountable {
559 return {
560 async handleRequest(
561 req: http.IncomingMessage,
562 res: http.ServerResponse,
563 // aimock strips the mount prefix ('/mistral'), so pathname is
564 // '/v1/embeddings'.
565 pathname: string,
566 ): Promise<boolean> {
567 if (pathname !== '/v1/embeddings' || req.method !== 'POST') return false
568 const bodyText = await readBody(req)
569 let model = 'mistral-embed'
570 let inputs: Array<string> = ['']
571 try {
572 const body = JSON.parse(bodyText) as {
573 model?: string
574 input?: string | Array<string>
575 }
576 if (body.model) model = body.model
577 inputs = Array.isArray(body.input) ? body.input : [body.input ?? '']
578 } catch {
579 // Malformed body — respond with a single vector anyway.
580 }
581 res.statusCode = 200
582 res.setHeader('Content-Type', 'application/json')
583 res.end(
584 JSON.stringify({
585 id: 'embd-e2e',
586 object: 'list',
587 model,
588 usage: { prompt_tokens: 6, completion_tokens: 0, total_tokens: 6 },
589 data: inputs.map((_, index) => ({
590 object: 'embedding',
591 embedding: [...EMBED_VECTOR],
592 index,
593 })),
594 }),
595 )
596 return true
597 },
598 }
600​
601/**
602 * Mounts Gemini Omni Flash's Interactions-API video generation flow under a
603 * dedicated `/omni-video` prefix (the adapter under test sets its baseUrl to
604 * it, so requests land on `/omni-video/v1beta/interactions`):
605 *
606 * - `POST /v1beta/interactions` — creates the background job and returns an
607 * `in_progress` interaction with an id.
608 * - `GET /v1beta/interactions/{id}` — polls the job. The mock completes
609 * immediately with the raw wire shape: a `model_output` step carrying an
610 * inline base64 `video` content block plus `output_tokens_by_modality`
611 * usage, which the adapter maps to a `data:video/mp4;base64,…` URL.
612 */
613function geminiOmniVideoMount(): Mountable {
614 const JOB_ID = 'v1_omni-video-e2e'
615 // Minimal MP4-ish base64 payload — the spec only asserts the <video>
616 // element renders with the data: URL the adapter builds from it.
617 const VIDEO_BASE64 = 'AAAAIGZ0eXBpc29tAAACAGlzb21pc28y'
618 return {
619 async handleRequest(
620 req: http.IncomingMessage,
621 res: http.ServerResponse,
622 // aimock strips the mount prefix ('/omni-video') and any query
623 // string, so pathname looks like '/v1beta/interactions' or
624 // '/v1beta/interactions/{id}'.
625 pathname: string,
626 ): Promise<boolean> {
627 if (pathname === '/v1beta/interactions' && req.method === 'POST') {
628 await drainBody(req)
629 res.statusCode = 200
630 res.setHeader('Content-Type', 'application/json')
631 res.end(
632 JSON.stringify({
633 id: JOB_ID,
634 object: 'interaction',
635 status: 'in_progress',
636 model: 'gemini-omni-flash-preview',
637 }),
638 )
639 return true
640 }
641​
642 const pollMatch = pathname.match(/^\/v1beta\/interactions\/([^/]+)$/)
643 if (pollMatch && req.method === 'GET') {
644 res.statusCode = 200
645 res.setHeader('Content-Type', 'application/json')
646 res.end(
647 JSON.stringify({
648 id: pollMatch[1],
649 object: 'interaction',
650 status: 'completed',
651 model: 'gemini-omni-flash-preview',
652 usage: {
653 total_input_tokens: 12,
654 total_output_tokens: 57920,
655 total_tokens: 57932,
656 output_tokens_by_modality: [{ modality: 'video', tokens: 57920 }],
657 },
658 steps: [
659 {
660 type: 'user_input',
661 content: [{ type: 'text', text: 'a guitar being played' }],
662 },
663 {
664 type: 'model_output',
665 content: [
666 {
667 type: 'video',
668 mime_type: 'video/mp4',
669 data: VIDEO_BASE64,
670 },
671 ],
672 },
673 ],
674 }),
675 )
676 return true
677 }
678​
679 return false
680 },
681 }
683​
684/**
685 * Fake audio payloads keyed by Seed Speech's `audio_config.format`.
686 *
687 * The TTS adapter labels its result from the format it *requested*
688 * (`getContentType`), and it always sends `audio_config.format` explicitly —
689 * defaulting to `mp3` when the caller names no format. So the mount has to
690 * answer in whichever container the request asked for, or the adapter builds a
691 * mislabeled `data:` URI (mp3 bytes announced as `audio/wav`, say).
692 *
693 * Each payload is only as real as it needs to be: the specs assert that the
694 * `<audio>` element renders, not that it plays. `ogg_opus` is not exercised by
695 * any spec today — its magic bytes are a placeholder so an unexpected format
696 * still yields a plausible container rather than a silent mismatch.
697 */
698const FAKE_AUDIO_BY_FORMAT: Record<string, Buffer> = {
699 mp3: FAKE_MP3_BYTES,
700 wav: buildSilentWav(),
701 pcm: FAKE_PCM_BYTES,
702 ogg_opus: Buffer.from('OggS'),
704​
705/**
706 * Minimal RIFF/WAV container: a 44-byte header describing 16-bit mono PCM at
707 * 24 kHz, followed by silence.
708 */
709function buildSilentWav(): Buffer {
710 const samples = Buffer.alloc(64)
711 const header = Buffer.alloc(44)
712 header.write('RIFF', 0, 'ascii')
713 header.writeUInt32LE(36 + samples.length, 4)
714 header.write('WAVE', 8, 'ascii')
715 header.write('fmt ', 12, 'ascii')
716 header.writeUInt32LE(16, 16) // PCM chunk size
717 header.writeUInt16LE(1, 20) // format: PCM
718 header.writeUInt16LE(1, 22) // channels
719 header.writeUInt32LE(24000, 24) // sample rate
720 header.writeUInt32LE(24000 * 2, 28) // byte rate
721 header.writeUInt16LE(2, 32) // block align
722 header.writeUInt16LE(16, 34) // bits per sample
723 header.write('data', 36, 'ascii')
724 header.writeUInt32LE(samples.length, 40)
725 return Buffer.concat([header, samples])
727​
728/**
729 * Reads a mounted request body as a JSON object, or `undefined` when the body
730 * is absent, malformed, or not an object.
731 *
732 * The three BytePlus mounts below **validate** what the adapters send instead
733 * of draining it, which deliberately deviates from the `drainBody` house style
734 * every other mount in this file uses. The reason: BytePlus is the only
735 * provider in this suite with neither aimock fixtures nor record mode
736 * (aimock's `RecordProviderKey` union has no `byteplus` entry), so nothing
737 * else pins the request wire shape. With a canned 200, an adapter regression —
738 * a dropped `text_prompt`, a `speaker` that stopped nesting under
739 * `references`, an empty Seedance `content[]` — would still be answered
740 * successfully and the spec would pass green. A 400 turns that into a failing
741 * spec, which is the whole point of these mounts existing.
742 */
743async function readJsonRequestBody(
744 req: http.IncomingMessage,
745): Promise<Record<string, unknown> | undefined> {
746 const raw = await readBody(req)
747 try {
748 const parsed: unknown = JSON.parse(raw)
749 if (typeof parsed !== 'object' || parsed === null) return undefined
750 return parsed as Record<string, unknown>
751 } catch {
752 return undefined
753 }
755​
756/** Narrow an arbitrary JSON value to an object so nested fields can be read. */
757function asRecord(value: unknown): Record<string, unknown> | undefined {
758 if (typeof value !== 'object' || value === null || Array.isArray(value)) {
759 return undefined
760 }
761 return value as Record<string, unknown>
763​
764/**
765 * Rejects with Ark's error envelope — `{ error: { code, message } }` with a
766 * dotted string code. Matching the real envelope means `bytePlusArkError`
767 * renders the reason into the thrown message, so a validation failure shows up
768 * in the spec output as the actual missing field.
769 */
770function rejectArkRequest(res: http.ServerResponse, message: string): true {
771 res.statusCode = 400
772 res.setHeader('Content-Type', 'application/json')
773 res.end(JSON.stringify({ error: { code: 'InvalidParameter', message } }))
774 return true
776​
777/**
778 * Rejects with Seed Speech's error envelope — a flat numeric `code` plus
779 * `message`, which is what `bytePlusVoiceError` parses.
780 */
781function rejectVoiceRequest(res: http.ServerResponse, message: string): true {
782 res.statusCode = 400
783 res.setHeader('Content-Type', 'application/json')
784 res.end(JSON.stringify({ code: 45000001, message }))
785 return true
787​
788/**
789 * Mounts BytePlus Seedance's asynchronous video task API:
790 *
791 * - `POST /api/v3/contents/generations/tasks` — submits the job, returns `{ id }`.
792 * - `GET /api/v3/contents/generations/tasks/{id}` — polls it.
793 *
794 * aimock's native `/v1/videos` handling models OpenAI's job API, not Ark's, so
795 * this is hand-mocked. Every poll answers `succeeded`, matching the openai
796 * `onVideo` fixture and `geminiVeoMount` — the `fetcher` transport's
797 * `generateVideoFn` calls `getVideoJobStatus` exactly once after creating the
798 * job, so a mock that reports `running` first has no second poll to recover on.
799 * The queued/running branches of the adapter's status map are unit-tested.
800 *
801 * The success body mirrors a captured live task (see the Phase 0 probe notes):
802 * `content.video_url` plus `usage.completion_tokens`, `seed`, `resolution`,
803 * `ratio`, `duration`, the lowercase `framespersecond`, and `output_format`.
804 * `updated_at` matters — `getVideoUrl` anchors its 24-hour `expiresAt` to it.
805 * The `model` is echoed back from the submitted task rather than hardcoded, so
806 * the poll response can't drift from what the adapter actually asked for.
807 *
808 * The create request is validated (see `readJsonRequestBody`): Ark requires a
809 * string `model` and a non-empty `content[]`, and answers `MissingParameter`
810 * without them — a live-probed behaviour worth preserving here, since an
811 * adapter that stopped building `content[]` would otherwise still get a job id.
812 *
813 * Anything that isn't a task path returns false so Ark's OpenAI-compatible
814 * chat and Seedream image requests reach aimock's native handlers.
815 */
816function byteplusSeedanceMount(): Mountable {
817 const VIDEO_URL = 'https://example.com/guitar-store.mp4'
818 const TASKS_PATH = '/contents/generations/tasks'
819 // Model per submitted task id, so the poll can echo what was requested.
820 const jobModels = new Map<string, string>()
821 let nextTaskId = 0
822​
823 return {
824 async handleRequest(
825 req: http.IncomingMessage,
826 res: http.ServerResponse,
827 // aimock strips the mount prefix ('/api/v3'), so pathname looks like
828 // '/contents/generations/tasks' or '/contents/generations/tasks/{id}'.
829 pathname: string,
830 ): Promise<boolean> {
831 if (pathname === TASKS_PATH && req.method === 'POST') {
832 const body = await readJsonRequestBody(req)
833 if (!body) {
834 return rejectArkRequest(res, 'Malformed JSON body.')
835 }
836 if (typeof body.model !== 'string' || body.model.length === 0) {
837 return rejectArkRequest(res, 'MissingParameter: model.')
838 }
839 if (!Array.isArray(body.content) || body.content.length === 0) {
840 return rejectArkRequest(
841 res,
842 'MissingParameter: content must be a non-empty array.',
843 )
844 }
845​
846 const id = `cgt-e2e-${++nextTaskId}`
847 jobModels.set(id, body.model)
848 res.statusCode = 200
849 res.setHeader('Content-Type', 'application/json')
850 res.end(JSON.stringify({ id }))
851 return true
852 }
853​
854 const pollMatch = pathname.match(
855 /^\/contents\/generations\/tasks\/([^/]+)$/,
856 )
857 if (pollMatch && req.method === 'GET') {
858 const jobId = pollMatch[1]!
859 const nowSeconds = Math.floor(Date.now() / 1000)
860 res.statusCode = 200
861 res.setHeader('Content-Type', 'application/json')
862 res.end(
863 JSON.stringify({
864 id: jobId,
865 model: jobModels.get(jobId),
866 status: 'succeeded',
867 created_at: nowSeconds - 30,
868 updated_at: nowSeconds,
869 content: { video_url: VIDEO_URL },
870 usage: { completion_tokens: 39285, total_tokens: 39285 },
871 seed: 1234567890,
872 resolution: '480p',
873 ratio: '16:9',
874 duration: 5,
875 framespersecond: 24,
876 output_format: 'mp4',
877 service_tier: 'default',
878 }),
879 )
880 return true
881 }
882​
883 // Not a Seedance path — fall through to aimock's compat-path
884 // normalization (Ark chat + Seedream image live under the same prefix).
885 return false
886 },
887 }
889​
890/**
891 * Mounts Seed Speech's synchronous TTS endpoint,
892 * `POST /api/v3/tts/create`.
893 *
894 * The request is validated against the decoded wire schema (see
895 * `readJsonRequestBody` for why these mounts validate at all). Three fields
896 * pin the shapes most likely to regress silently:
897 *
898 * - `text_prompt` — the synthesis field. There is no request-side `text`; that
899 * belongs to the *other* endpoint (`/tts/unidirectional`), so a rename to
900 * `text` is exactly the kind of drift worth catching.
901 * - `references[0].speaker` — the voice nests inside `references[]`. A
902 * top-level `speaker` is ignored by the real server, which would otherwise
903 * look like success here.
904 * - `audio_config.format` — always sent explicitly by the adapter.
905 *
906 * The response echoes that requested format's container (see
907 * `FAKE_AUDIO_BY_FORMAT`), because the adapter derives its result's content
908 * type from what it asked for, not from anything in this payload.
909 *
910 * The envelope is the documented one: a numeric `code` (0 on success), base64
911 * `audio`, `duration` / `original_duration` in **seconds**, and a temporary
912 * `url`. Note that a non-zero `code` can arrive on an HTTP 200 — the adapter
913 * rejects `code !== 0`, so this must send 0 for the success path to hold.
914 * `subtitle` is omitted: the adapter only asks for it via `enable_subtitle`,
915 * which this feature doesn't set.
916 */
917function byteplusTTSMount(): Mountable {
918 return {
919 async handleRequest(
920 req: http.IncomingMessage,
921 res: http.ServerResponse,
922 pathname: string,
923 ): Promise<boolean> {
924 if (pathname !== '/tts/create' || req.method !== 'POST') return false
925​
926 const body = await readJsonRequestBody(req)
927 if (!body) {
928 return rejectVoiceRequest(res, 'Malformed JSON body.')
929 }
930 if (typeof body.text_prompt !== 'string' || !body.text_prompt) {
931 return rejectVoiceRequest(
932 res,
933 'Missing text_prompt (note: the synthesis field is text_prompt, not text).',
934 )
935 }
936 const references = Array.isArray(body.references)
937 ? body.references
938 : undefined
939 const speaker = asRecord(references?.[0])?.speaker
940 if (typeof speaker !== 'string' || !speaker) {
941 return rejectVoiceRequest(
942 res,
943 'Missing references[0].speaker (the voice nests inside references[], not at the top level).',
944 )
945 }
946 const audioConfig = asRecord(body.audio_config)
947 const format = audioConfig?.format
948 if (typeof format !== 'string' || !(format in FAKE_AUDIO_BY_FORMAT)) {
949 return rejectVoiceRequest(
950 res,
951 `Missing or unsupported audio_config.format: ${String(format)}.`,
952 )
953 }
954​
955 res.statusCode = 200
956 res.setHeader('Content-Type', 'application/json')
957 res.end(
958 JSON.stringify({
959 code: 0,
960 message: 'Success',
961 audio: FAKE_AUDIO_BY_FORMAT[format]!.toString('base64'),
962 duration: 2.4,
963 original_duration: 2.4,
964 url: `https://example.com/welcome-to-the-guitar-store.${format}`,
965 // Timings only come back when the caller opted in. No spec sets
966 // `enable_subtitle` today; this keeps the branch honest if one does.
967 // Subtitle times are MILLISECONDS even though `duration` above is
968 // seconds — the endpoint genuinely mixes units, so don't "fix" it.
969 ...(audioConfig?.enable_subtitle === true && {
970 subtitle: {
971 sentences: [
972 {
973 text: 'welcome to the guitar store',
974 start_time: 0,
975 end_time: 2400,
976 },
977 ],
978 },
979 }),
980 }),
981 )
982 return true
983 },
984 }
986​
987/**
988 * Mounts Seed Speech's synchronous ASR endpoint,
989 * `POST /api/v3/auc/bigmodel/recognize/flash`.
990 *
991 * The transcript matches the other providers' transcription mocks so
992 * `transcription.spec.ts` asserts the same "Fender Stratocaster" text for
993 * every provider. Wire timings are **milliseconds** (the adapter converts
994 * them to seconds), and the payload uses the nested `result` spelling rather
995 * than the flat aliases.
996 *
997 * The request is validated for an `audio.url` or `audio.data` (see
998 * `readJsonRequestBody`): the endpoint takes the clip one way or the other,
999 * and an adapter that sent neither would otherwise still get a transcript back
1000 * and pass.
1001 */
1002function byteplusASRMount(): Mountable {
1003 return {
1004 async handleRequest(
1005 req: http.IncomingMessage,
1006 res: http.ServerResponse,
1007 pathname: string,
1008 ): Promise<boolean> {
1009 if (
1010 pathname !== '/auc/bigmodel/recognize/flash' ||
1011 req.method !== 'POST'
1012 ) {
1013 return false
1015​
1016 const body = await readJsonRequestBody(req)
1017 if (!body) {
1018 return rejectVoiceRequest(res, 'Malformed JSON body.')
1020 const audio = asRecord(body.audio)
1021 const hasUrl = typeof audio?.url === 'string' && audio.url.length > 0
1022 const hasData = typeof audio?.data === 'string' && audio.data.length > 0
1023 if (!hasUrl && !hasData) {
1024 return rejectVoiceRequest(
1025 res,
1026 'Missing audio: exactly one of audio.url or audio.data is required.',
1029​
1030 res.statusCode = 200
1031 res.setHeader('Content-Type', 'application/json')
1032 res.end(
1033 JSON.stringify({
1034 audio_info: { duration: 2400 },
1035 result: {
1036 text: 'I would like to buy a Fender Stratocaster please',
1037 utterances: [
1039 text: 'I would like to buy a Fender Stratocaster please',
1040 start_time: 0,
1041 end_time: 2400,
1042 words: [
1043 { text: 'I', start_time: 0, end_time: 100 },
1044 { text: 'would', start_time: 100, end_time: 300 },
1045 { text: 'like', start_time: 300, end_time: 500 },
1046 { text: 'to', start_time: 500, end_time: 600 },
1047 { text: 'buy', start_time: 600, end_time: 800 },
1048 { text: 'a', start_time: 800, end_time: 900 },
1049 { text: 'Fender', start_time: 900, end_time: 1300 },
1050 { text: 'Stratocaster', start_time: 1300, end_time: 2000 },
1051 { text: 'please', start_time: 2000, end_time: 2400 },
1052 ],
1053 },
1054 ],
1055 },
1056 }),
1058 return true
1059 },
1062​
1063/**
1064 * Mounts a Claude-shaped SSE response that includes a client `tool_use` block
1065 * followed by a `web_fetch` `server_tool_use` block, plus its
1066 * `web_fetch_tool_result`. Reproduces the streaming scenario from issue #604
1067 * — the adapter must not let server-tool `input_json_delta`s leak into the
1068 * prior client tool's input buffer.
1070 * The first turn returns the mixed tool_use + server_tool_use response so the
1071 * adapter can dispatch the client tool. The second turn (after the client
1072 * tool result is fed back) returns a simple text completion so the agent
1073 * loop can settle.
1074 */
1075function anthropicServerToolBugMount(): Mountable {
1076 return {
1077 async handleRequest(
1078 req: http.IncomingMessage,
1079 res: http.ServerResponse,
1080 pathname: string,
1081 ): Promise<boolean> {
1082 // The Anthropic SDK posts to /v1/messages; query string (?beta=...)
1083 // is stripped from `pathname` by aimock before dispatch.
1084 if (req.method !== 'POST' || !pathname.startsWith('/v1/messages')) {
1085 return false
1087​
1088 const bodyText = await readBody(req)
1089 let hasToolResult = false
1090 try {
1091 const body = JSON.parse(bodyText) as {
1092 messages?: Array<{
1093 role: string
1094 content?: Array<{ type: string }> | string
1095 }>
1097 hasToolResult = (body.messages ?? []).some(
1098 (m) =>
1099 Array.isArray(m.content) &&
1100 m.content.some((c) => c.type === 'tool_result'),
1102 } catch {
1103 // Malformed body — fall through and emit the first-turn stream.
1105​
1106 const events = hasToolResult
1107 ? buildFollowUpEvents()
1108 : buildToolPlusServerToolEvents()
1109​
1110 res.statusCode = 200
1111 res.setHeader('Content-Type', 'text/event-stream')
1112 res.setHeader('Cache-Control', 'no-cache')
1113 res.setHeader('Connection', 'keep-alive')
1114 for (const event of events) {
1115 res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
1117 res.end()
1118 return true
1119 },
1122​
1123/**
1124 * Emits an OpenAI-compatible chat-completion SSE stream that ends with a
1125 * usage-only trailing chunk carrying OpenRouter's `cost` / `cost_details`.
1126 * Snake_case on the wire is camelCased by the `@openrouter/sdk` parser, so the
1127 * adapter sees `usage.cost` and `usage.costDetails.upstreamInferenceCost`.
1128 */
1129function openRouterCostMount(): Mountable {
1130 return {
1131 async handleRequest(
1132 req: http.IncomingMessage,
1133 res: http.ServerResponse,
1134 pathname: string,
1135 ): Promise<boolean> {
1136 // The mount prefix (/openrouter-cost) is stripped before dispatch; the
1137 // SDK posts to <serverURL>/chat/completions where serverURL ends in /v1.
1138 if (
1139 req.method !== 'POST' ||
1140 !pathname.startsWith('/v1/chat/completions')
1141 ) {
1142 return false
1144 await drainBody(req)
1145​
1146 const base = {
1147 id: 'chatcmpl-cost-e2e',
1148 object: 'chat.completion.chunk',
1149 // The @openrouter/sdk chunk schema requires a numeric `created`.
1150 created: 1700000000,
1151 model: 'openai/gpt-4o',
1153 const chunks: Array<Record<string, unknown>> = [
1155 ...base,
1156 choices: [
1158 index: 0,
1159 delta: { role: 'assistant', content: 'Hi' },
1160 finish_reason: null,
1161 },
1162 ],
1163 },
1165 ...base,
1166 choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
1167 },
1168 // Trailing usage-only chunk — the whole point of the test. Field names
1169 // mirror OpenRouter's CostDetails schema (camelCased by the SDK parser).
1171 ...base,
1172 choices: [],
1173 usage: {
1174 prompt_tokens: 11,
1175 completion_tokens: 3,
1176 total_tokens: 14,
1177 cost: 0.0042,
1178 cost_details: {
1179 upstream_inference_completions_cost: 0.0026,
1180 upstream_inference_cost: 0.0038,
1181 upstream_inference_prompt_cost: 0.0012,
1182 },
1183 },
1184 },
1186​
1187 res.statusCode = 200
1188 res.setHeader('Content-Type', 'text/event-stream')
1189 res.setHeader('Cache-Control', 'no-cache')
1190 res.setHeader('Connection', 'keep-alive')
1191 for (const chunk of chunks) {
1192 res.write(`data: ${JSON.stringify(chunk)}\n\n`)
1194 res.write('data: [DONE]\n\n')
1195 res.end()
1196 return true
1197 },
1200​
1201/**
1202 * Emits an OpenAI-compatible chat-completion SSE stream that ends with a
1203 * usage-only chunk carrying `prompt_tokens_details` / `completion_tokens_details`.
1204 * The shared `@tanstack/openai-base` extractor normalizes these into the
1205 * canonical `TokenUsage` detail breakdowns, proving detailed usage survives
1206 * end-to-end through the chat pipeline.
1207 */
1208function openaiUsageDetailsMount(): Mountable {
1209 return {
1210 async handleRequest(
1211 req: http.IncomingMessage,
1212 res: http.ServerResponse,
1213 pathname: string,
1214 ): Promise<boolean> {
1215 // The mount prefix (/openai-usage-details) is stripped before dispatch;
1216 // the SDK posts to <serverURL>/chat/completions where serverURL ends /v1.
1217 if (
1218 req.method !== 'POST' ||
1219 !pathname.startsWith('/v1/chat/completions')
1220 ) {
1221 return false
1223 await drainBody(req)
1224​
1225 const base = {
1226 id: 'chatcmpl-usage-details-e2e',
1227 object: 'chat.completion.chunk',
1228 created: 1700000000,
1229 model: 'gpt-4o',
1231 const chunks: Array<Record<string, unknown>> = [
1233 ...base,
1234 choices: [
1236 index: 0,
1237 delta: { role: 'assistant', content: 'Hi' },
1238 finish_reason: null,
1239 },
1240 ],
1241 },
1243 ...base,
1244 choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
1245 },
1246 // Trailing usage-only chunk with detailed breakdowns — the point of the
1247 // test. Mirrors OpenAI's `stream_options: { include_usage: true }` shape.
1249 ...base,
1250 choices: [],
1251 usage: {
1252 prompt_tokens: 100,
1253 completion_tokens: 50,
1254 total_tokens: 150,
1255 prompt_tokens_details: { cached_tokens: 80 },
1256 completion_tokens_details: { reasoning_tokens: 30 },
1257 },
1258 },
1260​
1261 res.statusCode = 200
1262 res.setHeader('Content-Type', 'text/event-stream')
1263 res.setHeader('Cache-Control', 'no-cache')
1264 res.setHeader('Connection', 'keep-alive')
1265 for (const chunk of chunks) {
1266 res.write(`data: ${JSON.stringify(chunk)}\n\n`)
1268 res.write('data: [DONE]\n\n')
1269 res.end()
1270 return true
1271 },
1274​
1275/**
1276 * Mounts the non-streaming Anthropic `/v1/messages` response the text adapter's
1277 * `structuredOutput()` expects: a tool-forced `structured_output` `tool_use`
1278 * block plus a `usage` object carrying `input_tokens` / `output_tokens` /
1279 * `cache_read_input_tokens`. `buildAnthropicUsage` normalizes those into
1280 * `promptTokens` / `completionTokens` / `promptTokensDetails.cachedTokens`.
1281 * Drives the #758 fallback-path usage regression.
1282 */
1283function anthropicStructuredUsageMount(): Mountable {
1284 return {
1285 async handleRequest(
1286 req: http.IncomingMessage,
1287 res: http.ServerResponse,
1288 // The mount prefix (/anthropic-structured-usage) is stripped before
1289 // dispatch; the Anthropic SDK posts to <baseURL>/v1/messages and aimock
1290 // strips the ?beta=... query string from `pathname`.
1291 pathname: string,
1292 ): Promise<boolean> {
1293 if (req.method !== 'POST' || !pathname.startsWith('/v1/messages')) {
1294 return false
1296 // structuredOutput() makes a non-streaming request (stream: false), so
1297 // respond with a single JSON message rather than an SSE stream.
1298 await drainBody(req)
1299 res.statusCode = 200
1300 res.setHeader('Content-Type', 'application/json')
1301 res.end(
1302 JSON.stringify({
1303 id: 'msg_structured_usage_e2e',
1304 type: 'message',
1305 role: 'assistant',
1306 model: 'claude-opus-4-1',
1307 content: [
1309 type: 'tool_use',
1310 id: 'toolu_structured_output',
1311 name: 'structured_output',
1312 input: { recommendation: 'Fender Stratocaster', price: 1299 },
1313 },
1314 ],
1315 stop_reason: 'tool_use',
1316 stop_sequence: null,
1317 usage: {
1318 input_tokens: 125,
1319 output_tokens: 1346,
1320 cache_read_input_tokens: 5760,
1321 },
1322 }),
1324 return true
1325 },
1328​
1329function buildToolPlusServerToolEvents(): Array<Record<string, unknown>> {
1330 const messageId = 'msg_bug_604'
1331 const model = 'claude-sonnet-4-5'
1332 return [
1334 type: 'message_start',
1335 message: {
1336 id: messageId,
1337 type: 'message',
1338 role: 'assistant',
1339 content: [],
1340 model,
1341 stop_reason: null,
1342 stop_sequence: null,
1343 usage: { input_tokens: 10, output_tokens: 0 },
1344 },
1345 },
1347 type: 'content_block_start',
1348 index: 0,
1349 content_block: {
1350 type: 'tool_use',
1351 id: 'toolu_client_weather',
1352 name: 'lookup_weather',
1353 input: {},
1354 },
1355 },
1357 type: 'content_block_delta',
1358 index: 0,
1359 delta: {
1360 type: 'input_json_delta',
1361 partial_json: '{"location":"Berlin"}',
1362 },
1363 },
1364 { type: 'content_block_stop', index: 0 },
1366 type: 'content_block_start',
1367 index: 1,
1368 content_block: {
1369 type: 'server_tool_use',
1370 id: 'srvtoolu_web_fetch',
1371 name: 'web_fetch',
1372 input: {},
1373 },
1374 },
1376 type: 'content_block_delta',
1377 index: 1,
1378 delta: {
1379 type: 'input_json_delta',
1380 partial_json: '{"url":"https://example.com"}',
1381 },
1382 },
1383 { type: 'content_block_stop', index: 1 },
1385 type: 'content_block_start',
1386 index: 2,
1387 content_block: {
1388 type: 'web_fetch_tool_result',
1389 tool_use_id: 'srvtoolu_web_fetch',
1390 content: {
1391 type: 'web_fetch_result',
1392 url: 'https://example.com',
1393 content: {
1394 type: 'document',
1395 source: { type: 'text', media_type: 'text/plain', data: 'ok' },
1396 },
1397 retrieved_at: '2026-01-01T00:00:00Z',
1398 },
1399 },
1400 },
1401 { type: 'content_block_stop', index: 2 },
1403 type: 'message_delta',
1404 delta: { stop_reason: 'tool_use', stop_sequence: null },
1405 usage: { output_tokens: 20 },
1406 },
1407 { type: 'message_stop' },
1410​
1411function buildFollowUpEvents(): Array<Record<string, unknown>> {
1412 const messageId = 'msg_bug_604_followup'
1413 const model = 'claude-sonnet-4-5'
1414 return [
1416 type: 'message_start',
1417 message: {
1418 id: messageId,
1419 type: 'message',
1420 role: 'assistant',
1421 content: [],
1422 model,
1423 stop_reason: null,
1424 stop_sequence: null,
1425 usage: { input_tokens: 30, output_tokens: 0 },
1426 },
1427 },
1429 type: 'content_block_start',
1430 index: 0,
1431 content_block: { type: 'text', text: '' },
1432 },
1434 type: 'content_block_delta',
1435 index: 0,
1436 delta: { type: 'text_delta', text: 'Berlin is sunny.' },
1437 },
1438 { type: 'content_block_stop', index: 0 },
1440 type: 'message_delta',
1441 delta: { stop_reason: 'end_turn', stop_sequence: null },
1442 usage: { output_tokens: 5 },
1443 },
1444 { type: 'message_stop' },
1447​
1448function readBody(req: http.IncomingMessage): Promise<string> {
1449 return new Promise((resolve, reject) => {
1450 const chunks: Array<Buffer> = []
1451 req.on('data', (c: Buffer) => chunks.push(c))
1452 req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1453 req.on('error', reject)
1454 })
1456​
1457function drainBody(req: http.IncomingMessage): Promise<void> {
1458 return new Promise((resolve, reject) => {
1459 req.on('data', () => {})
1460 req.on('end', () => resolve())
1461 req.on('error', reject)
1462 })