@copilotkit/aimock 1.37.4 → 1.38.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.
Files changed (153) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +22 -0
  4. package/README.md +27 -9
  5. package/dist/agui-recorder.cjs +6 -0
  6. package/dist/agui-recorder.cjs.map +1 -1
  7. package/dist/agui-recorder.d.cts.map +1 -1
  8. package/dist/agui-recorder.d.ts.map +1 -1
  9. package/dist/agui-recorder.js +6 -0
  10. package/dist/agui-recorder.js.map +1 -1
  11. package/dist/agui-types.d.ts.map +1 -1
  12. package/dist/api-key-auth.cjs +166 -0
  13. package/dist/api-key-auth.cjs.map +1 -0
  14. package/dist/api-key-auth.d.cts +17 -0
  15. package/dist/api-key-auth.d.cts.map +1 -0
  16. package/dist/api-key-auth.d.ts +17 -0
  17. package/dist/api-key-auth.d.ts.map +1 -0
  18. package/dist/api-key-auth.js +158 -0
  19. package/dist/api-key-auth.js.map +1 -0
  20. package/dist/cli.cjs +4 -1
  21. package/dist/cli.cjs.map +1 -1
  22. package/dist/cli.js +4 -1
  23. package/dist/cli.js.map +1 -1
  24. package/dist/config-loader.cjs +4 -2
  25. package/dist/config-loader.cjs.map +1 -1
  26. package/dist/config-loader.d.cts +2 -1
  27. package/dist/config-loader.d.cts.map +1 -1
  28. package/dist/config-loader.d.ts +2 -1
  29. package/dist/config-loader.d.ts.map +1 -1
  30. package/dist/config-loader.js +5 -3
  31. package/dist/config-loader.js.map +1 -1
  32. package/dist/fal-audio.cjs +2 -0
  33. package/dist/fal-audio.cjs.map +1 -1
  34. package/dist/fal-audio.d.cts.map +1 -1
  35. package/dist/fal-audio.d.ts.map +1 -1
  36. package/dist/fal-audio.js +2 -0
  37. package/dist/fal-audio.js.map +1 -1
  38. package/dist/fal.cjs +4 -1
  39. package/dist/fal.cjs.map +1 -1
  40. package/dist/fal.d.cts.map +1 -1
  41. package/dist/fal.d.ts.map +1 -1
  42. package/dist/fal.js +4 -1
  43. package/dist/fal.js.map +1 -1
  44. package/dist/fixture-loader.cjs +0 -0
  45. package/dist/fixture-loader.cjs.map +1 -1
  46. package/dist/fixture-loader.d.cts +3 -1
  47. package/dist/fixture-loader.d.cts.map +1 -1
  48. package/dist/fixture-loader.d.ts +3 -1
  49. package/dist/fixture-loader.d.ts.map +1 -1
  50. package/dist/fixture-loader.js +0 -0
  51. package/dist/fixture-loader.js.map +1 -1
  52. package/dist/grok-video.cjs +9 -2
  53. package/dist/grok-video.cjs.map +1 -1
  54. package/dist/grok-video.js +10 -3
  55. package/dist/grok-video.js.map +1 -1
  56. package/dist/helpers.cjs +16 -22
  57. package/dist/helpers.cjs.map +1 -1
  58. package/dist/helpers.d.cts.map +1 -1
  59. package/dist/helpers.d.ts.map +1 -1
  60. package/dist/helpers.js +16 -21
  61. package/dist/helpers.js.map +1 -1
  62. package/dist/index.d.cts +2 -2
  63. package/dist/index.d.ts +2 -2
  64. package/dist/llmock.cjs +14 -3
  65. package/dist/llmock.cjs.map +1 -1
  66. package/dist/llmock.d.cts +4 -2
  67. package/dist/llmock.d.cts.map +1 -1
  68. package/dist/llmock.d.ts +4 -2
  69. package/dist/llmock.d.ts.map +1 -1
  70. package/dist/llmock.js +15 -5
  71. package/dist/llmock.js.map +1 -1
  72. package/dist/openrouter-chat.cjs +333 -0
  73. package/dist/openrouter-chat.cjs.map +1 -0
  74. package/dist/openrouter-chat.js +325 -0
  75. package/dist/openrouter-chat.js.map +1 -0
  76. package/dist/openrouter-video.cjs +24 -7
  77. package/dist/openrouter-video.cjs.map +1 -1
  78. package/dist/openrouter-video.d.cts.map +1 -1
  79. package/dist/openrouter-video.d.ts.map +1 -1
  80. package/dist/openrouter-video.js +25 -8
  81. package/dist/openrouter-video.js.map +1 -1
  82. package/dist/provider-auth.cjs +20 -0
  83. package/dist/provider-auth.cjs.map +1 -1
  84. package/dist/provider-auth.js +20 -1
  85. package/dist/provider-auth.js.map +1 -1
  86. package/dist/recorder.cjs +50 -8
  87. package/dist/recorder.cjs.map +1 -1
  88. package/dist/recorder.d.cts.map +1 -1
  89. package/dist/recorder.d.ts.map +1 -1
  90. package/dist/recorder.js +50 -10
  91. package/dist/recorder.js.map +1 -1
  92. package/dist/responses.cjs +200 -89
  93. package/dist/responses.cjs.map +1 -1
  94. package/dist/responses.d.cts +18 -3
  95. package/dist/responses.d.cts.map +1 -1
  96. package/dist/responses.d.ts +18 -3
  97. package/dist/responses.d.ts.map +1 -1
  98. package/dist/responses.js +199 -90
  99. package/dist/responses.js.map +1 -1
  100. package/dist/server.cjs +156 -66
  101. package/dist/server.cjs.map +1 -1
  102. package/dist/server.d.cts +1 -1
  103. package/dist/server.d.cts.map +1 -1
  104. package/dist/server.d.ts +1 -1
  105. package/dist/server.d.ts.map +1 -1
  106. package/dist/server.js +157 -68
  107. package/dist/server.js.map +1 -1
  108. package/dist/sse-writer.cjs +3 -0
  109. package/dist/sse-writer.cjs.map +1 -1
  110. package/dist/sse-writer.d.cts +8 -0
  111. package/dist/sse-writer.d.cts.map +1 -1
  112. package/dist/sse-writer.d.ts +8 -0
  113. package/dist/sse-writer.d.ts.map +1 -1
  114. package/dist/sse-writer.js +3 -0
  115. package/dist/sse-writer.js.map +1 -1
  116. package/dist/stream-collapse.cjs +26 -0
  117. package/dist/stream-collapse.cjs.map +1 -1
  118. package/dist/stream-collapse.d.cts +7 -0
  119. package/dist/stream-collapse.d.cts.map +1 -1
  120. package/dist/stream-collapse.d.ts +7 -0
  121. package/dist/stream-collapse.d.ts.map +1 -1
  122. package/dist/stream-collapse.js +26 -0
  123. package/dist/stream-collapse.js.map +1 -1
  124. package/dist/transcription.cjs +49 -2
  125. package/dist/transcription.cjs.map +1 -1
  126. package/dist/transcription.d.cts.map +1 -1
  127. package/dist/transcription.d.ts.map +1 -1
  128. package/dist/transcription.js +50 -3
  129. package/dist/transcription.js.map +1 -1
  130. package/dist/types.d.cts +187 -5
  131. package/dist/types.d.cts.map +1 -1
  132. package/dist/types.d.ts +187 -5
  133. package/dist/types.d.ts.map +1 -1
  134. package/dist/veo-video.cjs +9 -2
  135. package/dist/veo-video.cjs.map +1 -1
  136. package/dist/veo-video.js +10 -3
  137. package/dist/veo-video.js.map +1 -1
  138. package/dist/ws-realtime.cjs +306 -57
  139. package/dist/ws-realtime.cjs.map +1 -1
  140. package/dist/ws-realtime.d.cts +1 -0
  141. package/dist/ws-realtime.d.cts.map +1 -1
  142. package/dist/ws-realtime.d.ts +1 -0
  143. package/dist/ws-realtime.d.ts.map +1 -1
  144. package/dist/ws-realtime.js +307 -58
  145. package/dist/ws-realtime.js.map +1 -1
  146. package/dist/ws-responses.cjs +11 -6
  147. package/dist/ws-responses.cjs.map +1 -1
  148. package/dist/ws-responses.d.cts.map +1 -1
  149. package/dist/ws-responses.d.ts.map +1 -1
  150. package/dist/ws-responses.js +12 -7
  151. package/dist/ws-responses.js.map +1 -1
  152. package/package.json +1 -1
  153. package/skills/write-fixtures/SKILL.md +53 -19
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","names":[],"sources":["../src/helpers.ts"],"sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport type * as http from \"node:http\";\nimport type { IncomingHttpHeaders } from \"node:http\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nimport type { Logger } from \"./logger.js\";\nimport { isReasoningModel } from \"./model-utils.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureResponse,\n ResponseFactory,\n TextResponse,\n ToolCallResponse,\n ContentWithToolCallsResponse,\n ErrorResponse,\n EmbeddingResponse,\n ImageResponse,\n AudioResponse,\n TranscriptionResponse,\n VideoResponse,\n RawJSONResponse,\n SSEChunk,\n ToolCall,\n FixtureBlock,\n FixtureFileBlock,\n ChatCompletion,\n ResponseOverrides,\n} from \"./types.js\";\n\nconst REDACTED_HEADERS = new Set([\"authorization\", \"x-api-key\", \"api-key\"]);\n\n/**\n * Resolve effective strict mode from per-request header and server default.\n * Header values override the server default — same precedence pattern as chaos\n * config headers (see resolveChaosConfig in chaos.ts).\n *\n * Header: `X-AIMock-Strict` — \"true\"/\"1\" → strict on, \"false\"/\"0\" → strict off.\n * When absent or unrecognised, falls back to the server-level default.\n */\nexport function resolveStrictMode(\n serverDefault: boolean | undefined,\n rawHeaders?: IncomingHttpHeaders,\n): boolean {\n if (rawHeaders) {\n const header = rawHeaders[\"x-aimock-strict\"];\n const val = typeof header === \"string\" ? header : Array.isArray(header) ? header[0] : undefined;\n if (val === \"true\" || val === \"1\") return true;\n if (val === \"false\" || val === \"0\") return false;\n }\n return serverDefault ?? false;\n}\n\n/**\n * Returns `true` or `false` when the X-AIMock-Strict header overrides the\n * server default, or `undefined` when it doesn't. Designed to be spread\n * directly into a journal entry's `response` object:\n *\n * response: { status, fixture, ...strictOverrideField(defaults.strict, req.headers) }\n */\nexport function strictOverrideField(\n serverDefault: boolean | undefined,\n rawHeaders?: IncomingHttpHeaders,\n): { strictOverride?: boolean } {\n const effective = resolveStrictMode(serverDefault, rawHeaders);\n if (effective !== (serverDefault ?? false)) {\n return { strictOverride: effective };\n }\n return {};\n}\n\n/**\n * Build the strict-mode 503 error message, distinguishing a true no-match from\n * a sequence/turn-exhausted miss.\n *\n * `skippedBySequenceOrTurn` is the count reported by `matchFixtureDiagnostic`\n * (router.ts): the number of fixtures that matched the request SHAPE but were\n * rejected ONLY by their `sequenceIndex`/`turnIndex` count state.\n *\n * - `0` → `\"Strict mode: no fixture matched\"` (no candidate had a matching shape)\n * - `>0` → `\"Strict mode: N candidate fixture(s) skipped by sequence/turn state\"`\n *\n * The HTTP status (503) and error envelope shape are unchanged at every call\n * site — only this message string differs. Endpoints with no sequence/turn\n * gates always pass `0` and therefore see the generic message.\n */\nexport function strictNoMatchMessage(skippedBySequenceOrTurn: number): string {\n if (skippedBySequenceOrTurn > 0) {\n return `Strict mode: ${skippedBySequenceOrTurn} candidate fixture(s) skipped by sequence/turn state`;\n }\n return \"Strict mode: no fixture matched\";\n}\n\n/**\n * Build the strict-mode error LOG line, mirroring {@link strictNoMatchMessage}'s\n * disambiguation so the error log distinguishes the two miss kinds too.\n */\nexport function strictNoMatchLogLine(\n method: string,\n url: string,\n skippedBySequenceOrTurn: number,\n): string {\n if (skippedBySequenceOrTurn > 0) {\n return `STRICT: ${skippedBySequenceOrTurn} candidate fixture(s) skipped by sequence/turn state for ${method} ${url}`;\n }\n return `STRICT: No fixture matched for ${method} ${url}`;\n}\n\n/**\n * Resolve the reasoning string to actually emit for a given model.\n *\n * aimock synthesizes a reasoning channel whenever a fixture carries a\n * `reasoning` string, regardless of the requested model. But a non-reasoning\n * model (e.g. `gpt-4.1`) would emit no reasoning against the real provider, so\n * replaying it is a false green (see aimock#254). This gates the emission on\n * the requested model's capability:\n *\n * - no fixture reasoning → undefined (no-op, short-circuit)\n * - reasoning-capable model → emit unchanged, no log\n * - non-reasoning model, strict OFF → `logger.warn`, still emit (preserves\n * current behavior)\n * - non-reasoning model, strict ON → `logger.error`, suppress (return undefined)\n *\n * Capability is decided from the REQUESTED model id (what the backend was wired\n * to), not any `overrides.model` echoed in the payload.\n */\nexport function resolveReasoningForModel(\n reasoning: string | undefined,\n model: string | undefined,\n strict: boolean,\n logger: Logger,\n): string | undefined {\n if (!reasoning) return undefined;\n if (isReasoningModel(model)) return reasoning;\n if (strict) {\n logger.error(\n `Strict mode: fixture has a reasoning channel but model \"${model}\" is not reasoning-capable — suppressing reasoning emission`,\n );\n return undefined;\n }\n logger.warn(\n `Fixture has a reasoning channel but model \"${model}\" is not reasoning-capable — the real provider would emit no reasoning. Emitting anyway (set X-AIMock-Strict: true to suppress).`,\n );\n return reasoning;\n}\n\n/**\n * Resolve the encrypted reasoning artifacts (`reasoningSignature` and\n * `redactedThinking`) to actually emit for a given model.\n *\n * `redacted_thinking` blocks and a thinking `signature` ARE part of the\n * reasoning channel — they are just the encrypted form of it — so they must be\n * gated on the same model-capability resolution as the plaintext `reasoning`\n * string (see resolveReasoningForModel). Gating only the plaintext channel\n * leaves a half-gated reasoning path: replaying a fixture recorded from a\n * reasoning model against a non-reasoning model would strip the `thinking`\n * block but still emit `redacted_thinking` blocks, which the real provider for\n * that model would never produce.\n *\n * Capability is decided from the REQUESTED model id, independently of whether a\n * plaintext `reasoning` string is present — a fixture may carry only\n * `redactedThinking` with no plaintext reasoning.\n *\n * - reasoning-capable model → emit both unchanged, no log\n * - non-reasoning model, no artifacts → no-op, nothing to suppress\n * - non-reasoning model, strict OFF → `logger.warn`, still emit (preserves\n * current behavior)\n * - non-reasoning model, strict ON → `logger.error`, suppress both\n *\n * Must be invoked alongside resolveReasoningForModel with identical model/strict\n * inputs so the plaintext and encrypted channels stay suppressed together.\n */\nexport function resolveReasoningArtifactsForModel(\n reasoningSignature: string | undefined,\n redactedThinking: string[] | undefined,\n model: string | undefined,\n strict: boolean,\n logger: Logger,\n): { reasoningSignature?: string; redactedThinking?: string[] } {\n const hasArtifacts = reasoningSignature !== undefined || (redactedThinking?.length ?? 0) > 0;\n if (!hasArtifacts || isReasoningModel(model)) {\n return { reasoningSignature, redactedThinking };\n }\n if (strict) {\n logger.error(\n `Strict mode: fixture has encrypted reasoning artifacts (redacted_thinking/signature) but model \"${model}\" is not reasoning-capable — suppressing reasoning emission`,\n );\n return {};\n }\n logger.warn(\n `Fixture has encrypted reasoning artifacts (redacted_thinking/signature) but model \"${model}\" is not reasoning-capable — the real provider would emit no reasoning. Emitting anyway (set X-AIMock-Strict: true to suppress).`,\n );\n return { reasoningSignature, redactedThinking };\n}\n\nexport function flattenHeaders(headers: http.IncomingHttpHeaders): Record<string, string> {\n const flat: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n if (REDACTED_HEADERS.has(key.toLowerCase())) {\n flat[key] = \"[REDACTED]\";\n } else {\n flat[key] = Array.isArray(value) ? value.join(\", \") : value;\n }\n }\n return flat;\n}\n\nexport function isResponseFactory(r: FixtureResponse | ResponseFactory): r is ResponseFactory {\n return typeof r === \"function\";\n}\n\nexport async function resolveResponse(\n fixture: Fixture,\n request: ChatCompletionRequest,\n): Promise<FixtureResponse> {\n if (typeof fixture.response === \"function\") {\n try {\n const raw = await fixture.response(request);\n return normalizeFactoryResponse(raw);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Response factory threw: ${msg}`, { cause: err });\n }\n }\n return fixture.response;\n}\n\nfunction normalizeFactoryResponse(raw: FixtureResponse): FixtureResponse {\n const r = { ...raw } as Record<string, unknown>;\n if (typeof r.content === \"object\" && r.content !== null) {\n r.content = JSON.stringify(r.content);\n }\n if (Array.isArray(r.toolCalls)) {\n r.toolCalls = (r.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 // Mirror the toolCalls[].arguments idiom for the optional ordered `blocks`\n // array: auto-stringify object `arguments` on each `toolCall` block so a\n // programmatic ResponseFactory may return objects (resolveFixtureBlocks\n // requires string `arguments`). Text blocks and string arguments pass\n // through unchanged. Matches the loader's block handling.\n if (Array.isArray(r.blocks)) {\n r.blocks = (r.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 return r as unknown as FixtureResponse;\n}\n\nexport function generateId(prefix = \"chatcmpl\"): string {\n return `${prefix}-${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolCallId(): string {\n return `call_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateMessageId(): string {\n return `msg_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolUseId(): string {\n return `toolu_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function isTextResponse(r: FixtureResponse): r is TextResponse {\n return \"content\" in r && typeof (r as TextResponse).content === \"string\" && !(\"toolCalls\" in r);\n}\n\nexport function isToolCallResponse(r: FixtureResponse): r is ToolCallResponse {\n return (\n \"toolCalls\" in r &&\n Array.isArray((r as ToolCallResponse).toolCalls) &&\n !(\"content\" in r && typeof (r as unknown as Record<string, unknown>).content === \"string\")\n );\n}\n\nexport function isContentWithToolCallsResponse(\n r: FixtureResponse,\n): r is ContentWithToolCallsResponse {\n const o = r as ContentWithToolCallsResponse;\n // LEGACY / COMBINED shape — BOTH content (string) + toolCalls (array). This\n // clause is byte-identical to the original guard, so every fixture that\n // matched before still matches here and is classified exactly as before.\n const hasContentAndToolCalls =\n \"content\" in r &&\n typeof o.content === \"string\" &&\n \"toolCalls\" in r &&\n Array.isArray(o.toolCalls);\n // BLOCKS-ONLY shape (additive, #274 F0) — a non-empty `blocks` array with no\n // content/toolCalls. This is a pure RELAXATION: it recognizes MORE, never\n // reclassifies an existing fixture. A blocks-only fixture cannot be claimed by\n // any earlier/looser guard in the dispatch order — `isTextResponse` requires a\n // string `content` AND `!(\"toolCalls\" in r)`, and `isToolCallResponse`\n // requires a `toolCalls` array — so it would otherwise fall through to 500.\n // `isAudioResponse` (checked first everywhere) requires an `audio` field, which\n // blocks-only lacks, so there is no overlap there either.\n const hasNonEmptyBlocks = Array.isArray(o.blocks) && o.blocks.length > 0;\n return hasContentAndToolCalls || hasNonEmptyBlocks;\n}\n\n/**\n * Validate and pass through the ordered `blocks` field of a combined\n * content+toolCalls fixture. Used ONLY on the new block-iteration path (when a\n * fixture explicitly sets `blocks`); it is NOT a legacy-order reconstructor —\n * fixtures without `blocks` never reach this function and keep their unchanged\n * text-first path.\n *\n * An EMPTY `blocks` array is treated as \"no blocks\" by every builder's\n * streaming gate (`blocks && blocks.length > 0`), so it falls back to the\n * legacy `{content, toolCalls}` path and never reaches this function — the gate\n * is the single source of truth for \"has blocks\". This validator therefore only\n * ever runs on a non-empty array.\n *\n * Accepts the relaxed on-disk {@link FixtureFileBlock} input shape — a\n * `toolCall` block's `arguments` may be a string OR a JSON object/array — which\n * makes the object-tolerance below type-visible and mirrors how\n * normalizeResponse types its file-form input (see {@link FixtureFileBlock} /\n * {@link FixtureFileContentWithToolCallsResponse}). The in-memory\n * {@link FixtureBlock} form (string `arguments`) is a structural subtype, so\n * existing callers that pass `FixtureBlock[]` continue to type-check.\n *\n * Returns the blocks in array order, NORMALIZED to {@link FixtureBlock}: a\n * `text` block with a string `text`, or a `toolCall` block with string `name` +\n * string `arguments` (object/array `arguments` is JSON.stringified) and an\n * optional string `id`. The return type guarantees `arguments: string` — every\n * caller relies on that. Throws on a malformed array or entry — same fail-fast\n * idiom as the other fixture validators in this module (see e.g. the factory\n * guard at {@link resolveResponse}).\n */\nexport function resolveFixtureBlocks(blocks: FixtureFileBlock[]): FixtureBlock[] {\n if (!Array.isArray(blocks)) {\n throw new Error(`Invalid fixture blocks: expected an array, got ${typeof blocks}`);\n }\n // Validate each block and return a normalized COPY. Builders iterate the\n // result and must not observe later mutations of — nor be able to mutate —\n // the caller's stored fixture array, and block objects are consumed read-only\n // downstream, so we never mutate the input in place: any normalization (e.g.\n // stringifying object `arguments`) is applied to a fresh per-block copy.\n return blocks.map((block, i) => {\n if (block === null || typeof block !== \"object\") {\n throw new Error(`Invalid fixture block at index ${i}: expected an object`);\n }\n const b = block as Record<string, unknown>;\n if (b.type === \"text\") {\n if (typeof b.text !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"text\" block requires a string \"text\" field`,\n );\n }\n return { type: \"text\", text: b.text };\n } else if (b.type === \"toolCall\") {\n if (typeof b.name !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"toolCall\" block requires a string \"name\" field`,\n );\n }\n if (b.id !== undefined && typeof b.id !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"toolCall\" block \"id\" must be a string when present`,\n );\n }\n // `arguments` is a JSON string in normalized (file-load) form. The\n // programmatic path (addFixture/addFixtures/prependFixture) stores RAW\n // fixtures with no normalizeResponse pass, so an OBJECT `arguments` can\n // reach here. Be tolerant: stringify an object/array (mirroring\n // normalizeResponse's `JSON.stringify`) into a fresh block copy so the\n // programmatic path is safe and the caller's stored fixture is untouched.\n // A string stays byte-identical (file-load path unchanged); any other\n // type is still rejected.\n if (typeof b.arguments === \"object\" && b.arguments !== null) {\n return { ...b, arguments: JSON.stringify(b.arguments) } as unknown as FixtureBlock;\n }\n if (typeof b.arguments !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"toolCall\" block requires a string or object \"arguments\" field`,\n );\n }\n return { ...b, type: \"toolCall\", name: b.name, arguments: b.arguments } as FixtureBlock;\n } else {\n throw new Error(\n `Invalid fixture block at index ${i}: unknown type ${JSON.stringify(b.type)} (expected \"text\" or \"toolCall\")`,\n );\n }\n });\n}\n\nexport function isErrorResponse(r: FixtureResponse): r is ErrorResponse {\n return (\n \"error\" in r &&\n (r as ErrorResponse).error !== null &&\n typeof (r as ErrorResponse).error === \"object\" &&\n \"message\" in ((r as ErrorResponse).error as Record<string, unknown>) &&\n typeof ((r as ErrorResponse).error as Record<string, unknown>).message === \"string\"\n );\n}\n\n/**\n * Serialize an ErrorResponse to JSON, stripping the internal-only `status`\n * field that controls the HTTP status code but should never appear in the\n * response body. Real LLM APIs don't include it.\n */\nexport function serializeErrorResponse(response: ErrorResponse): string {\n return JSON.stringify({\n error: {\n message: response.error.message,\n type: response.error.type ?? \"server_error\",\n param: response.error.param ?? null,\n code: response.error.code ?? null,\n },\n });\n}\n\nexport function isEmbeddingResponse(r: FixtureResponse): r is EmbeddingResponse {\n return \"embedding\" in r && Array.isArray((r as EmbeddingResponse).embedding);\n}\n\nexport function isImageResponse(r: FixtureResponse): r is ImageResponse {\n return (\n (\"image\" in r && typeof r.image === \"object\" && r.image != null) ||\n (\"images\" in r && Array.isArray((r as ImageResponse).images))\n );\n}\n\nexport function isAudioResponse(r: FixtureResponse): r is AudioResponse {\n if (!(\"audio\" in r)) return false;\n const a = (r as AudioResponse).audio;\n return typeof a === \"string\" || (typeof a === \"object\" && a !== null && \"b64Json\" in a);\n}\n\n/**\n * Map audio format shorthand to MIME content types.\n * Shared between speech, ElevenLabs, and fal audio handlers.\n */\nexport const FORMAT_TO_CONTENT_TYPE: Record<string, string> = {\n mp3: \"audio/mpeg\",\n opus: \"audio/opus\",\n aac: \"audio/aac\",\n flac: \"audio/flac\",\n wav: \"audio/wav\",\n pcm: \"audio/pcm\",\n};\n\n/**\n * Resolve a format string (e.g. \"mp3\", \"opus\") to its MIME content type.\n * Falls back to \"application/octet-stream\" for unknown formats.\n */\nexport function formatToMime(format: string): string {\n return FORMAT_TO_CONTENT_TYPE[format] ?? \"application/octet-stream\";\n}\n\nexport function isTranscriptionResponse(r: FixtureResponse): r is TranscriptionResponse {\n return (\n \"transcription\" in r &&\n (r as TranscriptionResponse).transcription != null &&\n typeof (r as TranscriptionResponse).transcription === \"object\"\n );\n}\n\nexport function isVideoResponse(r: FixtureResponse): r is VideoResponse {\n return (\n \"video\" in r &&\n (r as VideoResponse).video != null &&\n typeof (r as VideoResponse).video === \"object\"\n );\n}\n\nexport function isJSONResponse(r: FixtureResponse): r is RawJSONResponse {\n return \"json\" in r && (r as RawJSONResponse).json !== undefined;\n}\n\nexport function extractOverrides(\n response: TextResponse | ToolCallResponse | ContentWithToolCallsResponse,\n): ResponseOverrides {\n const r = response;\n return {\n ...(r.id !== undefined && { id: r.id }),\n ...(r.created !== undefined && { created: r.created }),\n ...(r.model !== undefined && { model: r.model }),\n ...(r.usage !== undefined && { usage: r.usage }),\n ...(r.systemFingerprint !== undefined && { systemFingerprint: r.systemFingerprint }),\n ...(r.finishReason !== undefined && { finishReason: r.finishReason }),\n ...(r.role !== undefined && { role: r.role }),\n };\n}\n\n// ─── Token estimation ────────────────────────────────────────────────────\n\n/**\n * Rough token count estimation based on character length.\n * Uses the ~4 characters per token heuristic common for English text.\n */\nexport function estimateTokens(text: string): number {\n return Math.max(1, Math.ceil(text.length / 4));\n}\n\n/**\n * Estimate prompt tokens from a request's messages array.\n */\nexport function estimatePromptTokens(messages: ChatCompletionRequest[\"messages\"]): number {\n let totalChars = 0;\n for (const msg of messages) {\n if (typeof msg.content === \"string\") {\n totalChars += msg.content.length;\n } else if (Array.isArray(msg.content)) {\n for (const part of msg.content) {\n if (part.text) totalChars += part.text.length;\n }\n }\n }\n return Math.max(1, Math.ceil(totalChars / 4));\n}\n\n/**\n * Build usage object: use explicit overrides if provided, otherwise estimate.\n */\nfunction resolveUsage(\n overrides: ResponseOverrides | undefined,\n promptText: string,\n completionText: string,\n): { prompt_tokens: number; completion_tokens: number; total_tokens: number } {\n if (overrides?.usage) {\n const u = overrides.usage;\n const prompt = u.prompt_tokens ?? u.input_tokens ?? u.promptTokenCount ?? 0;\n const completion = u.completion_tokens ?? u.output_tokens ?? u.candidatesTokenCount ?? 0;\n return {\n prompt_tokens: prompt,\n completion_tokens: completion,\n total_tokens: u.total_tokens ?? u.totalTokenCount ?? prompt + completion,\n };\n }\n const prompt = estimateTokens(promptText || \"x\");\n const completion = estimateTokens(completionText || \"x\");\n return {\n prompt_tokens: prompt,\n completion_tokens: completion,\n total_tokens: prompt + completion,\n };\n}\n\n/**\n * Build an SSE usage chunk for streaming responses.\n * OpenAI emits this as the final chunk before [DONE] when\n * stream_options.include_usage is true. It has an empty choices array.\n */\nexport function buildUsageChunk(\n id: string,\n model: string,\n created: number,\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number },\n fingerprint?: string,\n): SSEChunk {\n return {\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [],\n usage,\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n };\n}\n\nexport function buildTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): SSEChunk[] {\n const id = overrides?.id ?? generateId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const chunks: SSEChunk[] = [];\n const fingerprint = overrides?.systemFingerprint;\n\n // Reasoning chunks (emitted before content, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: \"\" },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [{ index: 0, delta: { content: slice }, logprobs: null, finish_reason: null }],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: {}, logprobs: null, finish_reason: overrides?.finishReason ?? \"stop\" },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n}\n\nexport function buildToolCallChunks(\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): SSEChunk[] {\n const id = overrides?.id ?? generateId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const chunks: SSEChunk[] = [];\n const fingerprint = overrides?.systemFingerprint;\n\n // Reasoning chunks (emitted before tool calls, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: null },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {},\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n}\n\n// Non-streaming response builders\n\nexport function buildTextCompletion(\n content: string,\n model: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n requestMessages?: ChatCompletionRequest[\"messages\"],\n): ChatCompletion {\n const promptText = requestMessages\n ? requestMessages\n .map((m) =>\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map((p) => p.text ?? \"\").join(\"\")\n : \"\",\n )\n .join(\"\")\n : \"\";\n return {\n id: overrides?.id ?? generateId(),\n object: \"chat.completion\",\n created: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n choices: [\n {\n index: 0,\n message: {\n role: overrides?.role ?? \"assistant\",\n content,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n },\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"stop\",\n },\n ],\n usage: resolveUsage(overrides, promptText, content),\n ...(overrides?.systemFingerprint !== undefined && {\n system_fingerprint: overrides.systemFingerprint,\n }),\n };\n}\n\nexport function buildToolCallCompletion(\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n requestMessages?: ChatCompletionRequest[\"messages\"],\n): ChatCompletion {\n const promptText = requestMessages\n ? requestMessages\n .map((m) =>\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map((p) => p.text ?? \"\").join(\"\")\n : \"\",\n )\n .join(\"\")\n : \"\";\n const completionText = toolCalls.map((tc) => tc.name + tc.arguments).join(\"\");\n return {\n id: overrides?.id ?? generateId(),\n object: \"chat.completion\",\n created: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n choices: [\n {\n index: 0,\n message: {\n role: overrides?.role ?? \"assistant\",\n content: null,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n usage: resolveUsage(overrides, promptText, completionText),\n ...(overrides?.systemFingerprint !== undefined && {\n system_fingerprint: overrides.systemFingerprint,\n }),\n };\n}\n\nexport function buildContentWithToolCallsChunks(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): SSEChunk[] {\n const id = overrides?.id ?? generateId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const chunks: SSEChunk[] = [];\n const fingerprint = overrides?.systemFingerprint;\n\n if (blocks && blocks.length > 0) {\n // NEW: emit chunks in fixture block array order.\n //\n // DEGENERATE PROVIDER NOTE: in OpenAI chat-completions, `delta.content` and\n // `delta.tool_calls` are SEPARATE channels that the client merges with no\n // positional interleaving. So \"tool-call-before-text\" is NOT semantically\n // observable to a real client — it reassembles content and tool calls into\n // their own buckets regardless of chunk order. We still emit honest\n // array-order chunks (the SSE chunk SEQUENCE is the contract this path\n // asserts), but we do NOT fake interleaving the channel cannot express.\n const ordered = resolveFixtureBlocks(blocks);\n\n // Reasoning chunks (emitted first, OpenRouter format) — unchanged from legacy.\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk — preserved exactly as the legacy path.\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: \"\" },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Tool-call `index` is assigned in encounter order across the block array.\n let tcIdx = 0;\n for (const block of ordered) {\n if (block.type === \"text\") {\n for (let i = 0; i < block.text.length; i += chunkSize) {\n const slice = block.text.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [{ index: 0, delta: { content: slice }, logprobs: null, finish_reason: null }],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n } else {\n const tcId = block.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: block.name, arguments: \"\" },\n },\n ],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Argument streaming chunks\n const args = block.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n tcIdx++;\n }\n }\n\n // Finish chunk — preserved exactly as the legacy path.\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {},\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n }\n\n // EXISTING legacy code, byte-for-byte UNCHANGED.\n // Reasoning chunks (emitted before content, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: \"\" },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [{ index: 0, delta: { content: slice }, logprobs: null, finish_reason: null }],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {},\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n}\n\n// NOTE (#274): this NON-streaming OpenAI chat-completions builder is\n// intentionally degenerate w.r.t. `blocks` ordering. A chat.completion puts\n// `message.content` and `message.tool_calls` in SEPARATE fields on a single\n// message object — they are NOT a positionally-observable array, so a\n// tool-first `blocks` fixture cannot be expressed in the wire shape. Honoring\n// block order here would be a no-op, so the legacy content+tool_calls fields\n// are unchanged. (Order-observable surfaces — Claude `content[]`, Gemini\n// `parts[]`, Responses `output[]` — DO honor block order; see those builders.)\nexport function buildContentWithToolCallsCompletion(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n requestMessages?: ChatCompletionRequest[\"messages\"],\n): ChatCompletion {\n const promptText = requestMessages\n ? requestMessages\n .map((m) =>\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map((p) => p.text ?? \"\").join(\"\")\n : \"\",\n )\n .join(\"\")\n : \"\";\n const completionText = content + toolCalls.map((tc) => tc.name + tc.arguments).join(\"\");\n return {\n id: overrides?.id ?? generateId(),\n object: \"chat.completion\",\n created: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n choices: [\n {\n index: 0,\n message: {\n role: overrides?.role ?? \"assistant\",\n content,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n usage: resolveUsage(overrides, promptText, completionText),\n ...(overrides?.systemFingerprint !== undefined && {\n system_fingerprint: overrides.systemFingerprint,\n }),\n };\n}\n\n// ─── HTTP helpers ─────────────────────────────────────────────────────────\n\nconst DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024; // 10 MB\n\nexport function readBody(\n req: http.IncomingMessage,\n maxBytes: number = DEFAULT_MAX_BODY_BYTES,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n let settled = false;\n req.on(\"data\", (chunk: Buffer) => {\n if (settled) return;\n totalBytes += chunk.length;\n if (totalBytes > maxBytes) {\n settled = true;\n req.destroy();\n reject(new Error(`Request body exceeded size limit of ${maxBytes} bytes`));\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => {\n if (!settled) {\n settled = true;\n resolve(Buffer.concat(chunks).toString());\n }\n });\n req.on(\"error\", (err) => {\n if (!settled) {\n settled = true;\n reject(err);\n }\n });\n });\n}\n\n// ─── Pattern matching ─────────────────────────────────────────────────────\n\n/**\n * Case-insensitive substring/regex match used for search, rerank, and\n * moderation endpoints where exact casing rarely matters. String patterns\n * are lowercased on both sides before comparison.\n *\n * Note: This intentionally differs from the case-sensitive matching in\n * {@link matchFixture} (router.ts), where fixture authors expect exact\n * string matching against chat completion user messages.\n */\nexport function matchesPattern(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.toLowerCase().includes(pattern.toLowerCase());\n }\n // A global/sticky RegExp carries mutable `lastIndex` state that `.test()`\n // advances. Save and restore it so callers reusing the same regex object\n // (search/rerank/moderation filter loops) are not left with mutated state\n // and get consistent results across repeated calls.\n const savedLastIndex = pattern.lastIndex;\n pattern.lastIndex = 0;\n const result = pattern.test(text);\n pattern.lastIndex = savedLastIndex;\n return result;\n}\n\nexport function getTestId(req: http.IncomingMessage): string {\n const headerValue = req.headers[\"x-test-id\"];\n if (Array.isArray(headerValue)) {\n if (headerValue.length > 0 && headerValue[0]) return headerValue[0];\n } else if (typeof headerValue === \"string\" && headerValue) {\n return headerValue;\n }\n\n const url = req.url ?? \"/\";\n const qIdx = url.indexOf(\"?\");\n if (qIdx !== -1) {\n const params = new URLSearchParams(url.slice(qIdx + 1));\n const queryValue = params.get(\"testId\");\n if (queryValue) return queryValue;\n }\n\n return DEFAULT_TEST_ID;\n}\n\nexport function getContext(req: http.IncomingMessage): string | undefined {\n const headerValue = req.headers[\"x-aimock-context\"];\n if (Array.isArray(headerValue)) {\n if (headerValue.length > 0 && headerValue[0]) return headerValue[0];\n } else if (typeof headerValue === \"string\" && headerValue) {\n return headerValue;\n }\n return undefined;\n}\n\n// ─── Snapshot recording helpers ──────────────────────────────────────────────\n\n/**\n * Convert a test ID (e.g. Playwright titlePath) into a filesystem-safe slug\n * suitable for use as a directory name in snapshot-style recording.\n */\nexport function slugifyTestId(testId: string): string {\n return testId\n .replace(/^.*?\\.(?:spec|test|e2e)\\.(?:tsx|ts|jsx|js|mjs|cjs)(?=\\s|›|$)\\s*›?\\s*/i, \"\") // strip test file extension prefix\n .replace(/\\s*[›>]\\s*/g, \"--\") // Playwright titlePath separator → double dash\n .replace(/[^\\w-]/g, \"-\") // non-word chars → dash\n .replace(/-{3,}/g, \"--\") // collapse 3+ dashes to double\n .replace(/^-+|-+$/g, \"\") // trim leading/trailing dashes\n .toLowerCase();\n}\n\n/**\n * Make a request context (the `X-AIMock-Context` header value) safe to use as\n * a single directory segment in a recorded-fixture path. The header is\n * attacker-controllable, so a raw value containing `../`, path separators, or\n * an absolute-path prefix would let the written fixture escape the configured\n * fixtures base directory. Mirrors `slugifyTestId`: non-word characters\n * (including `/`, `\\`, and `.`) collapse to dashes, so the result is always a\n * single flat segment with no traversal semantics. Returns \"\" when the value\n * sanitizes to nothing (caller treats that as \"no context segment\").\n */\nexport function slugifyContext(context: string): string {\n return context\n .replace(/[^\\w-]/g, \"-\") // non-word chars (incl. / \\ . :) → dash\n .replace(/-{3,}/g, \"--\") // collapse 3+ dashes to double\n .replace(/^-+|-+$/g, \"\") // trim leading/trailing dashes\n .toLowerCase();\n}\n\n// ─── Embedding helpers ─────────────────────────────────────────────────────\n\nconst DEFAULT_EMBEDDING_DIMENSIONS = 1536;\n\n/**\n * Generate a deterministic embedding vector from input text.\n * Hashes the input with SHA-256 and spreads the hash bytes across\n * the requested number of dimensions, producing values in [-1, 1].\n */\nexport function generateDeterministicEmbedding(\n input: string,\n dimensions: number = DEFAULT_EMBEDDING_DIMENSIONS,\n): number[] {\n let currentHash = createHash(\"sha256\").update(input).digest();\n const embedding: number[] = new Array(dimensions);\n for (let i = 0; i < dimensions; i++) {\n if (i > 0 && i % 32 === 0) {\n currentHash = createHash(\"sha256\").update(currentHash).digest();\n }\n // Map 0-255 → -1.0 to 1.0\n embedding[i] = currentHash[i % 32] / 127.5 - 1;\n }\n return embedding;\n}\n\nexport interface EmbeddingAPIResponse {\n object: \"list\";\n data: { object: \"embedding\"; index: number; embedding: number[] }[];\n model: string;\n usage: { prompt_tokens: number; total_tokens: number };\n}\n\n/**\n * Build an OpenAI-format embeddings API response for one or more inputs.\n */\nexport function buildEmbeddingResponse(\n embeddings: number[][],\n model: string,\n usage?: { prompt_tokens?: number; total_tokens?: number },\n): EmbeddingAPIResponse {\n return {\n object: \"list\",\n data: embeddings.map((embedding, index) => ({\n object: \"embedding\" as const,\n index,\n embedding,\n })),\n model,\n usage: { prompt_tokens: usage?.prompt_tokens ?? 0, total_tokens: usage?.total_tokens ?? 0 },\n };\n}\n"],"mappings":";;;;;AA6BA,MAAM,mBAAmB,IAAI,IAAI;CAAC;CAAiB;CAAa;CAAU,CAAC;;;;;;;;;AAU3E,SAAgB,kBACd,eACA,YACS;AACT,KAAI,YAAY;EACd,MAAM,SAAS,WAAW;EAC1B,MAAM,MAAM,OAAO,WAAW,WAAW,SAAS,MAAM,QAAQ,OAAO,GAAG,OAAO,KAAK;AACtF,MAAI,QAAQ,UAAU,QAAQ,IAAK,QAAO;AAC1C,MAAI,QAAQ,WAAW,QAAQ,IAAK,QAAO;;AAE7C,QAAO,iBAAiB;;;;;;;;;AAU1B,SAA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AQ;EACR,MAAM,WAAW,KAAK,WAAW,WAAW;GAC1C,QAAQ;GACR;GACA;GACD,EAAE;EACH;EACA,OAAO;GAAE,eAAe,OAAO,iBAAiB;GAAG,cAAc,OAAO,gBAAgB;GAAG;EAC5F"}
1
+ {"version":3,"file":"helpers.js","names":[],"sources":["../src/helpers.ts"],"sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport type * as http from \"node:http\";\nimport type { IncomingHttpHeaders } from \"node:http\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nimport type { Logger } from \"./logger.js\";\nimport { isReasoningModel } from \"./model-utils.js\";\nimport { isRecognizedApiKeyHeader } from \"./api-key-auth.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureResponse,\n ResponseFactory,\n TextResponse,\n ToolCallResponse,\n ContentWithToolCallsResponse,\n ErrorResponse,\n EmbeddingResponse,\n ImageResponse,\n AudioResponse,\n TranscriptionResponse,\n VideoResponse,\n RawJSONResponse,\n SSEChunk,\n ToolCall,\n FixtureBlock,\n FixtureFileBlock,\n ChatCompletion,\n ResponseOverrides,\n} from \"./types.js\";\n\n/**\n * Resolve effective strict mode from per-request header and server default.\n * Header values override the server default — same precedence pattern as chaos\n * config headers (see resolveChaosConfig in chaos.ts).\n *\n * Header: `X-AIMock-Strict` — \"true\"/\"1\" → strict on, \"false\"/\"0\" → strict off.\n * When absent or unrecognised, falls back to the server-level default.\n */\nexport function resolveStrictMode(\n serverDefault: boolean | undefined,\n rawHeaders?: IncomingHttpHeaders,\n): boolean {\n if (rawHeaders) {\n const header = rawHeaders[\"x-aimock-strict\"];\n const val = typeof header === \"string\" ? header : Array.isArray(header) ? header[0] : undefined;\n if (val === \"true\" || val === \"1\") return true;\n if (val === \"false\" || val === \"0\") return false;\n }\n return serverDefault ?? false;\n}\n\n/**\n * Returns `true` or `false` when the X-AIMock-Strict header overrides the\n * server default, or `undefined` when it doesn't. Designed to be spread\n * directly into a journal entry's `response` object:\n *\n * response: { status, fixture, ...strictOverrideField(defaults.strict, req.headers) }\n */\nexport function strictOverrideField(\n serverDefault: boolean | undefined,\n rawHeaders?: IncomingHttpHeaders,\n): { strictOverride?: boolean } {\n const effective = resolveStrictMode(serverDefault, rawHeaders);\n if (effective !== (serverDefault ?? false)) {\n return { strictOverride: effective };\n }\n return {};\n}\n\n/**\n * Build the strict-mode 503 error message, distinguishing a true no-match from\n * a sequence/turn-exhausted miss.\n *\n * `skippedBySequenceOrTurn` is the count reported by `matchFixtureDiagnostic`\n * (router.ts): the number of fixtures that matched the request SHAPE but were\n * rejected ONLY by their `sequenceIndex`/`turnIndex` count state.\n *\n * - `0` → `\"Strict mode: no fixture matched\"` (no candidate had a matching shape)\n * - `>0` → `\"Strict mode: N candidate fixture(s) skipped by sequence/turn state\"`\n *\n * The HTTP status (503) and error envelope shape are unchanged at every call\n * site — only this message string differs. Endpoints with no sequence/turn\n * gates always pass `0` and therefore see the generic message.\n */\nexport function strictNoMatchMessage(skippedBySequenceOrTurn: number): string {\n if (skippedBySequenceOrTurn > 0) {\n return `Strict mode: ${skippedBySequenceOrTurn} candidate fixture(s) skipped by sequence/turn state`;\n }\n return \"Strict mode: no fixture matched\";\n}\n\n/**\n * Build the strict-mode error LOG line, mirroring {@link strictNoMatchMessage}'s\n * disambiguation so the error log distinguishes the two miss kinds too.\n */\nexport function strictNoMatchLogLine(\n method: string,\n url: string,\n skippedBySequenceOrTurn: number,\n): string {\n if (skippedBySequenceOrTurn > 0) {\n return `STRICT: ${skippedBySequenceOrTurn} candidate fixture(s) skipped by sequence/turn state for ${method} ${url}`;\n }\n return `STRICT: No fixture matched for ${method} ${url}`;\n}\n\n/**\n * Resolve the reasoning string to actually emit for a given model.\n *\n * aimock synthesizes a reasoning channel whenever a fixture carries a\n * `reasoning` string, regardless of the requested model. But a non-reasoning\n * model (e.g. `gpt-4.1`) would emit no reasoning against the real provider, so\n * replaying it is a false green (see aimock#254). This gates the emission on\n * the requested model's capability:\n *\n * - no fixture reasoning → undefined (no-op, short-circuit)\n * - reasoning-capable model → emit unchanged, no log\n * - non-reasoning model, strict OFF → `logger.warn`, still emit (preserves\n * current behavior)\n * - non-reasoning model, strict ON → `logger.error`, suppress (return undefined)\n *\n * Capability is decided from the REQUESTED model id (what the backend was wired\n * to), not any `overrides.model` echoed in the payload.\n */\nexport function resolveReasoningForModel(\n reasoning: string | undefined,\n model: string | undefined,\n strict: boolean,\n logger: Logger,\n): string | undefined {\n if (!reasoning) return undefined;\n if (isReasoningModel(model)) return reasoning;\n if (strict) {\n logger.error(\n `Strict mode: fixture has a reasoning channel but model \"${model}\" is not reasoning-capable — suppressing reasoning emission`,\n );\n return undefined;\n }\n logger.warn(\n `Fixture has a reasoning channel but model \"${model}\" is not reasoning-capable — the real provider would emit no reasoning. Emitting anyway (set X-AIMock-Strict: true to suppress).`,\n );\n return reasoning;\n}\n\n/**\n * Resolve the encrypted reasoning artifacts (`reasoningSignature` and\n * `redactedThinking`) to actually emit for a given model.\n *\n * `redacted_thinking` blocks and a thinking `signature` ARE part of the\n * reasoning channel — they are just the encrypted form of it — so they must be\n * gated on the same model-capability resolution as the plaintext `reasoning`\n * string (see resolveReasoningForModel). Gating only the plaintext channel\n * leaves a half-gated reasoning path: replaying a fixture recorded from a\n * reasoning model against a non-reasoning model would strip the `thinking`\n * block but still emit `redacted_thinking` blocks, which the real provider for\n * that model would never produce.\n *\n * Capability is decided from the REQUESTED model id, independently of whether a\n * plaintext `reasoning` string is present — a fixture may carry only\n * `redactedThinking` with no plaintext reasoning.\n *\n * - reasoning-capable model → emit both unchanged, no log\n * - non-reasoning model, no artifacts → no-op, nothing to suppress\n * - non-reasoning model, strict OFF → `logger.warn`, still emit (preserves\n * current behavior)\n * - non-reasoning model, strict ON → `logger.error`, suppress both\n *\n * Must be invoked alongside resolveReasoningForModel with identical model/strict\n * inputs so the plaintext and encrypted channels stay suppressed together.\n */\nexport function resolveReasoningArtifactsForModel(\n reasoningSignature: string | undefined,\n redactedThinking: string[] | undefined,\n model: string | undefined,\n strict: boolean,\n logger: Logger,\n): { reasoningSignature?: string; redactedThinking?: string[] } {\n const hasArtifacts = reasoningSignature !== undefined || (redactedThinking?.length ?? 0) > 0;\n if (!hasArtifacts || isReasoningModel(model)) {\n return { reasoningSignature, redactedThinking };\n }\n if (strict) {\n logger.error(\n `Strict mode: fixture has encrypted reasoning artifacts (redacted_thinking/signature) but model \"${model}\" is not reasoning-capable — suppressing reasoning emission`,\n );\n return {};\n }\n logger.warn(\n `Fixture has encrypted reasoning artifacts (redacted_thinking/signature) but model \"${model}\" is not reasoning-capable — the real provider would emit no reasoning. Emitting anyway (set X-AIMock-Strict: true to suppress).`,\n );\n return { reasoningSignature, redactedThinking };\n}\n\nexport function flattenHeaders(headers: http.IncomingHttpHeaders): Record<string, string> {\n const flat: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n if (isRecognizedApiKeyHeader(key)) {\n flat[key] = \"[REDACTED]\";\n } else {\n flat[key] = Array.isArray(value) ? value.join(\", \") : value;\n }\n }\n return flat;\n}\n\nexport function isResponseFactory(r: FixtureResponse | ResponseFactory): r is ResponseFactory {\n return typeof r === \"function\";\n}\n\nexport async function resolveResponse(\n fixture: Fixture,\n request: ChatCompletionRequest,\n): Promise<FixtureResponse> {\n if (typeof fixture.response === \"function\") {\n try {\n const raw = await fixture.response(request);\n return normalizeFactoryResponse(raw);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Response factory threw: ${msg}`, { cause: err });\n }\n }\n return fixture.response;\n}\n\nfunction normalizeFactoryResponse(raw: FixtureResponse): FixtureResponse {\n const r = { ...raw } as Record<string, unknown>;\n if (typeof r.content === \"object\" && r.content !== null) {\n r.content = JSON.stringify(r.content);\n }\n if (Array.isArray(r.toolCalls)) {\n r.toolCalls = (r.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 // Mirror the toolCalls[].arguments idiom for the optional ordered `blocks`\n // array: auto-stringify object `arguments` on each `toolCall` block so a\n // programmatic ResponseFactory may return objects (resolveFixtureBlocks\n // requires string `arguments`). Text blocks and string arguments pass\n // through unchanged. Matches the loader's block handling.\n if (Array.isArray(r.blocks)) {\n r.blocks = (r.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 return r as unknown as FixtureResponse;\n}\n\nexport function generateId(prefix = \"chatcmpl\"): string {\n return `${prefix}-${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolCallId(): string {\n return `call_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateMessageId(): string {\n return `msg_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function generateToolUseId(): string {\n return `toolu_${randomBytes(12).toString(\"base64url\")}`;\n}\n\nexport function isTextResponse(r: FixtureResponse): r is TextResponse {\n return \"content\" in r && typeof (r as TextResponse).content === \"string\" && !(\"toolCalls\" in r);\n}\n\nexport function isToolCallResponse(r: FixtureResponse): r is ToolCallResponse {\n return (\n \"toolCalls\" in r &&\n Array.isArray((r as ToolCallResponse).toolCalls) &&\n !(\"content\" in r && typeof (r as unknown as Record<string, unknown>).content === \"string\")\n );\n}\n\nexport function isContentWithToolCallsResponse(\n r: FixtureResponse,\n): r is ContentWithToolCallsResponse {\n const o = r as ContentWithToolCallsResponse;\n // LEGACY / COMBINED shape — BOTH content (string) + toolCalls (array). This\n // clause is byte-identical to the original guard, so every fixture that\n // matched before still matches here and is classified exactly as before.\n const hasContentAndToolCalls =\n \"content\" in r &&\n typeof o.content === \"string\" &&\n \"toolCalls\" in r &&\n Array.isArray(o.toolCalls);\n // BLOCKS-ONLY shape (additive, #274 F0) — a non-empty `blocks` array with no\n // content/toolCalls. This is a pure RELAXATION: it recognizes MORE, never\n // reclassifies an existing fixture. A blocks-only fixture cannot be claimed by\n // any earlier/looser guard in the dispatch order — `isTextResponse` requires a\n // string `content` AND `!(\"toolCalls\" in r)`, and `isToolCallResponse`\n // requires a `toolCalls` array — so it would otherwise fall through to 500.\n // `isAudioResponse` (checked first everywhere) requires an `audio` field, which\n // blocks-only lacks, so there is no overlap there either.\n const hasNonEmptyBlocks = Array.isArray(o.blocks) && o.blocks.length > 0;\n return hasContentAndToolCalls || hasNonEmptyBlocks;\n}\n\n/**\n * Validate and pass through the ordered `blocks` field of a combined\n * content+toolCalls fixture. Used ONLY on the new block-iteration path (when a\n * fixture explicitly sets `blocks`); it is NOT a legacy-order reconstructor —\n * fixtures without `blocks` never reach this function and keep their unchanged\n * text-first path.\n *\n * An EMPTY `blocks` array is treated as \"no blocks\" by every builder's\n * streaming gate (`blocks && blocks.length > 0`), so it falls back to the\n * legacy `{content, toolCalls}` path and never reaches this function — the gate\n * is the single source of truth for \"has blocks\". This validator therefore only\n * ever runs on a non-empty array.\n *\n * Accepts the relaxed on-disk {@link FixtureFileBlock} input shape — a\n * `toolCall` block's `arguments` may be a string OR a JSON object/array — which\n * makes the object-tolerance below type-visible and mirrors how\n * normalizeResponse types its file-form input (see {@link FixtureFileBlock} /\n * {@link FixtureFileContentWithToolCallsResponse}). The in-memory\n * {@link FixtureBlock} form (string `arguments`) is a structural subtype, so\n * existing callers that pass `FixtureBlock[]` continue to type-check.\n *\n * Returns the blocks in array order, NORMALIZED to {@link FixtureBlock}: a\n * `text` block with a string `text`, or a `toolCall` block with string `name` +\n * string `arguments` (object/array `arguments` is JSON.stringified) and an\n * optional string `id`. The return type guarantees `arguments: string` — every\n * caller relies on that. Throws on a malformed array or entry — same fail-fast\n * idiom as the other fixture validators in this module (see e.g. the factory\n * guard at {@link resolveResponse}).\n */\nexport function resolveFixtureBlocks(blocks: FixtureFileBlock[]): FixtureBlock[] {\n if (!Array.isArray(blocks)) {\n throw new Error(`Invalid fixture blocks: expected an array, got ${typeof blocks}`);\n }\n // Validate each block and return a normalized COPY. Builders iterate the\n // result and must not observe later mutations of — nor be able to mutate —\n // the caller's stored fixture array, and block objects are consumed read-only\n // downstream, so we never mutate the input in place: any normalization (e.g.\n // stringifying object `arguments`) is applied to a fresh per-block copy.\n return blocks.map((block, i) => {\n if (block === null || typeof block !== \"object\") {\n throw new Error(`Invalid fixture block at index ${i}: expected an object`);\n }\n const b = block as Record<string, unknown>;\n if (b.type === \"text\") {\n if (typeof b.text !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"text\" block requires a string \"text\" field`,\n );\n }\n return { type: \"text\", text: b.text };\n } else if (b.type === \"toolCall\") {\n if (typeof b.name !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"toolCall\" block requires a string \"name\" field`,\n );\n }\n if (b.id !== undefined && typeof b.id !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"toolCall\" block \"id\" must be a string when present`,\n );\n }\n // `arguments` is a JSON string in normalized (file-load) form. The\n // programmatic path (addFixture/addFixtures/prependFixture) stores RAW\n // fixtures with no normalizeResponse pass, so an OBJECT `arguments` can\n // reach here. Be tolerant: stringify an object/array (mirroring\n // normalizeResponse's `JSON.stringify`) into a fresh block copy so the\n // programmatic path is safe and the caller's stored fixture is untouched.\n // A string stays byte-identical (file-load path unchanged); any other\n // type is still rejected.\n if (typeof b.arguments === \"object\" && b.arguments !== null) {\n return { ...b, arguments: JSON.stringify(b.arguments) } as unknown as FixtureBlock;\n }\n if (typeof b.arguments !== \"string\") {\n throw new Error(\n `Invalid fixture block at index ${i}: \"toolCall\" block requires a string or object \"arguments\" field`,\n );\n }\n return { ...b, type: \"toolCall\", name: b.name, arguments: b.arguments } as FixtureBlock;\n } else {\n throw new Error(\n `Invalid fixture block at index ${i}: unknown type ${JSON.stringify(b.type)} (expected \"text\" or \"toolCall\")`,\n );\n }\n });\n}\n\nexport function isErrorResponse(r: FixtureResponse): r is ErrorResponse {\n return (\n \"error\" in r &&\n (r as ErrorResponse).error !== null &&\n typeof (r as ErrorResponse).error === \"object\" &&\n \"message\" in ((r as ErrorResponse).error as Record<string, unknown>) &&\n typeof ((r as ErrorResponse).error as Record<string, unknown>).message === \"string\"\n );\n}\n\n/**\n * Serialize an ErrorResponse to JSON, stripping the internal-only `status`\n * field that controls the HTTP status code but should never appear in the\n * response body. Real LLM APIs don't include it.\n */\nexport function serializeErrorResponse(response: ErrorResponse): string {\n return JSON.stringify({\n error: {\n message: response.error.message,\n type: response.error.type ?? \"server_error\",\n param: response.error.param ?? null,\n code: response.error.code ?? null,\n },\n });\n}\n\nexport function isEmbeddingResponse(r: FixtureResponse): r is EmbeddingResponse {\n return \"embedding\" in r && Array.isArray((r as EmbeddingResponse).embedding);\n}\n\nexport function isImageResponse(r: FixtureResponse): r is ImageResponse {\n return (\n (\"image\" in r && typeof r.image === \"object\" && r.image != null) ||\n (\"images\" in r && Array.isArray((r as ImageResponse).images))\n );\n}\n\nexport function isAudioResponse(r: FixtureResponse): r is AudioResponse {\n if (!(\"audio\" in r)) return false;\n const a = (r as AudioResponse).audio;\n return typeof a === \"string\" || (typeof a === \"object\" && a !== null && \"b64Json\" in a);\n}\n\n/**\n * Map audio format shorthand to MIME content types.\n * Shared between speech, ElevenLabs, and fal audio handlers.\n */\nexport const FORMAT_TO_CONTENT_TYPE: Record<string, string> = {\n mp3: \"audio/mpeg\",\n opus: \"audio/opus\",\n aac: \"audio/aac\",\n flac: \"audio/flac\",\n wav: \"audio/wav\",\n pcm: \"audio/pcm\",\n};\n\n/**\n * Resolve a format string (e.g. \"mp3\", \"opus\") to its MIME content type.\n * Falls back to \"application/octet-stream\" for unknown formats.\n */\nexport function formatToMime(format: string): string {\n return FORMAT_TO_CONTENT_TYPE[format] ?? \"application/octet-stream\";\n}\n\nexport function isTranscriptionResponse(r: FixtureResponse): r is TranscriptionResponse {\n return (\n \"transcription\" in r &&\n (r as TranscriptionResponse).transcription != null &&\n typeof (r as TranscriptionResponse).transcription === \"object\"\n );\n}\n\nexport function isVideoResponse(r: FixtureResponse): r is VideoResponse {\n return (\n \"video\" in r &&\n (r as VideoResponse).video != null &&\n typeof (r as VideoResponse).video === \"object\"\n );\n}\n\nexport function isJSONResponse(r: FixtureResponse): r is RawJSONResponse {\n return \"json\" in r && (r as RawJSONResponse).json !== undefined;\n}\n\nexport function extractOverrides(\n response: TextResponse | ToolCallResponse | ContentWithToolCallsResponse,\n): ResponseOverrides {\n const r = response;\n return {\n ...(r.id !== undefined && { id: r.id }),\n ...(r.created !== undefined && { created: r.created }),\n ...(r.model !== undefined && { model: r.model }),\n ...(r.usage !== undefined && { usage: r.usage }),\n ...(r.systemFingerprint !== undefined && { systemFingerprint: r.systemFingerprint }),\n ...(r.finishReason !== undefined && { finishReason: r.finishReason }),\n ...(r.role !== undefined && { role: r.role }),\n ...(r.provider !== undefined && { provider: r.provider }),\n ...(r.nativeFinishReason !== undefined && { nativeFinishReason: r.nativeFinishReason }),\n };\n}\n\n// ─── Token estimation ────────────────────────────────────────────────────\n\n/**\n * Rough token count estimation based on character length.\n * Uses the ~4 characters per token heuristic common for English text.\n */\nexport function estimateTokens(text: string): number {\n return Math.max(1, Math.ceil(text.length / 4));\n}\n\n/**\n * Estimate prompt tokens from a request's messages array.\n */\nexport function estimatePromptTokens(messages: ChatCompletionRequest[\"messages\"]): number {\n let totalChars = 0;\n for (const msg of messages) {\n if (typeof msg.content === \"string\") {\n totalChars += msg.content.length;\n } else if (Array.isArray(msg.content)) {\n for (const part of msg.content) {\n if (part.text) totalChars += part.text.length;\n }\n }\n }\n return Math.max(1, Math.ceil(totalChars / 4));\n}\n\n/**\n * Build usage object: use explicit overrides if provided, otherwise estimate.\n *\n * Shared by BOTH the non-streaming completion builders (below) and the\n * streaming usage-chunk sites in server.ts — the single source of truth for\n * \"explicit token override wins, cost-only override still estimates\". Exported\n * so the streaming path does not re-implement the estimation logic.\n */\nexport function resolveUsage(\n overrides: ResponseOverrides | undefined,\n promptText: string,\n completionText: string,\n): { prompt_tokens: number; completion_tokens: number; total_tokens: number } {\n if (overrides?.usage) {\n const u = overrides.usage;\n // A usage override that scripts only cost fields (e.g. `{ cost: 0.5 }`)\n // carries NO token counts. Real providers always report real token usage,\n // so estimate the counts rather than forcing them to 0 — otherwise a\n // cost-scripting fixture is unfaithful (cost present, tokens 0). When the\n // override DOES set any token count we preserve the explicit-or-zero merge\n // behavior, and any explicit token value always wins.\n const hasExplicitTokens =\n u.prompt_tokens !== undefined ||\n u.completion_tokens !== undefined ||\n u.total_tokens !== undefined ||\n u.input_tokens !== undefined ||\n u.output_tokens !== undefined ||\n u.promptTokenCount !== undefined ||\n u.candidatesTokenCount !== undefined ||\n u.totalTokenCount !== undefined;\n const fallbackPrompt = hasExplicitTokens ? 0 : estimateTokens(promptText || \"x\");\n const fallbackCompletion = hasExplicitTokens ? 0 : estimateTokens(completionText || \"x\");\n const prompt = u.prompt_tokens ?? u.input_tokens ?? u.promptTokenCount ?? fallbackPrompt;\n const completion =\n u.completion_tokens ?? u.output_tokens ?? u.candidatesTokenCount ?? fallbackCompletion;\n return {\n prompt_tokens: prompt,\n completion_tokens: completion,\n total_tokens: u.total_tokens ?? u.totalTokenCount ?? prompt + completion,\n };\n }\n const prompt = estimateTokens(promptText || \"x\");\n const completion = estimateTokens(completionText || \"x\");\n return {\n prompt_tokens: prompt,\n completion_tokens: completion,\n total_tokens: prompt + completion,\n };\n}\n\n/**\n * Build an SSE usage chunk for streaming responses.\n * OpenAI emits this as the final chunk before [DONE] when\n * stream_options.include_usage is true. It has an empty choices array.\n */\nexport function buildUsageChunk(\n id: string,\n model: string,\n created: number,\n usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number },\n fingerprint?: string,\n): SSEChunk {\n return {\n id,\n object: \"chat.completion.chunk\",\n created,\n model,\n choices: [],\n usage,\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n };\n}\n\nexport function buildTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): SSEChunk[] {\n const id = overrides?.id ?? generateId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const chunks: SSEChunk[] = [];\n const fingerprint = overrides?.systemFingerprint;\n\n // Reasoning chunks (emitted before content, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: \"\" },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [{ index: 0, delta: { content: slice }, logprobs: null, finish_reason: null }],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: {}, logprobs: null, finish_reason: overrides?.finishReason ?? \"stop\" },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n}\n\nexport function buildToolCallChunks(\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): SSEChunk[] {\n const id = overrides?.id ?? generateId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const chunks: SSEChunk[] = [];\n const fingerprint = overrides?.systemFingerprint;\n\n // Reasoning chunks (emitted before tool calls, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: null },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {},\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n}\n\n// Non-streaming response builders\n\nexport function buildTextCompletion(\n content: string,\n model: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n requestMessages?: ChatCompletionRequest[\"messages\"],\n): ChatCompletion {\n const promptText = requestMessages\n ? requestMessages\n .map((m) =>\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map((p) => p.text ?? \"\").join(\"\")\n : \"\",\n )\n .join(\"\")\n : \"\";\n return {\n id: overrides?.id ?? generateId(),\n object: \"chat.completion\",\n created: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n choices: [\n {\n index: 0,\n message: {\n role: overrides?.role ?? \"assistant\",\n content,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n },\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"stop\",\n },\n ],\n usage: resolveUsage(overrides, promptText, content),\n ...(overrides?.systemFingerprint !== undefined && {\n system_fingerprint: overrides.systemFingerprint,\n }),\n };\n}\n\nexport function buildToolCallCompletion(\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n requestMessages?: ChatCompletionRequest[\"messages\"],\n): ChatCompletion {\n const promptText = requestMessages\n ? requestMessages\n .map((m) =>\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map((p) => p.text ?? \"\").join(\"\")\n : \"\",\n )\n .join(\"\")\n : \"\";\n const completionText = toolCalls.map((tc) => tc.name + tc.arguments).join(\"\");\n return {\n id: overrides?.id ?? generateId(),\n object: \"chat.completion\",\n created: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n choices: [\n {\n index: 0,\n message: {\n role: overrides?.role ?? \"assistant\",\n content: null,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n usage: resolveUsage(overrides, promptText, completionText),\n ...(overrides?.systemFingerprint !== undefined && {\n system_fingerprint: overrides.systemFingerprint,\n }),\n };\n}\n\nexport function buildContentWithToolCallsChunks(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): SSEChunk[] {\n const id = overrides?.id ?? generateId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const chunks: SSEChunk[] = [];\n const fingerprint = overrides?.systemFingerprint;\n\n if (blocks && blocks.length > 0) {\n // NEW: emit chunks in fixture block array order.\n //\n // DEGENERATE PROVIDER NOTE: in OpenAI chat-completions, `delta.content` and\n // `delta.tool_calls` are SEPARATE channels that the client merges with no\n // positional interleaving. So \"tool-call-before-text\" is NOT semantically\n // observable to a real client — it reassembles content and tool calls into\n // their own buckets regardless of chunk order. We still emit honest\n // array-order chunks (the SSE chunk SEQUENCE is the contract this path\n // asserts), but we do NOT fake interleaving the channel cannot express.\n const ordered = resolveFixtureBlocks(blocks);\n\n // Reasoning chunks (emitted first, OpenRouter format) — unchanged from legacy.\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk — preserved exactly as the legacy path.\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: \"\" },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Tool-call `index` is assigned in encounter order across the block array.\n let tcIdx = 0;\n for (const block of ordered) {\n if (block.type === \"text\") {\n for (let i = 0; i < block.text.length; i += chunkSize) {\n const slice = block.text.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [{ index: 0, delta: { content: slice }, logprobs: null, finish_reason: null }],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n } else {\n const tcId = block.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: block.name, arguments: \"\" },\n },\n ],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Argument streaming chunks\n const args = block.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n tcIdx++;\n }\n }\n\n // Finish chunk — preserved exactly as the legacy path.\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {},\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n }\n\n // EXISTING legacy code, byte-for-byte UNCHANGED.\n // Reasoning chunks (emitted before content, OpenRouter format)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n { index: 0, delta: { reasoning_content: slice }, logprobs: null, finish_reason: null },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Role chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: { role: overrides?.role ?? \"assistant\", content: \"\" },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Content chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [{ index: 0, delta: { content: slice }, logprobs: null, finish_reason: null }],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n\n // Tool call chunks — one initial chunk per tool call, then argument chunks\n for (let tcIdx = 0; tcIdx < toolCalls.length; tcIdx++) {\n const tc = toolCalls[tcIdx];\n const tcId = tc.id || generateToolCallId();\n\n // Initial tool call chunk (id + function name)\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [\n {\n index: tcIdx,\n id: tcId,\n type: \"function\",\n function: { name: tc.name, arguments: \"\" },\n },\n ],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n // Argument streaming chunks\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {\n tool_calls: [{ index: tcIdx, function: { arguments: slice } }],\n },\n logprobs: null,\n finish_reason: null,\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n }\n }\n\n // Finish chunk\n chunks.push({\n id,\n object: \"chat.completion.chunk\",\n created,\n model: effectiveModel,\n choices: [\n {\n index: 0,\n delta: {},\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n ...(fingerprint !== undefined && { system_fingerprint: fingerprint }),\n });\n\n return chunks;\n}\n\n// NOTE (#274): this NON-streaming OpenAI chat-completions builder is\n// intentionally degenerate w.r.t. `blocks` ordering. A chat.completion puts\n// `message.content` and `message.tool_calls` in SEPARATE fields on a single\n// message object — they are NOT a positionally-observable array, so a\n// tool-first `blocks` fixture cannot be expressed in the wire shape. Honoring\n// block order here would be a no-op, so the legacy content+tool_calls fields\n// are unchanged. (Order-observable surfaces — Claude `content[]`, Gemini\n// `parts[]`, Responses `output[]` — DO honor block order; see those builders.)\nexport function buildContentWithToolCallsCompletion(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n requestMessages?: ChatCompletionRequest[\"messages\"],\n): ChatCompletion {\n const promptText = requestMessages\n ? requestMessages\n .map((m) =>\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content.map((p) => p.text ?? \"\").join(\"\")\n : \"\",\n )\n .join(\"\")\n : \"\";\n const completionText = content + toolCalls.map((tc) => tc.name + tc.arguments).join(\"\");\n return {\n id: overrides?.id ?? generateId(),\n object: \"chat.completion\",\n created: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n choices: [\n {\n index: 0,\n message: {\n role: overrides?.role ?? \"assistant\",\n content,\n refusal: null,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id || generateToolCallId(),\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n })),\n },\n logprobs: null,\n finish_reason: overrides?.finishReason ?? \"tool_calls\",\n },\n ],\n usage: resolveUsage(overrides, promptText, completionText),\n ...(overrides?.systemFingerprint !== undefined && {\n system_fingerprint: overrides.systemFingerprint,\n }),\n };\n}\n\n// ─── HTTP helpers ─────────────────────────────────────────────────────────\n\nconst DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024; // 10 MB\n\nexport function readBody(\n req: http.IncomingMessage,\n maxBytes: number = DEFAULT_MAX_BODY_BYTES,\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n let settled = false;\n req.on(\"data\", (chunk: Buffer) => {\n if (settled) return;\n totalBytes += chunk.length;\n if (totalBytes > maxBytes) {\n settled = true;\n req.destroy();\n reject(new Error(`Request body exceeded size limit of ${maxBytes} bytes`));\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => {\n if (!settled) {\n settled = true;\n resolve(Buffer.concat(chunks).toString());\n }\n });\n req.on(\"error\", (err) => {\n if (!settled) {\n settled = true;\n reject(err);\n }\n });\n });\n}\n\n// ─── Pattern matching ─────────────────────────────────────────────────────\n\n/**\n * Case-insensitive substring/regex match used for search, rerank, and\n * moderation endpoints where exact casing rarely matters. String patterns\n * are lowercased on both sides before comparison.\n *\n * Note: This intentionally differs from the case-sensitive matching in\n * {@link matchFixture} (router.ts), where fixture authors expect exact\n * string matching against chat completion user messages.\n */\nexport function matchesPattern(text: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return text.toLowerCase().includes(pattern.toLowerCase());\n }\n // A global/sticky RegExp carries mutable `lastIndex` state that `.test()`\n // advances. Save and restore it so callers reusing the same regex object\n // (search/rerank/moderation filter loops) are not left with mutated state\n // and get consistent results across repeated calls.\n const savedLastIndex = pattern.lastIndex;\n pattern.lastIndex = 0;\n const result = pattern.test(text);\n pattern.lastIndex = savedLastIndex;\n return result;\n}\n\nexport function getTestId(req: http.IncomingMessage): string {\n const headerValue = req.headers[\"x-test-id\"];\n if (Array.isArray(headerValue)) {\n if (headerValue.length > 0 && headerValue[0]) return headerValue[0];\n } else if (typeof headerValue === \"string\" && headerValue) {\n return headerValue;\n }\n\n const url = req.url ?? \"/\";\n const qIdx = url.indexOf(\"?\");\n if (qIdx !== -1) {\n const params = new URLSearchParams(url.slice(qIdx + 1));\n const queryValue = params.get(\"testId\");\n if (queryValue) return queryValue;\n }\n\n return DEFAULT_TEST_ID;\n}\n\nexport function getContext(req: http.IncomingMessage): string | undefined {\n const headerValue = req.headers[\"x-aimock-context\"];\n if (Array.isArray(headerValue)) {\n if (headerValue.length > 0 && headerValue[0]) return headerValue[0];\n } else if (typeof headerValue === \"string\" && headerValue) {\n return headerValue;\n }\n return undefined;\n}\n\n// ─── Snapshot recording helpers ──────────────────────────────────────────────\n\n/**\n * Convert a test ID (e.g. Playwright titlePath) into a filesystem-safe slug\n * suitable for use as a directory name in snapshot-style recording.\n */\nexport function slugifyTestId(testId: string): string {\n return testId\n .replace(/^.*?\\.(?:spec|test|e2e)\\.(?:tsx|ts|jsx|js|mjs|cjs)(?=\\s|›|$)\\s*›?\\s*/i, \"\") // strip test file extension prefix\n .replace(/\\s*[›>]\\s*/g, \"--\") // Playwright titlePath separator → double dash\n .replace(/[^\\w-]/g, \"-\") // non-word chars → dash\n .replace(/-{3,}/g, \"--\") // collapse 3+ dashes to double\n .replace(/^-+|-+$/g, \"\") // trim leading/trailing dashes\n .toLowerCase();\n}\n\n/**\n * Make a request context (the `X-AIMock-Context` header value) safe to use as\n * a single directory segment in a recorded-fixture path. The header is\n * attacker-controllable, so a raw value containing `../`, path separators, or\n * an absolute-path prefix would let the written fixture escape the configured\n * fixtures base directory. Mirrors `slugifyTestId`: non-word characters\n * (including `/`, `\\`, and `.`) collapse to dashes, so the result is always a\n * single flat segment with no traversal semantics. Returns \"\" when the value\n * sanitizes to nothing (caller treats that as \"no context segment\").\n */\nexport function slugifyContext(context: string): string {\n return context\n .replace(/[^\\w-]/g, \"-\") // non-word chars (incl. / \\ . :) → dash\n .replace(/-{3,}/g, \"--\") // collapse 3+ dashes to double\n .replace(/^-+|-+$/g, \"\") // trim leading/trailing dashes\n .toLowerCase();\n}\n\n// ─── Embedding helpers ─────────────────────────────────────────────────────\n\nconst DEFAULT_EMBEDDING_DIMENSIONS = 1536;\n\n/**\n * Generate a deterministic embedding vector from input text.\n * Hashes the input with SHA-256 and spreads the hash bytes across\n * the requested number of dimensions, producing values in [-1, 1].\n */\nexport function generateDeterministicEmbedding(\n input: string,\n dimensions: number = DEFAULT_EMBEDDING_DIMENSIONS,\n): number[] {\n let currentHash = createHash(\"sha256\").update(input).digest();\n const embedding: number[] = new Array(dimensions);\n for (let i = 0; i < dimensions; i++) {\n if (i > 0 && i % 32 === 0) {\n currentHash = createHash(\"sha256\").update(currentHash).digest();\n }\n // Map 0-255 → -1.0 to 1.0\n embedding[i] = currentHash[i % 32] / 127.5 - 1;\n }\n return embedding;\n}\n\nexport interface EmbeddingAPIResponse {\n object: \"list\";\n data: { object: \"embedding\"; index: number; embedding: number[] }[];\n model: string;\n usage: { prompt_tokens: number; total_tokens: number };\n}\n\n/**\n * Build an OpenAI-format embeddings API response for one or more inputs.\n */\nexport function buildEmbeddingResponse(\n embeddings: number[][],\n model: string,\n usage?: { prompt_tokens?: number; total_tokens?: number },\n): EmbeddingAPIResponse {\n return {\n object: \"list\",\n data: embeddings.map((embedding, index) => ({\n object: \"embedding\" as const,\n index,\n embedding,\n })),\n model,\n usage: { prompt_tokens: usage?.prompt_tokens ?? 0, total_tokens: usage?.total_tokens ?? 0 },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAsCA,SAAgB,kBACd,eACA,YACS;AACT,KAAI,YAAY;EACd,MAAM,SAAS,WAAW;EAC1B,MAAM,MAAM,OAAO,WAAW,WAAW,SAAS,MAAM,QAAQ,OAAO,GAAG,OAAO,KAAK;AACtF,MAAI,QAAQ,UAAU,QA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I,IAAI,KAAK,IAAI,OAAO,EACtB,eAAc,WAAW,SAAS,CAAC,OAAO,YAAY,CAAC,QAAQ;AAGjE,YAAU,KAAK,YAAY,IAAI,MAAM,QAAQ;;AAE/C,QAAO;;;;;AAaT,SAAgB,uBACd,YACA,OACA,OACsB;AACtB,QAAO;EACL,QAAQ;EACR,MAAM,WAAW,KAAK,WAAW,WAAW;GAC1C,QAAQ;GACR;GACA;GACD,EAAE;EACH;EACA,OAAO;GAAE,eAAe,OAAO,iBAAiB;GAAG,cAAc,OAAO,gBAAgB;GAAG;EAC5F"}
package/dist/index.d.cts CHANGED
@@ -2,7 +2,7 @@ import { DEFAULT_TEST_ID } from "./constants.cjs";
2
2
  import { Journal } from "./journal.cjs";
