@copilotkit/aimock 1.37.4 → 1.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +48 -0
- package/README.md +50 -11
- package/dist/agui-handler.cjs +20 -18
- package/dist/agui-handler.cjs.map +1 -1
- package/dist/agui-handler.d.cts +8 -1
- package/dist/agui-handler.d.cts.map +1 -1
- package/dist/agui-handler.d.ts +8 -1
- package/dist/agui-handler.d.ts.map +1 -1
- package/dist/agui-handler.js +20 -18
- package/dist/agui-handler.js.map +1 -1
- package/dist/agui-recorder.cjs +6 -0
- package/dist/agui-recorder.cjs.map +1 -1
- package/dist/agui-recorder.d.cts.map +1 -1
- package/dist/agui-recorder.d.ts.map +1 -1
- package/dist/agui-recorder.js +6 -0
- package/dist/agui-recorder.js.map +1 -1
- package/dist/agui-stub.d.cts +2 -2
- package/dist/agui-stub.d.ts +2 -2
- package/dist/agui-types.d.cts +19 -1
- package/dist/agui-types.d.cts.map +1 -1
- package/dist/agui-types.d.ts +19 -1
- package/dist/agui-types.d.ts.map +1 -1
- package/dist/aimock-cli.cjs +1 -1
- package/dist/aimock-cli.cjs.map +1 -1
- package/dist/aimock-cli.js +1 -1
- package/dist/aimock-cli.js.map +1 -1
- package/dist/api-key-auth.cjs +166 -0
- package/dist/api-key-auth.cjs.map +1 -0
- package/dist/api-key-auth.d.cts +17 -0
- package/dist/api-key-auth.d.cts.map +1 -0
- package/dist/api-key-auth.d.ts +17 -0
- package/dist/api-key-auth.d.ts.map +1 -0
- package/dist/api-key-auth.js +158 -0
- package/dist/api-key-auth.js.map +1 -0
- package/dist/cli.cjs +14 -11
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +14 -11
- package/dist/cli.js.map +1 -1
- package/dist/config-loader.cjs +4 -2
- package/dist/config-loader.cjs.map +1 -1
- package/dist/config-loader.d.cts +2 -1
- package/dist/config-loader.d.cts.map +1 -1
- package/dist/config-loader.d.ts +2 -1
- package/dist/config-loader.d.ts.map +1 -1
- package/dist/config-loader.js +5 -3
- package/dist/config-loader.js.map +1 -1
- package/dist/fal-audio.cjs +2 -0
- package/dist/fal-audio.cjs.map +1 -1
- package/dist/fal-audio.d.cts.map +1 -1
- package/dist/fal-audio.d.ts.map +1 -1
- package/dist/fal-audio.js +2 -0
- package/dist/fal-audio.js.map +1 -1
- package/dist/fal.cjs +4 -1
- package/dist/fal.cjs.map +1 -1
- package/dist/fal.d.cts.map +1 -1
- package/dist/fal.d.ts.map +1 -1
- package/dist/fal.js +4 -1
- package/dist/fal.js.map +1 -1
- package/dist/fixture-loader.cjs +0 -0
- package/dist/fixture-loader.cjs.map +1 -1
- package/dist/fixture-loader.d.cts +3 -1
- package/dist/fixture-loader.d.cts.map +1 -1
- package/dist/fixture-loader.d.ts +3 -1
- package/dist/fixture-loader.d.ts.map +1 -1
- package/dist/fixture-loader.js +0 -0
- package/dist/fixture-loader.js.map +1 -1
- package/dist/grok-video.cjs +9 -2
- package/dist/grok-video.cjs.map +1 -1
- package/dist/grok-video.js +10 -3
- package/dist/grok-video.js.map +1 -1
- package/dist/helpers.cjs +16 -22
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +16 -21
- package/dist/helpers.js.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/llmock.cjs +37 -12
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +26 -2
- package/dist/llmock.d.cts.map +1 -1
- package/dist/llmock.d.ts +26 -2
- package/dist/llmock.d.ts.map +1 -1
- package/dist/llmock.js +39 -15
- package/dist/llmock.js.map +1 -1
- package/dist/openrouter-chat.cjs +333 -0
- package/dist/openrouter-chat.cjs.map +1 -0
- package/dist/openrouter-chat.js +325 -0
- package/dist/openrouter-chat.js.map +1 -0
- package/dist/openrouter-video.cjs +24 -7
- package/dist/openrouter-video.cjs.map +1 -1
- package/dist/openrouter-video.d.cts.map +1 -1
- package/dist/openrouter-video.d.ts.map +1 -1
- package/dist/openrouter-video.js +25 -8
- package/dist/openrouter-video.js.map +1 -1
- package/dist/provider-auth.cjs +20 -0
- package/dist/provider-auth.cjs.map +1 -1
- package/dist/provider-auth.js +20 -1
- package/dist/provider-auth.js.map +1 -1
- package/dist/recorder.cjs +50 -8
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.d.cts.map +1 -1
- package/dist/recorder.d.ts.map +1 -1
- package/dist/recorder.js +50 -10
- package/dist/recorder.js.map +1 -1
- package/dist/responses.cjs +200 -89
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts +18 -3
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts +18 -3
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +199 -90
- package/dist/responses.js.map +1 -1
- package/dist/server.cjs +190 -83
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +7 -2
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts +7 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +190 -85
- package/dist/server.js.map +1 -1
- package/dist/sse-writer.cjs +3 -0
- package/dist/sse-writer.cjs.map +1 -1
- package/dist/sse-writer.d.cts +8 -0
- package/dist/sse-writer.d.cts.map +1 -1
- package/dist/sse-writer.d.ts +8 -0
- package/dist/sse-writer.d.ts.map +1 -1
- package/dist/sse-writer.js +3 -0
- package/dist/sse-writer.js.map +1 -1
- package/dist/stream-collapse.cjs +103 -0
- package/dist/stream-collapse.cjs.map +1 -1
- package/dist/stream-collapse.d.cts +7 -0
- package/dist/stream-collapse.d.cts.map +1 -1
- package/dist/stream-collapse.d.ts +7 -0
- package/dist/stream-collapse.d.ts.map +1 -1
- package/dist/stream-collapse.js +103 -0
- package/dist/stream-collapse.js.map +1 -1
- package/dist/transcription.cjs +49 -2
- package/dist/transcription.cjs.map +1 -1
- package/dist/transcription.d.cts.map +1 -1
- package/dist/transcription.d.ts.map +1 -1
- package/dist/transcription.js +50 -3
- package/dist/transcription.js.map +1 -1
- package/dist/types.d.cts +187 -5
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +187 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/vector-types.d.ts.map +1 -1
- package/dist/veo-video.cjs +9 -2
- package/dist/veo-video.cjs.map +1 -1
- package/dist/veo-video.js +10 -3
- package/dist/veo-video.js.map +1 -1
- package/dist/ws-gemini-live.cjs +41 -6
- package/dist/ws-gemini-live.cjs.map +1 -1
- package/dist/ws-gemini-live.js +41 -6
- package/dist/ws-gemini-live.js.map +1 -1
- package/dist/ws-realtime.cjs +306 -57
- package/dist/ws-realtime.cjs.map +1 -1
- package/dist/ws-realtime.d.cts +1 -0
- package/dist/ws-realtime.d.cts.map +1 -1
- package/dist/ws-realtime.d.ts +1 -0
- package/dist/ws-realtime.d.ts.map +1 -1
- package/dist/ws-realtime.js +307 -58
- package/dist/ws-realtime.js.map +1 -1
- package/dist/ws-responses.cjs +11 -6
- package/dist/ws-responses.cjs.map +1 -1
- package/dist/ws-responses.d.cts.map +1 -1
- package/dist/ws-responses.d.ts.map +1 -1
- package/dist/ws-responses.js +12 -7
- package/dist/ws-responses.js.map +1 -1
- package/package.json +3 -2
- package/skills/write-fixtures/SKILL.md +53 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fixture-loader.d.cts","names":[],"sources":["../src/fixture-loader.ts"],"sourcesContent":[],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"fixture-loader.d.cts","names":[],"sources":["../src/fixture-loader.ts"],"sourcesContent":[],"mappings":";;;;;;;AA+BA;;;;;AA0HgB,iBA1HA,iBAAA,CA0He,GAAA,EA1HQ,mBA0HR,CAAA,EA1H8B,eA0H9B;AAA4B,iBAA3C,eAAA,CAA2C,QAAA,EAAA,MAAA,EAAA,MAAA,CAAA,EAAA,MAAA,CAAA,EAAS,OAAT,EAAA;AAAS,iBA6BpD,mBAAA,CA7BoD,OAAA,EAAA,MAAA,EAAA,MAAA,CAAA,EA6BN,MA7BM,CAAA,EA6BG,OA7BH,EAAA;AAAO,UAgF1D,gBAAA,CAhF0D;EA6B3D,QAAA,EAAA,OAAA,GAAA,SAAmB;EAAA,YAAA,EAAA,MAAA;SAA2B,EAAA,MAAA;;AAAgB,iBA8Q9D,gBAAA,CA9Q8D,QAAA,EA8QnC,OA9QmC,EAAA,CAAA,EA8QvB,gBA9QuB,EAAA;AAmD9E"}
|
package/dist/fixture-loader.d.ts
CHANGED
|
@@ -6,7 +6,9 @@ import { Fixture, FixtureFileResponse, FixtureResponse } from "./types.js";
|
|
|
6
6
|
/**
|
|
7
7
|
* Auto-stringify object-valued `content` and `toolCalls[].arguments` fields.
|
|
8
8
|
* This lets fixture authors write plain JSON objects instead of escaped strings.
|
|
9
|
-
* All other fields (including ResponseOverrides
|
|
9
|
+
* All other fields (including ResponseOverrides, and the ErrorResponse
|
|
10
|
+
* `fallthrough` OpenRouter-failover flag) pass through unmodified via the
|
|
11
|
+
* shallow clone below.
|
|
10
12
|
*/
|
|
11
13
|
declare function normalizeResponse(raw: FixtureFileResponse): FixtureResponse;
|
|
12
14
|
declare function loadFixtureFile(filePath: string, logger?: Logger): Fixture[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fixture-loader.d.ts","names":[],"sources":["../src/fixture-loader.ts"],"sourcesContent":[],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"fixture-loader.d.ts","names":[],"sources":["../src/fixture-loader.ts"],"sourcesContent":[],"mappings":";;;;;;;AA+BA;;;;;AA0HgB,iBA1HA,iBAAA,CA0He,GAAA,EA1HQ,mBA0HR,CAAA,EA1H8B,eA0H9B;AAA4B,iBAA3C,eAAA,CAA2C,QAAA,EAAA,MAAA,EAAA,MAAA,CAAA,EAAA,MAAA,CAAA,EAAS,OAAT,EAAA;AAAS,iBA6BpD,mBAAA,CA7BoD,OAAA,EAAA,MAAA,EAAA,MAAA,CAAA,EA6BN,MA7BM,CAAA,EA6BG,OA7BH,EAAA;AAAO,UAgF1D,gBAAA,CAhF0D;EA6B3D,QAAA,EAAA,OAAA,GAAA,SAAmB;EAAA,YAAA,EAAA,MAAA;SAA2B,EAAA,MAAA;;AAAgB,iBA8Q9D,gBAAA,CA9Q8D,QAAA,EA8QnC,OA9QmC,EAAA,CAAA,EA8QvB,gBA9QuB,EAAA;AAmD9E"}
|
package/dist/fixture-loader.js
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fixture-loader.js","names":[],"sources":["../src/fixture-loader.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type {\n Fixture,\n FixtureFile,\n FixtureFileEntry,\n FixtureFileResponse,\n FixtureResponse,\n ResponseOverrides,\n} from \"./types.js\";\nimport {\n isTextResponse,\n isToolCallResponse,\n isContentWithToolCallsResponse,\n isErrorResponse,\n isEmbeddingResponse,\n isImageResponse,\n isAudioResponse,\n isTranscriptionResponse,\n isVideoResponse,\n isJSONResponse,\n} from \"./helpers.js\";\nimport type { Logger } from \"./logger.js\";\n\n/**\n * Auto-stringify object-valued `content` and `toolCalls[].arguments` fields.\n * This lets fixture authors write plain JSON objects instead of escaped strings.\n * All other fields (including ResponseOverrides) pass through unmodified.\n */\nexport function normalizeResponse(raw: FixtureFileResponse): FixtureResponse {\n // Shallow-clone so we don't mutate the parsed JSON input.\n const response = { ...raw } as Record<string, unknown>;\n\n // Auto-stringify object content (e.g. structured output)\n if (typeof response.content === \"object\" && response.content !== null) {\n response.content = JSON.stringify(response.content);\n }\n\n // Auto-stringify object arguments in toolCalls\n if (Array.isArray(response.toolCalls)) {\n response.toolCalls = (response.toolCalls as Array<Record<string, unknown>>).map((tc) => {\n if (typeof tc.arguments === \"object\" && tc.arguments !== null) {\n return { ...tc, arguments: JSON.stringify(tc.arguments) };\n }\n return tc;\n });\n }\n\n // Carry the optional ordered `blocks` array through, mirroring the\n // toolCalls[].arguments idiom above: auto-stringify object `arguments` on\n // each `toolCall` block. Gated on Array.isArray so a malformed (non-array)\n // `blocks` value passes through untouched rather than crashing — downstream\n // validation/builders own shape rejection. Absent `blocks` → key absent.\n if (Array.isArray(response.blocks)) {\n response.blocks = (response.blocks as Array<Record<string, unknown>>).map((block) => {\n if (\n block != null &&\n block.type === \"toolCall\" &&\n typeof block.arguments === \"object\" &&\n block.arguments !== null\n ) {\n return { ...block, arguments: JSON.stringify(block.arguments) };\n }\n return block;\n });\n }\n\n return response as unknown as FixtureResponse;\n}\n\nexport function entryToFixture(entry: FixtureFileEntry, logger?: Logger): Fixture {\n const fixture: Fixture = {\n match: {\n userMessage: entry.match.userMessage,\n systemMessage: entry.match.systemMessage,\n inputText: entry.match.inputText,\n toolCallId: entry.match.toolCallId,\n toolResultContains: entry.match.toolResultContains,\n toolName: entry.match.toolName,\n model: entry.match.model,\n responseFormat: entry.match.responseFormat,\n endpoint: entry.match.endpoint,\n ...(entry.match.sequenceIndex !== undefined && { sequenceIndex: entry.match.sequenceIndex }),\n ...(entry.match.turnIndex !== undefined && {\n turnIndex: entry.match.turnIndex,\n }),\n ...(entry.match.hasToolResult !== undefined && {\n hasToolResult: entry.match.hasToolResult,\n }),\n ...(entry.match.context !== undefined && { context: entry.match.context }),\n },\n response: normalizeResponse(entry.response),\n ...(entry.latency !== undefined && { latency: entry.latency }),\n ...(entry.chunkSize !== undefined && { chunkSize: entry.chunkSize }),\n ...(entry.truncateAfterChunks !== undefined && {\n truncateAfterChunks: entry.truncateAfterChunks,\n }),\n ...(entry.disconnectAfterMs !== undefined && { disconnectAfterMs: entry.disconnectAfterMs }),\n ...(entry.streamingProfile !== undefined && { streamingProfile: entry.streamingProfile }),\n ...(entry.recordedTimings !== undefined && { recordedTimings: entry.recordedTimings }),\n ...(entry.replaySpeed != null && { replaySpeed: entry.replaySpeed }),\n ...(entry.chaos !== undefined && { chaos: entry.chaos }),\n ...(entry.metadata !== undefined && { metadata: entry.metadata }),\n };\n\n // Sanitize recordedTimings to guard against NaN or negative values that\n // would silently degrade replay timing calculations.\n if (fixture.recordedTimings) {\n const rt = fixture.recordedTimings;\n if (!Number.isFinite(rt.ttftMs) || rt.ttftMs < 0) rt.ttftMs = 0;\n rt.interChunkDelaysMs = Array.isArray(rt.interChunkDelaysMs)\n ? rt.interChunkDelaysMs.filter((d) => Number.isFinite(d) && d >= 0)\n : [];\n if (!Number.isFinite(rt.totalDurationMs) || rt.totalDurationMs < 0) rt.totalDurationMs = 0;\n }\n\n if (fixture.replaySpeed != null && fixture.replaySpeed <= 0) {\n logger?.warn(`Fixture replaySpeed must be positive, got ${fixture.replaySpeed}. Ignoring.`);\n delete fixture.replaySpeed;\n }\n\n return fixture;\n}\n\n/**\n * Serialise a match value (string | string[] | RegExp | undefined) into a\n * dedup-key fragment that is kind-aware, so a string, a RegExp with the same\n * source, and an array containing that string do not collide. A plain template\n * literal would coerce `/foo/` and `\"foo\"` to the same text and join `[\"foo\"]`\n * to `\"foo\"`, wrongly deduping fixtures that the router would treat as distinct.\n * Used by the duplicate-userMessage dedup key in validateFixtures.\n */\nfunction serializeMatcher(value: string | string[] | RegExp | undefined): string {\n if (value === undefined) return \"\";\n if (value instanceof RegExp) return `re:${value.source}\u0000${value.flags}`;\n if (Array.isArray(value)) return `arr:${JSON.stringify(value)}`;\n return `str:${value}`;\n}\n\n// Logging helper — uses logger if provided, falls back to console.warn.\nfunction warn(logger: Logger | undefined, msg: string, ...rest: unknown[]): void {\n if (logger) {\n logger.warn(msg, ...rest);\n } else {\n console.warn(`[fixture-loader] ${msg}`, ...rest);\n }\n}\n\nexport function loadFixtureFile(filePath: string, logger?: Logger): Fixture[] {\n let raw: string;\n try {\n raw = readFileSync(filePath, \"utf-8\");\n } catch (err) {\n warn(logger, `Could not read file ${filePath}:`, err);\n return [];\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n warn(logger, `Invalid JSON in ${filePath}:`, err);\n return [];\n }\n\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n !Array.isArray((parsed as FixtureFile).fixtures)\n ) {\n warn(logger, `Missing or invalid \"fixtures\" array in ${filePath}`);\n return [];\n }\n\n return (parsed as FixtureFile).fixtures.map((e) => entryToFixture(e, logger));\n}\n\nexport function loadFixturesFromDir(dirPath: string, logger?: Logger): Fixture[] {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n warn(logger, `Could not read directory ${dirPath}:`, err);\n return [];\n }\n\n const jsonFiles: string[] = [];\n const subdirs: string[] = [];\n for (const name of entries) {\n const fullPath = join(dirPath, name);\n try {\n if (statSync(fullPath).isDirectory()) {\n subdirs.push(name);\n continue;\n }\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\") {\n warn(logger, `Could not stat ${fullPath}:`, err);\n }\n continue;\n }\n if (name.endsWith(\".json\")) {\n jsonFiles.push(name);\n }\n }\n jsonFiles.sort();\n\n const fixtures: Fixture[] = [];\n for (const name of jsonFiles) {\n const filePath = join(dirPath, name);\n fixtures.push(...loadFixtureFile(filePath, logger));\n }\n\n // Recurse into all subdirectories (full depth) to support nested layouts\n // like showcase/aimock/d6/<integration>/<feature>.json.\n subdirs.sort();\n for (const sub of subdirs) {\n fixtures.push(...loadFixturesFromDir(join(dirPath, sub), logger));\n }\n\n return fixtures;\n}\n\n// ---------------------------------------------------------------------------\n// Fixture validation\n// ---------------------------------------------------------------------------\n\nexport interface ValidationResult {\n severity: \"error\" | \"warning\";\n fixtureIndex: number;\n message: string;\n}\n\nfunction validateReasoning(\n response: { reasoning?: unknown },\n fixtureIndex: number,\n results: ValidationResult[],\n): void {\n if (response.reasoning !== undefined) {\n if (typeof response.reasoning !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: \"reasoning must be a string\",\n });\n } else if (response.reasoning === \"\") {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message: \"reasoning is empty string — no reasoning events will be emitted\",\n });\n }\n }\n}\n\nfunction validateWebSearches(\n response: { webSearches?: unknown },\n fixtureIndex: number,\n results: ValidationResult[],\n): void {\n if (response.webSearches !== undefined) {\n if (!Array.isArray(response.webSearches)) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: \"webSearches must be an array of strings\",\n });\n } else if (response.webSearches.length === 0) {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message: \"webSearches is empty array — no web search events will be emitted\",\n });\n } else {\n for (let j = 0; j < response.webSearches.length; j++) {\n if (typeof response.webSearches[j] !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `webSearches[${j}] is not a string`,\n });\n break;\n }\n if (response.webSearches[j] === \"\") {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message: `webSearches[${j}] is empty string`,\n });\n }\n }\n }\n }\n}\n\nfunction validateBlocks(\n response: { blocks?: unknown; content?: unknown; toolCalls?: unknown },\n fixtureIndex: number,\n results: ValidationResult[],\n): void {\n if (response.blocks === undefined) return;\n\n // Mirrors the toolCalls checks: reject malformed `blocks` at LOAD time so a\n // bad blocks array never reaches the dispatch/builder (where\n // resolveFixtureBlocks throws AFTER the journal has already recorded\n // status:200, yielding a journal-200/client-500 mismatch). #274 F3+F8.\n if (!Array.isArray(response.blocks)) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks must be an array, got ${typeof response.blocks}`,\n });\n return;\n }\n\n for (let j = 0; j < response.blocks.length; j++) {\n const block = response.blocks[j] as Record<string, unknown> | null | undefined;\n if (typeof block !== \"object\" || block === null) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}] must be an object`,\n });\n continue;\n }\n if (block.type !== \"text\" && block.type !== \"toolCall\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].type must be \"text\" or \"toolCall\", got ${JSON.stringify(block.type)}`,\n });\n continue;\n }\n if (block.type === \"text\") {\n if (typeof block.text !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].text must be a string, got ${typeof block.text}`,\n });\n } else if (block.text === \"\") {\n // Mirror the content/toolCalls \"empty string\" rejection: an empty-text\n // block produces a meaningless/spurious wire chunk on replay.\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].text is empty string`,\n });\n }\n } else {\n // toolCall block — mirror toolCalls[] name + arguments checks.\n if (typeof block.name !== \"string\" || block.name === \"\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].name must be a non-empty string`,\n });\n }\n // `arguments` is JSON-string in runtime form (normalizeResponse already\n // stringified object/array args); accept a valid-JSON string or an object.\n if (typeof block.arguments === \"string\") {\n try {\n JSON.parse(block.arguments);\n } catch {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].arguments is not valid JSON: ${block.arguments}`,\n });\n }\n } else if (typeof block.arguments !== \"object\" || block.arguments === null) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].arguments must be a JSON string or object, got ${typeof block.arguments}`,\n });\n }\n if (block.id !== undefined && typeof block.id !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].id must be a string, got ${typeof block.id}`,\n });\n }\n }\n }\n\n // blocks-vs-content/toolCalls divergence (#274 P2). When a fixture carries\n // BOTH `blocks` AND legacy `content`/`toolCalls` (allowed but unusual now\n // that blocks-only is first-class), builders stream `blocks` and IGNORE the\n // redundant `content`/`toolCalls`. If those disagree it is a silent footgun,\n // so WARN (not a hard error). Stay silent on the clean blocks-only path\n // (neither legacy field present) — that is the intended shape.\n const hasLegacyContent = typeof response.content === \"string\";\n const hasLegacyToolCalls = Array.isArray(response.toolCalls);\n if ((hasLegacyContent || hasLegacyToolCalls) && Array.isArray(response.blocks)) {\n const textBlocks = response.blocks.filter(\n (b): b is { type: \"text\"; text: string } =>\n b != null &&\n typeof b === \"object\" &&\n (b as { type?: unknown }).type === \"text\" &&\n typeof (b as { text?: unknown }).text === \"string\",\n );\n const toolCallBlockNames = response.blocks\n .filter(\n (b): b is { type: \"toolCall\"; name: string } =>\n b != null &&\n typeof b === \"object\" &&\n (b as { type?: unknown }).type === \"toolCall\" &&\n typeof (b as { name?: unknown }).name === \"string\",\n )\n .map((b) => b.name);\n\n // Text divergence: blocks' concatenated text vs legacy `content`.\n if (hasLegacyContent) {\n const blocksText = textBlocks.map((b) => b.text).join(\"\");\n if (blocksText !== response.content) {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message:\n \"blocks text diverges from content — builders stream blocks and ignore the redundant content field\",\n });\n }\n }\n\n // ToolCall divergence: blocks' ordered toolCall names vs legacy `toolCalls`.\n if (hasLegacyToolCalls) {\n const legacyNames = (response.toolCalls as Array<{ name?: unknown }>).map((tc) =>\n typeof tc?.name === \"string\" ? tc.name : undefined,\n );\n const sameNames =\n legacyNames.length === toolCallBlockNames.length &&\n legacyNames.every((n, k) => n === toolCallBlockNames[k]);\n if (!sameNames) {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message:\n \"blocks toolCalls diverge from toolCalls — builders stream blocks and ignore the redundant toolCalls field\",\n });\n }\n }\n }\n}\n\nexport function validateFixtures(fixtures: Fixture[]): ValidationResult[] {\n const results: ValidationResult[] = [];\n\n const seenUserMessages = new Map<string, number>();\n\n for (let i = 0; i < fixtures.length; i++) {\n const f = fixtures[i];\n const response = f.response;\n\n // Skip response-shape validation for function responses — they are\n // evaluated at runtime so we cannot statically inspect them.\n if (typeof response === \"function\") {\n // Still validate match fields and numeric options below.\n } else {\n // --- Error checks ---\n\n // Response type recognition\n // Note: isContentWithToolCallsResponse must be checked before isTextResponse\n // and isToolCallResponse since it is a structural superset of both.\n if (\n !isContentWithToolCallsResponse(response) &&\n !isTextResponse(response) &&\n !isToolCallResponse(response) &&\n !isErrorResponse(response) &&\n !isEmbeddingResponse(response) &&\n !isImageResponse(response) &&\n !isAudioResponse(response) &&\n !isTranscriptionResponse(response) &&\n !isVideoResponse(response) &&\n !isJSONResponse(response)\n ) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message:\n \"response is not a recognized type (must have content, toolCalls, error, embedding, image, audio, transcription, video, or json)\",\n });\n }\n\n // When a non-empty ordered `blocks` array is present, the builders stream\n // `blocks` and IGNORE the legacy `content` mirror (see validateBlocks's\n // divergence note + isContentWithToolCallsResponse's BLOCKS-ONLY clause).\n // So an empty-string `content` is harmless in that case and must NOT raise\n // the \"content is empty string\" hard error. Fixtures WITHOUT blocks keep\n // the error (an empty content with no blocks produces no output).\n const hasNonEmptyBlocks =\n Array.isArray((response as { blocks?: unknown }).blocks) &&\n (response as { blocks: unknown[] }).blocks.length > 0;\n\n // Text response checks\n if (isTextResponse(response)) {\n if (response.content === \"\" && !hasNonEmptyBlocks) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"content is empty string\",\n });\n }\n validateReasoning(response, i, results);\n validateWebSearches(response, i, results);\n }\n\n // ContentWithToolCalls response checks\n if (isContentWithToolCallsResponse(response)) {\n // The guard now also matches a BLOCKS-ONLY fixture (non-empty `blocks`,\n // no `content`/`toolCalls`). For that shape the content/toolCalls checks\n // below don't apply (and `content`/`toolCalls` are undefined) — the\n // ordered `blocks` array is validated separately by `validateBlocks`\n // immediately after this block. So gate the legacy field checks on the\n // fields actually being present, mirroring the builders' branch-on-blocks.\n if (typeof response.content === \"string\") {\n if (response.content === \"\" && !hasNonEmptyBlocks) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"content is empty string\",\n });\n }\n }\n if (Array.isArray(response.toolCalls)) {\n if (response.toolCalls.length === 0) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: \"toolCalls array is empty — fixture will never produce tool calls\",\n });\n }\n for (let j = 0; j < response.toolCalls.length; j++) {\n const tc = response.toolCalls[j];\n if (!tc.name) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].name is empty`,\n });\n }\n try {\n JSON.parse(tc.arguments);\n } catch {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].arguments is not valid JSON: ${tc.arguments}`,\n });\n }\n }\n }\n validateReasoning(response, i, results);\n validateWebSearches(response, i, results);\n }\n\n // Optional ordered `blocks` checks — validated whenever present on the\n // response, regardless of which content/toolCalls guard matched, so a\n // malformed blocks array is rejected at LOAD rather than at dispatch.\n validateBlocks(\n response as { blocks?: unknown; content?: unknown; toolCalls?: unknown },\n i,\n results,\n );\n\n // Tool call response checks\n if (isToolCallResponse(response)) {\n if (response.toolCalls.length === 0) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: \"toolCalls array is empty — fixture will never produce tool calls\",\n });\n }\n for (let j = 0; j < response.toolCalls.length; j++) {\n const tc = response.toolCalls[j];\n if (!tc.name) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].name is empty`,\n });\n }\n try {\n JSON.parse(tc.arguments);\n } catch {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].arguments is not valid JSON: ${tc.arguments}`,\n });\n }\n }\n validateWebSearches(response, i, results);\n }\n\n // Error response checks\n if (isErrorResponse(response)) {\n if (!response.error.message) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"error.message is empty\",\n });\n }\n if (response.status !== undefined && (response.status < 100 || response.status > 599)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `error status ${response.status} is not a valid HTTP status code`,\n });\n }\n }\n\n // Embedding response checks\n if (isEmbeddingResponse(response)) {\n if (response.embedding.length === 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"embedding array is empty\",\n });\n }\n for (let j = 0; j < response.embedding.length; j++) {\n if (typeof response.embedding[j] !== \"number\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `embedding[${j}] is not a number`,\n });\n break; // one error is enough\n }\n }\n }\n\n // Audio response checks — validate object-form audio\n if (isAudioResponse(response) && typeof response.audio === \"object\") {\n const audioObj = response.audio;\n if (typeof audioObj.b64Json !== \"string\" || audioObj.b64Json === \"\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"audio.b64Json must be a non-empty string\",\n });\n }\n if (audioObj.contentType !== undefined && typeof audioObj.contentType !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `audio.contentType must be a string, got ${typeof audioObj.contentType}`,\n });\n }\n }\n\n // Validate ResponseOverrides fields\n if (\n isTextResponse(response) ||\n isToolCallResponse(response) ||\n isContentWithToolCallsResponse(response)\n ) {\n const r = response as ResponseOverrides;\n if (r.id !== undefined && typeof r.id !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"id\" must be a string, got ${typeof r.id}`,\n });\n }\n if (r.created !== undefined && (typeof r.created !== \"number\" || r.created < 0)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"created\" must be a non-negative number`,\n });\n }\n if (r.model !== undefined && typeof r.model !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"model\" must be a string, got ${typeof r.model}`,\n });\n }\n if (r.finishReason !== undefined && typeof r.finishReason !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"finishReason\" must be a string, got ${typeof r.finishReason}`,\n });\n }\n if (r.role !== undefined && typeof r.role !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"role\" must be a string, got ${typeof r.role}`,\n });\n }\n if (r.systemFingerprint !== undefined && typeof r.systemFingerprint !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"systemFingerprint\" must be a string, got ${typeof r.systemFingerprint}`,\n });\n }\n if (r.usage !== undefined) {\n if (typeof r.usage !== \"object\" || r.usage === null || Array.isArray(r.usage)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"usage\" must be an object`,\n });\n } else {\n // Check all known usage fields are numbers if present\n for (const key of Object.keys(r.usage)) {\n const val = (r.usage as Record<string, unknown>)[key];\n if (val !== undefined && typeof val !== \"number\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"usage.${key}\" must be a number, got ${typeof val}`,\n });\n }\n }\n }\n }\n }\n } // end: skip response-shape validation for function responses\n\n // Numeric sanity checks\n if (f.latency !== undefined && f.latency < 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"latency must be >= 0\",\n });\n }\n if (f.chunkSize !== undefined && f.chunkSize < 1) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chunkSize must be >= 1\",\n });\n }\n if (f.truncateAfterChunks !== undefined && f.truncateAfterChunks < 1) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"truncateAfterChunks must be >= 1\",\n });\n }\n if (f.disconnectAfterMs !== undefined && f.disconnectAfterMs < 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"disconnectAfterMs must be >= 0\",\n });\n }\n if (f.streamingProfile !== undefined) {\n const sp = f.streamingProfile;\n if (sp.ttft !== undefined && sp.ttft < 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"streamingProfile.ttft must be >= 0\",\n });\n }\n if (sp.tps !== undefined && sp.tps <= 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"streamingProfile.tps must be > 0\",\n });\n }\n if (sp.jitter !== undefined && (sp.jitter < 0 || sp.jitter > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"streamingProfile.jitter must be between 0 and 1\",\n });\n }\n }\n if (f.chaos !== undefined) {\n const ch = f.chaos;\n if (ch.dropRate !== undefined && (ch.dropRate < 0 || ch.dropRate > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chaos.dropRate must be between 0 and 1\",\n });\n }\n if (ch.malformedRate !== undefined && (ch.malformedRate < 0 || ch.malformedRate > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chaos.malformedRate must be between 0 and 1\",\n });\n }\n if (ch.disconnectRate !== undefined && (ch.disconnectRate < 0 || ch.disconnectRate > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chaos.disconnectRate must be between 0 and 1\",\n });\n }\n }\n\n // Match field type checks\n if (f.match.turnIndex !== undefined) {\n if (\n typeof f.match.turnIndex !== \"number\" ||\n f.match.turnIndex < 0 ||\n !Number.isInteger(f.match.turnIndex)\n ) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"match.turnIndex must be a non-negative integer\",\n });\n }\n }\n if (f.match.sequenceIndex !== undefined) {\n if (\n typeof f.match.sequenceIndex !== \"number\" ||\n f.match.sequenceIndex < 0 ||\n !Number.isInteger(f.match.sequenceIndex)\n ) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"match.sequenceIndex must be a non-negative integer\",\n });\n }\n }\n if (f.match.hasToolResult !== undefined && typeof f.match.hasToolResult !== \"boolean\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.hasToolResult must be a boolean, got ${typeof f.match.hasToolResult}`,\n });\n }\n if (f.match.toolResultContains !== undefined) {\n if (typeof f.match.toolResultContains !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.toolResultContains must be a string, got ${typeof f.match.toolResultContains}`,\n });\n } else if (f.match.toolResultContains.length === 0) {\n // An empty substring is always contained, so the gate would silently\n // act as \"last message is any tool result\" — reject it as an authoring\n // mistake rather than let it shadow later fixtures.\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"match.toolResultContains must be a non-empty string\",\n });\n }\n }\n if (f.match.systemMessage !== undefined) {\n const sm = f.match.systemMessage;\n if (typeof sm === \"string\") {\n // ok\n } else if (Array.isArray(sm)) {\n if (sm.length === 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.systemMessage array must contain at least one substring`,\n });\n } else {\n for (let j = 0; j < sm.length; j++) {\n if (typeof sm[j] !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.systemMessage[${j}] must be a string, got ${typeof sm[j]}`,\n });\n }\n }\n }\n } else {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.systemMessage must be a string or string[], got ${typeof sm}`,\n });\n }\n }\n if (f.match.context !== undefined && typeof f.match.context !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.context must be a string, got ${typeof f.match.context}`,\n });\n }\n\n // --- Warning checks ---\n\n // Duplicate userMessage shadowing — two fixtures are only genuine\n // duplicates when they would match the SAME requests, so the dedup key must\n // include EVERY match discriminator the router (matchFixtureDiagnostic in\n // router.ts) actually gates on: userMessage, systemMessage, inputText,\n // toolCallId, toolResultContains, toolName, model, responseFormat, endpoint,\n // context, sequenceIndex, turnIndex, and hasToolResult. Omitting any of these\n // (the old key only carried turnIndex/hasToolResult/toolResultContains/\n // sequenceIndex/context) flags two legitimately-distinct fixtures — e.g. two\n // that differ ONLY in toolCallId or model — as false duplicates.\n //\n // `predicate` is a function and cannot be compared for equivalence, so it is\n // never folded into a shared key: a fixture carrying a predicate is treated\n // as unconditionally distinct (keyed by its own index) so it neither shadows\n // nor is shadowed by another fixture on the userMessage axis.\n //\n // Values are serialised kind-aware so RegExp / string[] matchers do not\n // collide (a template literal would coerce a RegExp to its source and an\n // array via join, losing the distinction) — mirroring describeMatch in\n // router.ts.\n const um = f.match.userMessage;\n if (typeof um === \"string\" && um) {\n const m = f.match;\n const dedupKey =\n m.predicate !== undefined\n ? `predicate:${i}`\n : [\n serializeMatcher(m.userMessage),\n serializeMatcher(m.systemMessage),\n serializeMatcher(m.inputText),\n m.toolCallId,\n m.toolResultContains,\n m.toolName,\n serializeMatcher(m.model),\n m.responseFormat,\n m.endpoint,\n m.context,\n m.sequenceIndex,\n m.turnIndex,\n m.hasToolResult,\n ]\n .map((v) => (v === undefined ? \"\" : String(v)))\n .join(\"|\");\n const prev = seenUserMessages.get(dedupKey);\n if (prev !== undefined) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: `duplicate userMessage '${um}' — shadows fixture ${prev}`,\n });\n } else {\n seenUserMessages.set(dedupKey, i);\n }\n }\n\n // Catch-all not in last position\n const match = f.match;\n const hasDiscriminator =\n match.endpoint !== undefined ||\n match.context !== undefined ||\n match.userMessage !== undefined ||\n match.systemMessage !== undefined ||\n match.inputText !== undefined ||\n match.responseFormat !== undefined ||\n match.toolCallId !== undefined ||\n match.toolResultContains !== undefined ||\n match.toolName !== undefined ||\n match.model !== undefined ||\n match.predicate !== undefined ||\n match.turnIndex !== undefined ||\n match.sequenceIndex !== undefined ||\n match.hasToolResult !== undefined;\n\n if (!hasDiscriminator && i < fixtures.length - 1) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: `empty match acts as catch-all but is not the last fixture — shadows fixtures ${i + 1}+`,\n });\n }\n }\n\n return results;\n}\n"],"mappings":";;;;;;;;;;AA6BA,SAAgB,kBAAkB,KAA2C;CAE3E,MAAM,WAAW,EAAE,GAAG,KAAK;AAG3B,KAAI,OAAO,SAAS,YAAY,YAAY,SAAS,YAAY,KAC/D,UAAS,UAAU,KAAK,UAAU,SAAS,QAAQ;AAIrD,KAAI,MAAM,QAAQ,SAAS,UAAU,CACnC,UAAS,YAAa,SAAS,UAA6C,KAAK,OAAO;AACtF,MAAI,OAAO,GAAG,cAAc,YAAY,GAAG,cAAc,KACvD,QAAO;GAAE,GAAG;GAAI,WAAW,KAAK,UAAU,GAAG,UAAU;GAAE;AAE3D,SAAO;GACP;AAQJ,KAAI,MAAM,QAAQ,SAAS,OAAO,CAChC,UAAS,SAAU,SAAS,OAA0C,KAAK,UAAU;AACnF,MACE,SAAS,QACT,MAAM,SAAS,cACf,OAAO,MAAM,cAAc,YAC3B,MAAM,cAAc,KAEpB,QAAO;GAAE,GAAG;GAAO,WAAW,KAAK,UAAU,MAAM,UAAU;GAAE;AAEjE,SAAO;GACP;AAGJ,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,SAAY,KAAK,OAAO,EAAE,CAAE,CAC9C,KAAK,IAAI;GAClB,MAAM,OAAO,iBAAiB,IAAI,SAAS;AAC3C,OAAI,SAAS,OACX,SAAQ,KAAK;IACX,UAAU;IACV,cAAc;IACd,SAAS,0BAA0B,GAAG,sBAAsB;IAC7D,CAAC;OAEF,kBAAiB,IAAI,UAAU,EAAE;;EAKrC,MAAM,QAAQ,EAAE;AAiBhB,MAAI,EAfF,MAAM,aAAa,UACnB,MAAM,YAAY,UAClB,MAAM,gBAAgB,UACtB,MAAM,kBAAkB,UACxB,MAAM,cAAc,UACpB,MAAM,mBAAmB,UACzB,MAAM,eAAe,UACrB,MAAM,uBAAuB,UAC7B,MAAM,aAAa,UACnB,MAAM,UAAU,UAChB,MAAM,cAAc,UACpB,MAAM,cAAc,UACpB,MAAM,kBAAkB,UACxB,MAAM,kBAAkB,WAED,IAAI,SAAS,SAAS,EAC7C,SAAQ,KAAK;GACX,UAAU;GACV,cAAc;GACd,SAAS,gFAAgF,IAAI,EAAE;GAChG,CAAC;;AAIN,QAAO"}
|
|
1
|
+
{"version":3,"file":"fixture-loader.js","names":[],"sources":["../src/fixture-loader.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type {\n Fixture,\n FixtureFile,\n FixtureFileEntry,\n FixtureFileResponse,\n FixtureResponse,\n ResponseOverrides,\n} from \"./types.js\";\nimport {\n isTextResponse,\n isToolCallResponse,\n isContentWithToolCallsResponse,\n isErrorResponse,\n isEmbeddingResponse,\n isImageResponse,\n isAudioResponse,\n isTranscriptionResponse,\n isVideoResponse,\n isJSONResponse,\n} from \"./helpers.js\";\nimport type { Logger } from \"./logger.js\";\n\n/**\n * Auto-stringify object-valued `content` and `toolCalls[].arguments` fields.\n * This lets fixture authors write plain JSON objects instead of escaped strings.\n * All other fields (including ResponseOverrides, and the ErrorResponse\n * `fallthrough` OpenRouter-failover flag) pass through unmodified via the\n * shallow clone below.\n */\nexport function normalizeResponse(raw: FixtureFileResponse): FixtureResponse {\n // Shallow-clone so we don't mutate the parsed JSON input.\n const response = { ...raw } as Record<string, unknown>;\n\n // Auto-stringify object content (e.g. structured output)\n if (typeof response.content === \"object\" && response.content !== null) {\n response.content = JSON.stringify(response.content);\n }\n\n // Auto-stringify object arguments in toolCalls\n if (Array.isArray(response.toolCalls)) {\n response.toolCalls = (response.toolCalls as Array<Record<string, unknown>>).map((tc) => {\n if (typeof tc.arguments === \"object\" && tc.arguments !== null) {\n return { ...tc, arguments: JSON.stringify(tc.arguments) };\n }\n return tc;\n });\n }\n\n // Carry the optional ordered `blocks` array through, mirroring the\n // toolCalls[].arguments idiom above: auto-stringify object `arguments` on\n // each `toolCall` block. Gated on Array.isArray so a malformed (non-array)\n // `blocks` value passes through untouched rather than crashing — downstream\n // validation/builders own shape rejection. Absent `blocks` → key absent.\n if (Array.isArray(response.blocks)) {\n response.blocks = (response.blocks as Array<Record<string, unknown>>).map((block) => {\n if (\n block != null &&\n block.type === \"toolCall\" &&\n typeof block.arguments === \"object\" &&\n block.arguments !== null\n ) {\n return { ...block, arguments: JSON.stringify(block.arguments) };\n }\n return block;\n });\n }\n\n return response as unknown as FixtureResponse;\n}\n\nexport function entryToFixture(entry: FixtureFileEntry, logger?: Logger): Fixture {\n const fixture: Fixture = {\n match: {\n userMessage: entry.match.userMessage,\n systemMessage: entry.match.systemMessage,\n inputText: entry.match.inputText,\n toolCallId: entry.match.toolCallId,\n toolResultContains: entry.match.toolResultContains,\n toolName: entry.match.toolName,\n model: entry.match.model,\n responseFormat: entry.match.responseFormat,\n endpoint: entry.match.endpoint,\n ...(entry.match.sequenceIndex !== undefined && { sequenceIndex: entry.match.sequenceIndex }),\n ...(entry.match.turnIndex !== undefined && {\n turnIndex: entry.match.turnIndex,\n }),\n ...(entry.match.hasToolResult !== undefined && {\n hasToolResult: entry.match.hasToolResult,\n }),\n ...(entry.match.context !== undefined && { context: entry.match.context }),\n },\n response: normalizeResponse(entry.response),\n ...(entry.latency !== undefined && { latency: entry.latency }),\n ...(entry.chunkSize !== undefined && { chunkSize: entry.chunkSize }),\n ...(entry.truncateAfterChunks !== undefined && {\n truncateAfterChunks: entry.truncateAfterChunks,\n }),\n ...(entry.disconnectAfterMs !== undefined && { disconnectAfterMs: entry.disconnectAfterMs }),\n ...(entry.streamingProfile !== undefined && { streamingProfile: entry.streamingProfile }),\n ...(entry.recordedTimings !== undefined && { recordedTimings: entry.recordedTimings }),\n ...(entry.replaySpeed != null && { replaySpeed: entry.replaySpeed }),\n ...(entry.chaos !== undefined && { chaos: entry.chaos }),\n ...(entry.openRouterProcessing !== undefined && {\n openRouterProcessing: entry.openRouterProcessing,\n }),\n ...(entry.metadata !== undefined && { metadata: entry.metadata }),\n };\n\n // Sanitize recordedTimings to guard against NaN or negative values that\n // would silently degrade replay timing calculations.\n if (fixture.recordedTimings) {\n const rt = fixture.recordedTimings;\n if (!Number.isFinite(rt.ttftMs) || rt.ttftMs < 0) rt.ttftMs = 0;\n rt.interChunkDelaysMs = Array.isArray(rt.interChunkDelaysMs)\n ? rt.interChunkDelaysMs.filter((d) => Number.isFinite(d) && d >= 0)\n : [];\n if (!Number.isFinite(rt.totalDurationMs) || rt.totalDurationMs < 0) rt.totalDurationMs = 0;\n }\n\n if (fixture.replaySpeed != null && fixture.replaySpeed <= 0) {\n logger?.warn(`Fixture replaySpeed must be positive, got ${fixture.replaySpeed}. Ignoring.`);\n delete fixture.replaySpeed;\n }\n\n return fixture;\n}\n\n/**\n * Serialise a match value (string | string[] | RegExp | undefined) into a\n * dedup-key fragment that is kind-aware, so a string, a RegExp with the same\n * source, and an array containing that string do not collide. A plain template\n * literal would coerce `/foo/` and `\"foo\"` to the same text and join `[\"foo\"]`\n * to `\"foo\"`, wrongly deduping fixtures that the router would treat as distinct.\n * Used by the duplicate-userMessage dedup key in validateFixtures.\n */\nfunction serializeMatcher(value: string | string[] | RegExp | undefined): string {\n if (value === undefined) return \"\";\n if (value instanceof RegExp) return `re:${value.source}\u0000${value.flags}`;\n if (Array.isArray(value)) return `arr:${JSON.stringify(value)}`;\n return `str:${value}`;\n}\n\n// Logging helper — uses logger if provided, falls back to console.warn.\nfunction warn(logger: Logger | undefined, msg: string, ...rest: unknown[]): void {\n if (logger) {\n logger.warn(msg, ...rest);\n } else {\n console.warn(`[fixture-loader] ${msg}`, ...rest);\n }\n}\n\nexport function loadFixtureFile(filePath: string, logger?: Logger): Fixture[] {\n let raw: string;\n try {\n raw = readFileSync(filePath, \"utf-8\");\n } catch (err) {\n warn(logger, `Could not read file ${filePath}:`, err);\n return [];\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n warn(logger, `Invalid JSON in ${filePath}:`, err);\n return [];\n }\n\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n !Array.isArray((parsed as FixtureFile).fixtures)\n ) {\n warn(logger, `Missing or invalid \"fixtures\" array in ${filePath}`);\n return [];\n }\n\n return (parsed as FixtureFile).fixtures.map((e) => entryToFixture(e, logger));\n}\n\nexport function loadFixturesFromDir(dirPath: string, logger?: Logger): Fixture[] {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n warn(logger, `Could not read directory ${dirPath}:`, err);\n return [];\n }\n\n const jsonFiles: string[] = [];\n const subdirs: string[] = [];\n for (const name of entries) {\n const fullPath = join(dirPath, name);\n try {\n if (statSync(fullPath).isDirectory()) {\n subdirs.push(name);\n continue;\n }\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\") {\n warn(logger, `Could not stat ${fullPath}:`, err);\n }\n continue;\n }\n if (name.endsWith(\".json\")) {\n jsonFiles.push(name);\n }\n }\n jsonFiles.sort();\n\n const fixtures: Fixture[] = [];\n for (const name of jsonFiles) {\n const filePath = join(dirPath, name);\n fixtures.push(...loadFixtureFile(filePath, logger));\n }\n\n // Recurse into all subdirectories (full depth) to support nested layouts\n // like showcase/aimock/d6/<integration>/<feature>.json.\n subdirs.sort();\n for (const sub of subdirs) {\n fixtures.push(...loadFixturesFromDir(join(dirPath, sub), logger));\n }\n\n return fixtures;\n}\n\n// ---------------------------------------------------------------------------\n// Fixture validation\n// ---------------------------------------------------------------------------\n\nexport interface ValidationResult {\n severity: \"error\" | \"warning\";\n fixtureIndex: number;\n message: string;\n}\n\nfunction validateReasoning(\n response: { reasoning?: unknown },\n fixtureIndex: number,\n results: ValidationResult[],\n): void {\n if (response.reasoning !== undefined) {\n if (typeof response.reasoning !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: \"reasoning must be a string\",\n });\n } else if (response.reasoning === \"\") {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message: \"reasoning is empty string — no reasoning events will be emitted\",\n });\n }\n }\n}\n\nfunction validateWebSearches(\n response: { webSearches?: unknown },\n fixtureIndex: number,\n results: ValidationResult[],\n): void {\n if (response.webSearches !== undefined) {\n if (!Array.isArray(response.webSearches)) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: \"webSearches must be an array of strings\",\n });\n } else if (response.webSearches.length === 0) {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message: \"webSearches is empty array — no web search events will be emitted\",\n });\n } else {\n for (let j = 0; j < response.webSearches.length; j++) {\n if (typeof response.webSearches[j] !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `webSearches[${j}] is not a string`,\n });\n break;\n }\n if (response.webSearches[j] === \"\") {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message: `webSearches[${j}] is empty string`,\n });\n }\n }\n }\n }\n}\n\nfunction validateBlocks(\n response: { blocks?: unknown; content?: unknown; toolCalls?: unknown },\n fixtureIndex: number,\n results: ValidationResult[],\n): void {\n if (response.blocks === undefined) return;\n\n // Mirrors the toolCalls checks: reject malformed `blocks` at LOAD time so a\n // bad blocks array never reaches the dispatch/builder (where\n // resolveFixtureBlocks throws AFTER the journal has already recorded\n // status:200, yielding a journal-200/client-500 mismatch). #274 F3+F8.\n if (!Array.isArray(response.blocks)) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks must be an array, got ${typeof response.blocks}`,\n });\n return;\n }\n\n for (let j = 0; j < response.blocks.length; j++) {\n const block = response.blocks[j] as Record<string, unknown> | null | undefined;\n if (typeof block !== \"object\" || block === null) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}] must be an object`,\n });\n continue;\n }\n if (block.type !== \"text\" && block.type !== \"toolCall\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].type must be \"text\" or \"toolCall\", got ${JSON.stringify(block.type)}`,\n });\n continue;\n }\n if (block.type === \"text\") {\n if (typeof block.text !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].text must be a string, got ${typeof block.text}`,\n });\n } else if (block.text === \"\") {\n // Mirror the content/toolCalls \"empty string\" rejection: an empty-text\n // block produces a meaningless/spurious wire chunk on replay.\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].text is empty string`,\n });\n }\n } else {\n // toolCall block — mirror toolCalls[] name + arguments checks.\n if (typeof block.name !== \"string\" || block.name === \"\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].name must be a non-empty string`,\n });\n }\n // `arguments` is JSON-string in runtime form (normalizeResponse already\n // stringified object/array args); accept a valid-JSON string or an object.\n if (typeof block.arguments === \"string\") {\n try {\n JSON.parse(block.arguments);\n } catch {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].arguments is not valid JSON: ${block.arguments}`,\n });\n }\n } else if (typeof block.arguments !== \"object\" || block.arguments === null) {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].arguments must be a JSON string or object, got ${typeof block.arguments}`,\n });\n }\n if (block.id !== undefined && typeof block.id !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex,\n message: `blocks[${j}].id must be a string, got ${typeof block.id}`,\n });\n }\n }\n }\n\n // blocks-vs-content/toolCalls divergence (#274 P2). When a fixture carries\n // BOTH `blocks` AND legacy `content`/`toolCalls` (allowed but unusual now\n // that blocks-only is first-class), builders stream `blocks` and IGNORE the\n // redundant `content`/`toolCalls`. If those disagree it is a silent footgun,\n // so WARN (not a hard error). Stay silent on the clean blocks-only path\n // (neither legacy field present) — that is the intended shape.\n const hasLegacyContent = typeof response.content === \"string\";\n const hasLegacyToolCalls = Array.isArray(response.toolCalls);\n if ((hasLegacyContent || hasLegacyToolCalls) && Array.isArray(response.blocks)) {\n const textBlocks = response.blocks.filter(\n (b): b is { type: \"text\"; text: string } =>\n b != null &&\n typeof b === \"object\" &&\n (b as { type?: unknown }).type === \"text\" &&\n typeof (b as { text?: unknown }).text === \"string\",\n );\n const toolCallBlockNames = response.blocks\n .filter(\n (b): b is { type: \"toolCall\"; name: string } =>\n b != null &&\n typeof b === \"object\" &&\n (b as { type?: unknown }).type === \"toolCall\" &&\n typeof (b as { name?: unknown }).name === \"string\",\n )\n .map((b) => b.name);\n\n // Text divergence: blocks' concatenated text vs legacy `content`.\n if (hasLegacyContent) {\n const blocksText = textBlocks.map((b) => b.text).join(\"\");\n if (blocksText !== response.content) {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message:\n \"blocks text diverges from content — builders stream blocks and ignore the redundant content field\",\n });\n }\n }\n\n // ToolCall divergence: blocks' ordered toolCall names vs legacy `toolCalls`.\n if (hasLegacyToolCalls) {\n const legacyNames = (response.toolCalls as Array<{ name?: unknown }>).map((tc) =>\n typeof tc?.name === \"string\" ? tc.name : undefined,\n );\n const sameNames =\n legacyNames.length === toolCallBlockNames.length &&\n legacyNames.every((n, k) => n === toolCallBlockNames[k]);\n if (!sameNames) {\n results.push({\n severity: \"warning\",\n fixtureIndex,\n message:\n \"blocks toolCalls diverge from toolCalls — builders stream blocks and ignore the redundant toolCalls field\",\n });\n }\n }\n }\n}\n\nexport function validateFixtures(fixtures: Fixture[]): ValidationResult[] {\n const results: ValidationResult[] = [];\n\n const seenUserMessages = new Map<string, number>();\n\n for (let i = 0; i < fixtures.length; i++) {\n const f = fixtures[i];\n const response = f.response;\n\n // Skip response-shape validation for function responses — they are\n // evaluated at runtime so we cannot statically inspect them.\n if (typeof response === \"function\") {\n // Still validate match fields and numeric options below.\n } else {\n // --- Error checks ---\n\n // Response type recognition\n // Note: isContentWithToolCallsResponse must be checked before isTextResponse\n // and isToolCallResponse since it is a structural superset of both.\n if (\n !isContentWithToolCallsResponse(response) &&\n !isTextResponse(response) &&\n !isToolCallResponse(response) &&\n !isErrorResponse(response) &&\n !isEmbeddingResponse(response) &&\n !isImageResponse(response) &&\n !isAudioResponse(response) &&\n !isTranscriptionResponse(response) &&\n !isVideoResponse(response) &&\n !isJSONResponse(response)\n ) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message:\n \"response is not a recognized type (must have content, toolCalls, error, embedding, image, audio, transcription, video, or json)\",\n });\n }\n\n // When a non-empty ordered `blocks` array is present, the builders stream\n // `blocks` and IGNORE the legacy `content` mirror (see validateBlocks's\n // divergence note + isContentWithToolCallsResponse's BLOCKS-ONLY clause).\n // So an empty-string `content` is harmless in that case and must NOT raise\n // the \"content is empty string\" hard error. Fixtures WITHOUT blocks keep\n // the error (an empty content with no blocks produces no output).\n const hasNonEmptyBlocks =\n Array.isArray((response as { blocks?: unknown }).blocks) &&\n (response as { blocks: unknown[] }).blocks.length > 0;\n\n // Text response checks\n if (isTextResponse(response)) {\n if (response.content === \"\" && !hasNonEmptyBlocks) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"content is empty string\",\n });\n }\n validateReasoning(response, i, results);\n validateWebSearches(response, i, results);\n }\n\n // ContentWithToolCalls response checks\n if (isContentWithToolCallsResponse(response)) {\n // The guard now also matches a BLOCKS-ONLY fixture (non-empty `blocks`,\n // no `content`/`toolCalls`). For that shape the content/toolCalls checks\n // below don't apply (and `content`/`toolCalls` are undefined) — the\n // ordered `blocks` array is validated separately by `validateBlocks`\n // immediately after this block. So gate the legacy field checks on the\n // fields actually being present, mirroring the builders' branch-on-blocks.\n if (typeof response.content === \"string\") {\n if (response.content === \"\" && !hasNonEmptyBlocks) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"content is empty string\",\n });\n }\n }\n if (Array.isArray(response.toolCalls)) {\n if (response.toolCalls.length === 0) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: \"toolCalls array is empty — fixture will never produce tool calls\",\n });\n }\n for (let j = 0; j < response.toolCalls.length; j++) {\n const tc = response.toolCalls[j];\n if (!tc.name) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].name is empty`,\n });\n }\n try {\n JSON.parse(tc.arguments);\n } catch {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].arguments is not valid JSON: ${tc.arguments}`,\n });\n }\n }\n }\n validateReasoning(response, i, results);\n validateWebSearches(response, i, results);\n }\n\n // Optional ordered `blocks` checks — validated whenever present on the\n // response, regardless of which content/toolCalls guard matched, so a\n // malformed blocks array is rejected at LOAD rather than at dispatch.\n validateBlocks(\n response as { blocks?: unknown; content?: unknown; toolCalls?: unknown },\n i,\n results,\n );\n\n // Tool call response checks\n if (isToolCallResponse(response)) {\n if (response.toolCalls.length === 0) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: \"toolCalls array is empty — fixture will never produce tool calls\",\n });\n }\n for (let j = 0; j < response.toolCalls.length; j++) {\n const tc = response.toolCalls[j];\n if (!tc.name) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].name is empty`,\n });\n }\n try {\n JSON.parse(tc.arguments);\n } catch {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `toolCalls[${j}].arguments is not valid JSON: ${tc.arguments}`,\n });\n }\n }\n validateWebSearches(response, i, results);\n }\n\n // Error response checks\n if (isErrorResponse(response)) {\n if (!response.error.message) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"error.message is empty\",\n });\n }\n if (response.status !== undefined && (response.status < 100 || response.status > 599)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `error status ${response.status} is not a valid HTTP status code`,\n });\n }\n // `fallthrough` gates OpenRouter `models[]` failover and is read as\n // `!== false`, so a non-boolean (`\"false\"`, 0, null) would silently\n // fall through — the OPPOSITE of the intended terminal behavior. Reject\n // it at load so the fail-closed half cannot quietly fail open.\n if (response.fallthrough !== undefined && typeof response.fallthrough !== \"boolean\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `error.fallthrough must be a boolean, got ${typeof response.fallthrough}`,\n });\n }\n }\n\n // Embedding response checks\n if (isEmbeddingResponse(response)) {\n if (response.embedding.length === 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"embedding array is empty\",\n });\n }\n for (let j = 0; j < response.embedding.length; j++) {\n if (typeof response.embedding[j] !== \"number\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `embedding[${j}] is not a number`,\n });\n break; // one error is enough\n }\n }\n }\n\n // Audio response checks — validate object-form audio\n if (isAudioResponse(response) && typeof response.audio === \"object\") {\n const audioObj = response.audio;\n if (typeof audioObj.b64Json !== \"string\" || audioObj.b64Json === \"\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"audio.b64Json must be a non-empty string\",\n });\n }\n if (audioObj.contentType !== undefined && typeof audioObj.contentType !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `audio.contentType must be a string, got ${typeof audioObj.contentType}`,\n });\n }\n }\n\n // Validate ResponseOverrides fields\n if (\n isTextResponse(response) ||\n isToolCallResponse(response) ||\n isContentWithToolCallsResponse(response)\n ) {\n const r = response as ResponseOverrides;\n if (r.id !== undefined && typeof r.id !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"id\" must be a string, got ${typeof r.id}`,\n });\n }\n if (r.created !== undefined && (typeof r.created !== \"number\" || r.created < 0)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"created\" must be a non-negative number`,\n });\n }\n if (r.model !== undefined && typeof r.model !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"model\" must be a string, got ${typeof r.model}`,\n });\n }\n if (r.finishReason !== undefined && typeof r.finishReason !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"finishReason\" must be a string, got ${typeof r.finishReason}`,\n });\n }\n if (r.role !== undefined && typeof r.role !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"role\" must be a string, got ${typeof r.role}`,\n });\n }\n if (r.systemFingerprint !== undefined && typeof r.systemFingerprint !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"systemFingerprint\" must be a string, got ${typeof r.systemFingerprint}`,\n });\n }\n if (r.usage !== undefined) {\n if (typeof r.usage !== \"object\" || r.usage === null || Array.isArray(r.usage)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"usage\" must be an object`,\n });\n } else {\n // Numeric token fields must be numbers, but the OpenRouter cost\n // sub-fields carry non-numeric shapes (see ResponseOverrides.usage\n // in types.ts): cost_details / prompt_tokens_details /\n // completion_tokens_details are objects and is_byok is a boolean.\n // Validate each per its documented type so cost-scripting fixtures\n // are not rejected with a misleading \"must be a number\" error.\n // Known numeric inner scalars per object field (see\n // OpenRouterUsageExtras in types.ts). Validating only these keeps\n // the index-signature ([key: string]: unknown) escape hatch open\n // for forward-compat fields while still catching malformed values\n // on the documented ones — otherwise a bad inner scalar (e.g.\n // cost_details.upstream_inference_cost: \"abc\") passes load-time\n // validation and only blows up at replay in the canonical SDK.\n const numericInnerFields: Record<string, readonly string[]> = {\n cost_details: [\n \"upstream_inference_cost\",\n \"upstream_inference_prompt_cost\",\n \"upstream_inference_completions_cost\",\n ],\n prompt_tokens_details: [\"cached_tokens\", \"cache_write_tokens\", \"audio_tokens\"],\n completion_tokens_details: [\"reasoning_tokens\"],\n };\n const objectUsageFields = new Set(Object.keys(numericInnerFields));\n for (const key of Object.keys(r.usage)) {\n const val = (r.usage as Record<string, unknown>)[key];\n if (val === undefined) continue;\n if (objectUsageFields.has(key)) {\n if (typeof val !== \"object\" || val === null || Array.isArray(val)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"usage.${key}\" must be an object, got ${\n Array.isArray(val) ? \"array\" : typeof val\n }`,\n });\n } else {\n // Type-check the documented inner scalars; each is optional\n // (required-if-present), so only validate keys that are set.\n const inner = val as Record<string, unknown>;\n for (const innerKey of numericInnerFields[key]) {\n const innerVal = inner[innerKey];\n if (innerVal !== undefined && typeof innerVal !== \"number\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"usage.${key}.${innerKey}\" must be a number, got ${typeof innerVal}`,\n });\n }\n }\n }\n } else if (key === \"is_byok\") {\n if (typeof val !== \"boolean\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"usage.is_byok\" must be a boolean, got ${typeof val}`,\n });\n }\n } else if (typeof val !== \"number\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `override \"usage.${key}\" must be a number, got ${typeof val}`,\n });\n }\n }\n }\n }\n }\n } // end: skip response-shape validation for function responses\n\n // Numeric sanity checks\n if (f.latency !== undefined && f.latency < 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"latency must be >= 0\",\n });\n }\n if (f.chunkSize !== undefined && f.chunkSize < 1) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chunkSize must be >= 1\",\n });\n }\n if (f.truncateAfterChunks !== undefined && f.truncateAfterChunks < 1) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"truncateAfterChunks must be >= 1\",\n });\n }\n if (f.disconnectAfterMs !== undefined && f.disconnectAfterMs < 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"disconnectAfterMs must be >= 0\",\n });\n }\n if (f.streamingProfile !== undefined) {\n const sp = f.streamingProfile;\n if (sp.ttft !== undefined && sp.ttft < 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"streamingProfile.ttft must be >= 0\",\n });\n }\n if (sp.tps !== undefined && sp.tps <= 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"streamingProfile.tps must be > 0\",\n });\n }\n if (sp.jitter !== undefined && (sp.jitter < 0 || sp.jitter > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"streamingProfile.jitter must be between 0 and 1\",\n });\n }\n }\n if (f.chaos !== undefined) {\n const ch = f.chaos;\n if (ch.dropRate !== undefined && (ch.dropRate < 0 || ch.dropRate > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chaos.dropRate must be between 0 and 1\",\n });\n }\n if (ch.malformedRate !== undefined && (ch.malformedRate < 0 || ch.malformedRate > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chaos.malformedRate must be between 0 and 1\",\n });\n }\n if (ch.disconnectRate !== undefined && (ch.disconnectRate < 0 || ch.disconnectRate > 1)) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"chaos.disconnectRate must be between 0 and 1\",\n });\n }\n }\n\n // Match field type checks\n if (f.match.turnIndex !== undefined) {\n if (\n typeof f.match.turnIndex !== \"number\" ||\n f.match.turnIndex < 0 ||\n !Number.isInteger(f.match.turnIndex)\n ) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"match.turnIndex must be a non-negative integer\",\n });\n }\n }\n if (f.match.sequenceIndex !== undefined) {\n if (\n typeof f.match.sequenceIndex !== \"number\" ||\n f.match.sequenceIndex < 0 ||\n !Number.isInteger(f.match.sequenceIndex)\n ) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"match.sequenceIndex must be a non-negative integer\",\n });\n }\n }\n if (f.match.hasToolResult !== undefined && typeof f.match.hasToolResult !== \"boolean\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.hasToolResult must be a boolean, got ${typeof f.match.hasToolResult}`,\n });\n }\n if (f.match.toolResultContains !== undefined) {\n if (typeof f.match.toolResultContains !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.toolResultContains must be a string, got ${typeof f.match.toolResultContains}`,\n });\n } else if (f.match.toolResultContains.length === 0) {\n // An empty substring is always contained, so the gate would silently\n // act as \"last message is any tool result\" — reject it as an authoring\n // mistake rather than let it shadow later fixtures.\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: \"match.toolResultContains must be a non-empty string\",\n });\n }\n }\n if (f.match.systemMessage !== undefined) {\n const sm = f.match.systemMessage;\n if (typeof sm === \"string\") {\n // ok\n } else if (Array.isArray(sm)) {\n if (sm.length === 0) {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.systemMessage array must contain at least one substring`,\n });\n } else {\n for (let j = 0; j < sm.length; j++) {\n if (typeof sm[j] !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.systemMessage[${j}] must be a string, got ${typeof sm[j]}`,\n });\n }\n }\n }\n } else {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.systemMessage must be a string or string[], got ${typeof sm}`,\n });\n }\n }\n if (f.match.context !== undefined && typeof f.match.context !== \"string\") {\n results.push({\n severity: \"error\",\n fixtureIndex: i,\n message: `match.context must be a string, got ${typeof f.match.context}`,\n });\n }\n\n // --- Warning checks ---\n\n // Duplicate userMessage shadowing — two fixtures are only genuine\n // duplicates when they would match the SAME requests, so the dedup key must\n // include EVERY match discriminator the router (matchFixtureDiagnostic in\n // router.ts) actually gates on: userMessage, systemMessage, inputText,\n // toolCallId, toolResultContains, toolName, model, responseFormat, endpoint,\n // context, sequenceIndex, turnIndex, and hasToolResult. Omitting any of these\n // (the old key only carried turnIndex/hasToolResult/toolResultContains/\n // sequenceIndex/context) flags two legitimately-distinct fixtures — e.g. two\n // that differ ONLY in toolCallId or model — as false duplicates.\n //\n // `predicate` is a function and cannot be compared for equivalence, so it is\n // never folded into a shared key: a fixture carrying a predicate is treated\n // as unconditionally distinct (keyed by its own index) so it neither shadows\n // nor is shadowed by another fixture on the userMessage axis.\n //\n // Values are serialised kind-aware so RegExp / string[] matchers do not\n // collide (a template literal would coerce a RegExp to its source and an\n // array via join, losing the distinction) — mirroring describeMatch in\n // router.ts.\n const um = f.match.userMessage;\n if (typeof um === \"string\" && um) {\n const m = f.match;\n const dedupKey =\n m.predicate !== undefined\n ? `predicate:${i}`\n : [\n serializeMatcher(m.userMessage),\n serializeMatcher(m.systemMessage),\n serializeMatcher(m.inputText),\n m.toolCallId,\n m.toolResultContains,\n m.toolName,\n serializeMatcher(m.model),\n m.responseFormat,\n m.endpoint,\n m.context,\n m.sequenceIndex,\n m.turnIndex,\n m.hasToolResult,\n ]\n .map((v) => (v === undefined ? \"\" : String(v)))\n .join(\"|\");\n const prev = seenUserMessages.get(dedupKey);\n if (prev !== undefined) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: `duplicate userMessage '${um}' — shadows fixture ${prev}`,\n });\n } else {\n seenUserMessages.set(dedupKey, i);\n }\n }\n\n // Catch-all not in last position\n const match = f.match;\n const hasDiscriminator =\n match.endpoint !== undefined ||\n match.context !== undefined ||\n match.userMessage !== undefined ||\n match.systemMessage !== undefined ||\n match.inputText !== undefined ||\n match.responseFormat !== undefined ||\n match.toolCallId !== undefined ||\n match.toolResultContains !== undefined ||\n match.toolName !== undefined ||\n match.model !== undefined ||\n match.predicate !== undefined ||\n match.turnIndex !== undefined ||\n match.sequenceIndex !== undefined ||\n match.hasToolResult !== undefined;\n\n if (!hasDiscriminator && i < fixtures.length - 1) {\n results.push({\n severity: \"warning\",\n fixtureIndex: i,\n message: `empty match acts as catch-all but is not the last fixture — shadows fixtures ${i + 1}+`,\n });\n }\n }\n\n return results;\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,SAAgB,kBAAkB,KAA2C;CAE3E,MAAM,WAA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AAO,YAAY,IAAI;GAChC,MAAM,IAAI,EAAE;GACZ,MAAM,WACJ,EAAE,cAAc,SACZ,aAAa,MACb;IACE,iBAAiB,EAAE,YAAY;IAC/B,iBAAiB,EAAE,cAAc;IACjC,iBAAiB,EAAE,UAAU;IAC7B,EAAE;IACF,EAAE;IACF,EAAE;IACF,iBAAiB,EAAE,MAAM;IACzB,EAAE;IACF,EAAE;IACF,EAAE;IACF,EAAE;IACF,EAAE;IACF,EAAE;IACH,CACE,KAAK,MAAO,MAAM,SAAY,KAAK,OAAO,EAAE,CAAE,CAC9C,KAAK,IAAI;GAClB,MAAM,OAAO,iBAAiB,IAAI,SAAS;AAC3C,OAAI,SAAS,OACX,SAAQ,KAAK;IACX,UAAU;IACV,cAAc;IACd,SAAS,0BAA0B,GAAG,sBAAsB;IAC7D,CAAC;OAEF,kBAAiB,IAAI,UAAU,EAAE;;EAKrC,MAAM,QAAQ,EAAE;AAiBhB,MAAI,EAfF,MAAM,aAAa,UACnB,MAAM,YAAY,UAClB,MAAM,gBAAgB,UACtB,MAAM,kBAAkB,UACxB,MAAM,cAAc,UACpB,MAAM,mBAAmB,UACzB,MAAM,eAAe,UACrB,MAAM,uBAAuB,UAC7B,MAAM,aAAa,UACnB,MAAM,UAAU,UAChB,MAAM,cAAc,UACpB,MAAM,cAAc,UACpB,MAAM,kBAAkB,UACxB,MAAM,kBAAkB,WAED,IAAI,SAAS,SAAS,EAC7C,SAAQ,KAAK;GACX,UAAU;GACV,cAAc;GACd,SAAS,gFAAgF,IAAI,EAAE;GAChG,CAAC;;AAIN,QAAO"}
|
package/dist/grok-video.cjs
CHANGED
|
@@ -505,9 +505,11 @@ async function proxyGrokVideoSubmit(args) {
|
|
|
505
505
|
const worldGeneration = jobs.generation;
|
|
506
506
|
let fetched;
|
|
507
507
|
try {
|
|
508
|
+
const headers = require_recorder.prepareEgressHeaders(req, submitUrl, "grok", record.providerKeys?.grok);
|
|
509
|
+
if (!headers) return proxyError("No configured provider credential");
|
|
508
510
|
const upstreamRes = await fetch(submitUrl, {
|
|
509
511
|
method: "POST",
|
|
510
|
-
headers
|
|
512
|
+
headers,
|
|
511
513
|
body: raw,
|
|
512
514
|
signal: require_video_proxy_shared.upstreamTimeoutSignal(record)
|
|
513
515
|
});
|
|
@@ -626,8 +628,13 @@ async function proxyGrokVideoRecordPoll(args) {
|
|
|
626
628
|
}
|
|
627
629
|
let fetched;
|
|
628
630
|
try {
|
|
631
|
+
const headers = require_recorder.prepareEgressHeaders(req, new URL(job.upstreamPollingUrl), "grok", record.providerKeys?.grok);
|
|
632
|
+
if (!headers) {
|
|
633
|
+
proxyError("No configured provider credential");
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
629
636
|
const upstreamRes = await fetch(job.upstreamPollingUrl, {
|
|
630
|
-
headers
|
|
637
|
+
headers,
|
|
631
638
|
signal: require_video_proxy_shared.upstreamTimeoutSignal(record)
|
|
632
639
|
});
|
|
633
640
|
fetched = {
|
package/dist/grok-video.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grok-video.cjs","names":["flattenHeaders","getContext","getTestId","matchFixtureDiagnostic","applyChaos","resolveStrictMode","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","resolveResponse","isErrorResponse","serializeErrorResponse","isVideoResponse","crypto","resolveProgression","testIdSuffix","resolveUpstreamUrl","buildForwardHeaders","upstreamTimeoutSignal","readEnvelopeText","buildFixtureMatch","persistFixture","sanitizeHeaderValue"],"sources":["../src/grok-video.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport crypto from \"node:crypto\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordConfig,\n VideoResponse,\n} from \"./types.js\";\nimport {\n isVideoResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { resolveProgression } from \"./fal.js\";\nimport {\n buildFixtureMatch,\n buildForwardHeaders,\n persistFixture,\n sanitizeHeaderValue,\n} from \"./recorder.js\";\nimport { resolveUpstreamUrl } from \"./url.js\";\nimport { handleVideoStatus, type VideoStateMap } from \"./video.js\";\nimport { readEnvelopeText, testIdSuffix, upstreamTimeoutSignal } from \"./video-proxy-shared.js\";\n\n/**\n * xAI Grok Imagine async video lifecycle mock. Submit\n * `POST /v1/videos/generations` returns `{ request_id }`; status\n * `GET /v1/videos/{request_id}` polls `pending → done | failed | expired` with\n * a synthesized `progress`. Multipart submits are rejected with HTTP 400\n * BEFORE body parse (the real API is JSON-only). `video.url` is served AS-IS —\n * aimock does NOT proxy or capture video bytes. With `record.providers.grok`\n * configured an unmatched submit becomes a live interactive proxy (submit +\n * poll forwarded 1:1, eager fixture capture of url/duration/cost on terminal\n * status). Strict mode wins.\n *\n * Grok status shares the `/v1/videos/{id}` path with Sora: the dispatch does a\n * job-map-first lookup and falls through to the UNCHANGED Sora\n * `handleVideoStatus` on a miss (disjoint id namespaces → unambiguous).\n *\n * cost_in_usd_ticks ↔ USD: USD = ticks / 1e10 (ASSUMED). Record persists USD in\n * `video.cost`; replay reconstructs ticks = round(cost * 1e10).\n */\n\ninterface GrokVideoRequest {\n model?: string;\n prompt?: string;\n [key: string]: unknown;\n}\n\nconst DEFAULT_GROK_VIDEO_MODEL = \"grok-imagine-video\";\n\n// USD ←→ Grok cost_in_usd_ticks conversion (ASSUMED: 1e10 ticks per USD).\nconst GROK_USD_TICKS_PER_USD = 1e10;\n\n// Default placeholder when a completed fixture omits `video.url` — every other\n// coercion on this surface is documented; the real API always returns a url.\nconst GROK_DEFAULT_VIDEO_URL = \"https://cdn.x.ai/aimock-placeholder-video.mp4\";\n\n// ─── GrokVideoJobMap (TTL + bounded) ────────────────────────────────────────\n\nexport const GROK_VIDEO_MAX_ENTRIES = 10_000;\nconst GROK_VIDEO_TTL_MS = 3_600_000; // 1 hour\n\ntype GrokVideoStatus = \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n\ninterface GrokVideoReplayJob {\n kind: \"replay\";\n requestId: string;\n status: GrokVideoStatus;\n /** Number of status polls the caller has made against this job. */\n pollCount: number;\n /** Poll-count threshold for `pending → in_progress` transition. */\n pollsBeforeInProgress: number;\n /** Poll-count threshold for the transition to the terminal status. */\n pollsBeforeCompleted: number;\n /** The matched fixture's video object (terminal status, url, duration, cost, error). */\n video: VideoResponse[\"video\"];\n /** Latch for the empty-`error` authoring warn on failed polls (once per job). */\n emptyErrorWarned?: boolean;\n}\n\n/**\n * A job whose lifecycle is proxied live upstream (record mode, no fixture\n * matched at submit). Every client poll is forwarded 1:1 to\n * `upstreamPollingUrl`; when the upstream reports a terminal status (`done`/\n * `failed`) the entry is captured as a fixture and MUTATED into a terminal\n * GrokVideoReplayJob. `expired` (and any unrepresentable status) pass through\n * with a warn and keep proxying. Under `record.proxyOnly` nothing is ever\n * captured or mutated.\n */\ninterface GrokVideoRecordJob {\n kind: \"record\";\n /** The mock-issued requestId the client polls with. */\n requestId: string;\n /** Last upstream status relayed to the client. */\n status: GrokVideoStatus;\n /** Upstream's own request id (recorded as the fixture's video.id). */\n upstreamRequestId: string;\n /** Origin-validated absolute upstream URL proxied on every client poll. */\n upstreamPollingUrl: string;\n /** Match snapshot built at submit time (post requestTransform). */\n match: Fixture[\"match\"];\n /**\n * Set synchronously before the first await of the eager-capture sequence so\n * a concurrent terminal poll relays the upstream body instead of starting a\n * second capture/persist.\n */\n capturing?: boolean;\n}\n\nexport type GrokVideoJob = GrokVideoReplayJob | GrokVideoRecordJob;\n\ninterface GrokVideoEntry {\n job: GrokVideoJob;\n createdAt: number;\n}\n\n/**\n * Per-testId job state for the Grok video handler. Mirrors OpenRouterVideoJobMap\n * (openrouter-video.ts): lazy TTL eviction on `get`, FIFO eviction of the\n * oldest entries on `set` when over capacity, delete-before-set TTL refresh,\n * monotonic world-generation counter for reset-mid-flight detection, no\n * background sweep timer. Keys are `${testId}:${requestId}`.\n */\nexport class GrokVideoJobMap {\n private readonly entries = new Map<string, GrokVideoEntry>();\n private worldGeneration = 0;\n\n get generation(): number {\n return this.worldGeneration;\n }\n\n get(key: string): GrokVideoJob | undefined {\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n if (Date.now() - entry.createdAt > GROK_VIDEO_TTL_MS) {\n this.entries.delete(key);\n return undefined;\n }\n return entry.job;\n }\n\n set(key: string, job: GrokVideoJob): void {\n this.entries.delete(key);\n this.entries.set(key, { job, createdAt: Date.now() });\n if (this.entries.size > GROK_VIDEO_MAX_ENTRIES) {\n const excess = this.entries.size - GROK_VIDEO_MAX_ENTRIES;\n const iter = this.entries.keys();\n for (let i = 0; i < excess; i++) {\n const next = iter.next();\n if (!next.done) this.entries.delete(next.value);\n }\n }\n }\n\n delete(key: string): boolean {\n return this.entries.delete(key);\n }\n\n clear(): void {\n this.entries.clear();\n this.worldGeneration++;\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n\n// ─── Job progression ────────────────────────────────────────────────────────\n\n/**\n * Maps the fixture's terminal video status onto the job lifecycle. Anything\n * that is not \"failed\" — including a fixture authored as \"processing\" — is\n * treated as completed, since this surface always drives jobs to a terminal\n * state.\n */\nfunction terminalStatus(job: GrokVideoReplayJob): GrokVideoStatus {\n return job.video.status === \"failed\" ? \"failed\" : \"completed\";\n}\n\n/**\n * Mutates a job in place to advance its state on a status poll.\n * `pending → in_progress → completed | failed` based on poll-count thresholds.\n * No-op once terminal. The in_progress threshold is checked first so a job\n * whose thresholds are equal still spends one poll in in_progress instead of\n * jumping straight to the terminal status (fal advanceJob semantics).\n */\nfunction advanceJob(job: GrokVideoReplayJob): void {\n if (job.status === \"completed\" || job.status === \"failed\") return;\n\n job.pollCount += 1;\n if (job.status === \"pending\" && job.pollCount >= job.pollsBeforeInProgress) {\n job.status = \"in_progress\";\n } else if (job.pollCount >= job.pollsBeforeCompleted) {\n job.status = terminalStatus(job);\n }\n}\n\n/**\n * Synthesize the Grok wire `progress` (0..100) from poll-count progress toward\n * the completed threshold. A terminal-completed job is always 100 (the only way\n * to reach 100 — it is the wire signal for \"done\"). Every other state reports\n * its progress-at-failure/at-poll, capped at 99. A seed-terminal job with a\n * non-positive completion target has done zero polls toward completion, so it\n * reports 0 (a failed seed job is 0%, never 100).\n */\nfunction grokProgress(job: GrokVideoReplayJob): number {\n if (job.status === \"completed\") return 100;\n const target = job.pollsBeforeCompleted;\n if (target <= 0) return 0;\n const ratio = Math.min(1, job.pollCount / target);\n return Math.min(99, Math.round(ratio * 100));\n}\n\n/** Map the internal job status onto the Grok wire `status` token. */\nfunction grokWireStatus(status: GrokVideoStatus): \"done\" | \"failed\" | \"pending\" {\n if (status === \"completed\") return \"done\";\n if (status === \"failed\") return \"failed\";\n return \"pending\";\n}\n\n/**\n * Synthesizes a structurally valid journal body for field-validation 400s.\n * Mirrors openrouter-video's validationJournalBody: `model` stays a string and\n * `messages` is an empty array; underscore-prefixed keys are stripped so a\n * request cannot spoof handler-set discriminators.\n */\nfunction validationJournalBody(videoReq: GrokVideoRequest): ChatCompletionRequest {\n const rawModel = videoReq.model;\n const model =\n typeof rawModel === \"string\"\n ? rawModel\n : rawModel === undefined\n ? \"\"\n : JSON.stringify(rawModel);\n const sanitized = Object.fromEntries(\n Object.entries(videoReq).filter(([key]) => !key.startsWith(\"_\")),\n );\n return { ...sanitized, model, messages: [] };\n}\n\n// ─── POST /v1/videos/generations — submit ────────────────────────────────────\n\nexport async function handleGrokVideoCreate(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n jobs: GrokVideoJobMap,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/videos/generations\";\n const method = req.method ?? \"POST\";\n\n // MULTIPART REJECT FIRST — the real Grok API is JSON-only. Reject BEFORE any\n // body parse so a multipart body never reaches the JSON parser (and never\n // reuses Sora's accept-multipart branch).\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n if ((contentType ?? \"\").toLowerCase().includes(\"multipart/form-data\")) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n code: \"invalid_request\",\n error: \"multipart/form-data is not supported — the Grok video API is JSON-only\",\n }),\n );\n return;\n }\n\n let videoReq: GrokVideoRequest;\n try {\n videoReq = JSON.parse(raw) as GrokVideoRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({ code: \"invalid_json\", error: `Malformed JSON: ${detail}` }),\n );\n return;\n }\n\n // Reject bodies that parsed but are not a JSON object before touching fields.\n if (videoReq === null || typeof videoReq !== \"object\" || Array.isArray(videoReq)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({ code: \"invalid_request\", error: \"Request body must be a JSON object\" }),\n );\n return;\n }\n\n const parsedBody = validationJournalBody(videoReq);\n\n if (typeof videoReq.prompt !== \"string\" || !videoReq.prompt) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: parsedBody,\n response: { status: 400, fixture: null },\n });\n const message =\n videoReq.prompt === undefined\n ? \"Missing required parameter: 'prompt'\"\n : \"Invalid type for parameter: 'prompt' must be a non-empty string\";\n writeErrorResponse(res, 400, JSON.stringify({ code: \"invalid_request\", error: message }));\n return;\n }\n\n if (videoReq.model !== undefined && (typeof videoReq.model !== \"string\" || !videoReq.model)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: parsedBody,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n code: \"invalid_request\",\n error: \"Invalid type for parameter: 'model' must be a non-empty string\",\n }),\n );\n return;\n }\n\n const syntheticReq: ChatCompletionRequest = {\n model: videoReq.model ?? DEFAULT_GROK_VIDEO_MODEL,\n messages: [{ role: \"user\", content: videoReq.prompt }],\n _endpointType: \"video\",\n _videoProvider: \"grok\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n const snippet = videoReq.prompt.slice(0, 80);\n defaults.logger.debug(\n `No fixture matched for request (model=${syntheticReq.model}, msg=\"${snippet}\")`,\n );\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture\n ? \"fixture\"\n : resolveStrictMode(defaults.strict, req.headers)\n ? \"internal\"\n : defaults.record?.providers.grok\n ? \"proxy\"\n : \"internal\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({ code: \"no_fixture_match\", error: strictMessage }),\n );\n return;\n }\n\n if (defaults.record) {\n const outcome = await proxyGrokVideoSubmit({\n req,\n res,\n raw,\n syntheticReq,\n record: defaults.record,\n journal,\n defaults,\n jobs,\n method,\n path,\n });\n if (outcome === \"handled\") return;\n // outcome === \"no_upstream\" — fall through to 404 (fal convention).\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({ code: \"not_found\", error: \"No fixture matched\" }),\n );\n return;\n }\n\n const worldGeneration = jobs.generation;\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n if (res.destroyed || res.writableEnded) return;\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isVideoResponse(response)) {\n if (res.destroyed || res.writableEnded) return;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response is not a video type\", type: \"server_error\" },\n }),\n );\n return;\n }\n\n if (res.destroyed || res.writableEnded) return;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const fixtureStatus: string = response.video.status;\n if (fixtureStatus === \"processing\") {\n defaults.logger.warn(\n `Video fixture has status \"processing\" — treated as completed for /v1/videos/generations jobs`,\n );\n } else if (fixtureStatus !== \"completed\" && fixtureStatus !== \"failed\") {\n defaults.logger.warn(\n `Video fixture has unknown status \"${fixtureStatus}\" — treating as completed for /v1/videos/generations jobs`,\n );\n }\n\n const requestId = crypto.randomUUID();\n const progression = resolveProgression(defaults.grokVideo);\n const job: GrokVideoReplayJob = {\n kind: \"replay\",\n requestId,\n status: \"pending\",\n pollCount: 0,\n pollsBeforeInProgress: progression.pollsBeforeInProgress,\n pollsBeforeCompleted: progression.pollsBeforeCompleted,\n video: { ...response.video },\n };\n if (progression.pollsBeforeCompleted === 0) {\n job.status = terminalStatus(job);\n }\n if (jobs.generation === worldGeneration) {\n jobs.set(`${testId}:${requestId}`, job);\n } else {\n defaults.logger.warn(\n `Grok video submit resolved after a fixtures reset — not inserting job ${requestId} into the new world (its polls will 404)`,\n );\n }\n\n // Embed the testId in the RETURNED request_id (not the stored key) so a\n // multi-tenant client can poll the opaque id without an x-test-id header — the\n // testId travels via getTestId's `?testId=` fallback. Mirrors OpenRouter's\n // polling_url treatment; testIdSuffix is \"\" for the default testId (bare id).\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ request_id: requestId + testIdSuffix(testId, \"?\") }));\n}\n\n// ─── GET /v1/videos/{id} — status poll (Grok-first, Sora fall-through) ───────\n\nexport async function handleGrokVideoStatus(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n id: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n grokJobs: GrokVideoJobMap,\n videoStates: VideoStateMap,\n): Promise<void> {\n const testId = getTestId(req);\n const key = `${testId}:${id}`;\n const job = grokJobs.get(key);\n if (!job) {\n // Grok miss → Sora status, UNCHANGED (byte-for-byte; it sets CORS + rolls\n // chaos itself). Disjoint id namespaces make this unambiguous.\n handleVideoStatus(req, res, id, journal, defaults, setCorsHeaders, videoStates);\n return;\n }\n\n // Grok hit: this handler owns the response from here. Set CORS and roll\n // chaos (mirroring handleOpenRouterVideoStatus — chaos rolls before any work).\n setCorsHeaders(res);\n const path = req.url ?? `/v1/videos/${id}`;\n const method = req.method ?? \"GET\";\n\n if (\n applyChaos(\n res,\n null,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: null },\n \"internal\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (job.kind === \"record\") {\n if (resolveStrictMode(defaults.strict, req.headers)) {\n defaults.logger.error(\n `STRICT: video job ${id} is proxied live upstream (record mode) — refusing the upstream poll`,\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n code: \"no_fixture_match\",\n error: `Strict mode: video job ${id} is proxied live upstream (record mode) — nothing reaches an upstream under strict mode`,\n }),\n );\n return;\n }\n await proxyGrokVideoRecordPoll({\n req,\n res,\n job,\n key,\n testId,\n fixtures,\n journal,\n defaults,\n jobs: grokJobs,\n method,\n path,\n });\n return;\n }\n\n // Replay: guard BEFORE advancing or journaling (file convention).\n if (res.destroyed || res.writableEnded) return;\n advanceJob(job);\n grokJobs.set(key, job);\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 200, fixture: null },\n });\n\n const body = serializeGrokReplay(job, defaults);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n\n/**\n * Serialize a replay job into the Grok wire body. STORED `video.status` is the\n * 3-value VideoResponse union; the wire `status` is derived here\n * (completed → \"done\"). cost_in_usd_ticks is reconstructed from the stored USD\n * `video.cost` (round(cost * 1e10)).\n */\nfunction serializeGrokReplay(\n job: GrokVideoReplayJob,\n defaults: HandlerDefaults,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n request_id: job.requestId,\n status: grokWireStatus(job.status),\n progress: grokProgress(job),\n };\n if (job.status === \"completed\") {\n body.video = {\n url: job.video.url || GROK_DEFAULT_VIDEO_URL,\n duration: job.video.duration ?? 0,\n };\n body.usage = {\n cost_in_usd_ticks: Math.round((job.video.cost ?? 0) * GROK_USD_TICKS_PER_USD),\n };\n } else if (job.status === \"failed\") {\n if (job.video.error === \"\" && !job.emptyErrorWarned) {\n job.emptyErrorWarned = true;\n defaults.logger.warn(\n `Video fixture for job ${job.requestId} has an empty error message — using the default`,\n );\n }\n body.code = \"generation_failed\";\n body.error = job.video.error || \"Video generation failed\";\n }\n return body;\n}\n\n// ─── Record mode: live interactive proxy (submit) ────────────────────────────\n\nconst GROK_VIDEO_SUBMIT_PATH = \"/v1/videos/generations\";\n\n/**\n * Proxy an unmatched Grok video submit to the configured upstream and answer\n * the client with a mock-rewritten `{ request_id }`. The upstream lifecycle is\n * then driven interactively by the client's own polls. Returns \"no_upstream\"\n * when record mode has no grok provider URL — the caller falls through to 404.\n */\nasync function proxyGrokVideoSubmit(args: {\n req: http.IncomingMessage;\n res: http.ServerResponse;\n raw: string;\n syntheticReq: ChatCompletionRequest;\n record: RecordConfig;\n journal: Journal;\n defaults: HandlerDefaults;\n jobs: GrokVideoJobMap;\n method: string;\n path: string;\n}): Promise<\"handled\" | \"no_upstream\"> {\n const { req, res, raw, syntheticReq, record, journal, defaults, jobs, method, path } = args;\n\n const upstreamBase = record.providers.grok;\n if (!upstreamBase) {\n defaults.logger.warn(`No upstream URL configured for provider \"grok\" — cannot proxy`);\n return \"no_upstream\";\n }\n\n const proxyError = (msg: string): \"handled\" => {\n defaults.logger.error(`Grok video submit proxy failed: ${msg}`);\n if (res.destroyed || res.writableEnded) return \"handled\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 502,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 502,\n JSON.stringify({ code: \"proxy_error\", error: `Proxy to upstream failed: ${msg}` }),\n );\n return \"handled\";\n };\n\n let submitUrl: URL;\n let upstreamOrigin: string;\n try {\n submitUrl = resolveUpstreamUrl(upstreamBase, GROK_VIDEO_SUBMIT_PATH);\n upstreamOrigin = new URL(upstreamBase).origin;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return proxyError(`Invalid upstream URL: ${upstreamBase} (${msg})`);\n }\n\n defaults.logger.warn(\n `NO FIXTURE MATCH — proxying video submit to ${upstreamBase}${GROK_VIDEO_SUBMIT_PATH}`,\n );\n\n const worldGeneration = jobs.generation;\n\n let fetched: { status: number; contentType: string | null; text: string };\n try {\n const upstreamRes = await fetch(submitUrl, {\n method: \"POST\",\n headers: buildForwardHeaders(req),\n body: raw,\n signal: upstreamTimeoutSignal(record),\n });\n fetched = {\n status: upstreamRes.status,\n contentType: upstreamRes.headers.get(\"content-type\"),\n text: await readEnvelopeText(upstreamRes, record),\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Unknown proxy error\";\n return proxyError(msg);\n }\n\n if (fetched.status === 401 || fetched.status === 403) {\n defaults.logger.warn(\n `Upstream rejected the video submit (${fetched.status}) — relaying the upstream status`,\n );\n if (res.destroyed || res.writableEnded) return \"handled\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: fetched.status,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n res.writeHead(fetched.status, { \"Content-Type\": fetched.contentType ?? \"application/json\" });\n res.end(fetched.text);\n return \"handled\";\n }\n\n let upstreamRequestId: string;\n {\n if (fetched.status < 200 || fetched.status >= 300) {\n return proxyError(`Submit ${fetched.status}: ${fetched.text.slice(0, 200)}`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(fetched.text);\n } catch {\n return proxyError(`Submit returned non-JSON: ${fetched.text.slice(0, 200)}`);\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return proxyError(\"Submit response is not a JSON object\");\n }\n const envelope = parsed as Record<string, unknown>;\n upstreamRequestId = String(envelope.request_id ?? \"\").trim();\n if (!upstreamRequestId) {\n return proxyError(\"Submit response missing request_id\");\n }\n }\n\n // Construct the poll URL on the configured provider origin (Grok submit\n // returns only request_id, no polling_url — so there is nothing off-origin\n // to validate; we always build it ourselves on the trusted origin).\n void upstreamOrigin;\n const upstreamPollingUrl = resolveUpstreamUrl(\n upstreamBase,\n `/v1/videos/${encodeURIComponent(upstreamRequestId)}`,\n ).toString();\n\n const testId = getTestId(req);\n const matchRequest = defaults.requestTransform\n ? defaults.requestTransform(syntheticReq)\n : syntheticReq;\n const requestId = crypto.randomUUID();\n const job: GrokVideoRecordJob = {\n kind: \"record\",\n requestId,\n status: \"pending\",\n upstreamRequestId,\n upstreamPollingUrl,\n match: buildFixtureMatch(matchRequest, record),\n };\n if (jobs.generation === worldGeneration) {\n jobs.set(`${testId}:${requestId}`, job);\n } else {\n defaults.logger.warn(\n `Grok video submit for upstream request ${upstreamRequestId} completed after a fixtures reset — not inserting the job into the new world (its polls will 404)`,\n );\n }\n\n if (res.destroyed || res.writableEnded) return \"handled\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 200,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n\n // Embed the testId in the RETURNED request_id (see the replay submit) so\n // record-mode multi-tenant polls resolve via `?testId=`; the upstream poll\n // still uses the bare job.requestId / job.upstreamPollingUrl, untouched.\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ request_id: requestId + testIdSuffix(testId, \"?\") }));\n return \"handled\";\n}\n\n// ─── Record mode: live interactive proxy (status poll + eager capture) ───────\n\n/**\n * Proxy a status poll for a record-mode job 1:1 to the upstream and relay the\n * result with the mock requestId substituted. On `done` the rewritten body is\n * relayed IMMEDIATELY and an eager capture runs (synchronously here — there is\n * NO byte download, only the url/duration/cost from the terminal poll body —\n * but structured to mirror openrouter-video's terminal path). `failed`\n * persists a failed fixture synchronously. `expired` (and any unrepresentable\n * status) pass through with a warn and keep proxying. Every post-await map\n * mutation is identity-guarded. Each successful proxied poll refreshes the TTL.\n */\nasync function proxyGrokVideoRecordPoll(args: {\n req: http.IncomingMessage;\n res: http.ServerResponse;\n job: GrokVideoRecordJob;\n key: string;\n testId: string;\n fixtures: Fixture[];\n journal: Journal;\n defaults: HandlerDefaults;\n jobs: GrokVideoJobMap;\n method: string;\n path: string;\n}): Promise<void> {\n const { req, res, job, key, testId, fixtures, journal, defaults, jobs, method, path } = args;\n const logger = defaults.logger;\n\n const journalProxy = (status: number): void => {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: {\n status,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n };\n\n const proxyError = (msg: string): void => {\n logger.error(`Grok video poll proxy failed: ${msg}`);\n if (res.destroyed || res.writableEnded) return;\n journalProxy(502);\n writeErrorResponse(\n res,\n 502,\n JSON.stringify({ code: \"proxy_error\", error: `Proxy to upstream failed: ${msg}` }),\n );\n };\n\n const record = defaults.record;\n if (!record) {\n proxyError(\"record mode is no longer configured for an in-flight record job\");\n return;\n }\n\n let fetched: { status: number; contentType: string | null; text: string };\n try {\n const upstreamRes = await fetch(job.upstreamPollingUrl, {\n headers: buildForwardHeaders(req),\n signal: upstreamTimeoutSignal(record),\n });\n fetched = {\n status: upstreamRes.status,\n contentType: upstreamRes.headers.get(\"content-type\"),\n text: await readEnvelopeText(upstreamRes, record),\n };\n } catch (err) {\n proxyError(err instanceof Error ? err.message : \"Unknown proxy error\");\n return;\n }\n\n if (fetched.status === 401 || fetched.status === 403) {\n logger.warn(\n `Upstream rejected the status poll for job ${job.upstreamRequestId} (${fetched.status}) — relaying the upstream status`,\n );\n if (res.destroyed || res.writableEnded) return;\n journalProxy(fetched.status);\n res.writeHead(fetched.status, { \"Content-Type\": fetched.contentType ?? \"application/json\" });\n res.end(fetched.text);\n return;\n }\n\n let upstreamBody: Record<string, unknown>;\n {\n if (fetched.status < 200 || fetched.status >= 300) {\n proxyError(`Status ${fetched.status}: ${fetched.text.slice(0, 200)}`);\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(fetched.text);\n } catch {\n proxyError(`Status returned non-JSON: ${fetched.text.slice(0, 200)}`);\n return;\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n proxyError(\"Status response is not a JSON object\");\n return;\n }\n upstreamBody = parsed as Record<string, unknown>;\n }\n\n // Rewrite the relay so no upstream id escapes (request_id → mock id);\n // status/progress/video/usage pass through verbatim.\n const relayBody: Record<string, unknown> = { ...upstreamBody, request_id: job.requestId };\n\n const relayJson = (body: Record<string, unknown>): void => {\n if (res.destroyed || res.writableEnded) return;\n journalProxy(200);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n };\n\n const upstreamStatus = String(upstreamBody.status ?? \"\");\n\n if (upstreamStatus === \"pending\" || upstreamStatus === \"in_progress\") {\n if (jobs.get(key) === job) {\n if (!job.capturing && job.status !== \"completed\" && job.status !== \"failed\") {\n job.status = upstreamStatus === \"in_progress\" ? \"in_progress\" : \"pending\";\n }\n jobs.set(key, job); // TTL refresh\n }\n relayJson(relayBody);\n return;\n }\n\n if (upstreamStatus === \"done\") {\n if (record.proxyOnly) {\n if (jobs.get(key) === job) {\n job.status = \"completed\";\n jobs.set(key, job); // TTL refresh\n }\n relayJson(relayBody);\n return;\n }\n\n if (job.capturing || jobs.get(key) !== job) {\n if (jobs.get(key) === job) jobs.set(key, job); // TTL refresh\n relayJson(relayBody);\n return;\n }\n\n // Open the capturing window SYNCHRONOUSLY. There is no byte download, so\n // the capture is synchronous, but mirror the structure: latch capturing,\n // set terminal status, relay, persist, mutate to a terminal replay job.\n job.capturing = true;\n job.status = \"completed\";\n jobs.set(key, job);\n\n relayJson(relayBody);\n\n captureGrokVideoRecordFixture({\n job,\n key,\n testId,\n fixtures,\n defaults,\n jobs,\n record,\n upstreamBody,\n });\n return;\n }\n\n if (upstreamStatus === \"failed\") {\n if (record.proxyOnly) {\n if (jobs.get(key) === job) {\n job.status = \"failed\";\n jobs.set(key, job); // TTL refresh\n }\n relayJson(relayBody);\n return;\n }\n\n if (jobs.get(key) !== job) {\n relayJson(relayBody);\n return;\n }\n\n const rawError = upstreamBody.error;\n let error: string | undefined;\n if (typeof rawError === \"string\" && rawError) {\n error = rawError;\n } else if (rawError !== null && typeof rawError === \"object\" && !Array.isArray(rawError)) {\n const message = (rawError as Record<string, unknown>).message;\n if (typeof message === \"string\" && message) error = message;\n }\n if (error === undefined && rawError !== undefined && rawError !== null) {\n logger.warn(\n `Upstream video job ${job.upstreamRequestId} failed with an unusable error value (${JSON.stringify(rawError).slice(0, 100)}) — recording the fixture without an error message (replay serves the default)`,\n );\n }\n const video: VideoResponse[\"video\"] = {\n id: job.upstreamRequestId,\n status: \"failed\",\n ...(error !== undefined ? { error } : {}),\n };\n const persistResult = persistFixture({\n record,\n providerKey: \"grok\",\n testId,\n fixture: { match: job.match, response: { video } },\n fixtures,\n logger,\n });\n if (persistResult.kind === \"failed\" && !res.headersSent) {\n res.setHeader(\"X-AIMock-Record-Error\", sanitizeHeaderValue(persistResult.error));\n }\n jobs.set(key, {\n kind: \"replay\",\n requestId: job.requestId,\n status: \"failed\",\n pollCount: 0,\n pollsBeforeInProgress: 0,\n pollsBeforeCompleted: 0,\n video: { ...video },\n });\n relayJson(relayBody);\n return;\n }\n\n // expired / anything else: terminal upstream states not representable in\n // VideoResponse.status — pass through (id rewritten), record nothing, keep\n // proxying.\n logger.warn(\n `Upstream video job ${job.upstreamRequestId} reported status \"${upstreamStatus}\" — not representable in fixture video.status; passing through without recording`,\n );\n if (jobs.get(key) === job) {\n jobs.set(key, job);\n }\n relayJson(relayBody);\n}\n\n/**\n * Capture a completed Grok record job into a fixture (PERSIST only — NO byte\n * download): builds `video` from the terminal poll body (id = upstream\n * request_id, status = stored \"completed\", url/duration/cost), persists it, and\n * mutates the map entry into a terminal replay job. World-generation guard\n * before persist (a fixtures reset mid-flight invalidates the world).\n */\nfunction captureGrokVideoRecordFixture(args: {\n job: GrokVideoRecordJob;\n key: string;\n testId: string;\n fixtures: Fixture[];\n defaults: HandlerDefaults;\n jobs: GrokVideoJobMap;\n record: RecordConfig;\n upstreamBody: Record<string, unknown>;\n}): void {\n const { job, key, testId, fixtures, defaults, jobs, record, upstreamBody } = args;\n const logger = defaults.logger;\n\n try {\n const upstreamVideo =\n upstreamBody.video !== null &&\n typeof upstreamBody.video === \"object\" &&\n !Array.isArray(upstreamBody.video)\n ? (upstreamBody.video as Record<string, unknown>)\n : undefined;\n const rawUrl = upstreamVideo?.url;\n const url = typeof rawUrl === \"string\" && rawUrl ? rawUrl : GROK_DEFAULT_VIDEO_URL;\n const rawDuration = upstreamVideo?.duration;\n const duration = typeof rawDuration === \"number\" ? rawDuration : undefined;\n\n const usage =\n upstreamBody.usage !== null &&\n typeof upstreamBody.usage === \"object\" &&\n !Array.isArray(upstreamBody.usage)\n ? (upstreamBody.usage as Record<string, unknown>)\n : undefined;\n const rawTicks = usage?.cost_in_usd_ticks;\n const cost = typeof rawTicks === \"number\" ? rawTicks / GROK_USD_TICKS_PER_USD : undefined;\n\n const video: VideoResponse[\"video\"] = {\n id: job.upstreamRequestId,\n status: \"completed\",\n url,\n ...(duration !== undefined ? { duration } : {}),\n ...(cost !== undefined ? { cost } : {}),\n };\n\n // World-generation guard: a fixtures reset clears the job map, so map\n // identity is a valid proxy for \"same world\".\n if (jobs.get(key) !== job) {\n logger.warn(\n `Grok video capture for job ${job.upstreamRequestId} discarded: the job map no longer holds this job (fixtures reset or TTL eviction) — nothing persisted`,\n );\n return;\n }\n persistFixture({\n record,\n providerKey: \"grok\",\n testId,\n fixture: { match: job.match, response: { video } },\n fixtures,\n logger,\n });\n\n if (jobs.get(key) === job) {\n jobs.set(key, {\n kind: \"replay\",\n requestId: job.requestId,\n status: \"completed\",\n pollCount: 0,\n pollsBeforeInProgress: 0,\n pollsBeforeCompleted: 0,\n video: { ...video },\n });\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n logger.error(\n `Grok video capture for job ${job.upstreamRequestId} failed unexpectedly (${msg}) — fixture not persisted; the job keeps proxying live`,\n );\n } finally {\n // Reset unconditionally (defense-in-depth): the flag lives on this `job`\n // object, so clearing it is always safe — harmless on an orphaned/replaced\n // job (the success path swaps in a fresh replay entry; the old object is\n // discarded either way). The previous `jobs.get(key) === job` guard was a\n // latent landmine: if capture were ever made async/detached, an eviction\n // mid-flight would leave `capturing=true` stuck forever and silently block\n // re-capture. Unconditional reset removes that hazard.\n job.capturing = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA8DA,MAAM,2BAA2B;AAGjC,MAAM,yBAAyB;AAI/B,MAAM,yBAAyB;AAI/B,MAAa,yBAAyB;AACtC,MAAM,oBAAoB;;;;;;;;AA+D1B,IAAa,kBAAb,MAA6B;CAC3B,AAAiB,0BAAU,IAAI,KAA6B;CAC5D,AAAQ,kBAAkB;CAE1B,IAAI,aAAqB;AACvB,SAAO,KAAK;;CAGd,IAAI,KAAuC;EACzC,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;AACnC,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,KAAK,KAAK,GAAG,MAAM,YAAY,mBAAmB;AACpD,QAAK,QAAQ,OAAO,IAAI;AACxB;;AAEF,SAAO,MAAM;;CAGf,IAAI,KAAa,KAAyB;AACxC,OAAK,QAAQ,OAAO,IAAI;AACxB,OAAK,QAAQ,IAAI,KAAK;GAAE;GAAK,WAAW,KAAK,KAAK;GAAE,CAAC;AACrD,MAAI,KAAK,QAAQ,OAAO,wBAAwB;GAC9C,MAAM,SAAS,KAAK,QAAQ,OAAO;GACnC,MAAM,OAAO,KAAK,QAAQ,MAAM;AAChC,QAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK;IAC/B,MAAM,OAAO,KAAK,MAAM;AACxB,QAAI,CAAC,KAAK,KAAM,MAAK,QAAQ,OAAO,KAAK,MAAM;;;;CAKrD,OAAO,KAAsB;AAC3B,SAAO,KAAK,QAAQ,OAAO,IAAI;;CAGjC,QAAc;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QACvB,OAAO,aAAa,UAAU,YAC9B,CAAC,MAAM,QAAQ,aAAa,MAAM,GAC7B,aAAa,QACd;EACN,MAAM,SAAS,eAAe;EAC9B,MAAM,MAAM,OAAO,WAAW,YAAY,SAAS,SAAS;EAC5D,MAAM,cAAc,eAAe;EACnC,MAAM,WAAW,OAAO,gBAAgB,WAAW,cAAc;EAQjE,MAAM,YALJ,aAAa,UAAU,QACvB,OAAO,aAAa,UAAU,YAC9B,CAAC,MAAM,QAAQ,aAAa,MAAM,GAC7B,aAAa,QACd,SACkB;EACxB,MAAM,OAAO,OAAO,aAAa,WAAW,WAAW,yBAAyB;EAEhF,MAAM,QAAgC;GACpC,IAAI,IAAI;GACR,QAAQ;GACR;GACA,GAAI,aAAa,SAAY,EAAE,UAAU,GAAG,EAAE;GAC9C,GAAI,SAAS,SAAY,EAAE,MAAM,GAAG,EAAE;GACvC;AAID,MAAI,KAAK,IAAI,IAAI,KAAK,KAAK;AACzB,UAAO,KACL,8BAA8B,IAAI,kBAAkB,uGACrD;AACD;;AAEF,kCAAe;GACb;GACA,aAAa;GACb;GACA,SAAS;IAAE,OAAO,IAAI;IAAO,UAAU,EAAE,OAAO;IAAE;GAClD;GACA;GACD,CAAC;AAEF,MAAI,KAAK,IAAI,IAAI,KAAK,IACpB,MAAK,IAAI,KAAK;GACZ,MAAM;GACN,WAAW,IAAI;GACf,QAAQ;GACR,WAAW;GACX,uBAAuB;GACvB,sBAAsB;GACtB,OAAO,EAAE,GAAG,OAAO;GACpB,CAAC;UAEG,KAAK;EACZ,MAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAC5D,SAAO,MACL,8BAA8B,IAAI,kBAAkB,wBAAwB,IAAI,wDACjF;WACO;AAQR,MAAI,YAAY"}
|
|
1
|
+
{"version":3,"file":"grok-video.cjs","names":["flattenHeaders","getContext","getTestId","matchFixtureDiagnostic","applyChaos","resolveStrictMode","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","resolveResponse","isErrorResponse","serializeErrorResponse","isVideoResponse","crypto","resolveProgression","testIdSuffix","resolveUpstreamUrl","prepareEgressHeaders","upstreamTimeoutSignal","readEnvelopeText","buildFixtureMatch","persistFixture","sanitizeHeaderValue"],"sources":["../src/grok-video.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport crypto from \"node:crypto\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordConfig,\n VideoResponse,\n} from \"./types.js\";\nimport {\n isVideoResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { resolveProgression } from \"./fal.js\";\nimport {\n buildFixtureMatch,\n prepareEgressHeaders,\n persistFixture,\n sanitizeHeaderValue,\n} from \"./recorder.js\";\nimport { resolveUpstreamUrl } from \"./url.js\";\nimport { handleVideoStatus, type VideoStateMap } from \"./video.js\";\nimport { readEnvelopeText, testIdSuffix, upstreamTimeoutSignal } from \"./video-proxy-shared.js\";\n\n/**\n * xAI Grok Imagine async video lifecycle mock. Submit\n * `POST /v1/videos/generations` returns `{ request_id }`; status\n * `GET /v1/videos/{request_id}` polls `pending → done | failed | expired` with\n * a synthesized `progress`. Multipart submits are rejected with HTTP 400\n * BEFORE body parse (the real API is JSON-only). `video.url` is served AS-IS —\n * aimock does NOT proxy or capture video bytes. With `record.providers.grok`\n * configured an unmatched submit becomes a live interactive proxy (submit +\n * poll forwarded 1:1, eager fixture capture of url/duration/cost on terminal\n * status). Strict mode wins.\n *\n * Grok status shares the `/v1/videos/{id}` path with Sora: the dispatch does a\n * job-map-first lookup and falls through to the UNCHANGED Sora\n * `handleVideoStatus` on a miss (disjoint id namespaces → unambiguous).\n *\n * cost_in_usd_ticks ↔ USD: USD = ticks / 1e10 (ASSUMED). Record persists USD in\n * `video.cost`; replay reconstructs ticks = round(cost * 1e10).\n */\n\ninterface GrokVideoRequest {\n model?: string;\n prompt?: string;\n [key: string]: unknown;\n}\n\nconst DEFAULT_GROK_VIDEO_MODEL = \"grok-imagine-video\";\n\n// USD ←→ Grok cost_in_usd_ticks conversion (ASSUMED: 1e10 ticks per USD).\nconst GROK_USD_TICKS_PER_USD = 1e10;\n\n// Default placeholder when a completed fixture omits `video.url` — every other\n// coercion on this surface is documented; the real API always returns a url.\nconst GROK_DEFAULT_VIDEO_URL = \"https://cdn.x.ai/aimock-placeholder-video.mp4\";\n\n// ─── GrokVideoJobMap (TTL + bounded) ────────────────────────────────────────\n\nexport const GROK_VIDEO_MAX_ENTRIES = 10_000;\nconst GROK_VIDEO_TTL_MS = 3_600_000; // 1 hour\n\ntype GrokVideoStatus = \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n\ninterface GrokVideoReplayJob {\n kind: \"replay\";\n requestId: string;\n status: GrokVideoStatus;\n /** Number of status polls the caller has made against this job. */\n pollCount: number;\n /** Poll-count threshold for `pending → in_progress` transition. */\n pollsBeforeInProgress: number;\n /** Poll-count threshold for the transition to the terminal status. */\n pollsBeforeCompleted: number;\n /** The matched fixture's video object (terminal status, url, duration, cost, error). */\n video: VideoResponse[\"video\"];\n /** Latch for the empty-`error` authoring warn on failed polls (once per job). */\n emptyErrorWarned?: boolean;\n}\n\n/**\n * A job whose lifecycle is proxied live upstream (record mode, no fixture\n * matched at submit). Every client poll is forwarded 1:1 to\n * `upstreamPollingUrl`; when the upstream reports a terminal status (`done`/\n * `failed`) the entry is captured as a fixture and MUTATED into a terminal\n * GrokVideoReplayJob. `expired` (and any unrepresentable status) pass through\n * with a warn and keep proxying. Under `record.proxyOnly` nothing is ever\n * captured or mutated.\n */\ninterface GrokVideoRecordJob {\n kind: \"record\";\n /** The mock-issued requestId the client polls with. */\n requestId: string;\n /** Last upstream status relayed to the client. */\n status: GrokVideoStatus;\n /** Upstream's own request id (recorded as the fixture's video.id). */\n upstreamRequestId: string;\n /** Origin-validated absolute upstream URL proxied on every client poll. */\n upstreamPollingUrl: string;\n /** Match snapshot built at submit time (post requestTransform). */\n match: Fixture[\"match\"];\n /**\n * Set synchronously before the first await of the eager-capture sequence so\n * a concurrent terminal poll relays the upstream body instead of starting a\n * second capture/persist.\n */\n capturing?: boolean;\n}\n\nexport type GrokVideoJob = GrokVideoReplayJob | GrokVideoRecordJob;\n\ninterface GrokVideoEntry {\n job: GrokVideoJob;\n createdAt: number;\n}\n\n/**\n * Per-testId job state for the Grok video handler. Mirrors OpenRouterVideoJobMap\n * (openrouter-video.ts): lazy TTL eviction on `get`, FIFO eviction of the\n * oldest entries on `set` when over capacity, delete-before-set TTL refresh,\n * monotonic world-generation counter for reset-mid-flight detection, no\n * background sweep timer. Keys are `${testId}:${requestId}`.\n */\nexport class GrokVideoJobMap {\n private readonly entries = new Map<string, GrokVideoEntry>();\n private worldGeneration = 0;\n\n get generation(): number {\n return this.worldGeneration;\n }\n\n get(key: string): GrokVideoJob | undefined {\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n if (Date.now() - entry.createdAt > GROK_VIDEO_TTL_MS) {\n this.entries.delete(key);\n return undefined;\n }\n return entry.job;\n }\n\n set(key: string, job: GrokVideoJob): void {\n this.entries.delete(key);\n this.entries.set(key, { job, createdAt: Date.now() });\n if (this.entries.size > GROK_VIDEO_MAX_ENTRIES) {\n const excess = this.entries.size - GROK_VIDEO_MAX_ENTRIES;\n const iter = this.entries.keys();\n for (let i = 0; i < excess; i++) {\n const next = iter.next();\n if (!next.done) this.entries.delete(next.value);\n }\n }\n }\n\n delete(key: string): boolean {\n return this.entries.delete(key);\n }\n\n clear(): void {\n this.entries.clear();\n this.worldGeneration++;\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n\n// ─── Job progression ────────────────────────────────────────────────────────\n\n/**\n * Maps the fixture's terminal video status onto the job lifecycle. Anything\n * that is not \"failed\" — including a fixture authored as \"processing\" — is\n * treated as completed, since this surface always drives jobs to a terminal\n * state.\n */\nfunction terminalStatus(job: GrokVideoReplayJob): GrokVideoStatus {\n return job.video.status === \"failed\" ? \"failed\" : \"completed\";\n}\n\n/**\n * Mutates a job in place to advance its state on a status poll.\n * `pending → in_progress → completed | failed` based on poll-count thresholds.\n * No-op once terminal. The in_progress threshold is checked first so a job\n * whose thresholds are equal still spends one poll in in_progress instead of\n * jumping straight to the terminal status (fal advanceJob semantics).\n */\nfunction advanceJob(job: GrokVideoReplayJob): void {\n if (job.status === \"completed\" || job.status === \"failed\") return;\n\n job.pollCount += 1;\n if (job.status === \"pending\" && job.pollCount >= job.pollsBeforeInProgress) {\n job.status = \"in_progress\";\n } else if (job.pollCount >= job.pollsBeforeCompleted) {\n job.status = terminalStatus(job);\n }\n}\n\n/**\n * Synthesize the Grok wire `progress` (0..100) from poll-count progress toward\n * the completed threshold. A terminal-completed job is always 100 (the only way\n * to reach 100 — it is the wire signal for \"done\"). Every other state reports\n * its progress-at-failure/at-poll, capped at 99. A seed-terminal job with a\n * non-positive completion target has done zero polls toward completion, so it\n * reports 0 (a failed seed job is 0%, never 100).\n */\nfunction grokProgress(job: GrokVideoReplayJob): number {\n if (job.status === \"completed\") return 100;\n const target = job.pollsBeforeCompleted;\n if (target <= 0) return 0;\n const ratio = Math.min(1, job.pollCount / target);\n return Math.min(99, Math.round(ratio * 100));\n}\n\n/** Map the internal job status onto the Grok wire `status` token. */\nfunction grokWireStatus(status: GrokVideoStatus): \"done\" | \"failed\" | \"pending\" {\n if (status === \"completed\") return \"done\";\n if (status === \"failed\") return \"failed\";\n return \"pending\";\n}\n\n/**\n * Synthesizes a structurally valid journal body for field-validation 400s.\n * Mirrors openrouter-video's validationJournalBody: `model` stays a string and\n * `messages` is an empty array; underscore-prefixed keys are stripped so a\n * request cannot spoof handler-set discriminators.\n */\nfunction validationJournalBody(videoReq: GrokVideoRequest): ChatCompletionRequest {\n const rawModel = videoReq.model;\n const model =\n typeof rawModel === \"string\"\n ? rawModel\n : rawModel === undefined\n ? \"\"\n : JSON.stringify(rawModel);\n const sanitized = Object.fromEntries(\n Object.entries(videoReq).filter(([key]) => !key.startsWith(\"_\")),\n );\n return { ...sanitized, model, messages: [] };\n}\n\n// ─── POST /v1/videos/generations — submit ────────────────────────────────────\n\nexport async function handleGrokVideoCreate(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n jobs: GrokVideoJobMap,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/videos/generations\";\n const method = req.method ?? \"POST\";\n\n // MULTIPART REJECT FIRST — the real Grok API is JSON-only. Reject BEFORE any\n // body parse so a multipart body never reaches the JSON parser (and never\n // reuses Sora's accept-multipart branch).\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n if ((contentType ?? \"\").toLowerCase().includes(\"multipart/form-data\")) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n code: \"invalid_request\",\n error: \"multipart/form-data is not supported — the Grok video API is JSON-only\",\n }),\n );\n return;\n }\n\n let videoReq: GrokVideoRequest;\n try {\n videoReq = JSON.parse(raw) as GrokVideoRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({ code: \"invalid_json\", error: `Malformed JSON: ${detail}` }),\n );\n return;\n }\n\n // Reject bodies that parsed but are not a JSON object before touching fields.\n if (videoReq === null || typeof videoReq !== \"object\" || Array.isArray(videoReq)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({ code: \"invalid_request\", error: \"Request body must be a JSON object\" }),\n );\n return;\n }\n\n const parsedBody = validationJournalBody(videoReq);\n\n if (typeof videoReq.prompt !== \"string\" || !videoReq.prompt) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: parsedBody,\n response: { status: 400, fixture: null },\n });\n const message =\n videoReq.prompt === undefined\n ? \"Missing required parameter: 'prompt'\"\n : \"Invalid type for parameter: 'prompt' must be a non-empty string\";\n writeErrorResponse(res, 400, JSON.stringify({ code: \"invalid_request\", error: message }));\n return;\n }\n\n if (videoReq.model !== undefined && (typeof videoReq.model !== \"string\" || !videoReq.model)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: parsedBody,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n code: \"invalid_request\",\n error: \"Invalid type for parameter: 'model' must be a non-empty string\",\n }),\n );\n return;\n }\n\n const syntheticReq: ChatCompletionRequest = {\n model: videoReq.model ?? DEFAULT_GROK_VIDEO_MODEL,\n messages: [{ role: \"user\", content: videoReq.prompt }],\n _endpointType: \"video\",\n _videoProvider: \"grok\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n const snippet = videoReq.prompt.slice(0, 80);\n defaults.logger.debug(\n `No fixture matched for request (model=${syntheticReq.model}, msg=\"${snippet}\")`,\n );\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture\n ? \"fixture\"\n : resolveStrictMode(defaults.strict, req.headers)\n ? \"internal\"\n : defaults.record?.providers.grok\n ? \"proxy\"\n : \"internal\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({ code: \"no_fixture_match\", error: strictMessage }),\n );\n return;\n }\n\n if (defaults.record) {\n const outcome = await proxyGrokVideoSubmit({\n req,\n res,\n raw,\n syntheticReq,\n record: defaults.record,\n journal,\n defaults,\n jobs,\n method,\n path,\n });\n if (outcome === \"handled\") return;\n // outcome === \"no_upstream\" — fall through to 404 (fal convention).\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({ code: \"not_found\", error: \"No fixture matched\" }),\n );\n return;\n }\n\n const worldGeneration = jobs.generation;\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n if (res.destroyed || res.writableEnded) return;\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isVideoResponse(response)) {\n if (res.destroyed || res.writableEnded) return;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response is not a video type\", type: \"server_error\" },\n }),\n );\n return;\n }\n\n if (res.destroyed || res.writableEnded) return;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const fixtureStatus: string = response.video.status;\n if (fixtureStatus === \"processing\") {\n defaults.logger.warn(\n `Video fixture has status \"processing\" — treated as completed for /v1/videos/generations jobs`,\n );\n } else if (fixtureStatus !== \"completed\" && fixtureStatus !== \"failed\") {\n defaults.logger.warn(\n `Video fixture has unknown status \"${fixtureStatus}\" — treating as completed for /v1/videos/generations jobs`,\n );\n }\n\n const requestId = crypto.randomUUID();\n const progression = resolveProgression(defaults.grokVideo);\n const job: GrokVideoReplayJob = {\n kind: \"replay\",\n requestId,\n status: \"pending\",\n pollCount: 0,\n pollsBeforeInProgress: progression.pollsBeforeInProgress,\n pollsBeforeCompleted: progression.pollsBeforeCompleted,\n video: { ...response.video },\n };\n if (progression.pollsBeforeCompleted === 0) {\n job.status = terminalStatus(job);\n }\n if (jobs.generation === worldGeneration) {\n jobs.set(`${testId}:${requestId}`, job);\n } else {\n defaults.logger.warn(\n `Grok video submit resolved after a fixtures reset — not inserting job ${requestId} into the new world (its polls will 404)`,\n );\n }\n\n // Embed the testId in the RETURNED request_id (not the stored key) so a\n // multi-tenant client can poll the opaque id without an x-test-id header — the\n // testId travels via getTestId's `?testId=` fallback. Mirrors OpenRouter's\n // polling_url treatment; testIdSuffix is \"\" for the default testId (bare id).\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ request_id: requestId + testIdSuffix(testId, \"?\") }));\n}\n\n// ─── GET /v1/videos/{id} — status poll (Grok-first, Sora fall-through) ───────\n\nexport async function handleGrokVideoStatus(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n id: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n grokJobs: GrokVideoJobMap,\n videoStates: VideoStateMap,\n): Promise<void> {\n const testId = getTestId(req);\n const key = `${testId}:${id}`;\n const job = grokJobs.get(key);\n if (!job) {\n // Grok miss → Sora status, UNCHANGED (byte-for-byte; it sets CORS + rolls\n // chaos itself). Disjoint id namespaces make this unambiguous.\n handleVideoStatus(req, res, id, journal, defaults, setCorsHeaders, videoStates);\n return;\n }\n\n // Grok hit: this handler owns the response from here. Set CORS and roll\n // chaos (mirroring handleOpenRouterVideoStatus — chaos rolls before any work).\n setCorsHeaders(res);\n const path = req.url ?? `/v1/videos/${id}`;\n const method = req.method ?? \"GET\";\n\n if (\n applyChaos(\n res,\n null,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: null },\n \"internal\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (job.kind === \"record\") {\n if (resolveStrictMode(defaults.strict, req.headers)) {\n defaults.logger.error(\n `STRICT: video job ${id} is proxied live upstream (record mode) — refusing the upstream poll`,\n );\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n code: \"no_fixture_match\",\n error: `Strict mode: video job ${id} is proxied live upstream (record mode) — nothing reaches an upstream under strict mode`,\n }),\n );\n return;\n }\n await proxyGrokVideoRecordPoll({\n req,\n res,\n job,\n key,\n testId,\n fixtures,\n journal,\n defaults,\n jobs: grokJobs,\n method,\n path,\n });\n return;\n }\n\n // Replay: guard BEFORE advancing or journaling (file convention).\n if (res.destroyed || res.writableEnded) return;\n advanceJob(job);\n grokJobs.set(key, job);\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 200, fixture: null },\n });\n\n const body = serializeGrokReplay(job, defaults);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n\n/**\n * Serialize a replay job into the Grok wire body. STORED `video.status` is the\n * 3-value VideoResponse union; the wire `status` is derived here\n * (completed → \"done\"). cost_in_usd_ticks is reconstructed from the stored USD\n * `video.cost` (round(cost * 1e10)).\n */\nfunction serializeGrokReplay(\n job: GrokVideoReplayJob,\n defaults: HandlerDefaults,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n request_id: job.requestId,\n status: grokWireStatus(job.status),\n progress: grokProgress(job),\n };\n if (job.status === \"completed\") {\n body.video = {\n url: job.video.url || GROK_DEFAULT_VIDEO_URL,\n duration: job.video.duration ?? 0,\n };\n body.usage = {\n cost_in_usd_ticks: Math.round((job.video.cost ?? 0) * GROK_USD_TICKS_PER_USD),\n };\n } else if (job.status === \"failed\") {\n if (job.video.error === \"\" && !job.emptyErrorWarned) {\n job.emptyErrorWarned = true;\n defaults.logger.warn(\n `Video fixture for job ${job.requestId} has an empty error message — using the default`,\n );\n }\n body.code = \"generation_failed\";\n body.error = job.video.error || \"Video generation failed\";\n }\n return body;\n}\n\n// ─── Record mode: live interactive proxy (submit) ────────────────────────────\n\nconst GROK_VIDEO_SUBMIT_PATH = \"/v1/videos/generations\";\n\n/**\n * Proxy an unmatched Grok video submit to the configured upstream and answer\n * the client with a mock-rewritten `{ request_id }`. The upstream lifecycle is\n * then driven interactively by the client's own polls. Returns \"no_upstream\"\n * when record mode has no grok provider URL — the caller falls through to 404.\n */\nasync function proxyGrokVideoSubmit(args: {\n req: http.IncomingMessage;\n res: http.ServerResponse;\n raw: string;\n syntheticReq: ChatCompletionRequest;\n record: RecordConfig;\n journal: Journal;\n defaults: HandlerDefaults;\n jobs: GrokVideoJobMap;\n method: string;\n path: string;\n}): Promise<\"handled\" | \"no_upstream\"> {\n const { req, res, raw, syntheticReq, record, journal, defaults, jobs, method, path } = args;\n\n const upstreamBase = record.providers.grok;\n if (!upstreamBase) {\n defaults.logger.warn(`No upstream URL configured for provider \"grok\" — cannot proxy`);\n return \"no_upstream\";\n }\n\n const proxyError = (msg: string): \"handled\" => {\n defaults.logger.error(`Grok video submit proxy failed: ${msg}`);\n if (res.destroyed || res.writableEnded) return \"handled\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 502,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 502,\n JSON.stringify({ code: \"proxy_error\", error: `Proxy to upstream failed: ${msg}` }),\n );\n return \"handled\";\n };\n\n let submitUrl: URL;\n let upstreamOrigin: string;\n try {\n submitUrl = resolveUpstreamUrl(upstreamBase, GROK_VIDEO_SUBMIT_PATH);\n upstreamOrigin = new URL(upstreamBase).origin;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return proxyError(`Invalid upstream URL: ${upstreamBase} (${msg})`);\n }\n\n defaults.logger.warn(\n `NO FIXTURE MATCH — proxying video submit to ${upstreamBase}${GROK_VIDEO_SUBMIT_PATH}`,\n );\n\n const worldGeneration = jobs.generation;\n\n let fetched: { status: number; contentType: string | null; text: string };\n try {\n const headers = prepareEgressHeaders(req, submitUrl, \"grok\", record.providerKeys?.grok);\n if (!headers) return proxyError(\"No configured provider credential\");\n const upstreamRes = await fetch(submitUrl, {\n method: \"POST\",\n headers,\n body: raw,\n signal: upstreamTimeoutSignal(record),\n });\n fetched = {\n status: upstreamRes.status,\n contentType: upstreamRes.headers.get(\"content-type\"),\n text: await readEnvelopeText(upstreamRes, record),\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Unknown proxy error\";\n return proxyError(msg);\n }\n\n if (fetched.status === 401 || fetched.status === 403) {\n defaults.logger.warn(\n `Upstream rejected the video submit (${fetched.status}) — relaying the upstream status`,\n );\n if (res.destroyed || res.writableEnded) return \"handled\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: fetched.status,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n res.writeHead(fetched.status, { \"Content-Type\": fetched.contentType ?? \"application/json\" });\n res.end(fetched.text);\n return \"handled\";\n }\n\n let upstreamRequestId: string;\n {\n if (fetched.status < 200 || fetched.status >= 300) {\n return proxyError(`Submit ${fetched.status}: ${fetched.text.slice(0, 200)}`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(fetched.text);\n } catch {\n return proxyError(`Submit returned non-JSON: ${fetched.text.slice(0, 200)}`);\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return proxyError(\"Submit response is not a JSON object\");\n }\n const envelope = parsed as Record<string, unknown>;\n upstreamRequestId = String(envelope.request_id ?? \"\").trim();\n if (!upstreamRequestId) {\n return proxyError(\"Submit response missing request_id\");\n }\n }\n\n // Construct the poll URL on the configured provider origin (Grok submit\n // returns only request_id, no polling_url — so there is nothing off-origin\n // to validate; we always build it ourselves on the trusted origin).\n void upstreamOrigin;\n const upstreamPollingUrl = resolveUpstreamUrl(\n upstreamBase,\n `/v1/videos/${encodeURIComponent(upstreamRequestId)}`,\n ).toString();\n\n const testId = getTestId(req);\n const matchRequest = defaults.requestTransform\n ? defaults.requestTransform(syntheticReq)\n : syntheticReq;\n const requestId = crypto.randomUUID();\n const job: GrokVideoRecordJob = {\n kind: \"record\",\n requestId,\n status: \"pending\",\n upstreamRequestId,\n upstreamPollingUrl,\n match: buildFixtureMatch(matchRequest, record),\n };\n if (jobs.generation === worldGeneration) {\n jobs.set(`${testId}:${requestId}`, job);\n } else {\n defaults.logger.warn(\n `Grok video submit for upstream request ${upstreamRequestId} completed after a fixtures reset — not inserting the job into the new world (its polls will 404)`,\n );\n }\n\n if (res.destroyed || res.writableEnded) return \"handled\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 200,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n\n // Embed the testId in the RETURNED request_id (see the replay submit) so\n // record-mode multi-tenant polls resolve via `?testId=`; the upstream poll\n // still uses the bare job.requestId / job.upstreamPollingUrl, untouched.\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ request_id: requestId + testIdSuffix(testId, \"?\") }));\n return \"handled\";\n}\n\n// ─── Record mode: live interactive proxy (status poll + eager capture) ───────\n\n/**\n * Proxy a status poll for a record-mode job 1:1 to the upstream and relay the\n * result with the mock requestId substituted. On `done` the rewritten body is\n * relayed IMMEDIATELY and an eager capture runs (synchronously here — there is\n * NO byte download, only the url/duration/cost from the terminal poll body —\n * but structured to mirror openrouter-video's terminal path). `failed`\n * persists a failed fixture synchronously. `expired` (and any unrepresentable\n * status) pass through with a warn and keep proxying. Every post-await map\n * mutation is identity-guarded. Each successful proxied poll refreshes the TTL.\n */\nasync function proxyGrokVideoRecordPoll(args: {\n req: http.IncomingMessage;\n res: http.ServerResponse;\n job: GrokVideoRecordJob;\n key: string;\n testId: string;\n fixtures: Fixture[];\n journal: Journal;\n defaults: HandlerDefaults;\n jobs: GrokVideoJobMap;\n method: string;\n path: string;\n}): Promise<void> {\n const { req, res, job, key, testId, fixtures, journal, defaults, jobs, method, path } = args;\n const logger = defaults.logger;\n\n const journalProxy = (status: number): void => {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: {\n status,\n fixture: null,\n source: \"proxy\",\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n };\n\n const proxyError = (msg: string): void => {\n logger.error(`Grok video poll proxy failed: ${msg}`);\n if (res.destroyed || res.writableEnded) return;\n journalProxy(502);\n writeErrorResponse(\n res,\n 502,\n JSON.stringify({ code: \"proxy_error\", error: `Proxy to upstream failed: ${msg}` }),\n );\n };\n\n const record = defaults.record;\n if (!record) {\n proxyError(\"record mode is no longer configured for an in-flight record job\");\n return;\n }\n\n let fetched: { status: number; contentType: string | null; text: string };\n try {\n const target = new URL(job.upstreamPollingUrl);\n const headers = prepareEgressHeaders(req, target, \"grok\", record.providerKeys?.grok);\n if (!headers) {\n proxyError(\"No configured provider credential\");\n return;\n }\n const upstreamRes = await fetch(job.upstreamPollingUrl, {\n headers,\n signal: upstreamTimeoutSignal(record),\n });\n fetched = {\n status: upstreamRes.status,\n contentType: upstreamRes.headers.get(\"content-type\"),\n text: await readEnvelopeText(upstreamRes, record),\n };\n } catch (err) {\n proxyError(err instanceof Error ? err.message : \"Unknown proxy error\");\n return;\n }\n\n if (fetched.status === 401 || fetched.status === 403) {\n logger.warn(\n `Upstream rejected the status poll for job ${job.upstreamRequestId} (${fetched.status}) — relaying the upstream status`,\n );\n if (res.destroyed || res.writableEnded) return;\n journalProxy(fetched.status);\n res.writeHead(fetched.status, { \"Content-Type\": fetched.contentType ?? \"application/json\" });\n res.end(fetched.text);\n return;\n }\n\n let upstreamBody: Record<string, unknown>;\n {\n if (fetched.status < 200 || fetched.status >= 300) {\n proxyError(`Status ${fetched.status}: ${fetched.text.slice(0, 200)}`);\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(fetched.text);\n } catch {\n proxyError(`Status returned non-JSON: ${fetched.text.slice(0, 200)}`);\n return;\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n proxyError(\"Status response is not a JSON object\");\n return;\n }\n upstreamBody = parsed as Record<string, unknown>;\n }\n\n // Rewrite the relay so no upstream id escapes (request_id → mock id);\n // status/progress/video/usage pass through verbatim.\n const relayBody: Record<string, unknown> = { ...upstreamBody, request_id: job.requestId };\n\n const relayJson = (body: Record<string, unknown>): void => {\n if (res.destroyed || res.writableEnded) return;\n journalProxy(200);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n };\n\n const upstreamStatus = String(upstreamBody.status ?? \"\");\n\n if (upstreamStatus === \"pending\" || upstreamStatus === \"in_progress\") {\n if (jobs.get(key) === job) {\n if (!job.capturing && job.status !== \"completed\" && job.status !== \"failed\") {\n job.status = upstreamStatus === \"in_progress\" ? \"in_progress\" : \"pending\";\n }\n jobs.set(key, job); // TTL refresh\n }\n relayJson(relayBody);\n return;\n }\n\n if (upstreamStatus === \"done\") {\n if (record.proxyOnly) {\n if (jobs.get(key) === job) {\n job.status = \"completed\";\n jobs.set(key, job); // TTL refresh\n }\n relayJson(relayBody);\n return;\n }\n\n if (job.capturing || jobs.get(key) !== job) {\n if (jobs.get(key) === job) jobs.set(key, job); // TTL refresh\n relayJson(relayBody);\n return;\n }\n\n // Open the capturing window SYNCHRONOUSLY. There is no byte download, so\n // the capture is synchronous, but mirror the structure: latch capturing,\n // set terminal status, relay, persist, mutate to a terminal replay job.\n job.capturing = true;\n job.status = \"completed\";\n jobs.set(key, job);\n\n relayJson(relayBody);\n\n captureGrokVideoRecordFixture({\n job,\n key,\n testId,\n fixtures,\n defaults,\n jobs,\n record,\n upstreamBody,\n });\n return;\n }\n\n if (upstreamStatus === \"failed\") {\n if (record.proxyOnly) {\n if (jobs.get(key) === job) {\n job.status = \"failed\";\n jobs.set(key, job); // TTL refresh\n }\n relayJson(relayBody);\n return;\n }\n\n if (jobs.get(key) !== job) {\n relayJson(relayBody);\n return;\n }\n\n const rawError = upstreamBody.error;\n let error: string | undefined;\n if (typeof rawError === \"string\" && rawError) {\n error = rawError;\n } else if (rawError !== null && typeof rawError === \"object\" && !Array.isArray(rawError)) {\n const message = (rawError as Record<string, unknown>).message;\n if (typeof message === \"string\" && message) error = message;\n }\n if (error === undefined && rawError !== undefined && rawError !== null) {\n logger.warn(\n `Upstream video job ${job.upstreamRequestId} failed with an unusable error value (${JSON.stringify(rawError).slice(0, 100)}) — recording the fixture without an error message (replay serves the default)`,\n );\n }\n const video: VideoResponse[\"video\"] = {\n id: job.upstreamRequestId,\n status: \"failed\",\n ...(error !== undefined ? { error } : {}),\n };\n const persistResult = persistFixture({\n record,\n providerKey: \"grok\",\n testId,\n fixture: { match: job.match, response: { video } },\n fixtures,\n logger,\n });\n if (persistResult.kind === \"failed\" && !res.headersSent) {\n res.setHeader(\"X-AIMock-Record-Error\", sanitizeHeaderValue(persistResult.error));\n }\n jobs.set(key, {\n kind: \"replay\",\n requestId: job.requestId,\n status: \"failed\",\n pollCount: 0,\n pollsBeforeInProgress: 0,\n pollsBeforeCompleted: 0,\n video: { ...video },\n });\n relayJson(relayBody);\n return;\n }\n\n // expired / anything else: terminal upstream states not representable in\n // VideoResponse.status — pass through (id rewritten), record nothing, keep\n // proxying.\n logger.warn(\n `Upstream video job ${job.upstreamRequestId} reported status \"${upstreamStatus}\" — not representable in fixture video.status; passing through without recording`,\n );\n if (jobs.get(key) === job) {\n jobs.set(key, job);\n }\n relayJson(relayBody);\n}\n\n/**\n * Capture a completed Grok record job into a fixture (PERSIST only — NO byte\n * download): builds `video` from the terminal poll body (id = upstream\n * request_id, status = stored \"completed\", url/duration/cost), persists it, and\n * mutates the map entry into a terminal replay job. World-generation guard\n * before persist (a fixtures reset mid-flight invalidates the world).\n */\nfunction captureGrokVideoRecordFixture(args: {\n job: GrokVideoRecordJob;\n key: string;\n testId: string;\n fixtures: Fixture[];\n defaults: HandlerDefaults;\n jobs: GrokVideoJobMap;\n record: RecordConfig;\n upstreamBody: Record<string, unknown>;\n}): void {\n const { job, key, testId, fixtures, defaults, jobs, record, upstreamBody } = args;\n const logger = defaults.logger;\n\n try {\n const upstreamVideo =\n upstreamBody.video !== null &&\n typeof upstreamBody.video === \"object\" &&\n !Array.isArray(upstreamBody.video)\n ? (upstreamBody.video as Record<string, unknown>)\n : undefined;\n const rawUrl = upstreamVideo?.url;\n const url = typeof rawUrl === \"string\" && rawUrl ? rawUrl : GROK_DEFAULT_VIDEO_URL;\n const rawDuration = upstreamVideo?.duration;\n const duration = typeof rawDuration === \"number\" ? rawDuration : undefined;\n\n const usage =\n upstreamBody.usage !== null &&\n typeof upstreamBody.usage === \"object\" &&\n !Array.isArray(upstreamBody.usage)\n ? (upstreamBody.usage as Record<string, unknown>)\n : undefined;\n const rawTicks = usage?.cost_in_usd_ticks;\n const cost = typeof rawTicks === \"number\" ? rawTicks / GROK_USD_TICKS_PER_USD : undefined;\n\n const video: VideoResponse[\"video\"] = {\n id: job.upstreamRequestId,\n status: \"completed\",\n url,\n ...(duration !== undefined ? { duration } : {}),\n ...(cost !== undefined ? { cost } : {}),\n };\n\n // World-generation guard: a fixtures reset clears the job map, so map\n // identity is a valid proxy for \"same world\".\n if (jobs.get(key) !== job) {\n logger.warn(\n `Grok video capture for job ${job.upstreamRequestId} discarded: the job map no longer holds this job (fixtures reset or TTL eviction) — nothing persisted`,\n );\n return;\n }\n persistFixture({\n record,\n providerKey: \"grok\",\n testId,\n fixture: { match: job.match, response: { video } },\n fixtures,\n logger,\n });\n\n if (jobs.get(key) === job) {\n jobs.set(key, {\n kind: \"replay\",\n requestId: job.requestId,\n status: \"completed\",\n pollCount: 0,\n pollsBeforeInProgress: 0,\n pollsBeforeCompleted: 0,\n video: { ...video },\n });\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n logger.error(\n `Grok video capture for job ${job.upstreamRequestId} failed unexpectedly (${msg}) — fixture not persisted; the job keeps proxying live`,\n );\n } finally {\n // Reset unconditionally (defense-in-depth): the flag lives on this `job`\n // object, so clearing it is always safe — harmless on an orphaned/replaced\n // job (the success path swaps in a fresh replay entry; the old object is\n // discarded either way). The previous `jobs.get(key) === job` guard was a\n // latent landmine: if capture were ever made async/detached, an eviction\n // mid-flight would leave `capturing=true` stuck forever and silently block\n // re-capture. Unconditional reset removes that hazard.\n job.capturing = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA8DA,MAAM,2BAA2B;AAGjC,MAAM,yBAAyB;AAI/B,MAAM,yBAAyB;AAI/B,MAAa,yBAAyB;AACtC,MAAM,oBAAoB;;;;;;;;AA+D1B,IAAa,kBAAb,MAA6B;CAC3B,AAAiB,0BAAU,IAAI,KAA6B;CAC5D,AAAQ,kBAAkB;CAE1B,IAAI,aAAqB;AACvB,SAAO,KAAK;;CAGd,IAAI,KAAuC;EACzC,MAAM,QAAQ,KAA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