import { LLMock } from '@copilotkit/aimock' import fs from 'fs' import http from 'http' import path from 'path' import { fileURLToPath } from 'url' import { isDeepStrictEqual } from 'node:util' import { EventStreamCodec } from '@smithy/eventstream-codec' import type { Mountable } from '@copilotkit/aimock' declare global { // Read back by global-teardown.ts, which Playwright runs in the same process. var __aimock: LLMock | undefined } const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) /** * Directories to skip when loading JSON fixtures. * - 'recorded' is for record-mode output * - 'video-gen' uses programmatic registration (needs match.endpoint) */ const SKIP_FIXTURE_DIRS = new Set(['recorded', 'video-gen']) export default async function globalSetup() { const mock = new LLMock({ port: 4010, host: '127.0.0.1', logLevel: 'info' }) // Load all JSON fixture directories (except skipped ones) const fixturesDir = path.resolve(__dirname, 'fixtures') const entries = fs.readdirSync(fixturesDir, { withFileTypes: true }) for (const entry of entries) { if (entry.isDirectory() && !SKIP_FIXTURE_DIRS.has(entry.name)) { await mock.loadFixtureDir(path.join(fixturesDir, entry.name)) } } // Register media fixtures programmatically (require match.endpoint) registerMediaFixtures(mock) // Mount xAI-shaped audio routes (/v1/tts, /v1/stt) — these are NOT // OpenAI-compatible so aimock's onSpeech/onTranscription helpers don't cover // them. Use mock.mount() to handle the paths directly. mock.mount('/v1/tts', grokTTSMount()) mock.mount('/v1/stt', grokSTTMount()) // ElevenLabs TTS (/v1/text-to-speech/{voiceId}) and STT (/v1/speech-to-text) // are not yet covered by aimock helpers (1.17 added /v1/sound-generation // and /v1/music/* but not these). Mount them here following the grok // pattern above. mock.mount('/v1/text-to-speech', elevenLabsTTSMount()) mock.mount('/v1/speech-to-text', elevenLabsSTTMount()) mock.mount('/tts/bytes', cartesiaTTSMount()) mock.mount('/stt', cartesiaSTTMount()) // aimock has no OpenAI GPT-Live route (POST /v1/live/sessions). mock.mount('/v1/live/sessions', openaiLiveMount()) // Gemini TTS hits the standard Gemini generateContent endpoint // (POST /v1beta/models/{model}:generateContent) with // responseModalities: ['AUDIO']. aimock's native Gemini audio helper derives // the mime type from the fixture's `format`/`contentType`, so it can't emit // the raw `audio/L16;codec=pcm;rate=24000` PCM that real Gemini TTS returns. // Mount the TTS model's generateContent path directly so we can hand back // PCM and exercise the adapter's PCM→WAV normalization. The path is specific // to the TTS model, so it doesn't intercept Gemini chat/summarize requests. mock.mount( '/v1beta/models/gemini-3.1-flash-tts-preview:generateContent', geminiTTSMount(), ) // aimock's Gemini handler reads `parameters`, so it cannot validate the raw // `parametersJsonSchema` field. A model-specific mount keeps this check from // intercepting the other Gemini chat tests. mock.mount( '/v1beta/models/gemini-2.5-flash-lite:streamGenerateContent', geminiJsonSchemaToolMount(), ) // `chat({ reasoning })` wire check for Gemini: aimock's journal normalizes // the body, so this mount checks `generationConfig.thinkingConfig` itself. mock.mount('/reasoning-wire-gemini', geminiReasoningWireMount()) // Gemini Veo video generation. aimock does not mock the long-running // `:predictLongRunning` + operations-polling pair Veo uses, so mount both // here. Non-Veo paths // under /v1beta/models (chat, images) return false and fall through to // aimock's native Gemini handlers. mock.mount('/v1beta/models', geminiVeoMount()) // Embedding endpoints aimock doesn't cover natively. OpenAI's // /v1/embeddings IS covered natively (JSON fixture in fixtures/embedding/), // but the other embedding providers need custom mounts: // // - Gemini: @google/genai posts to `{model}:batchEmbedContents` on the // MLDev (API-key) surface; aimock 1.34 only handles `:embedContent`. // Mounted on the same '/v1beta/models' prefix as the Veo mount above — // mounts are tried in order and each returns false for paths it doesn't // own, so both coexist and non-matching paths still fall through to // aimock's native Gemini handlers. // - Ollama: the ollama SDK's `embed()` (POST /api/embed) expects the batch // `embeddings: number[][]` shape; aimock's native handler responds with // the legacy singular `embedding` field, which crashes the adapter. // - Mistral: the Mistral SDK Zod-validates the /v1/embeddings response and // requires an `id` field aimock's OpenAI-format response builder omits. // The adapter under test points its serverURL at the '/mistral' prefix. mock.mount('/v1beta/models', geminiBatchEmbedMount()) mock.mount('/api/embed', ollamaEmbedMount()) mock.mount('/mistral', mistralEmbeddingsMount()) // Gemini native image generation. The adapter posts to the Interactions // API. This dedicated prefix leaves aimock's /v1beta/interactions handler // free for the stateful text tests. One mount covers the #1104 size wire // (response_format) and the modelOptions wire (safety_settings / // thinking_level), plus a chained edit. mock.mount('/gemini-image', geminiNativeImageMount()) // Gemini Omni Flash video generation (Interactions API). aimock handles // synchronous text interactions natively, but not background video jobs // (POST /v1beta/interactions with background:true → poll // GET /v1beta/interactions/{id} → inline base64 mp4). The adapter under // test points its baseUrl at this dedicated prefix so aimock's native // interactions handling stays untouched for the stateful-interactions // text tests. mock.mount('/omni-video', geminiOmniVideoMount()) // Agentic video understanding (standard Gemini chat adapter). A video part // with metadata.processing:'agentic' routes through the non-streaming // interactions.create(), which reads `output_text`. aimock's native // interactions handler defaults to streaming SSE (keyed off `stream !== // false`), so it can't serve create(). This dedicated prefix returns a // completed JSON interaction instead. See the video-understanding provider // block in src/lib/providers.ts. mock.mount('/vu-interactions', geminiVideoUnderstandingMount()) // Anthropic server_tool_use bug reproduction (issue #604). aimock can't // natively synthesize `server_tool_use` / `web_fetch_tool_result` content // blocks, so this mount hand-crafts the raw SSE Claude would emit when a // client `tool_use` is followed by a `web_fetch` `server_tool_use` in the // same response. The corresponding api.anthropic-bug-test.ts route points // the Anthropic adapter here. mock.mount('/anthropic-bug-test', anthropicServerToolBugMount()) // OpenRouter per-request cost capture. aimock's OpenAI-compatible chat // helper doesn't synthesize OpenRouter's `usage.cost` / `usage.cost_details`, // and crucially those land on a trailing usage-only chunk (choices: []) that // arrives AFTER the finish_reason chunk. This mount hand-crafts that exact // wire shape so the companion spec can assert cost reaches RUN_FINISHED.usage. mock.mount('/openrouter-cost', openRouterCostMount()) // OpenAI-compatible detailed usage capture. aimock's chat helper doesn't // synthesize `prompt_tokens_details` / `completion_tokens_details`, so this // mount hand-crafts a chat-completion stream whose trailing usage chunk // carries cached prompt tokens and reasoning completion tokens. The companion // spec asserts those reach `RUN_FINISHED.usage` as the canonical // `promptTokensDetails.cachedTokens` / `completionTokensDetails.reasoningTokens`. mock.mount('/openai-usage-details', openaiUsageDetailsMount()) // Moonshot (Kimi) usage shape: `cached_tokens` at the root of `usage` and // `cache_write_tokens` under `prompt_tokens_details` // (https://platform.kimi.ai/docs/api/chat). mock.mount( '/moonshot-usage-details', openaiUsageDetailsMount({ prompt_tokens: 1000, completion_tokens: 50, total_tokens: 1050, cached_tokens: 800, prompt_tokens_details: { cached_tokens: 800, cache_write_tokens: 150 }, }), ) // Provider-executed web search responses need native Responses/Gemini wire // items that aimock does not synthesize. These mounts feed the adapter E2E // route deterministic search calls and grounding metadata. // OpenAI Responses usage for a call that writes the prompt cache (#1734). // aimock's native Responses helper cannot emit `input_tokens_details`. mock.mount('/openai-responses-usage', openaiResponsesUsageMount()) mock.mount('/provider-search-openai', openaiProviderSearchMount()) mock.mount('/provider-search-gemini', geminiProviderSearchMount()) // Google Search beside a function tool on Gemini 3. Answers like the // Gemini API: the flag is required, and the second step must send the // signed toolCall/toolResponse parts back around the function call. mock.mount('/gemini-server-tools', geminiServerToolsMount()) // Bedrock Converse prompt caching. aimock cannot replay the Converse // `vnd.amazon.eventstream` protocol, so this mount encodes the frames itself // and drives the real `@aws-sdk/client-bedrock-runtime` client. It reports // which request sections ended with a `cachePoint` block and answers with // Bedrock's cache usage counters; the companion spec asserts both. mock.mount('/bedrock-converse-cache', bedrockConverseCacheMount()) mock.mount('/bedrock-rerank', bedrockRerankMount()) // decide() usage on a failed answer mapping. aimock has no OpenAI Decisions // endpoint, so this mount hand-crafts a `/v1/decisions` response with valid // usage and a choice with no entry in `probabilities`. The companion spec // asserts `decide()` rejects and still reports that usage. mock.mount('/evaluate-usage-on-failure', evaluateUsageOnFailureMount()) // Failed evaluate requests. TypeSafe takes a path prefix, but the Vercel // Gateway adapter keeps only the origin of its baseURL, so that mount sits on // the real evaluate path. Both answer only requests carrying the // `x-evaluate-http-status` header and fall through otherwise. // embed() abort: `/v1/embeddings` never answers, and `/status` reports // whether the client closed the request. The embedding-abort spec checks // that `embed({ timeout })` cancels the real HTTP request. mock.mount('/embedding-abort', embeddingAbortMount()) mock.mount('/evaluate-http-status', evaluateHttpStatusMount()) mock.mount('/v4/ai/evaluation-model', evaluateHttpStatusMount()) // OpenAI's transcription streaming protocol is not synthesized by aimock. // Keep this on a dedicated base URL so all other audio requests continue to // use aimock's native transcription fixture. mock.mount('/transcription-stream', openaiTranscriptionStreamMount()) // aimock has no OpenAI Decisions API route, so this mount answers // `/v1/decisions` with a refusal plus usage for the evaluate-refusal spec. mock.mount('/evaluate-refusal', evaluateRefusalMount()) // aimock has no Gemini Decisions API route, so this mount answers // `/v1beta/decisions` with a happy-path choice/score/boolean answer plus // Gemini-shaped usage for the evaluate-gemini spec. mock.mount('/evaluate-gemini', geminiDecisionsMount()) // BytePlus. Ark (chat, Seedream image, Seedance video) serves its whole data // plane under /api/v3, and Seed Speech (TTS/ASR) mounts its own endpoints at // the same prefix on a different host — which collapses onto one prefix here // because every adapter points at this single mock. Chat and image are NOT // handled by these mounts: aimock's compat-path normalizer rewrites // `/api/v3/chat/completions` and `/api/v3/images/generations` to their /v1 // equivalents, so each mount returns false for anything it doesn't own and // those two fall through to the native handlers. Mounts are matched by raw // pathname *before* that normalization, so ordering here is safe. // ElevenLabs voice design. aimock 1.34 has no /v1/text-to-voice routes at // all — neither the design half nor the create half — so both are mounted // here. Everything else under /v1 falls through to aimock's native handlers. mock.mount('/v1/text-to-voice', elevenlabsVoiceMount()) mock.mount('/api/v3', byteplusSeedanceMount()) mock.mount('/api/v3', byteplusTTSMount()) mock.mount('/api/v3', byteplusASRMount()) await mock.start() console.log(`[aimock] started on port 4010`) globalThis.__aimock = mock } function registerMediaFixtures(mock: LLMock) { // Transcription: onTranscription sets match.endpoint = "transcription". // `duration` is only served on verbose_json responses (whisper-1's default // mode) — the otel middleware spec asserts it surfaces as the // self-describing `billed` usage on the transcription span. mock.onTranscription({ transcription: { text: 'I would like to buy a Fender Stratocaster please', duration: 2.4, }, }) // Video: onVideo sets match.endpoint = "video" // id + status are required for the OpenAI SDK's videos API to work: // - POST /v1/videos reads response.id for the job ID // - GET /v1/videos/{id} reads response.status to determine completion mock.onVideo('a guitar being played in a store', { video: { url: 'https://example.com/guitar-store.mp4', id: 'video-job-e2e', status: 'completed', }, }) // Image-to-video: the Sora adapter uploads the image part as // `input_reference`, which makes the OpenAI SDK switch to a multipart // POST /v1/videos. aimock 1.29 extracts the `prompt` form field from // multipart bodies, so matching works the same as the JSON case above. mock.onVideo('animate this product photo', { video: { url: 'https://example.com/product-animated.mp4', id: 'video-job-i2v-e2e', status: 'completed', }, }) // ElevenLabs music (/v1/music/*) and SFX (/v1/sound-generation) are // covered natively by aimock 1.17 — fixtures live under // fixtures/audio-gen/ and fixtures/sound-effects/ and are loaded by the // generic loadFixtureDir() loop above. } /** * Minimal MP3 bytes — just enough for the