3
3
  import { LogLevel, Logger } from "./logger.cjs";
4
4
  import { MetricsRegistry, createMetricsRegistry, normalizePathLabel } from "./metrics.cjs";
5
- import { AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureFile, FixtureFileContentWithToolCallsResponse, FixtureFileEntry, FixtureFileResponse, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, ImageItem, ImageResponse, JournalEntry, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, ResponseOverrides, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse } from "./types.cjs";
5
+ import { ApiKeyAuthConfig, AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureFile, FixtureFileContentWithToolCallsResponse, FixtureFileEntry, FixtureFileResponse, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, ImageItem, ImageResponse, JournalEntry, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, ResponseOverrides, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse } from "./types.cjs";
6
6
  import { A2AAgentDefinition, A2AArtifact, A2AMessage, A2AMockOptions, A2APart, A2ARole, A2AStreamEvent, A2ATask, A2ATaskResponse, A2ATaskState } from "./a2a-types.cjs";
7
7
  import { A2AMock } from "./a2a-mock.cjs";
8
8
  import { AGUIActivityDeltaEvent, AGUIActivitySnapshotEvent, AGUIBaseEvent, AGUICustomEvent, AGUIEvent, AGUIEventType, AGUIFixture, AGUIFixtureMatch, AGUIInterrupt, AGUIMessage, AGUIMessageContentPart, AGUIMessageRole, AGUIMessagesSnapshotEvent, AGUIMockOptions, AGUIRawEvent, AGUIReasoningEncryptedValueEvent, AGUIReasoningEncryptedValueSubtype, AGUIReasoningEndEvent, AGUIReasoningMessageChunkEvent, AGUIReasoningMessageContentEvent, AGUIReasoningMessageEndEvent, AGUIReasoningMessageStartEvent, AGUIReasoningStartEvent, AGUIRecordConfig, AGUIResumeEntry, AGUIRunAgentInput, AGUIRunErrorEvent, AGUIRunFinishedEvent, AGUIRunFinishedOutcome, AGUIRunStartedEvent, AGUIStateDeltaEvent, AGUIStateSnapshotEvent, AGUIStepFinishedEvent, AGUIStepStartedEvent, AGUITextMessageChunkEvent, AGUITextMessageContentEvent, AGUITextMessageEndEvent, AGUITextMessageRole, AGUITextMessageStartEvent, AGUIThinkingEndEvent, AGUIThinkingStartEvent, AGUIThinkingTextMessageContentEvent, AGUIThinkingTextMessageEndEvent, AGUIThinkingTextMessageStartEvent, AGUIToolCall, AGUIToolCallArgsEvent, AGUIToolCallChunkEvent, AGUIToolCallEndEvent, AGUIToolCallResultEvent, AGUIToolCallStartEvent, AGUIToolDefinition } from "./agui-types.cjs";
@@ -55,4 +55,4 @@ import { MCPMock } from "./mcp-mock.cjs";
55
55
  import { VectorMock } from "./vector-mock.cjs";
56
56
  import { JsonRpcDispatcherOptions, JsonRpcResponse, MethodHandler, createJsonRpcDispatcher } from "./jsonrpc.cjs";
57
57
  import { MockSuite, MockSuiteOptions, createMockSuite } from "./suite.cjs";
58
- export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, type AudioResponse, type ChaosAction, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type Fixture, type FixtureBlock, type FixtureFile, type FixtureFileContentWithToolCallsResponse, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, type FixtureMatch, type FixtureOpts, type FixtureResponse, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, Journal, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, type MatchFixtureDiagnostic, type MethodHandler, type MetricsRegistry, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, type RawJSONResponse, type RecordConfig, type RecordProviderKey, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesSSEEvent, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, VEO_VIDEO_MAX_ENTRIES, type ValidationResult, type VectorCollection, type VectorEntry, VectorMock, type VectorMockOptions, type VectorQuery, VeoVideoJobMap, type VideoResponse, VideoStateMap, WebSocketConnection, applyChaos, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBedrock, handleBedrockStream, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleEmbeddings, handleFal, handleFalQueue, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixturesFromDir, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, resolveFixtureBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
58
+ export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, type ApiKeyAuthConfig, type AudioResponse, type ChaosAction, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type Fixture, type FixtureBlock, type FixtureFile, type FixtureFileContentWithToolCallsResponse, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, type FixtureMatch, type FixtureOpts, type FixtureResponse, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, Journal, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, type MatchFixtureDiagnostic, type MethodHandler, type MetricsRegistry, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, type RawJSONResponse, type RecordConfig, type RecordProviderKey, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesSSEEvent, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, VEO_VIDEO_MAX_ENTRIES, type ValidationResult, type VectorCollection, type VectorEntry, VectorMock, type VectorMockOptions, type VectorQuery, VeoVideoJobMap, type VideoResponse, VideoStateMap, WebSocketConnection, applyChaos, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBedrock, handleBedrockStream, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleEmbeddings, handleFal, handleFalQueue, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixturesFromDir, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, resolveFixtureBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { DEFAULT_TEST_ID } from "./constants.js";
2
2
  import { Journal } from "./journal.js";
3
3
  import { LogLevel, Logger } from "./logger.js";
4
4
  import { MetricsRegistry, createMetricsRegistry, normalizePathLabel } from "./metrics.js";
5
- import { AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureFile, FixtureFileContentWithToolCallsResponse, FixtureFileEntry, FixtureFileResponse, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, ImageItem, ImageResponse, JournalEntry, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, ResponseOverrides, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse } from "./types.js";
5
+ import { ApiKeyAuthConfig, AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureFile, FixtureFileContentWithToolCallsResponse, FixtureFileEntry, FixtureFileResponse, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, ImageItem, ImageResponse, JournalEntry, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, ResponseOverrides, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse } from "./types.js";
6
6
  import { A2AAgentDefinition, A2AArtifact, A2AMessage, A2AMockOptions, A2APart, A2ARole, A2AStreamEvent, A2ATask, A2ATaskResponse, A2ATaskState } from "./a2a-types.js";
7
7
  import { A2AMock } from "./a2a-mock.js";
8
8
  import { AGUIActivityDeltaEvent, AGUIActivitySnapshotEvent, AGUIBaseEvent, AGUICustomEvent, AGUIEvent, AGUIEventType, AGUIFixture, AGUIFixtureMatch, AGUIInterrupt, AGUIMessage, AGUIMessageContentPart, AGUIMessageRole, AGUIMessagesSnapshotEvent, AGUIMockOptions, AGUIRawEvent, AGUIReasoningEncryptedValueEvent, AGUIReasoningEncryptedValueSubtype, AGUIReasoningEndEvent, AGUIReasoningMessageChunkEvent, AGUIReasoningMessageContentEvent, AGUIReasoningMessageEndEvent, AGUIReasoningMessageStartEvent, AGUIReasoningStartEvent, AGUIRecordConfig, AGUIResumeEntry, AGUIRunAgentInput, AGUIRunErrorEvent, AGUIRunFinishedEvent, AGUIRunFinishedOutcome, AGUIRunStartedEvent, AGUIStateDeltaEvent, AGUIStateSnapshotEvent, AGUIStepFinishedEvent, AGUIStepStartedEvent, AGUITextMessageChunkEvent, AGUITextMessageContentEvent, AGUITextMessageEndEvent, AGUITextMessageRole, AGUITextMessageStartEvent, AGUIThinkingEndEvent, AGUIThinkingStartEvent, AGUIThinkingTextMessageContentEvent, AGUIThinkingTextMessageEndEvent, AGUIThinkingTextMessageStartEvent, AGUIToolCall, AGUIToolCallArgsEvent, AGUIToolCallChunkEvent, AGUIToolCallEndEvent, AGUIToolCallResultEvent, AGUIToolCallStartEvent, AGUIToolDefinition } from "./agui-types.js";
@@ -55,4 +55,4 @@ import { MCPMock } from "./mcp-mock.js";
55
55
  import { VectorMock } from "./vector-mock.js";
56
56
  import { JsonRpcDispatcherOptions, JsonRpcResponse, MethodHandler, createJsonRpcDispatcher } from "./jsonrpc.js";
57
57
  import { MockSuite, MockSuiteOptions, createMockSuite } from "./suite.js";
58
- export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, type AudioResponse, type ChaosAction, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type Fixture, type FixtureBlock, type FixtureFile, type FixtureFileContentWithToolCallsResponse, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, type FixtureMatch, type FixtureOpts, type FixtureResponse, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, Journal, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, type MatchFixtureDiagnostic, type MethodHandler, type MetricsRegistry, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, type RawJSONResponse, type RecordConfig, type RecordProviderKey, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesSSEEvent, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, VEO_VIDEO_MAX_ENTRIES, type ValidationResult, type VectorCollection, type VectorEntry, VectorMock, type VectorMockOptions, type VectorQuery, VeoVideoJobMap, type VideoResponse, VideoStateMap, WebSocketConnection, applyChaos, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBedrock, handleBedrockStream, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleEmbeddings, handleFal, handleFalQueue, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixturesFromDir, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, resolveFixtureBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
58
+ export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, type ApiKeyAuthConfig, type AudioResponse, type ChaosAction, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type Fixture, type FixtureBlock, type FixtureFile, type FixtureFileContentWithToolCallsResponse, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, type FixtureMatch, type FixtureOpts, type FixtureResponse, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, Journal, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, type MatchFixtureDiagnostic, type MethodHandler, type MetricsRegistry, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, type RawJSONResponse, type RecordConfig, type RecordProviderKey, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesSSEEvent, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, VEO_VIDEO_MAX_ENTRIES, type ValidationResult, type VectorCollection, type VectorEntry, VectorMock, type VectorMockOptions, type VectorQuery, VeoVideoJobMap, type VideoResponse, VideoStateMap, WebSocketConnection, applyChaos, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBedrock, handleBedrockStream, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleEmbeddings, handleFal, handleFalQueue, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixturesFromDir, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, resolveFixtureBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
package/dist/llmock.cjs CHANGED
@@ -12,8 +12,10 @@ var LLMock = class LLMock {
12
12
  mounts = [];
13
13
  serverInstance = null;
14
14
  options;
15
- constructor(options) {
15
+ resolvedInboundAuth;
16
+ constructor(options, resolvedInboundAuth) {
16
17
  this.options = options ?? {};
18
+ this.resolvedInboundAuth = resolvedInboundAuth;
17
19
  }
18
20
  addFixture(fixture) {
19
21
  this.fixtures.push(fixture);
@@ -323,11 +325,15 @@ var LLMock = class LLMock {
323
325
  }
324
326
  async start() {
325
327
  if (this.serverInstance) throw new Error("Server already started");
326
- this.serverInstance = await require_server.createServer(this.fixtures, this.options, this.mounts, {
328
+ this.serverInstance = await (this.resolvedInboundAuth ? require_server.createServerWithResolvedAuth(this.fixtures, this.options, this.resolvedInboundAuth, this.mounts, {
327
329
  search: this.searchFixtures,
328
330
  rerank: this.rerankFixtures,
329
331
  moderation: this.moderationFixtures
330
- });
332
+ }) : require_server.createServer(this.fixtures, this.options, this.mounts, {
333
+ search: this.searchFixtures,
334
+ rerank: this.rerankFixtures,
335
+ moderation: this.moderationFixtures
336
+ }));
331
337
  return this.serverInstance.url;
332
338
  }
333
339
  async stop() {
@@ -360,7 +366,12 @@ var LLMock = class LLMock {
360
366
  return instance;
361
367
  }
362
368
  };
369
+ /** @internal Configuration startup preserves a policy resolved from the selected source. */
370
+ function createLLMockWithResolvedAuth(options, resolvedAuth) {
371
+ return new LLMock(options, resolvedAuth);
372
+ }
363
373
 
364
374
  //#endregion
365
375
  exports.LLMock = LLMock;
376
+ exports.createLLMockWithResolvedAuth = createLLMockWithResolvedAuth;
366
377
  //# sourceMappingURL=llmock.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"llmock.cjs","names":["loadFixtureFile","loadFixturesFromDir","entryToFixture","validateFixtures","normalizeResponse","imageResponseToFalJson","videoResponseToFalJson","createServer"],"sources":["../src/llmock.ts"],"sourcesContent":["import type {\n AudioResponse,\n ChaosConfig,\n EmbeddingFixtureOpts,\n FalQueueOpts,\n Fixture,\n FixtureFileEntry,\n FixtureFileResponse,\n FixtureMatch,\n FixtureOpts,\n FixtureResponse,\n ImageResponse,\n MockServerOptions,\n Mountable,\n RecordConfig,\n ResponseFactory,\n TranscriptionResponse,\n VideoResponse,\n} from \"./types.js\";\nimport { createServer, type ServerInstance } from \"./server.js\";\nimport {\n loadFixtureFile,\n loadFixturesFromDir,\n entryToFixture,\n normalizeResponse,\n validateFixtures,\n} from \"./fixture-loader.js\";\nimport { Journal } from \"./journal.js\";\nimport type { SearchFixture, SearchResult } from \"./search.js\";\nimport type { RerankFixture, RerankResult } from \"./rerank.js\";\nimport type { ModerationFixture, ModerationResult } from \"./moderation.js\";\nimport { falJobs } from \"./fal-audio.js\";\nimport { falQueueStates, imageResponseToFalJson, videoResponseToFalJson } from \"./fal.js\";\n\nexport class LLMock {\n private fixtures: Fixture[] = [];\n private searchFixtures: SearchFixture[] = [];\n private rerankFixtures: RerankFixture[] = [];\n private moderationFixtures: ModerationFixture[] = [];\n private mounts: Array<{ path: string; handler: Mountable }> = [];\n private serverInstance: ServerInstance | null = null;\n private options: MockServerOptions;\n\n constructor(options?: MockServerOptions) {\n this.options = options ?? {};\n }\n\n // ---- Fixture management ----\n\n addFixture(fixture: Fixture): this {\n this.fixtures.push(fixture);\n return this;\n }\n\n addFixtures(fixtures: Fixture[]): this {\n this.fixtures.push(...fixtures);\n return this;\n }\n\n prependFixture(fixture: Fixture): this {\n this.fixtures.unshift(fixture);\n return this;\n }\n\n getFixtures(): readonly Fixture[] {\n return this.fixtures;\n }\n\n loadFixtureFile(filePath: string): this {\n this.fixtures.push(...loadFixtureFile(filePath));\n return this;\n }\n\n loadFixtureDir(dirPath: string): this {\n this.fixtures.push(...loadFixturesFromDir(dirPath));\n return this;\n }\n\n /**\n * Add fixtures from a JSON string or pre-parsed array of fixture entries.\n * Validates all fixtures and throws if any have severity \"error\".\n */\n addFixturesFromJSON(input: string | FixtureFileEntry[]): this {\n let entries: FixtureFileEntry[];\n if (typeof input === \"string\") {\n try {\n entries = JSON.parse(input);\n } catch (err) {\n throw new Error(\n `addFixturesFromJSON: invalid JSON — ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n } else {\n entries = input;\n }\n const converted = entries.map((e) => entryToFixture(e));\n const issues = validateFixtures(converted);\n const errors = issues.filter((i) => i.severity === \"error\");\n if (errors.length > 0) {\n throw new Error(`Fixture validation failed: ${JSON.stringify(errors)}`);\n }\n this.fixtures.push(...converted);\n return this;\n }\n\n // Uses length = 0 to preserve array reference identity — the running\n // server reads this same array on every request.\n clearFixtures(): this {\n this.fixtures.length = 0;\n return this;\n }\n\n // ---- Convenience ----\n\n on(\n match: FixtureMatch,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.addFixture({\n match,\n response: typeof response === \"function\" ? response : normalizeResponse(response),\n ...opts,\n });\n }\n\n onMessage(\n pattern: string | RegExp,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ userMessage: pattern }, response, opts);\n }\n\n onEmbedding(\n pattern: string | RegExp,\n response: FixtureFileResponse | ResponseFactory,\n opts?: EmbeddingFixtureOpts,\n ): this {\n return this.on({ inputText: pattern }, response, opts);\n }\n\n onJsonOutput(pattern: string | RegExp, jsonContent: object | string, opts?: FixtureOpts): this {\n const content = typeof jsonContent === \"string\" ? jsonContent : JSON.stringify(jsonContent);\n return this.on({ userMessage: pattern, responseFormat: \"json_object\" }, { content }, opts);\n }\n\n onToolCall(\n name: string,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ toolName: name }, response, opts);\n }\n\n onToolResult(\n id: string,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ toolCallId: id }, response, opts);\n }\n\n onTurn(\n turn: number,\n pattern: string | RegExp,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ userMessage: pattern, turnIndex: turn }, response, opts);\n }\n\n onImage(prompt: string | RegExp, response: ImageResponse): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"image\" },\n response,\n });\n }\n\n onSpeech(input: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: input, endpoint: \"speech\" },\n response,\n });\n }\n\n onTranscription(response: TranscriptionResponse): this {\n return this.addFixture({\n match: { endpoint: \"transcription\" },\n response,\n });\n }\n\n onTranslation(response: TranscriptionResponse): this {\n return this.addFixture({\n match: { endpoint: \"translation\" },\n response,\n });\n }\n\n onVideo(prompt: string | RegExp, response: VideoResponse): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"video\" },\n response,\n });\n }\n\n onAudio(input: string | RegExp, response: AudioResponse): this {\n return this.addFixture({ match: { userMessage: input }, response });\n }\n\n onSoundEffect(text: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: text, endpoint: \"audio-gen\" },\n response,\n });\n }\n\n onMusic(prompt: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"audio-gen\" },\n response,\n });\n }\n\n onElevenLabsTTS(text: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: text, endpoint: \"elevenlabs-tts\" },\n response,\n });\n }\n\n onFalAudio(prompt: string | RegExp, response: AudioResponse, model?: string): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"fal-audio\", ...(model ? { model } : {}) },\n response,\n });\n }\n\n // fal.queue.* is the dominant client API; onFalRun is a sync alias.\n //\n // `opts.billableUnits` rides through to the completed `queue-result`\n // response's `x-fal-billable-units` header (emitted alongside\n // `x-fal-request-id`), letting consumers like `@tanstack/ai-fal` surface a\n // billed-units value on replay. Omit it to preserve the header-less default.\n onFalQueue(modelOrPrompt: string | RegExp, response: unknown, opts?: FalQueueOpts): this {\n const { billableUnits, ...fixtureOpts } = opts ?? {};\n return this.addFixture({\n match: { model: modelOrPrompt, endpoint: \"fal\" },\n response: { json: response, ...(billableUnits != null ? { billableUnits } : {}) },\n ...fixtureOpts,\n });\n }\n\n onFalRun(modelOrPrompt: string | RegExp, response: unknown, opts?: FalQueueOpts): this {\n return this.onFalQueue(modelOrPrompt, response, opts);\n }\n\n /**\n * Register a fal.ai image fixture. Wraps an `ImageResponse` (the shape used\n * by `onImage` and OpenAI/Azure image fixtures) into fal's image envelope\n * before storing it as a `RawJSONResponse`. Defaults `width`/`height` to\n * 1024 when the fixture's `ImageItem` doesn't carry them.\n */\n onFalImage(modelOrPrompt: string | RegExp, response: ImageResponse, opts?: FalQueueOpts): this {\n return this.onFalQueue(modelOrPrompt, imageResponseToFalJson(response), opts);\n }\n\n /**\n * Register a fal.ai video fixture. Wraps a `VideoResponse` into fal's video\n * envelope (`{ video: { url, content_type, file_name, file_size }, seed }`)\n * before storing it as a `RawJSONResponse`.\n */\n onFalVideo(modelOrPrompt: string | RegExp, response: VideoResponse, opts?: FalQueueOpts): this {\n return this.onFalQueue(modelOrPrompt, videoResponseToFalJson(response), opts);\n }\n\n // ---- Service mock convenience methods ----\n\n onSearch(pattern: string | RegExp, results: SearchResult[]): this {\n this.searchFixtures.push({ match: pattern, results });\n return this;\n }\n\n onRerank(pattern: string | RegExp, results: RerankResult[]): this {\n this.rerankFixtures.push({ match: pattern, results });\n return this;\n }\n\n onModerate(pattern: string | RegExp, result: ModerationResult): this {\n this.moderationFixtures.push({ match: pattern, result });\n return this;\n }\n\n /**\n * Queue a one-shot error that will be returned for the next matching\n * request, then automatically removed. Implemented as an internal fixture\n * with a `predicate` that always matches (so it fires first) and spliced\n * at the front of the fixture list.\n */\n nextRequestError(\n status: number,\n errorBody?: { message?: string; type?: string; code?: string },\n ): this {\n const errorResponse: FixtureResponse = {\n error: {\n message: errorBody?.message ?? \"Injected error\",\n type: errorBody?.type ?? \"server_error\",\n code: errorBody?.code,\n },\n status,\n };\n // An injected error is only a valid response for endpoints that can carry\n // an error envelope. Mirror the router's endpoint-compat table\n // (matchFixtureDiagnostic in router.ts): error responses are compatible\n // with chat / embedding / realtime* / fal and with requests that carry no\n // endpoint type, but NOT with multimedia endpoints (image, speech, video,\n // transcription, …). Gating consumption on this prevents an incompatible\n // request from matching the predicate and splicing — and thereby\n // destroying — a one-shot error intended for a different endpoint before\n // the router's own compat check would have skipped it.\n const errorEndpointCompatible = (req: import(\"./types.js\").ChatCompletionRequest) => {\n const reqEndpoint = req._endpointType as string | undefined;\n if (\n reqEndpoint === undefined ||\n reqEndpoint === \"chat\" ||\n reqEndpoint === \"embedding\" ||\n reqEndpoint.startsWith(\"realtime\") ||\n reqEndpoint === \"fal\"\n ) {\n return true;\n }\n return false;\n };\n const fixture: Fixture = {\n match: { predicate: errorEndpointCompatible },\n response: errorResponse,\n };\n // Insert at front so it matches before everything else\n this.fixtures.unshift(fixture);\n // Remove after first match — the journal records it so tests can assert.\n // Only consume (and splice) when the request endpoint is compatible; an\n // incompatible request returns false here, falls through to other\n // fixtures, and leaves this error pending for its intended endpoint.\n const original = fixture.match.predicate!;\n fixture.match.predicate = (req) => {\n const result = original(req);\n if (result) {\n // Remove synchronously on first match to prevent race conditions\n const idx = this.fixtures.indexOf(fixture);\n if (idx !== -1) this.fixtures.splice(idx, 1);\n }\n return result;\n };\n return this;\n }\n\n // ---- Mounts ----\n\n mount(path: string, handler: Mountable): this {\n this.mounts.push({ path, handler });\n\n // If server is already running, wire up journal, registry, and baseUrl immediately\n // so late mounts behave identically to pre-start mounts.\n if (this.serverInstance) {\n if (handler.setJournal) handler.setJournal(this.serverInstance.journal);\n if (handler.setBaseUrl) handler.setBaseUrl(this.serverInstance.url + path);\n const registry = this.serverInstance.defaults.registry;\n if (registry && handler.setRegistry) handler.setRegistry(registry);\n }\n\n return this;\n }\n\n // ---- Journal proxies ----\n\n getRequests(): import(\"./types.js\").JournalEntry[] {\n return this.journal.getAll();\n }\n\n getLastRequest(): import(\"./types.js\").JournalEntry | null {\n return this.journal.getLast();\n }\n\n clearRequests(): void {\n this.journal.clear();\n }\n\n resetMatchCounts(testId?: string): this {\n if (this.serverInstance) {\n this.serverInstance.journal.clearMatchCounts(testId);\n }\n return this;\n }\n\n // ---- Chaos ----\n\n setChaos(config: ChaosConfig): this {\n this.options.chaos = config;\n return this;\n }\n\n clearChaos(): this {\n delete this.options.chaos;\n return this;\n }\n\n // ---- Recording ----\n\n enableRecording(config: RecordConfig): this {\n this.options.record = config;\n return this;\n }\n\n disableRecording(): this {\n delete this.options.record;\n return this;\n }\n\n // ---- Reset ----\n\n reset(): this {\n this.clearFixtures();\n this.searchFixtures.length = 0;\n this.rerankFixtures.length = 0;\n this.moderationFixtures.length = 0;\n falJobs.clear();\n falQueueStates.clear();\n if (this.serverInstance) {\n this.serverInstance.journal.clear();\n this.serverInstance.videoStates.clear();\n this.serverInstance.openRouterVideoJobs.clear();\n }\n return this;\n }\n\n // ---- Server lifecycle ----\n\n async start(): Promise<string> {\n if (this.serverInstance) {\n throw new Error(\"Server already started\");\n }\n this.serverInstance = await createServer(this.fixtures, this.options, this.mounts, {\n search: this.searchFixtures,\n rerank: this.rerankFixtures,\n moderation: this.moderationFixtures,\n });\n return this.serverInstance.url;\n }\n\n async stop(): Promise<void> {\n if (!this.serverInstance) {\n throw new Error(\"Server not started\");\n }\n const { server } = this.serverInstance;\n await new Promise<void>((resolve, reject) => {\n server.close((err: Error | undefined) => (err ? reject(err) : resolve()));\n });\n this.serverInstance = null;\n }\n\n // ---- Accessors ----\n\n get journal(): Journal {\n if (!this.serverInstance) {\n throw new Error(\"Server not started\");\n }\n return this.serverInstance.journal;\n }\n\n get url(): string {\n if (!this.serverInstance) {\n throw new Error(\"Server not started\");\n }\n return this.serverInstance.url;\n }\n\n get baseUrl(): string {\n return this.url;\n }\n\n get port(): number {\n const parsed = new URL(this.url); // this.url throws if not started\n if (!parsed.port) {\n throw new Error(`Server URL has no explicit port: ${this.url}`);\n }\n return parseInt(parsed.port, 10);\n }\n\n // ---- Static factory ----\n\n static async create(options?: MockServerOptions): Promise<LLMock> {\n const instance = new LLMock(options);\n await instance.start();\n return instance;\n }\n}\n"],"mappings":";;;;;;AAkCA,IAAa,SAAb,MAAa,OAAO;CAClB,AAAQ,WAAsB,EAAE;CAChC,AAAQ,iBAAkC,EAAE;CAC5C,AAAQ,iBAAkC,EAAE;CAC5C,AAAQ,qBAA0C,EAAE;CACpD,AAAQ,SAAsD,EAAE;CAChE,AAAQ,iBAAwC;CAChD,AAAQ;CAER,YAAY,SAA6B;AACvC,OAAK,UAAU,WAAW,EAAE;;CAK9B,WAAW,SAAwB;AACjC,OAAK,SAAS,KAAK,QAAQ;AAC3B,SAAO;;CAGT,YAAY,UAA2B;AACrC,OAAK,SAAS,KAAK,GAAG,SAAS;AAC/B,SAAO;;CAGT,eAAe,SAAwB;AACrC,OAAK,SAAS,QAAQ,QAAQ;AAC9B,SAAO;;CAGT,cAAkC;AAChC,SAAO,KAAK;;CAGd,gBAAgB,UAAwB;AACtC,OAAK,SAAS,KAAK,GAAGA,uCAAgB,SAAS,CAAC;AAChD,SAAO;;CAGT,eAAe,SAAuB;AACpC,OAAK,SAAS,KAAK,GAAGC,2CAAoB,QAAQ,CAAC;AACnD,SAAO;;;;;;CAOT,oBAAoB,OAA0C;EAC5D,IAAI;AACJ,MAAI,OAAO,UAAU,SACnB,KAAI;AACF,aAAU,KAAK,MAAM,MAAM;WACpB,KAAK;AACZ,SAAM,IAAI,MACR,uCAAuC,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,GACxF;;MAGH,WAAU;EAEZ,MAAM,YAAY,QAAQ,KAAK,MAAMC,sCAAe,EAAE,CAAC;EAEvD,MAAM,SADSC,wCAAiB,UAAU,CACpB,QAAQ,MAAM,EAAE,aAAa,QAAQ;AAC3D,MAAI,OAAO,SAAS,EAClB,OAAM,IAAI,MAAM,8BAA8B,KAAK,UAAU,OAAO,GAAG;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AW;AAC3C,UAAO,OAAO,QAA4B,MAAM,OAAO,IAAI,GAAG,SAAS,CAAE;IACzE;AACF,OAAK,iBAAiB;;CAKxB,IAAI,UAAmB;AACrB,MAAI,CAAC,KAAK,eACR,OAAM,IAAI,MAAM,qBAAqB;AAEvC,SAAO,KAAK,eAAe;;CAG7B,IAAI,MAAc;AAChB,MAAI,CAAC,KAAK,eACR,OAAM,IAAI,MAAM,qBAAqB;AAEvC,SAAO,KAAK,eAAe;;CAG7B,IAAI,UAAkB;AACpB,SAAO,KAAK;;CAGd,IAAI,OAAe;EACjB,MAAM,SAAS,IAAI,IAAI,KAAK,IAAI;AAChC,MAAI,CAAC,OAAO,KACV,OAAM,IAAI,MAAM,oCAAoC,KAAK,MAAM;AAEjE,SAAO,SAAS,OAAO,MAAM,GAAG;;CAKlC,aAAa,OAAO,SAA8C;EAChE,MAAM,WAAW,IAAI,OAAO,QAAQ;AACpC,QAAM,SAAS,OAAO;AACtB,SAAO"}
1
+ {"version":3,"file":"llmock.cjs","names":["loadFixtureFile","loadFixturesFromDir","entryToFixture","validateFixtures","normalizeResponse","imageResponseToFalJson","videoResponseToFalJson","createServerWithResolvedAuth","createServer"],"sources":["../src/llmock.ts"],"sourcesContent":["import type {\n AudioResponse,\n ChaosConfig,\n EmbeddingFixtureOpts,\n FalQueueOpts,\n Fixture,\n FixtureFileEntry,\n FixtureFileResponse,\n FixtureMatch,\n FixtureOpts,\n FixtureResponse,\n ImageResponse,\n MockServerOptions,\n Mountable,\n RecordConfig,\n ResponseFactory,\n TranscriptionResponse,\n VideoResponse,\n} from \"./types.js\";\nimport { createServer, createServerWithResolvedAuth, type ServerInstance } from \"./server.js\";\nimport type { ResolvedInboundAuth } from \"./api-key-auth.js\";\nimport {\n loadFixtureFile,\n loadFixturesFromDir,\n entryToFixture,\n normalizeResponse,\n validateFixtures,\n} from \"./fixture-loader.js\";\nimport { Journal } from \"./journal.js\";\nimport type { SearchFixture, SearchResult } from \"./search.js\";\nimport type { RerankFixture, RerankResult } from \"./rerank.js\";\nimport type { ModerationFixture, ModerationResult } from \"./moderation.js\";\nimport { falJobs } from \"./fal-audio.js\";\nimport { falQueueStates, imageResponseToFalJson, videoResponseToFalJson } from \"./fal.js\";\n\nexport class LLMock {\n private fixtures: Fixture[] = [];\n private searchFixtures: SearchFixture[] = [];\n private rerankFixtures: RerankFixture[] = [];\n private moderationFixtures: ModerationFixture[] = [];\n private mounts: Array<{ path: string; handler: Mountable }> = [];\n private serverInstance: ServerInstance | null = null;\n private options: MockServerOptions;\n private readonly resolvedInboundAuth?: ResolvedInboundAuth;\n\n constructor(options?: MockServerOptions, resolvedInboundAuth?: ResolvedInboundAuth) {\n this.options = options ?? {};\n this.resolvedInboundAuth = resolvedInboundAuth;\n }\n\n // ---- Fixture management ----\n\n addFixture(fixture: Fixture): this {\n this.fixtures.push(fixture);\n return this;\n }\n\n addFixtures(fixtures: Fixture[]): this {\n this.fixtures.push(...fixtures);\n return this;\n }\n\n prependFixture(fixture: Fixture): this {\n this.fixtures.unshift(fixture);\n return this;\n }\n\n getFixtures(): readonly Fixture[] {\n return this.fixtures;\n }\n\n loadFixtureFile(filePath: string): this {\n this.fixtures.push(...loadFixtureFile(filePath));\n return this;\n }\n\n loadFixtureDir(dirPath: string): this {\n this.fixtures.push(...loadFixturesFromDir(dirPath));\n return this;\n }\n\n /**\n * Add fixtures from a JSON string or pre-parsed array of fixture entries.\n * Validates all fixtures and throws if any have severity \"error\".\n */\n addFixturesFromJSON(input: string | FixtureFileEntry[]): this {\n let entries: FixtureFileEntry[];\n if (typeof input === \"string\") {\n try {\n entries = JSON.parse(input);\n } catch (err) {\n throw new Error(\n `addFixturesFromJSON: invalid JSON — ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n } else {\n entries = input;\n }\n const converted = entries.map((e) => entryToFixture(e));\n const issues = validateFixtures(converted);\n const errors = issues.filter((i) => i.severity === \"error\");\n if (errors.length > 0) {\n throw new Error(`Fixture validation failed: ${JSON.stringify(errors)}`);\n }\n this.fixtures.push(...converted);\n return this;\n }\n\n // Uses length = 0 to preserve array reference identity — the running\n // server reads this same array on every request.\n clearFixtures(): this {\n this.fixtures.length = 0;\n return this;\n }\n\n // ---- Convenience ----\n\n on(\n match: FixtureMatch,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.addFixture({\n match,\n response: typeof response === \"function\" ? response : normalizeResponse(response),\n ...opts,\n });\n }\n\n onMessage(\n pattern: string | RegExp,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ userMessage: pattern }, response, opts);\n }\n\n onEmbedding(\n pattern: string | RegExp,\n response: FixtureFileResponse | ResponseFactory,\n opts?: EmbeddingFixtureOpts,\n ): this {\n return this.on({ inputText: pattern }, response, opts);\n }\n\n onJsonOutput(pattern: string | RegExp, jsonContent: object | string, opts?: FixtureOpts): this {\n const content = typeof jsonContent === \"string\" ? jsonContent : JSON.stringify(jsonContent);\n return this.on({ userMessage: pattern, responseFormat: \"json_object\" }, { content }, opts);\n }\n\n onToolCall(\n name: string,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ toolName: name }, response, opts);\n }\n\n onToolResult(\n id: string,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ toolCallId: id }, response, opts);\n }\n\n onTurn(\n turn: number,\n pattern: string | RegExp,\n response: FixtureFileResponse | ResponseFactory,\n opts?: FixtureOpts,\n ): this {\n return this.on({ userMessage: pattern, turnIndex: turn }, response, opts);\n }\n\n onImage(prompt: string | RegExp, response: ImageResponse): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"image\" },\n response,\n });\n }\n\n onSpeech(input: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: input, endpoint: \"speech\" },\n response,\n });\n }\n\n onTranscription(response: TranscriptionResponse): this {\n return this.addFixture({\n match: { endpoint: \"transcription\" },\n response,\n });\n }\n\n onTranslation(response: TranscriptionResponse): this {\n return this.addFixture({\n match: { endpoint: \"translation\" },\n response,\n });\n }\n\n onVideo(prompt: string | RegExp, response: VideoResponse): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"video\" },\n response,\n });\n }\n\n onAudio(input: string | RegExp, response: AudioResponse): this {\n return this.addFixture({ match: { userMessage: input }, response });\n }\n\n onSoundEffect(text: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: text, endpoint: \"audio-gen\" },\n response,\n });\n }\n\n onMusic(prompt: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"audio-gen\" },\n response,\n });\n }\n\n onElevenLabsTTS(text: string | RegExp, response: AudioResponse): this {\n return this.addFixture({\n match: { userMessage: text, endpoint: \"elevenlabs-tts\" },\n response,\n });\n }\n\n onFalAudio(prompt: string | RegExp, response: AudioResponse, model?: string): this {\n return this.addFixture({\n match: { userMessage: prompt, endpoint: \"fal-audio\", ...(model ? { model } : {}) },\n response,\n });\n }\n\n // fal.queue.* is the dominant client API; onFalRun is a sync alias.\n //\n // `opts.billableUnits` rides through to the completed `queue-result`\n // response's `x-fal-billable-units` header (emitted alongside\n // `x-fal-request-id`), letting consumers like `@tanstack/ai-fal` surface a\n // billed-units value on replay. Omit it to preserve the header-less default.\n onFalQueue(modelOrPrompt: string | RegExp, response: unknown, opts?: FalQueueOpts): this {\n const { billableUnits, ...fixtureOpts } = opts ?? {};\n return this.addFixture({\n match: { model: modelOrPrompt, endpoint: \"fal\" },\n response: { json: response, ...(billableUnits != null ? { billableUnits } : {}) },\n ...fixtureOpts,\n });\n }\n\n onFalRun(modelOrPrompt: string | RegExp, response: unknown, opts?: FalQueueOpts): this {\n return this.onFalQueue(modelOrPrompt, response, opts);\n }\n\n /**\n * Register a fal.ai image fixture. Wraps an `ImageResponse` (the shape used\n * by `onImage` and OpenAI/Azure image fixtures) into fal's image envelope\n * before storing it as a `RawJSONResponse`. Defaults `width`/`height` to\n * 1024 when the fixture's `ImageItem` doesn't carry them.\n */\n onFalImage(modelOrPrompt: string | RegExp, response: ImageResponse, opts?: FalQueueOpts): this {\n return this.onFalQueue(modelOrPrompt, imageResponseToFalJson(response), opts);\n }\n\n /**\n * Register a fal.ai video fixture. Wraps a `VideoResponse` into fal's video\n * envelope (`{ video: { url, content_type, file_name, file_size }, seed }`)\n * before storing it as a `RawJSONResponse`.\n */\n onFalVideo(modelOrPrompt: string | RegExp, response: VideoResponse, opts?: FalQueueOpts): this {\n return this.onFalQueue(modelOrPrompt, videoResponseToFalJson(response), opts);\n }\n\n // ---- Service mock convenience methods ----\n\n onSearch(pattern: string | RegExp, results: SearchResult[]): this {\n this.searchFixtures.push({ match: pattern, results });\n return this;\n }\n\n onRerank(pattern: string | RegExp, results: RerankResult[]): this {\n this.rerankFixtures.push({ match: pattern, results });\n return this;\n }\n\n onModerate(pattern: string | RegExp, result: ModerationResult): this {\n this.moderationFixtures.push({ match: pattern, result });\n return this;\n }\n\n /**\n * Queue a one-shot error that will be returned for the next matching\n * request, then automatically removed. Implemented as an internal fixture\n * with a `predicate` that always matches (so it fires first) and spliced\n * at the front of the fixture list.\n */\n nextRequestError(\n status: number,\n errorBody?: { message?: string; type?: string; code?: string },\n ): this {\n const errorResponse: FixtureResponse = {\n error: {\n message: errorBody?.message ?? \"Injected error\",\n type: errorBody?.type ?? \"server_error\",\n code: errorBody?.code,\n },\n status,\n };\n // An injected error is only a valid response for endpoints that can carry\n // an error envelope. Mirror the router's endpoint-compat table\n // (matchFixtureDiagnostic in router.ts): error responses are compatible\n // with chat / embedding / realtime* / fal and with requests that carry no\n // endpoint type, but NOT with multimedia endpoints (image, speech, video,\n // transcription, …). Gating consumption on this prevents an incompatible\n // request from matching the predicate and splicing — and thereby\n // destroying — a one-shot error intended for a different endpoint before\n // the router's own compat check would have skipped it.\n const errorEndpointCompatible = (req: import(\"./types.js\").ChatCompletionRequest) => {\n const reqEndpoint = req._endpointType as string | undefined;\n if (\n reqEndpoint === undefined ||\n reqEndpoint === \"chat\" ||\n reqEndpoint === \"embedding\" ||\n reqEndpoint.startsWith(\"realtime\") ||\n reqEndpoint === \"fal\"\n ) {\n return true;\n }\n return false;\n };\n const fixture: Fixture = {\n match: { predicate: errorEndpointCompatible },\n response: errorResponse,\n };\n // Insert at front so it matches before everything else\n this.fixtures.unshift(fixture);\n // Remove after first match — the journal records it so tests can assert.\n // Only consume (and splice) when the request endpoint is compatible; an\n // incompatible request returns false here, falls through to other\n // fixtures, and leaves this error pending for its intended endpoint.\n const original = fixture.match.predicate!;\n fixture.match.predicate = (req) => {\n const result = original(req);\n if (result) {\n // Remove synchronously on first match to prevent race conditions\n const idx = this.fixtures.indexOf(fixture);\n if (idx !== -1) this.fixtures.splice(idx, 1);\n }\n return result;\n };\n return this;\n }\n\n // ---- Mounts ----\n\n mount(path: string, handler: Mountable): this {\n this.mounts.push({ path, handler });\n\n // If server is already running, wire up journal, registry, and baseUrl immediately\n // so late mounts behave identically to pre-start mounts.\n if (this.serverInstance) {\n if (handler.setJournal) handler.setJournal(this.serverInstance.journal);\n if (handler.setBaseUrl) handler.setBaseUrl(this.serverInstance.url + path);\n const registry = this.serverInstance.defaults.registry;\n if (registry && handler.setRegistry) handler.setRegistry(registry);\n }\n\n return this;\n }\n\n // ---- Journal proxies ----\n\n getRequests(): import(\"./types.js\").JournalEntry[] {\n return this.journal.getAll();\n }\n\n getLastRequest(): import(\"./types.js\").JournalEntry | null {\n return this.journal.getLast();\n }\n\n clearRequests(): void {\n this.journal.clear();\n }\n\n resetMatchCounts(testId?: string): this {\n if (this.serverInstance) {\n this.serverInstance.journal.clearMatchCounts(testId);\n }\n return this;\n }\n\n // ---- Chaos ----\n\n setChaos(config: ChaosConfig): this {\n this.options.chaos = config;\n return this;\n }\n\n clearChaos(): this {\n delete this.options.chaos;\n return this;\n }\n\n // ---- Recording ----\n\n enableRecording(config: RecordConfig): this {\n this.options.record = config;\n return this;\n }\n\n disableRecording(): this {\n delete this.options.record;\n return this;\n }\n\n // ---- Reset ----\n\n reset(): this {\n this.clearFixtures();\n this.searchFixtures.length = 0;\n this.rerankFixtures.length = 0;\n this.moderationFixtures.length = 0;\n falJobs.clear();\n falQueueStates.clear();\n if (this.serverInstance) {\n this.serverInstance.journal.clear();\n this.serverInstance.videoStates.clear();\n this.serverInstance.openRouterVideoJobs.clear();\n }\n return this;\n }\n\n // ---- Server lifecycle ----\n\n async start(): Promise<string> {\n if (this.serverInstance) {\n throw new Error(\"Server already started\");\n }\n this.serverInstance = await (this.resolvedInboundAuth\n ? createServerWithResolvedAuth(\n this.fixtures,\n this.options,\n this.resolvedInboundAuth,\n this.mounts,\n {\n search: this.searchFixtures,\n rerank: this.rerankFixtures,\n moderation: this.moderationFixtures,\n },\n )\n : createServer(this.fixtures, this.options, this.mounts, {\n search: this.searchFixtures,\n rerank: this.rerankFixtures,\n moderation: this.moderationFixtures,\n }));\n return this.serverInstance.url;\n }\n\n async stop(): Promise<void> {\n if (!this.serverInstance) {\n throw new Error(\"Server not started\");\n }\n const { server } = this.serverInstance;\n await new Promise<void>((resolve, reject) => {\n server.close((err: Error | undefined) => (err ? reject(err) : resolve()));\n });\n this.serverInstance = null;\n }\n\n // ---- Accessors ----\n\n get journal(): Journal {\n if (!this.serverInstance) {\n throw new Error(\"Server not started\");\n }\n return this.serverInstance.journal;\n }\n\n get url(): string {\n if (!this.serverInstance) {\n throw new Error(\"Server not started\");\n }\n return this.serverInstance.url;\n }\n\n get baseUrl(): string {\n return this.url;\n }\n\n get port(): number {\n const parsed = new URL(this.url); // this.url throws if not started\n if (!parsed.port) {\n throw new Error(`Server URL has no explicit port: ${this.url}`);\n }\n return parseInt(parsed.port, 10);\n }\n\n // ---- Static factory ----\n\n static async create(options?: MockServerOptions): Promise<LLMock> {\n const instance = new LLMock(options);\n await instance.start();\n return instance;\n }\n}\n\n/** @internal Configuration startup preserves a policy resolved from the selected source. */\nexport function createLLMockWithResolvedAuth(\n options: MockServerOptions,\n res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