@copilotkit/aimock 1.40.0 → 1.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +28 -1
- package/README.md +5 -3
- package/dist/a2a-mock.cjs +18 -11
- package/dist/a2a-mock.cjs.map +1 -1
- package/dist/a2a-mock.d.cts +1 -0
- package/dist/a2a-mock.d.cts.map +1 -1
- package/dist/a2a-mock.d.ts +1 -0
- package/dist/a2a-mock.d.ts.map +1 -1
- package/dist/a2a-mock.js +18 -11
- package/dist/a2a-mock.js.map +1 -1
- package/dist/agui-handler.d.cts.map +1 -1
- package/dist/agui-handler.d.ts.map +1 -1
- package/dist/agui-mock.cjs +2 -0
- package/dist/agui-mock.cjs.map +1 -1
- package/dist/agui-mock.d.cts.map +1 -1
- package/dist/agui-mock.d.ts.map +1 -1
- package/dist/agui-mock.js +2 -0
- package/dist/agui-mock.js.map +1 -1
- package/dist/bedrock-converse.cjs +36 -2
- package/dist/bedrock-converse.cjs.map +1 -1
- package/dist/bedrock-converse.d.cts.map +1 -1
- package/dist/bedrock-converse.d.ts.map +1 -1
- package/dist/bedrock-converse.js +37 -3
- package/dist/bedrock-converse.js.map +1 -1
- package/dist/bedrock.cjs +50 -13
- package/dist/bedrock.cjs.map +1 -1
- package/dist/bedrock.d.cts.map +1 -1
- package/dist/bedrock.d.ts.map +1 -1
- package/dist/bedrock.js +51 -14
- package/dist/bedrock.js.map +1 -1
- package/dist/byteplus-video.cjs +954 -0
- package/dist/byteplus-video.cjs.map +1 -0
- package/dist/byteplus-video.d.cts +176 -0
- package/dist/byteplus-video.d.cts.map +1 -0
- package/dist/byteplus-video.d.ts +176 -0
- package/dist/byteplus-video.d.ts.map +1 -0
- package/dist/byteplus-video.js +947 -0
- package/dist/byteplus-video.js.map +1 -0
- package/dist/chaos.cjs +36 -7
- package/dist/chaos.cjs.map +1 -1
- package/dist/chaos.d.cts +8 -3
- package/dist/chaos.d.cts.map +1 -1
- package/dist/chaos.d.ts +8 -3
- package/dist/chaos.d.ts.map +1 -1
- package/dist/chaos.js +36 -8
- package/dist/chaos.js.map +1 -1
- package/dist/cli.cjs +5 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +5 -1
- package/dist/cli.js.map +1 -1
- package/dist/cohere.cjs +58 -5
- package/dist/cohere.cjs.map +1 -1
- package/dist/cohere.d.cts.map +1 -1
- package/dist/cohere.d.ts.map +1 -1
- package/dist/cohere.js +59 -6
- package/dist/cohere.js.map +1 -1
- package/dist/config-loader.d.cts.map +1 -1
- package/dist/elevenlabs-audio.cjs +36 -2
- package/dist/elevenlabs-audio.cjs.map +1 -1
- package/dist/elevenlabs-audio.d.cts.map +1 -1
- package/dist/elevenlabs-audio.d.ts.map +1 -1
- package/dist/elevenlabs-audio.js +37 -3
- package/dist/elevenlabs-audio.js.map +1 -1
- package/dist/embeddings.cjs +58 -3
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js +59 -4
- package/dist/embeddings.js.map +1 -1
- package/dist/fal-audio.cjs +38 -2
- package/dist/fal-audio.cjs.map +1 -1
- package/dist/fal-audio.d.cts.map +1 -1
- package/dist/fal-audio.d.ts.map +1 -1
- package/dist/fal-audio.js +39 -3
- package/dist/fal-audio.js.map +1 -1
- package/dist/fixture-loader.cjs +0 -0
- package/dist/fixture-loader.cjs.map +1 -1
- package/dist/fixture-loader.d.cts +9 -1
- package/dist/fixture-loader.d.cts.map +1 -1
- package/dist/fixture-loader.d.ts +9 -1
- package/dist/fixture-loader.d.ts.map +1 -1
- package/dist/fixture-loader.js +0 -0
- package/dist/fixture-loader.js.map +1 -1
- package/dist/gemini-embeddings.cjs +19 -1
- package/dist/gemini-embeddings.cjs.map +1 -1
- package/dist/gemini-embeddings.js +20 -2
- package/dist/gemini-embeddings.js.map +1 -1
- package/dist/gemini-interactions.cjs +15 -1
- package/dist/gemini-interactions.cjs.map +1 -1
- package/dist/gemini-interactions.d.cts.map +1 -1
- package/dist/gemini-interactions.d.ts.map +1 -1
- package/dist/gemini-interactions.js +16 -2
- package/dist/gemini-interactions.js.map +1 -1
- package/dist/gemini.cjs +70 -6
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.d.cts.map +1 -1
- package/dist/gemini.d.ts.map +1 -1
- package/dist/gemini.js +71 -7
- package/dist/gemini.js.map +1 -1
- package/dist/grok-video.cjs +2 -2
- package/dist/grok-video.cjs.map +1 -1
- package/dist/grok-video.d.cts.map +1 -1
- package/dist/grok-video.d.ts.map +1 -1
- package/dist/grok-video.js +2 -2
- package/dist/grok-video.js.map +1 -1
- package/dist/helpers.cjs +160 -5
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +152 -6
- package/dist/helpers.js.map +1 -1
- package/dist/images.cjs +24 -6
- package/dist/images.cjs.map +1 -1
- package/dist/images.d.cts +11 -3
- package/dist/images.d.cts.map +1 -1
- package/dist/images.d.ts +11 -3
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +25 -7
- package/dist/images.js.map +1 -1
- package/dist/index.cjs +7 -0
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/llmock.cjs +15 -0
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +12 -0
- package/dist/llmock.d.cts.map +1 -1
- package/dist/llmock.d.ts +12 -0
- package/dist/llmock.d.ts.map +1 -1
- package/dist/llmock.js +16 -1
- package/dist/llmock.js.map +1 -1
- package/dist/mcp-mock.cjs +11 -0
- package/dist/mcp-mock.cjs.map +1 -1
- package/dist/mcp-mock.d.cts.map +1 -1
- package/dist/mcp-mock.d.ts.map +1 -1
- package/dist/mcp-mock.js +11 -0
- package/dist/mcp-mock.js.map +1 -1
- package/dist/messages.cjs +18 -1
- package/dist/messages.cjs.map +1 -1
- package/dist/messages.d.cts.map +1 -1
- package/dist/messages.d.ts.map +1 -1
- package/dist/messages.js +19 -2
- package/dist/messages.js.map +1 -1
- package/dist/metrics.cjs +20 -0
- package/dist/metrics.cjs.map +1 -1
- package/dist/metrics.d.cts.map +1 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js +19 -1
- package/dist/metrics.js.map +1 -1
- package/dist/moderation.cjs +67 -3
- package/dist/moderation.cjs.map +1 -1
- package/dist/moderation.d.cts +1 -0
- package/dist/moderation.d.cts.map +1 -1
- package/dist/moderation.d.ts +1 -0
- package/dist/moderation.d.ts.map +1 -1
- package/dist/moderation.js +68 -4
- package/dist/moderation.js.map +1 -1
- package/dist/ollama.cjs +75 -5
- package/dist/ollama.cjs.map +1 -1
- package/dist/ollama.d.cts.map +1 -1
- package/dist/ollama.d.ts.map +1 -1
- package/dist/ollama.js +76 -6
- package/dist/ollama.js.map +1 -1
- package/dist/openrouter-video.cjs +4 -4
- package/dist/openrouter-video.cjs.map +1 -1
- package/dist/openrouter-video.d.cts.map +1 -1
- package/dist/openrouter-video.d.ts.map +1 -1
- package/dist/openrouter-video.js +4 -4
- package/dist/openrouter-video.js.map +1 -1
- package/dist/provider-auth.cjs +2 -0
- package/dist/provider-auth.cjs.map +1 -1
- package/dist/provider-auth.js +2 -0
- package/dist/provider-auth.js.map +1 -1
- package/dist/rerank.cjs +65 -2
- package/dist/rerank.cjs.map +1 -1
- package/dist/rerank.d.cts +1 -1
- package/dist/rerank.d.cts.map +1 -1
- package/dist/rerank.d.ts +1 -1
- package/dist/rerank.d.ts.map +1 -1
- package/dist/rerank.js +66 -3
- package/dist/rerank.js.map +1 -1
- package/dist/responses.cjs +18 -1
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +19 -2
- package/dist/responses.js.map +1 -1
- package/dist/router.cjs +1 -0
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.cts.map +1 -1
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +1 -0
- package/dist/router.js.map +1 -1
- package/dist/search.cjs +67 -3
- package/dist/search.cjs.map +1 -1
- package/dist/search.d.cts +1 -0
- package/dist/search.d.cts.map +1 -1
- package/dist/search.d.ts +1 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +68 -4
- package/dist/search.js.map +1 -1
- package/dist/server.cjs +406 -17
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +2 -0
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts +2 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +410 -21
- package/dist/server.js.map +1 -1
- package/dist/speech.cjs +18 -1
- package/dist/speech.cjs.map +1 -1
- package/dist/speech.d.cts.map +1 -1
- package/dist/speech.d.ts.map +1 -1
- package/dist/speech.js +19 -2
- package/dist/speech.js.map +1 -1
- package/dist/stream-collapse.cjs +2 -1
- package/dist/stream-collapse.cjs.map +1 -1
- package/dist/stream-collapse.js +2 -1
- package/dist/stream-collapse.js.map +1 -1
- package/dist/transcription.cjs +21 -2
- package/dist/transcription.cjs.map +1 -1
- package/dist/transcription.d.cts.map +1 -1
- package/dist/transcription.d.ts.map +1 -1
- package/dist/transcription.js +21 -2
- package/dist/transcription.js.map +1 -1
- package/dist/types.d.cts +58 -5
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +58 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/vector-mock.cjs +88 -0
- package/dist/vector-mock.cjs.map +1 -1
- package/dist/vector-mock.d.cts.map +1 -1
- package/dist/vector-mock.d.ts.map +1 -1
- package/dist/vector-mock.js +89 -1
- package/dist/vector-mock.js.map +1 -1
- package/dist/vector-types.d.cts.map +1 -1
- package/dist/veo-video.cjs +2 -2
- package/dist/veo-video.cjs.map +1 -1
- package/dist/veo-video.d.cts.map +1 -1
- package/dist/veo-video.d.ts.map +1 -1
- package/dist/veo-video.js +2 -2
- package/dist/veo-video.js.map +1 -1
- package/dist/video.cjs +19 -2
- package/dist/video.cjs.map +1 -1
- package/dist/video.d.cts.map +1 -1
- package/dist/video.d.ts.map +1 -1
- package/dist/video.js +20 -3
- package/dist/video.js.map +1 -1
- package/package.json +2 -2
package/dist/responses.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.js","names":[],"sources":["../src/responses.ts"],"sourcesContent":["/**\n * OpenAI Responses API support for aimock.\n *\n * Translates incoming /v1/responses requests into the ChatCompletionRequest\n * format used by the fixture router, and converts fixture responses back into\n * the Responses API streaming (or non-streaming) format expected by @ai-sdk/openai.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n FixtureBlock,\n HandlerDefaults,\n ResponseOverrides,\n StreamingProfile,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n generateId,\n generateToolCallId,\n resolveFixtureBlocks,\n extractOverrides,\n isTextResponse,\n isToolCallResponse,\n isContentWithToolCallsResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n resolveReasoningForModel,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { isReasoningModel } from \"./model-utils.js\";\nimport { matchFixtureDiagnostic, recordMatchOptions } from \"./router.js\";\nimport { writeErrorResponse, delay, calculateDelay } from \"./sse-writer.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\nimport type { RecordedTimings } from \"./types.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Responses API request types ────────────────────────────────────────────\n\ninterface ResponsesInputItem {\n role?: string;\n type?: string;\n content?: string | ResponsesContentPart[];\n call_id?: string;\n name?: string;\n arguments?: string;\n output?: string;\n id?: string;\n}\n\ninterface ResponsesContentPart {\n type: string;\n text?: string;\n}\n\ninterface ResponsesRequest {\n model: string;\n input: string | ResponsesInputItem[];\n instructions?: string;\n tools?: ResponsesToolDef[];\n tool_choice?: string | object;\n stream?: boolean;\n temperature?: number;\n max_output_tokens?: number;\n response_format?: { type: string; [key: string]: unknown };\n // Additional output data requested by the caller, e.g.\n // \"reasoning.encrypted_content\" (gates encrypted-reasoning emission).\n include?: string[];\n // Server-side storage flag. `false` (ZDR / stateless replay) is one of the\n // triggers for encrypted reasoning; see `requestWantsEncryptedReasoning`.\n store?: boolean;\n [key: string]: unknown;\n}\n\ninterface ResponsesToolDef {\n type: \"function\";\n name: string;\n description?: string;\n parameters?: object;\n strict?: boolean;\n}\n\n// ─── Input conversion: Responses → ChatCompletions messages ─────────────────\n\nfunction extractTextContent(content: string | ResponsesContentPart[] | undefined): string {\n if (!content) return \"\";\n if (typeof content === \"string\") return content;\n return content\n .filter((p) => p.type === \"input_text\" || p.type === \"output_text\")\n .map((p) => p.text ?? \"\")\n .join(\"\");\n}\n\nexport function responsesInputToMessages(req: ResponsesRequest): ChatMessage[] {\n const messages: ChatMessage[] = [];\n // Track item_reference placeholders so we can upgrade or clean them up\n const itemReferencePlaceholders = new WeakSet<ChatMessage>();\n\n // instructions field → system message\n if (req.instructions) {\n messages.push({ role: \"system\", content: req.instructions });\n }\n\n // The OpenAI Responses API accepts either a plain string or an array of input items.\n // When a string is passed, treat it as a single user message.\n if (typeof req.input === \"string\") {\n messages.push({ role: \"user\", content: req.input });\n return messages;\n }\n\n for (const item of req.input) {\n if (item.role === \"system\" || item.role === \"developer\") {\n messages.push({ role: \"system\", content: extractTextContent(item.content) });\n } else if (item.role === \"user\") {\n messages.push({ role: \"user\", content: extractTextContent(item.content) });\n } else if (item.role === \"assistant\") {\n messages.push({ role: \"assistant\", content: extractTextContent(item.content) });\n } else if (item.type === \"function_call\") {\n // Previous assistant tool call — emit as assistant message with tool_calls\n messages.push({\n role: \"assistant\",\n content: null,\n tool_calls: [\n {\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: item.name ?? \"\", arguments: item.arguments ?? \"\" },\n },\n ],\n });\n } else if (item.type === \"function_call_output\") {\n // Bug 1 fix: If there's no preceding assistant message with a matching\n // tool_call for this call_id, synthesize one. This happens when the AI SDK\n // sends [user, item_reference, function_call_output] — the item_reference\n // placeholder (see below) has no tool_calls, so we need a real assistant\n // message with the tool_call for turnIndex counting.\n const hasMatchingToolCall = messages.some(\n (m) => m.role === \"assistant\" && m.tool_calls?.some((tc) => tc.id === item.call_id),\n );\n if (!hasMatchingToolCall) {\n // Check if the last message is an item_reference placeholder — if so,\n // upgrade it to carry the tool_call instead of synthesizing a duplicate.\n const lastMsg = messages[messages.length - 1];\n if (\n lastMsg &&\n lastMsg.role === \"assistant\" &&\n itemReferencePlaceholders.has(lastMsg) &&\n !lastMsg.tool_calls\n ) {\n lastMsg.content = null;\n lastMsg.tool_calls = [\n {\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n },\n ];\n itemReferencePlaceholders.delete(lastMsg);\n } else {\n // Multi-fco case: look for a recent assistant with tool_calls that\n // belongs to the same turn. After the first fco upgrades a placeholder,\n // subsequent fco's see [assistant(call_A), tool(call_A)] — the last\n // assistant with tool_calls (right before the trailing tool messages)\n // is the correct target.\n let appended = false;\n for (let k = messages.length - 1; k >= 0; k--) {\n const m = messages[k];\n if (m.role === \"assistant\" && m.tool_calls) {\n m.tool_calls.push({\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n });\n appended = true;\n break;\n }\n // Stop scanning if we hit a user message — different turn\n if (m.role === \"user\") break;\n }\n if (!appended) {\n messages.push({\n role: \"assistant\",\n content: null,\n tool_calls: [\n {\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n },\n ],\n });\n }\n }\n }\n messages.push({\n role: \"tool\",\n content: item.output ?? \"\",\n tool_call_id: item.call_id,\n });\n } else if (item.type === \"item_reference\") {\n // Bug 6 fix: item_reference items represent prior assistant turns (text\n // or function_call). Push a placeholder so they count in assistantCount.\n // If a subsequent function_call_output arrives, the handler above will\n // upgrade this placeholder to carry tool_calls (avoiding double-count).\n const placeholder: ChatMessage = { role: \"assistant\", content: \"\" };\n itemReferencePlaceholders.add(placeholder);\n messages.push(placeholder);\n } else {\n // Skip local_shell_call, mcp_list_tools, etc. — not needed for fixture\n // matching.\n }\n }\n\n return messages;\n}\n\nfunction responsesToolsToCompletionsTools(\n tools?: ResponsesToolDef[],\n): ToolDefinition[] | undefined {\n if (!tools || tools.length === 0) return undefined;\n return tools\n .filter((t) => t.type === \"function\")\n .map((t) => ({\n type: \"function\" as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n}\n\nexport function responsesToCompletionRequest(req: ResponsesRequest): ChatCompletionRequest {\n return {\n model: req.model,\n messages: responsesInputToMessages(req),\n stream: req.stream,\n temperature: req.temperature,\n max_tokens: req.max_output_tokens,\n tools: responsesToolsToCompletionsTools(req.tools),\n tool_choice: req.tool_choice,\n response_format: req.response_format,\n };\n}\n\n// ─── Response building: fixture → Responses API format ──────────────────────\n\nfunction responsesStatus(finishReason: string | undefined, defaultStatus: string): string {\n if (!finishReason) return defaultStatus;\n if (finishReason === \"stop\") return \"completed\";\n if (finishReason === \"tool_calls\") return \"completed\";\n if (finishReason === \"length\") return \"incomplete\";\n if (finishReason === \"content_filter\") return \"failed\";\n return finishReason;\n}\n\nfunction responsesUsage(overrides?: ResponseOverrides): {\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n} {\n if (!overrides?.usage) return { input_tokens: 0, output_tokens: 0, total_tokens: 0 };\n const input = overrides.usage.input_tokens ?? overrides.usage.prompt_tokens ?? 0;\n const output = overrides.usage.output_tokens ?? overrides.usage.completion_tokens ?? 0;\n return {\n input_tokens: input,\n output_tokens: output,\n total_tokens: overrides.usage.total_tokens ?? input + output,\n };\n}\n\nfunction responseId(): string {\n return generateId(\"resp\");\n}\n\nfunction itemId(): string {\n return generateId(\"msg\");\n}\n\n// Streaming events for Responses API\n\nexport interface ResponsesSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\nexport function buildTextStreamEvents(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): ResponsesSSEEvent[] {\n const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(\n model,\n chunkSize,\n reasoning,\n webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n\n const { events: msgEvents, msgItem } = buildMessageOutputEvents(\n content,\n chunkSize,\n nextOutputIndex,\n );\n events.push(...msgEvents);\n\n events.push({\n type: \"response.completed\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output: [...prefixOutputItems, msgItem],\n usage: responsesUsage(overrides),\n },\n });\n\n return events;\n}\n\nexport function buildToolCallStreamEvents(\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): ResponsesSSEEvent[] {\n const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(\n model,\n chunkSize,\n reasoning,\n webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n\n const fcOutputItems: object[] = [];\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n const fcId = generateId(\"fc\");\n const outputIndex = nextOutputIndex + idx;\n\n // output_item.added (function_call)\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: tc.name,\n arguments: \"\",\n status: \"in_progress\",\n },\n });\n\n // function_call_arguments.delta\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n events.push({\n type: \"response.function_call_arguments.delta\",\n item_id: fcId,\n output_index: outputIndex,\n delta: slice,\n });\n }\n\n // function_call_arguments.done\n events.push({\n type: \"response.function_call_arguments.done\",\n item_id: fcId,\n output_index: outputIndex,\n arguments: args,\n });\n\n const doneItem = {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: tc.name,\n arguments: args,\n status: \"completed\",\n };\n\n // output_item.done\n events.push({\n type: \"response.output_item.done\",\n output_index: outputIndex,\n item: doneItem,\n });\n\n fcOutputItems.push(doneItem);\n }\n\n // response.completed\n events.push({\n type: \"response.completed\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output: [...prefixOutputItems, ...fcOutputItems],\n usage: responsesUsage(overrides),\n },\n });\n\n return events;\n}\n\n/**\n * Whether the incoming Responses request should receive encrypted reasoning.\n *\n * Two observed triggers, gated on EITHER:\n * - `include: [\"reasoning.encrypted_content\"]` — the explicit opt-in, and what\n * `agent-framework-openai` >= 1.11.0 auto-appends on its stateless-replay path\n * (it never sends `store`), so this is the branch that fires for real clients.\n * - `store: false` — captured responses carry the blob when not server-side\n * stored (ZDR) and omit it when stored; kept as a secondary trigger for\n * clients that go stateless without opting in via `include`.\n *\n * Stored / opted-out replays stay byte-identical. Exported so the WebSocket\n * Responses transport can share one gate.\n */\nexport function requestWantsEncryptedReasoning(req: ResponsesRequest): boolean {\n if (requestIncludesEncryptedReasoning(req)) return true;\n return req.store === false;\n}\n\n/**\n * Whether the request carries the EXPLICIT `include` opt-in — a strictly\n * narrower gate than `requestWantsEncryptedReasoning`, which also fires on\n * `store: false`.\n *\n * This is the gate for SYNTHESIZING a reasoning item that the fixture does not\n * declare (see `shouldSynthesizeBlobOnlyReasoning`), and it is deliberately the\n * narrow one. Attaching a field to an item aimock was already emitting is a much\n * smaller step than conjuring a whole output item that did not previously exist,\n * so the larger behavior change gets the gate that is directly observable in the\n * request rather than the inferred `store: false` one. `agent-framework-openai`\n * >= 1.11.0 auto-appends `include` on its stateless-replay path and never sends\n * `store` at all, so the motivating client is fully served by this branch — the\n * narrowing costs the feature nothing.\n *\n * Exported so the WebSocket Responses transport shares one gate.\n */\nexport function requestIncludesEncryptedReasoning(req: ResponsesRequest): boolean {\n const include = req.include;\n return Array.isArray(include) && include.includes(\"reasoning.encrypted_content\");\n}\n\n/**\n * Synthetic stand-in for OpenAI's opaque `reasoning.encrypted_content`. aimock\n * has no real ciphertext; it emits a base64 placeholder derived from the\n * reasoning id (stable for a given item, opaque like the real field). Consumers\n * store it (e.g. as agent-framework `protected_data`) and replay it verbatim;\n * aimock matches on content and ignores the echoed blob. Without it,\n * agent-framework-openai >= 1.11.0 hard-fails a reasoning + multi-tool chain on\n * the follow-up request. See microsoft/agent-framework#7233.\n *\n * aimock skips inbound reasoning items entirely, so it cannot reproduce\n * OpenAI's `invalid_encrypted_content` rejection of a mismatched blob/id — a\n * known replay-only limitation.\n */\nfunction syntheticEncryptedReasoning(reasoningId: string): string {\n return Buffer.from(`aimock-encrypted-reasoning:${reasoningId}`).toString(\"base64\");\n}\n\n/**\n * Build a Responses `reasoning` output item. `summaryText` controls the summary\n * (present for the terminal `done` / non-streaming item, omitted for the\n * in-progress `added` item); `emitEncrypted` controls the blob INDEPENDENTLY of\n * the summary, so a blob with an empty summary is expressible. aimock emits the\n * blob only on the terminal item and omits it on `added`: real OpenAI populates\n * `added` opportunistically, but the field is `anyOf: [string, null]` and\n * non-required, so consumers should read it at `done` and treat `added` as\n * best-effort — omitting there is legal and harmless.\n */\nfunction buildReasoningOutputItem(\n reasoningId: string,\n opts: { summaryText?: string; emitEncrypted?: boolean } = {},\n): Record<string, unknown> {\n const item: Record<string, unknown> = {\n type: \"reasoning\",\n id: reasoningId,\n summary:\n opts.summaryText === undefined ? [] : [{ type: \"summary_text\", text: opts.summaryText }],\n };\n if (opts.emitEncrypted) {\n item.encrypted_content = syntheticEncryptedReasoning(reasoningId);\n }\n return item;\n}\n\n/**\n * Whether to synthesize a summary-LESS reasoning item that exists purely to\n * carry the encrypted blob.\n *\n * Every reasoning item aimock emits otherwise originates in a fixture's declared\n * `reasoning` summary text. But a fixture RECORDED from the real stateless\n * agent-framework flow typically has NO summary — OpenAI returns `summary: []`\n * unless summaries are explicitly requested — so keying the item on a declared\n * summary starves the exact flow this feature exists to serve: fully opted in,\n * yet no reasoning item and therefore no blob. Real OpenAI, for a\n * reasoning-capable model, still returns a reasoning item (`summary: []`) with\n * the blob populated. So synthesize one, gated on:\n *\n * - the EXPLICIT `include` opt-in ONLY (`requestIncludesEncryptedReasoning`),\n * which is NARROWER than the `requestWantsEncryptedReasoning` gate that\n * controls the blob itself. A `store: false` request whose fixture declares no\n * summary therefore gets NO reasoning item, exactly as before this change.\n * Two reasons: (1) creating an output item that did not previously exist is a\n * bigger behavior change than adding a field to an item already being\n * emitted, so it earns the gate that is directly observable in the request\n * rather than the inferred one; (2) the `store: false` trigger's supporting\n * capture evidence is not verifiable from this repo, and a larger change must\n * not be stacked on an unverifiable premise. `agent-framework-openai` >=\n * 1.11.0 sends `include` and never `store`, so nothing is lost.\n * - the REQUESTED model's reasoning capability (aimock#254) — emitting a\n * reasoning item for gpt-4o would be LESS faithful, not more, since that\n * model has no reasoning channel at all. Unlike `resolveReasoningForModel`,\n * which fails open for a declared summary (a recorded summary is evidence the\n * model did reason), there is nothing to preserve here: a synthesized item on\n * a non-reasoning model would be pure fabrication, so this gate is hard.\n *\n * Note this is INDEPENDENT of `emitEncryptedReasoning`: when a fixture DOES\n * declare a summary, the blob still rides on it under either trigger (including\n * `store: false`), unchanged.\n */\nfunction shouldSynthesizeBlobOnlyReasoning(\n reasoning: string | undefined,\n model: string | undefined,\n synthesizeSummarylessReasoning: boolean,\n): boolean {\n if (reasoning) return false; // a declared summary already produces the item\n if (!synthesizeSummarylessReasoning) return false; // no explicit `include` opt-in\n return isReasoningModel(model);\n}\n\n/**\n * `reasoning` is `undefined` for a synthesized blob-only item (see\n * `shouldSynthesizeBlobOnlyReasoning`). In that case the item's `summary` is\n * `[]`, so the summary-part / summary-text events are SKIPPED entirely — they\n * would describe a part that does not exist on the item — leaving a coherent\n * `output_item.added` → `output_item.done` pair with nothing between.\n */\nfunction buildReasoningStreamEvents(\n reasoning: string | undefined,\n chunkSize: number,\n emitEncryptedReasoning = false,\n): ResponsesSSEEvent[] {\n const reasoningId = generateId(\"rs\");\n const events: ResponsesSSEEvent[] = [];\n\n events.push({\n type: \"response.output_item.added\",\n output_index: 0,\n item: buildReasoningOutputItem(reasoningId),\n });\n\n if (reasoning !== undefined) {\n events.push({\n type: \"response.reasoning_summary_part.added\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n part: { type: \"summary_text\", text: \"\" },\n });\n\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"response.reasoning_summary_text.delta\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n delta: slice,\n });\n }\n\n events.push({\n type: \"response.reasoning_summary_text.done\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n text: reasoning,\n });\n\n events.push({\n type: \"response.reasoning_summary_part.done\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n part: { type: \"summary_text\", text: reasoning },\n });\n }\n\n events.push({\n type: \"response.output_item.done\",\n output_index: 0,\n item: buildReasoningOutputItem(reasoningId, {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n });\n\n return events;\n}\n\nfunction buildWebSearchStreamEvents(\n queries: string[],\n startOutputIndex: number,\n): ResponsesSSEEvent[] {\n const events: ResponsesSSEEvent[] = [];\n\n for (let i = 0; i < queries.length; i++) {\n const searchId = generateId(\"ws\");\n const outputIndex = startOutputIndex + i;\n\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: {\n type: \"web_search_call\",\n id: searchId,\n status: \"in_progress\",\n action: { type: \"search\", query: queries[i] },\n },\n });\n\n events.push({\n type: \"response.output_item.done\",\n output_index: outputIndex,\n item: {\n type: \"web_search_call\",\n id: searchId,\n status: \"completed\",\n action: { type: \"search\", query: queries[i] },\n },\n });\n }\n\n return events;\n}\n\n// ─── Shared streaming helpers ────────────────────────────────────────────────\n\ninterface PreambleResult {\n respId: string;\n created: number;\n events: ResponsesSSEEvent[];\n prefixOutputItems: object[];\n nextOutputIndex: number;\n}\n\nfunction buildResponsePreamble(\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): PreambleResult {\n const respId = overrides?.id ?? responseId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const events: ResponsesSSEEvent[] = [];\n const prefixOutputItems: object[] = [];\n let nextOutputIndex = 0;\n\n events.push({\n type: \"response.created\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: effectiveModel,\n status: \"in_progress\",\n output: [],\n },\n });\n events.push({\n type: \"response.in_progress\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: effectiveModel,\n status: \"in_progress\",\n output: [],\n },\n });\n\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n const reasoningEvents = buildReasoningStreamEvents(\n reasoning,\n chunkSize,\n emitEncryptedReasoning,\n );\n events.push(...reasoningEvents);\n const doneEvent = reasoningEvents.find(\n (e) =>\n e.type === \"response.output_item.done\" &&\n (e.item as { type: string })?.type === \"reasoning\",\n );\n if (doneEvent) prefixOutputItems.push(doneEvent.item as object);\n nextOutputIndex++;\n }\n\n if (webSearches && webSearches.length > 0) {\n const searchEvents = buildWebSearchStreamEvents(webSearches, nextOutputIndex);\n events.push(...searchEvents);\n const doneEvents = searchEvents.filter(\n (e) =>\n e.type === \"response.output_item.done\" &&\n (e.item as { type: string })?.type === \"web_search_call\",\n );\n for (const de of doneEvents) prefixOutputItems.push(de.item as object);\n nextOutputIndex += webSearches.length;\n }\n\n return { respId, created, events, prefixOutputItems, nextOutputIndex };\n}\n\ninterface MessageBlockResult {\n events: ResponsesSSEEvent[];\n msgItem: object;\n}\n\nfunction buildMessageOutputEvents(\n content: string,\n chunkSize: number,\n outputIndex: number,\n): MessageBlockResult {\n const msgId = itemId();\n const events: ResponsesSSEEvent[] = [];\n\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: { type: \"message\", id: msgId, status: \"in_progress\", role: \"assistant\", content: [] },\n });\n events.push({\n type: \"response.content_part.added\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n part: { type: \"output_text\", text: \"\", annotations: [] },\n });\n\n for (let i = 0; i < content.length; i += chunkSize) {\n events.push({\n type: \"response.output_text.delta\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n delta: content.slice(i, i + chunkSize),\n });\n }\n\n events.push({\n type: \"response.output_text.done\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n text: content,\n });\n events.push({\n type: \"response.content_part.done\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n part: { type: \"output_text\", text: content, annotations: [] },\n });\n\n const msgItem = {\n type: \"message\",\n id: msgId,\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: content, annotations: [] }],\n };\n\n events.push({ type: \"response.output_item.done\", output_index: outputIndex, item: msgItem });\n\n return { events, msgItem };\n}\n\ninterface FunctionCallBlockResult {\n events: ResponsesSSEEvent[];\n fcItem: object;\n}\n\n/**\n * Emit the output_item.added → arguments deltas → arguments.done →\n * output_item.done events for a single function_call at `outputIndex`,\n * returning the completed item for the final `output` array. Behavior is\n * identical to the inline per-tool-call loop in the legacy path; both the\n * legacy branch and the ordered-blocks branch share this so wire output stays\n * byte-identical for a given (tool, outputIndex).\n */\nfunction buildFunctionCallOutputEvents(\n toolCall: ToolCall,\n chunkSize: number,\n outputIndex: number,\n): FunctionCallBlockResult {\n const callId = toolCall.id || generateToolCallId();\n const fcId = generateId(\"fc\");\n const args = toolCall.arguments;\n const events: ResponsesSSEEvent[] = [];\n\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: toolCall.name,\n arguments: \"\",\n status: \"in_progress\",\n },\n });\n\n for (let i = 0; i < args.length; i += chunkSize) {\n events.push({\n type: \"response.function_call_arguments.delta\",\n item_id: fcId,\n output_index: outputIndex,\n delta: args.slice(i, i + chunkSize),\n });\n }\n\n events.push({\n type: \"response.function_call_arguments.done\",\n item_id: fcId,\n output_index: outputIndex,\n arguments: args,\n });\n\n const fcItem = {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: toolCall.name,\n arguments: args,\n status: \"completed\",\n };\n events.push({ type: \"response.output_item.done\", output_index: outputIndex, item: fcItem });\n\n return { events, fcItem };\n}\n\n// ─── Non-streaming response builders ────────────────────────────────────────\n\nfunction buildOutputPrefix(\n content: string,\n model: string,\n reasoning?: string,\n webSearches?: string[],\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object[] {\n const output: object[] = [];\n\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n output.push(\n buildReasoningOutputItem(generateId(\"rs\"), {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n );\n }\n\n if (webSearches && webSearches.length > 0) {\n for (const query of webSearches) {\n output.push({\n type: \"web_search_call\",\n id: generateId(\"ws\"),\n status: \"completed\",\n action: { type: \"search\", query },\n });\n }\n }\n\n output.push({\n type: \"message\",\n id: itemId(),\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: content, annotations: [] }],\n });\n\n return output;\n}\n\nfunction buildResponseEnvelope(\n model: string,\n output: object[],\n overrides?: ResponseOverrides,\n): object {\n return {\n id: overrides?.id ?? responseId(),\n object: \"response\",\n created_at: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output,\n usage: responsesUsage(overrides),\n };\n}\n\nfunction buildTextResponse(\n content: string,\n model: string,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object {\n return buildResponseEnvelope(\n model,\n buildOutputPrefix(\n content,\n model,\n reasoning,\n webSearches,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n ),\n overrides,\n );\n}\n\nfunction buildToolCallResponse(\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object {\n const output: object[] = [];\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n output.push(\n buildReasoningOutputItem(generateId(\"rs\"), {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n );\n }\n if (webSearches && webSearches.length > 0) {\n for (const query of webSearches) {\n output.push({\n type: \"web_search_call\",\n id: generateId(\"ws\"),\n status: \"completed\",\n action: { type: \"search\", query },\n });\n }\n }\n for (const tc of toolCalls) {\n output.push({\n type: \"function_call\",\n id: generateId(\"fc\"),\n call_id: tc.id || generateToolCallId(),\n name: tc.name,\n arguments: tc.arguments,\n status: \"completed\",\n });\n }\n return buildResponseEnvelope(model, output, overrides);\n}\n\nexport function buildContentWithToolCallsStreamEvents(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): ResponsesSSEEvent[] {\n const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(\n model,\n chunkSize,\n reasoning,\n webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n\n // The output items assembled in emission order (after any reasoning /\n // web-search prefix items). Each output_index is assigned sequentially as we\n // walk the chosen item order, so the `output_index` on every emitted event\n // matches that item's slot in the final `response.completed.output` array.\n const orderedOutputItems: object[] = [];\n\n if (blocks && blocks.length > 0) {\n // NEW PATH: stream items in the fixture's block ARRAY ORDER. A toolCall\n // block placed before a text block therefore yields a function_call item at\n // a LOWER output_index than the message — it leads the output array.\n const ordered = resolveFixtureBlocks(blocks);\n let outputIndex = nextOutputIndex;\n for (const block of ordered) {\n if (block.type === \"text\") {\n const { events: msgEvents, msgItem } = buildMessageOutputEvents(\n block.text,\n chunkSize,\n outputIndex,\n );\n events.push(...msgEvents);\n orderedOutputItems.push(msgItem);\n } else {\n const { events: fcEvents, fcItem } = buildFunctionCallOutputEvents(\n { name: block.name, arguments: block.arguments, id: block.id },\n chunkSize,\n outputIndex,\n );\n events.push(...fcEvents);\n orderedOutputItems.push(fcItem);\n }\n outputIndex += 1;\n }\n } else {\n // LEGACY PATH: message item first, then function_call items — byte-for-byte\n // unchanged from the pre-blocks behavior (message always leads the output).\n const { events: msgEvents, msgItem } = buildMessageOutputEvents(\n content,\n chunkSize,\n nextOutputIndex,\n );\n events.push(...msgEvents);\n orderedOutputItems.push(msgItem);\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const fcOutputIndex = nextOutputIndex + 1 + idx;\n const { events: fcEvents, fcItem } = buildFunctionCallOutputEvents(\n toolCalls[idx],\n chunkSize,\n fcOutputIndex,\n );\n events.push(...fcEvents);\n orderedOutputItems.push(fcItem);\n }\n }\n\n events.push({\n type: \"response.completed\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output: [...prefixOutputItems, ...orderedOutputItems],\n usage: responsesUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildFunctionCallOutputItem(tc: { name: string; arguments: string; id?: string }): object {\n return {\n type: \"function_call\",\n id: generateId(\"fc\"),\n call_id: tc.id || generateToolCallId(),\n name: tc.name,\n arguments: tc.arguments,\n status: \"completed\",\n };\n}\n\nfunction buildMessageOutputItem(content: string): object {\n return {\n type: \"message\",\n id: itemId(),\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: content, annotations: [] }],\n };\n}\n\nfunction buildContentWithToolCallsResponse(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object {\n if (blocks && blocks.length > 0) {\n // NEW PATH: the non-streaming `output[]` array is positionally observable,\n // so emit the prefix (reasoning / web_search_call), then the blocks in\n // fixture ARRAY ORDER. A toolCall block before a text block therefore\n // yields a function_call item ahead of the message — matching the streaming\n // path's ordering for the same `blocks` fixture.\n const ordered = resolveFixtureBlocks(blocks);\n const output: object[] = [];\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n output.push(\n buildReasoningOutputItem(generateId(\"rs\"), {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n );\n }\n if (webSearches && webSearches.length > 0) {\n for (const query of webSearches) {\n output.push({\n type: \"web_search_call\",\n id: generateId(\"ws\"),\n status: \"completed\",\n action: { type: \"search\", query },\n });\n }\n }\n for (const block of ordered) {\n if (block.type === \"text\") {\n output.push(buildMessageOutputItem(block.text));\n } else {\n output.push(\n buildFunctionCallOutputItem({\n name: block.name,\n arguments: block.arguments,\n id: block.id,\n }),\n );\n }\n }\n return buildResponseEnvelope(model, output, overrides);\n }\n\n // LEGACY PATH: message item first, then function_call items — unchanged.\n const output = buildOutputPrefix(\n content,\n model,\n reasoning,\n webSearches,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n for (const tc of toolCalls) {\n output.push(buildFunctionCallOutputItem(tc));\n }\n return buildResponseEnvelope(model, output, overrides);\n}\n\n// ─── SSE writer for Responses API ───────────────────────────────────────────\n\ninterface ResponsesStreamOptions {\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nasync function writeResponsesSSEStream(\n res: http.ServerResponse,\n events: ResponsesSSEEvent[],\n optionsOrLatency?: number | ResponsesStreamOptions,\n): Promise<boolean> {\n const opts: ResponsesStreamOptions =\n typeof optionsOrLatency === \"number\" ? { latency: optionsOrLatency } : (optionsOrLatency ?? {});\n const latency = opts.latency ?? 0;\n const profile = opts.streamingProfile;\n const { recordedTimings, replaySpeed } = opts;\n const signal = opts.signal;\n const onChunkSent = opts.onChunkSent;\n\n if (res.writableEnded) return true;\n res.setHeader(\"Content-Type\", \"text/event-stream\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.setHeader(\"Connection\", \"keep-alive\");\n\n let chunkIndex = 0;\n for (const event of events) {\n const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);\n if (chunkDelay > 0) await delay(chunkDelay, signal);\n if (signal?.aborted) return false;\n if (res.writableEnded) return true;\n res.write(`event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`);\n onChunkSent?.();\n if (signal?.aborted) return false;\n chunkIndex++;\n }\n\n if (!res.writableEnded) {\n res.end();\n }\n return true;\n}\n\n// ─── Request handler ────────────────────────────────────────────────────────\n\nexport async function handleResponses(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n setCorsHeaders(res);\n\n let responsesReq: ResponsesRequest;\n try {\n responsesReq = JSON.parse(raw) as ResponsesRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = responsesToCompletionRequest(responsesReq);\n completionReq._endpointType = \"chat\";\n completionReq._context = getContext(req);\n\n // Emit a synthetic `reasoning.encrypted_content` only when the request wants it\n // (opted in via `include`, or stateless `store: false` — mirrors real OpenAI).\n // This is what agent-framework-openai >= 1.11.0 sends on stateless-replay\n // requests; without the blob it hard-fails a reasoning + multi-tool chain.\n // See microsoft/agent-framework#7233.\n const emitEncryptedReasoning = requestWantsEncryptedReasoning(responsesReq);\n // Synthesizing a reasoning item the fixture never declared is a bigger step\n // than adding a field to one already being emitted, so it takes the NARROWER\n // explicit-`include` gate: a `store: false` request with a summary-less fixture\n // keeps emitting no reasoning item at all. See\n // `shouldSynthesizeBlobOnlyReasoning`.\n const synthesizeSummarylessReasoning = requestIncludesEncryptedReasoning(responsesReq);\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n defaults.logger.debug(\n `Responses fixture matched for ${req.method ?? \"POST\"} ${req.url ?? \"/v1/responses\"}`,\n );\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n } else {\n defaults.logger.debug(\n `No responses fixture matched for ${req.method ?? \"POST\"} ${req.url ?? \"/v1/responses\"}`,\n );\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictStatus = 503;\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(\n strictNoMatchLogLine(\n req.method ?? \"POST\",\n req.url ?? \"/v1/responses\",\n skippedBySequenceOrTurn,\n ),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: strictStatus,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"openai\",\n req.url ?? \"/v1/responses\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, completionReq);\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n const fixtureTimings = fixture.recordedTimings;\n const effectiveReplaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Combined content + tool calls response\n if (isContentWithToolCallsResponse(response)) {\n const overrides = extractOverrides(response);\n // Gate reasoning emission on the requested model's capability (aimock#254).\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = resolveReasoningForModel(\n response.reasoning,\n completionReq.model,\n effectiveStrict,\n defaults.logger,\n );\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (responsesReq.stream !== true) {\n const body = buildContentWithToolCallsResponse(\n response.content ?? \"\",\n response.toolCalls ?? [],\n completionReq.model,\n effReasoning,\n response.webSearches,\n overrides,\n response.blocks,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildContentWithToolCallsStreamEvents(\n response.content ?? \"\",\n response.toolCalls ?? [],\n completionReq.model,\n chunkSize,\n effReasoning,\n response.webSearches,\n overrides,\n response.blocks,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeResponsesSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixtureTimings,\n replaySpeed: effectiveReplaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n const overrides = extractOverrides(response);\n // Gate reasoning emission on the requested model's capability (aimock#254).\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = resolveReasoningForModel(\n response.reasoning,\n completionReq.model,\n effectiveStrict,\n defaults.logger,\n );\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (responsesReq.stream !== true) {\n const body = buildTextResponse(\n response.content,\n completionReq.model,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildTextStreamEvents(\n response.content,\n completionReq.model,\n chunkSize,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeResponsesSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixtureTimings,\n replaySpeed: effectiveReplaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n const overrides = extractOverrides(response);\n // Gate reasoning emission on the requested model's capability (aimock#254).\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = resolveReasoningForModel(\n response.reasoning,\n completionReq.model,\n effectiveStrict,\n defaults.logger,\n );\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (responsesReq.stream !== true) {\n const body = buildToolCallResponse(\n response.toolCalls,\n completionReq.model,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildToolCallStreamEvents(\n response.toolCalls,\n completionReq.model,\n chunkSize,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeResponsesSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixtureTimings,\n replaySpeed: effectiveReplaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Unknown response type\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response did not match any known type\", type: \"server_error\" },\n }),\n );\n}\n"],"mappings":";;;;;;;;;AAgGA,SAAS,mBAAmB,SAA8D;AACxF,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAO,QACJ,QAAQ,MAAM,EAAE,SAAS,gBAAgB,EAAE,SAAS,cAAc,CAClE,KAAK,MAAM,EAAE,QAAQ,GAAG,CACxB,KAAK,GAAG;;AAGb,SA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tB,MAAM,IAAI,OAAO;GACjB,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK;IAAS;GACnC,CAAC;AACF,MAAI,aAAa,WAAW,MAAM;GAChC,MAAM,OAAO,sBACX,SAAS,WACT,cAAc,OACd,cACA,SAAS,aACT,WACA,wBACA,+BACD;AACD,OAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,OAAI,IAAI,KAAK,UAAU,KAAK,CAAC;SACxB;GACL,MAAM,SAAS,0BACb,SAAS,WACT,cAAc,OACd,WACA,cACA,SAAS,aACT,WACA,wBACA,+BACD;GACD,MAAM,eAAe,yBAAyB,QAAQ;AAStD,OAAI,CARc,MAAM,wBAAwB,KAAK,QAAQ;IAC3D;IACA,kBAAkB,QAAQ;IAC1B,iBAAiB;IACjB,aAAa;IACb,QAAQ,cAAc;IACtB,aAAa,cAAc;IAC5B,CAAC,EACc;AACd,QAAI,CAAC,IAAI,cAAe,KAAI,SAAS;AACrC,iBAAa,SAAS,cAAc;AACpC,iBAAa,SAAS,kBAAkB,cAAc,QAAQ;;AAEhE,iBAAc,SAAS;;AAEzB;;AAIF,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK;GAAS;EACnC,CAAC;AACF,oBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;EAAE,SAAS;EAAiD,MAAM;EAAgB,EAC1F,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"responses.js","names":[],"sources":["../src/responses.ts"],"sourcesContent":["/**\n * OpenAI Responses API support for aimock.\n *\n * Translates incoming /v1/responses requests into the ChatCompletionRequest\n * format used by the fixture router, and converts fixture responses back into\n * the Responses API streaming (or non-streaming) format expected by @ai-sdk/openai.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n FixtureBlock,\n HandlerDefaults,\n ResponseOverrides,\n StreamingProfile,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n generateId,\n generateToolCallId,\n resolveFixtureBlocks,\n extractOverrides,\n isTextResponse,\n isToolCallResponse,\n isContentWithToolCallsResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n isJsonObject,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n resolveReasoningForModel,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { isReasoningModel } from \"./model-utils.js\";\nimport { matchFixtureDiagnostic, recordMatchOptions } from \"./router.js\";\nimport { writeErrorResponse, delay, calculateDelay } from \"./sse-writer.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\nimport type { RecordedTimings } from \"./types.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Responses API request types ────────────────────────────────────────────\n\ninterface ResponsesInputItem {\n role?: string;\n type?: string;\n content?: string | ResponsesContentPart[];\n call_id?: string;\n name?: string;\n arguments?: string;\n output?: string;\n id?: string;\n}\n\ninterface ResponsesContentPart {\n type: string;\n text?: string;\n}\n\ninterface ResponsesRequest {\n model: string;\n input: string | ResponsesInputItem[];\n instructions?: string;\n tools?: ResponsesToolDef[];\n tool_choice?: string | object;\n stream?: boolean;\n temperature?: number;\n max_output_tokens?: number;\n response_format?: { type: string; [key: string]: unknown };\n // Additional output data requested by the caller, e.g.\n // \"reasoning.encrypted_content\" (gates encrypted-reasoning emission).\n include?: string[];\n // Server-side storage flag. `false` (ZDR / stateless replay) is one of the\n // triggers for encrypted reasoning; see `requestWantsEncryptedReasoning`.\n store?: boolean;\n [key: string]: unknown;\n}\n\ninterface ResponsesToolDef {\n type: \"function\";\n name: string;\n description?: string;\n parameters?: object;\n strict?: boolean;\n}\n\n// ─── Input conversion: Responses → ChatCompletions messages ─────────────────\n\nfunction extractTextContent(content: string | ResponsesContentPart[] | undefined): string {\n if (!content) return \"\";\n if (typeof content === \"string\") return content;\n return content\n .filter((p) => p.type === \"input_text\" || p.type === \"output_text\")\n .map((p) => p.text ?? \"\")\n .join(\"\");\n}\n\nexport function responsesInputToMessages(req: ResponsesRequest): ChatMessage[] {\n const messages: ChatMessage[] = [];\n // Track item_reference placeholders so we can upgrade or clean them up\n const itemReferencePlaceholders = new WeakSet<ChatMessage>();\n\n // instructions field → system message\n if (req.instructions) {\n messages.push({ role: \"system\", content: req.instructions });\n }\n\n // The OpenAI Responses API accepts either a plain string or an array of input items.\n // When a string is passed, treat it as a single user message.\n if (typeof req.input === \"string\") {\n messages.push({ role: \"user\", content: req.input });\n return messages;\n }\n\n for (const item of req.input) {\n if (item.role === \"system\" || item.role === \"developer\") {\n messages.push({ role: \"system\", content: extractTextContent(item.content) });\n } else if (item.role === \"user\") {\n messages.push({ role: \"user\", content: extractTextContent(item.content) });\n } else if (item.role === \"assistant\") {\n messages.push({ role: \"assistant\", content: extractTextContent(item.content) });\n } else if (item.type === \"function_call\") {\n // Previous assistant tool call — emit as assistant message with tool_calls\n messages.push({\n role: \"assistant\",\n content: null,\n tool_calls: [\n {\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: item.name ?? \"\", arguments: item.arguments ?? \"\" },\n },\n ],\n });\n } else if (item.type === \"function_call_output\") {\n // Bug 1 fix: If there's no preceding assistant message with a matching\n // tool_call for this call_id, synthesize one. This happens when the AI SDK\n // sends [user, item_reference, function_call_output] — the item_reference\n // placeholder (see below) has no tool_calls, so we need a real assistant\n // message with the tool_call for turnIndex counting.\n const hasMatchingToolCall = messages.some(\n (m) => m.role === \"assistant\" && m.tool_calls?.some((tc) => tc.id === item.call_id),\n );\n if (!hasMatchingToolCall) {\n // Check if the last message is an item_reference placeholder — if so,\n // upgrade it to carry the tool_call instead of synthesizing a duplicate.\n const lastMsg = messages[messages.length - 1];\n if (\n lastMsg &&\n lastMsg.role === \"assistant\" &&\n itemReferencePlaceholders.has(lastMsg) &&\n !lastMsg.tool_calls\n ) {\n lastMsg.content = null;\n lastMsg.tool_calls = [\n {\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n },\n ];\n itemReferencePlaceholders.delete(lastMsg);\n } else {\n // Multi-fco case: look for a recent assistant with tool_calls that\n // belongs to the same turn. After the first fco upgrades a placeholder,\n // subsequent fco's see [assistant(call_A), tool(call_A)] — the last\n // assistant with tool_calls (right before the trailing tool messages)\n // is the correct target.\n let appended = false;\n for (let k = messages.length - 1; k >= 0; k--) {\n const m = messages[k];\n if (m.role === \"assistant\" && m.tool_calls) {\n m.tool_calls.push({\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n });\n appended = true;\n break;\n }\n // Stop scanning if we hit a user message — different turn\n if (m.role === \"user\") break;\n }\n if (!appended) {\n messages.push({\n role: \"assistant\",\n content: null,\n tool_calls: [\n {\n id: item.call_id ?? generateToolCallId(),\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n },\n ],\n });\n }\n }\n }\n messages.push({\n role: \"tool\",\n content: item.output ?? \"\",\n tool_call_id: item.call_id,\n });\n } else if (item.type === \"item_reference\") {\n // Bug 6 fix: item_reference items represent prior assistant turns (text\n // or function_call). Push a placeholder so they count in assistantCount.\n // If a subsequent function_call_output arrives, the handler above will\n // upgrade this placeholder to carry tool_calls (avoiding double-count).\n const placeholder: ChatMessage = { role: \"assistant\", content: \"\" };\n itemReferencePlaceholders.add(placeholder);\n messages.push(placeholder);\n } else {\n // Skip local_shell_call, mcp_list_tools, etc. — not needed for fixture\n // matching.\n }\n }\n\n return messages;\n}\n\nfunction responsesToolsToCompletionsTools(\n tools?: ResponsesToolDef[],\n): ToolDefinition[] | undefined {\n if (!tools || tools.length === 0) return undefined;\n return tools\n .filter((t) => t.type === \"function\")\n .map((t) => ({\n type: \"function\" as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n}\n\nexport function responsesToCompletionRequest(req: ResponsesRequest): ChatCompletionRequest {\n return {\n model: req.model,\n messages: responsesInputToMessages(req),\n stream: req.stream,\n temperature: req.temperature,\n max_tokens: req.max_output_tokens,\n tools: responsesToolsToCompletionsTools(req.tools),\n tool_choice: req.tool_choice,\n response_format: req.response_format,\n };\n}\n\n// ─── Response building: fixture → Responses API format ──────────────────────\n\nfunction responsesStatus(finishReason: string | undefined, defaultStatus: string): string {\n if (!finishReason) return defaultStatus;\n if (finishReason === \"stop\") return \"completed\";\n if (finishReason === \"tool_calls\") return \"completed\";\n if (finishReason === \"length\") return \"incomplete\";\n if (finishReason === \"content_filter\") return \"failed\";\n return finishReason;\n}\n\nfunction responsesUsage(overrides?: ResponseOverrides): {\n input_tokens: number;\n output_tokens: number;\n total_tokens: number;\n} {\n if (!overrides?.usage) return { input_tokens: 0, output_tokens: 0, total_tokens: 0 };\n const input = overrides.usage.input_tokens ?? overrides.usage.prompt_tokens ?? 0;\n const output = overrides.usage.output_tokens ?? overrides.usage.completion_tokens ?? 0;\n return {\n input_tokens: input,\n output_tokens: output,\n total_tokens: overrides.usage.total_tokens ?? input + output,\n };\n}\n\nfunction responseId(): string {\n return generateId(\"resp\");\n}\n\nfunction itemId(): string {\n return generateId(\"msg\");\n}\n\n// Streaming events for Responses API\n\nexport interface ResponsesSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\nexport function buildTextStreamEvents(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): ResponsesSSEEvent[] {\n const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(\n model,\n chunkSize,\n reasoning,\n webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n\n const { events: msgEvents, msgItem } = buildMessageOutputEvents(\n content,\n chunkSize,\n nextOutputIndex,\n );\n events.push(...msgEvents);\n\n events.push({\n type: \"response.completed\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output: [...prefixOutputItems, msgItem],\n usage: responsesUsage(overrides),\n },\n });\n\n return events;\n}\n\nexport function buildToolCallStreamEvents(\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): ResponsesSSEEvent[] {\n const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(\n model,\n chunkSize,\n reasoning,\n webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n\n const fcOutputItems: object[] = [];\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n const fcId = generateId(\"fc\");\n const outputIndex = nextOutputIndex + idx;\n\n // output_item.added (function_call)\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: tc.name,\n arguments: \"\",\n status: \"in_progress\",\n },\n });\n\n // function_call_arguments.delta\n const args = tc.arguments;\n for (let i = 0; i < args.length; i += chunkSize) {\n const slice = args.slice(i, i + chunkSize);\n events.push({\n type: \"response.function_call_arguments.delta\",\n item_id: fcId,\n output_index: outputIndex,\n delta: slice,\n });\n }\n\n // function_call_arguments.done\n events.push({\n type: \"response.function_call_arguments.done\",\n item_id: fcId,\n output_index: outputIndex,\n arguments: args,\n });\n\n const doneItem = {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: tc.name,\n arguments: args,\n status: \"completed\",\n };\n\n // output_item.done\n events.push({\n type: \"response.output_item.done\",\n output_index: outputIndex,\n item: doneItem,\n });\n\n fcOutputItems.push(doneItem);\n }\n\n // response.completed\n events.push({\n type: \"response.completed\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output: [...prefixOutputItems, ...fcOutputItems],\n usage: responsesUsage(overrides),\n },\n });\n\n return events;\n}\n\n/**\n * Whether the incoming Responses request should receive encrypted reasoning.\n *\n * Two observed triggers, gated on EITHER:\n * - `include: [\"reasoning.encrypted_content\"]` — the explicit opt-in, and what\n * `agent-framework-openai` >= 1.11.0 auto-appends on its stateless-replay path\n * (it never sends `store`), so this is the branch that fires for real clients.\n * - `store: false` — captured responses carry the blob when not server-side\n * stored (ZDR) and omit it when stored; kept as a secondary trigger for\n * clients that go stateless without opting in via `include`.\n *\n * Stored / opted-out replays stay byte-identical. Exported so the WebSocket\n * Responses transport can share one gate.\n */\nexport function requestWantsEncryptedReasoning(req: ResponsesRequest): boolean {\n if (requestIncludesEncryptedReasoning(req)) return true;\n return req.store === false;\n}\n\n/**\n * Whether the request carries the EXPLICIT `include` opt-in — a strictly\n * narrower gate than `requestWantsEncryptedReasoning`, which also fires on\n * `store: false`.\n *\n * This is the gate for SYNTHESIZING a reasoning item that the fixture does not\n * declare (see `shouldSynthesizeBlobOnlyReasoning`), and it is deliberately the\n * narrow one. Attaching a field to an item aimock was already emitting is a much\n * smaller step than conjuring a whole output item that did not previously exist,\n * so the larger behavior change gets the gate that is directly observable in the\n * request rather than the inferred `store: false` one. `agent-framework-openai`\n * >= 1.11.0 auto-appends `include` on its stateless-replay path and never sends\n * `store` at all, so the motivating client is fully served by this branch — the\n * narrowing costs the feature nothing.\n *\n * Exported so the WebSocket Responses transport shares one gate.\n */\nexport function requestIncludesEncryptedReasoning(req: ResponsesRequest): boolean {\n const include = req.include;\n return Array.isArray(include) && include.includes(\"reasoning.encrypted_content\");\n}\n\n/**\n * Synthetic stand-in for OpenAI's opaque `reasoning.encrypted_content`. aimock\n * has no real ciphertext; it emits a base64 placeholder derived from the\n * reasoning id (stable for a given item, opaque like the real field). Consumers\n * store it (e.g. as agent-framework `protected_data`) and replay it verbatim;\n * aimock matches on content and ignores the echoed blob. Without it,\n * agent-framework-openai >= 1.11.0 hard-fails a reasoning + multi-tool chain on\n * the follow-up request. See microsoft/agent-framework#7233.\n *\n * aimock skips inbound reasoning items entirely, so it cannot reproduce\n * OpenAI's `invalid_encrypted_content` rejection of a mismatched blob/id — a\n * known replay-only limitation.\n */\nfunction syntheticEncryptedReasoning(reasoningId: string): string {\n return Buffer.from(`aimock-encrypted-reasoning:${reasoningId}`).toString(\"base64\");\n}\n\n/**\n * Build a Responses `reasoning` output item. `summaryText` controls the summary\n * (present for the terminal `done` / non-streaming item, omitted for the\n * in-progress `added` item); `emitEncrypted` controls the blob INDEPENDENTLY of\n * the summary, so a blob with an empty summary is expressible. aimock emits the\n * blob only on the terminal item and omits it on `added`: real OpenAI populates\n * `added` opportunistically, but the field is `anyOf: [string, null]` and\n * non-required, so consumers should read it at `done` and treat `added` as\n * best-effort — omitting there is legal and harmless.\n */\nfunction buildReasoningOutputItem(\n reasoningId: string,\n opts: { summaryText?: string; emitEncrypted?: boolean } = {},\n): Record<string, unknown> {\n const item: Record<string, unknown> = {\n type: \"reasoning\",\n id: reasoningId,\n summary:\n opts.summaryText === undefined ? [] : [{ type: \"summary_text\", text: opts.summaryText }],\n };\n if (opts.emitEncrypted) {\n item.encrypted_content = syntheticEncryptedReasoning(reasoningId);\n }\n return item;\n}\n\n/**\n * Whether to synthesize a summary-LESS reasoning item that exists purely to\n * carry the encrypted blob.\n *\n * Every reasoning item aimock emits otherwise originates in a fixture's declared\n * `reasoning` summary text. But a fixture RECORDED from the real stateless\n * agent-framework flow typically has NO summary — OpenAI returns `summary: []`\n * unless summaries are explicitly requested — so keying the item on a declared\n * summary starves the exact flow this feature exists to serve: fully opted in,\n * yet no reasoning item and therefore no blob. Real OpenAI, for a\n * reasoning-capable model, still returns a reasoning item (`summary: []`) with\n * the blob populated. So synthesize one, gated on:\n *\n * - the EXPLICIT `include` opt-in ONLY (`requestIncludesEncryptedReasoning`),\n * which is NARROWER than the `requestWantsEncryptedReasoning` gate that\n * controls the blob itself. A `store: false` request whose fixture declares no\n * summary therefore gets NO reasoning item, exactly as before this change.\n * Two reasons: (1) creating an output item that did not previously exist is a\n * bigger behavior change than adding a field to an item already being\n * emitted, so it earns the gate that is directly observable in the request\n * rather than the inferred one; (2) the `store: false` trigger's supporting\n * capture evidence is not verifiable from this repo, and a larger change must\n * not be stacked on an unverifiable premise. `agent-framework-openai` >=\n * 1.11.0 sends `include` and never `store`, so nothing is lost.\n * - the REQUESTED model's reasoning capability (aimock#254) — emitting a\n * reasoning item for gpt-4o would be LESS faithful, not more, since that\n * model has no reasoning channel at all. Unlike `resolveReasoningForModel`,\n * which fails open for a declared summary (a recorded summary is evidence the\n * model did reason), there is nothing to preserve here: a synthesized item on\n * a non-reasoning model would be pure fabrication, so this gate is hard.\n *\n * Note this is INDEPENDENT of `emitEncryptedReasoning`: when a fixture DOES\n * declare a summary, the blob still rides on it under either trigger (including\n * `store: false`), unchanged.\n */\nfunction shouldSynthesizeBlobOnlyReasoning(\n reasoning: string | undefined,\n model: string | undefined,\n synthesizeSummarylessReasoning: boolean,\n): boolean {\n if (reasoning) return false; // a declared summary already produces the item\n if (!synthesizeSummarylessReasoning) return false; // no explicit `include` opt-in\n return isReasoningModel(model);\n}\n\n/**\n * `reasoning` is `undefined` for a synthesized blob-only item (see\n * `shouldSynthesizeBlobOnlyReasoning`). In that case the item's `summary` is\n * `[]`, so the summary-part / summary-text events are SKIPPED entirely — they\n * would describe a part that does not exist on the item — leaving a coherent\n * `output_item.added` → `output_item.done` pair with nothing between.\n */\nfunction buildReasoningStreamEvents(\n reasoning: string | undefined,\n chunkSize: number,\n emitEncryptedReasoning = false,\n): ResponsesSSEEvent[] {\n const reasoningId = generateId(\"rs\");\n const events: ResponsesSSEEvent[] = [];\n\n events.push({\n type: \"response.output_item.added\",\n output_index: 0,\n item: buildReasoningOutputItem(reasoningId),\n });\n\n if (reasoning !== undefined) {\n events.push({\n type: \"response.reasoning_summary_part.added\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n part: { type: \"summary_text\", text: \"\" },\n });\n\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"response.reasoning_summary_text.delta\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n delta: slice,\n });\n }\n\n events.push({\n type: \"response.reasoning_summary_text.done\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n text: reasoning,\n });\n\n events.push({\n type: \"response.reasoning_summary_part.done\",\n item_id: reasoningId,\n output_index: 0,\n summary_index: 0,\n part: { type: \"summary_text\", text: reasoning },\n });\n }\n\n events.push({\n type: \"response.output_item.done\",\n output_index: 0,\n item: buildReasoningOutputItem(reasoningId, {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n });\n\n return events;\n}\n\nfunction buildWebSearchStreamEvents(\n queries: string[],\n startOutputIndex: number,\n): ResponsesSSEEvent[] {\n const events: ResponsesSSEEvent[] = [];\n\n for (let i = 0; i < queries.length; i++) {\n const searchId = generateId(\"ws\");\n const outputIndex = startOutputIndex + i;\n\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: {\n type: \"web_search_call\",\n id: searchId,\n status: \"in_progress\",\n action: { type: \"search\", query: queries[i] },\n },\n });\n\n events.push({\n type: \"response.output_item.done\",\n output_index: outputIndex,\n item: {\n type: \"web_search_call\",\n id: searchId,\n status: \"completed\",\n action: { type: \"search\", query: queries[i] },\n },\n });\n }\n\n return events;\n}\n\n// ─── Shared streaming helpers ────────────────────────────────────────────────\n\ninterface PreambleResult {\n respId: string;\n created: number;\n events: ResponsesSSEEvent[];\n prefixOutputItems: object[];\n nextOutputIndex: number;\n}\n\nfunction buildResponsePreamble(\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): PreambleResult {\n const respId = overrides?.id ?? responseId();\n const created = overrides?.created ?? Math.floor(Date.now() / 1000);\n const effectiveModel = overrides?.model ?? model;\n const events: ResponsesSSEEvent[] = [];\n const prefixOutputItems: object[] = [];\n let nextOutputIndex = 0;\n\n events.push({\n type: \"response.created\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: effectiveModel,\n status: \"in_progress\",\n output: [],\n },\n });\n events.push({\n type: \"response.in_progress\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: effectiveModel,\n status: \"in_progress\",\n output: [],\n },\n });\n\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n const reasoningEvents = buildReasoningStreamEvents(\n reasoning,\n chunkSize,\n emitEncryptedReasoning,\n );\n events.push(...reasoningEvents);\n const doneEvent = reasoningEvents.find(\n (e) =>\n e.type === \"response.output_item.done\" &&\n (e.item as { type: string })?.type === \"reasoning\",\n );\n if (doneEvent) prefixOutputItems.push(doneEvent.item as object);\n nextOutputIndex++;\n }\n\n if (webSearches && webSearches.length > 0) {\n const searchEvents = buildWebSearchStreamEvents(webSearches, nextOutputIndex);\n events.push(...searchEvents);\n const doneEvents = searchEvents.filter(\n (e) =>\n e.type === \"response.output_item.done\" &&\n (e.item as { type: string })?.type === \"web_search_call\",\n );\n for (const de of doneEvents) prefixOutputItems.push(de.item as object);\n nextOutputIndex += webSearches.length;\n }\n\n return { respId, created, events, prefixOutputItems, nextOutputIndex };\n}\n\ninterface MessageBlockResult {\n events: ResponsesSSEEvent[];\n msgItem: object;\n}\n\nfunction buildMessageOutputEvents(\n content: string,\n chunkSize: number,\n outputIndex: number,\n): MessageBlockResult {\n const msgId = itemId();\n const events: ResponsesSSEEvent[] = [];\n\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: { type: \"message\", id: msgId, status: \"in_progress\", role: \"assistant\", content: [] },\n });\n events.push({\n type: \"response.content_part.added\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n part: { type: \"output_text\", text: \"\", annotations: [] },\n });\n\n for (let i = 0; i < content.length; i += chunkSize) {\n events.push({\n type: \"response.output_text.delta\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n delta: content.slice(i, i + chunkSize),\n });\n }\n\n events.push({\n type: \"response.output_text.done\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n text: content,\n });\n events.push({\n type: \"response.content_part.done\",\n item_id: msgId,\n output_index: outputIndex,\n content_index: 0,\n part: { type: \"output_text\", text: content, annotations: [] },\n });\n\n const msgItem = {\n type: \"message\",\n id: msgId,\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: content, annotations: [] }],\n };\n\n events.push({ type: \"response.output_item.done\", output_index: outputIndex, item: msgItem });\n\n return { events, msgItem };\n}\n\ninterface FunctionCallBlockResult {\n events: ResponsesSSEEvent[];\n fcItem: object;\n}\n\n/**\n * Emit the output_item.added → arguments deltas → arguments.done →\n * output_item.done events for a single function_call at `outputIndex`,\n * returning the completed item for the final `output` array. Behavior is\n * identical to the inline per-tool-call loop in the legacy path; both the\n * legacy branch and the ordered-blocks branch share this so wire output stays\n * byte-identical for a given (tool, outputIndex).\n */\nfunction buildFunctionCallOutputEvents(\n toolCall: ToolCall,\n chunkSize: number,\n outputIndex: number,\n): FunctionCallBlockResult {\n const callId = toolCall.id || generateToolCallId();\n const fcId = generateId(\"fc\");\n const args = toolCall.arguments;\n const events: ResponsesSSEEvent[] = [];\n\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: toolCall.name,\n arguments: \"\",\n status: \"in_progress\",\n },\n });\n\n for (let i = 0; i < args.length; i += chunkSize) {\n events.push({\n type: \"response.function_call_arguments.delta\",\n item_id: fcId,\n output_index: outputIndex,\n delta: args.slice(i, i + chunkSize),\n });\n }\n\n events.push({\n type: \"response.function_call_arguments.done\",\n item_id: fcId,\n output_index: outputIndex,\n arguments: args,\n });\n\n const fcItem = {\n type: \"function_call\",\n id: fcId,\n call_id: callId,\n name: toolCall.name,\n arguments: args,\n status: \"completed\",\n };\n events.push({ type: \"response.output_item.done\", output_index: outputIndex, item: fcItem });\n\n return { events, fcItem };\n}\n\n// ─── Non-streaming response builders ────────────────────────────────────────\n\nfunction buildOutputPrefix(\n content: string,\n model: string,\n reasoning?: string,\n webSearches?: string[],\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object[] {\n const output: object[] = [];\n\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n output.push(\n buildReasoningOutputItem(generateId(\"rs\"), {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n );\n }\n\n if (webSearches && webSearches.length > 0) {\n for (const query of webSearches) {\n output.push({\n type: \"web_search_call\",\n id: generateId(\"ws\"),\n status: \"completed\",\n action: { type: \"search\", query },\n });\n }\n }\n\n output.push({\n type: \"message\",\n id: itemId(),\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: content, annotations: [] }],\n });\n\n return output;\n}\n\nfunction buildResponseEnvelope(\n model: string,\n output: object[],\n overrides?: ResponseOverrides,\n): object {\n return {\n id: overrides?.id ?? responseId(),\n object: \"response\",\n created_at: overrides?.created ?? Math.floor(Date.now() / 1000),\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output,\n usage: responsesUsage(overrides),\n };\n}\n\nfunction buildTextResponse(\n content: string,\n model: string,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object {\n return buildResponseEnvelope(\n model,\n buildOutputPrefix(\n content,\n model,\n reasoning,\n webSearches,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n ),\n overrides,\n );\n}\n\nfunction buildToolCallResponse(\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object {\n const output: object[] = [];\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n output.push(\n buildReasoningOutputItem(generateId(\"rs\"), {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n );\n }\n if (webSearches && webSearches.length > 0) {\n for (const query of webSearches) {\n output.push({\n type: \"web_search_call\",\n id: generateId(\"ws\"),\n status: \"completed\",\n action: { type: \"search\", query },\n });\n }\n }\n for (const tc of toolCalls) {\n output.push({\n type: \"function_call\",\n id: generateId(\"fc\"),\n call_id: tc.id || generateToolCallId(),\n name: tc.name,\n arguments: tc.arguments,\n status: \"completed\",\n });\n }\n return buildResponseEnvelope(model, output, overrides);\n}\n\nexport function buildContentWithToolCallsStreamEvents(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): ResponsesSSEEvent[] {\n const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(\n model,\n chunkSize,\n reasoning,\n webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n\n // The output items assembled in emission order (after any reasoning /\n // web-search prefix items). Each output_index is assigned sequentially as we\n // walk the chosen item order, so the `output_index` on every emitted event\n // matches that item's slot in the final `response.completed.output` array.\n const orderedOutputItems: object[] = [];\n\n if (blocks && blocks.length > 0) {\n // NEW PATH: stream items in the fixture's block ARRAY ORDER. A toolCall\n // block placed before a text block therefore yields a function_call item at\n // a LOWER output_index than the message — it leads the output array.\n const ordered = resolveFixtureBlocks(blocks);\n let outputIndex = nextOutputIndex;\n for (const block of ordered) {\n if (block.type === \"text\") {\n const { events: msgEvents, msgItem } = buildMessageOutputEvents(\n block.text,\n chunkSize,\n outputIndex,\n );\n events.push(...msgEvents);\n orderedOutputItems.push(msgItem);\n } else {\n const { events: fcEvents, fcItem } = buildFunctionCallOutputEvents(\n { name: block.name, arguments: block.arguments, id: block.id },\n chunkSize,\n outputIndex,\n );\n events.push(...fcEvents);\n orderedOutputItems.push(fcItem);\n }\n outputIndex += 1;\n }\n } else {\n // LEGACY PATH: message item first, then function_call items — byte-for-byte\n // unchanged from the pre-blocks behavior (message always leads the output).\n const { events: msgEvents, msgItem } = buildMessageOutputEvents(\n content,\n chunkSize,\n nextOutputIndex,\n );\n events.push(...msgEvents);\n orderedOutputItems.push(msgItem);\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const fcOutputIndex = nextOutputIndex + 1 + idx;\n const { events: fcEvents, fcItem } = buildFunctionCallOutputEvents(\n toolCalls[idx],\n chunkSize,\n fcOutputIndex,\n );\n events.push(...fcEvents);\n orderedOutputItems.push(fcItem);\n }\n }\n\n events.push({\n type: \"response.completed\",\n response: {\n id: respId,\n object: \"response\",\n created_at: created,\n model: overrides?.model ?? model,\n status: responsesStatus(overrides?.finishReason, \"completed\"),\n output: [...prefixOutputItems, ...orderedOutputItems],\n usage: responsesUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildFunctionCallOutputItem(tc: { name: string; arguments: string; id?: string }): object {\n return {\n type: \"function_call\",\n id: generateId(\"fc\"),\n call_id: tc.id || generateToolCallId(),\n name: tc.name,\n arguments: tc.arguments,\n status: \"completed\",\n };\n}\n\nfunction buildMessageOutputItem(content: string): object {\n return {\n type: \"message\",\n id: itemId(),\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: content, annotations: [] }],\n };\n}\n\nfunction buildContentWithToolCallsResponse(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n reasoning?: string,\n webSearches?: string[],\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n emitEncryptedReasoning = false,\n synthesizeSummarylessReasoning = false,\n): object {\n if (blocks && blocks.length > 0) {\n // NEW PATH: the non-streaming `output[]` array is positionally observable,\n // so emit the prefix (reasoning / web_search_call), then the blocks in\n // fixture ARRAY ORDER. A toolCall block before a text block therefore\n // yields a function_call item ahead of the message — matching the streaming\n // path's ordering for the same `blocks` fixture.\n const ordered = resolveFixtureBlocks(blocks);\n const output: object[] = [];\n if (\n reasoning ||\n shouldSynthesizeBlobOnlyReasoning(reasoning, model, synthesizeSummarylessReasoning)\n ) {\n output.push(\n buildReasoningOutputItem(generateId(\"rs\"), {\n summaryText: reasoning,\n emitEncrypted: emitEncryptedReasoning,\n }),\n );\n }\n if (webSearches && webSearches.length > 0) {\n for (const query of webSearches) {\n output.push({\n type: \"web_search_call\",\n id: generateId(\"ws\"),\n status: \"completed\",\n action: { type: \"search\", query },\n });\n }\n }\n for (const block of ordered) {\n if (block.type === \"text\") {\n output.push(buildMessageOutputItem(block.text));\n } else {\n output.push(\n buildFunctionCallOutputItem({\n name: block.name,\n arguments: block.arguments,\n id: block.id,\n }),\n );\n }\n }\n return buildResponseEnvelope(model, output, overrides);\n }\n\n // LEGACY PATH: message item first, then function_call items — unchanged.\n const output = buildOutputPrefix(\n content,\n model,\n reasoning,\n webSearches,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n for (const tc of toolCalls) {\n output.push(buildFunctionCallOutputItem(tc));\n }\n return buildResponseEnvelope(model, output, overrides);\n}\n\n// ─── SSE writer for Responses API ───────────────────────────────────────────\n\ninterface ResponsesStreamOptions {\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nasync function writeResponsesSSEStream(\n res: http.ServerResponse,\n events: ResponsesSSEEvent[],\n optionsOrLatency?: number | ResponsesStreamOptions,\n): Promise<boolean> {\n const opts: ResponsesStreamOptions =\n typeof optionsOrLatency === \"number\" ? { latency: optionsOrLatency } : (optionsOrLatency ?? {});\n const latency = opts.latency ?? 0;\n const profile = opts.streamingProfile;\n const { recordedTimings, replaySpeed } = opts;\n const signal = opts.signal;\n const onChunkSent = opts.onChunkSent;\n\n if (res.writableEnded) return true;\n res.setHeader(\"Content-Type\", \"text/event-stream\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.setHeader(\"Connection\", \"keep-alive\");\n\n let chunkIndex = 0;\n for (const event of events) {\n const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);\n if (chunkDelay > 0) await delay(chunkDelay, signal);\n if (signal?.aborted) return false;\n if (res.writableEnded) return true;\n res.write(`event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`);\n onChunkSent?.();\n if (signal?.aborted) return false;\n chunkIndex++;\n }\n\n if (!res.writableEnded) {\n res.end();\n }\n return true;\n}\n\n// ─── Request handler ────────────────────────────────────────────────────────\n\nexport async function handleResponses(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n setCorsHeaders(res);\n\n let responsesReq: ResponsesRequest;\n try {\n responsesReq = JSON.parse(raw) as ResponsesRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n },\n }),\n );\n return;\n }\n\n // Reject bodies that parsed but are not a JSON object (e.g. `null`) before\n // touching fields — otherwise `responsesReq.model` throws a TypeError that\n // surfaces as a 500 instead of a 400.\n if (!isJsonObject(responsesReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = responsesToCompletionRequest(responsesReq);\n completionReq._endpointType = \"chat\";\n completionReq._context = getContext(req);\n\n // Emit a synthetic `reasoning.encrypted_content` only when the request wants it\n // (opted in via `include`, or stateless `store: false` — mirrors real OpenAI).\n // This is what agent-framework-openai >= 1.11.0 sends on stateless-replay\n // requests; without the blob it hard-fails a reasoning + multi-tool chain.\n // See microsoft/agent-framework#7233.\n const emitEncryptedReasoning = requestWantsEncryptedReasoning(responsesReq);\n // Synthesizing a reasoning item the fixture never declared is a bigger step\n // than adding a field to one already being emitted, so it takes the NARROWER\n // explicit-`include` gate: a `store: false` request with a summary-less fixture\n // keeps emitting no reasoning item at all. See\n // `shouldSynthesizeBlobOnlyReasoning`.\n const synthesizeSummarylessReasoning = requestIncludesEncryptedReasoning(responsesReq);\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n defaults.logger.debug(\n `Responses fixture matched for ${req.method ?? \"POST\"} ${req.url ?? \"/v1/responses\"}`,\n );\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n } else {\n defaults.logger.debug(\n `No responses fixture matched for ${req.method ?? \"POST\"} ${req.url ?? \"/v1/responses\"}`,\n );\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictStatus = 503;\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(\n strictNoMatchLogLine(\n req.method ?? \"POST\",\n req.url ?? \"/v1/responses\",\n skippedBySequenceOrTurn,\n ),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: strictStatus,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"openai\",\n req.url ?? \"/v1/responses\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, completionReq);\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n const fixtureTimings = fixture.recordedTimings;\n const effectiveReplaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Combined content + tool calls response\n if (isContentWithToolCallsResponse(response)) {\n const overrides = extractOverrides(response);\n // Gate reasoning emission on the requested model's capability (aimock#254).\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = resolveReasoningForModel(\n response.reasoning,\n completionReq.model,\n effectiveStrict,\n defaults.logger,\n );\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (responsesReq.stream !== true) {\n const body = buildContentWithToolCallsResponse(\n response.content ?? \"\",\n response.toolCalls ?? [],\n completionReq.model,\n effReasoning,\n response.webSearches,\n overrides,\n response.blocks,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildContentWithToolCallsStreamEvents(\n response.content ?? \"\",\n response.toolCalls ?? [],\n completionReq.model,\n chunkSize,\n effReasoning,\n response.webSearches,\n overrides,\n response.blocks,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeResponsesSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixtureTimings,\n replaySpeed: effectiveReplaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n const overrides = extractOverrides(response);\n // Gate reasoning emission on the requested model's capability (aimock#254).\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = resolveReasoningForModel(\n response.reasoning,\n completionReq.model,\n effectiveStrict,\n defaults.logger,\n );\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (responsesReq.stream !== true) {\n const body = buildTextResponse(\n response.content,\n completionReq.model,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildTextStreamEvents(\n response.content,\n completionReq.model,\n chunkSize,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeResponsesSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixtureTimings,\n replaySpeed: effectiveReplaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n const overrides = extractOverrides(response);\n // Gate reasoning emission on the requested model's capability (aimock#254).\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = resolveReasoningForModel(\n response.reasoning,\n completionReq.model,\n effectiveStrict,\n defaults.logger,\n );\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (responsesReq.stream !== true) {\n const body = buildToolCallResponse(\n response.toolCalls,\n completionReq.model,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildToolCallStreamEvents(\n response.toolCalls,\n completionReq.model,\n chunkSize,\n effReasoning,\n response.webSearches,\n overrides,\n emitEncryptedReasoning,\n synthesizeSummarylessReasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeResponsesSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixtureTimings,\n replaySpeed: effectiveReplaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Unknown response type\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/responses\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response did not match any known type\", type: \"server_error\" },\n }),\n );\n}\n"],"mappings":";;;;;;;;;AAiGA,SAAS,mBAAmB,SAA8D;AACxF,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAO,QACJ,QAAQ,MAAM,EAAE,SAAS,gBAAgB,EAAE,SAAS,cAAc,CAClE,KAAK,MAAM,EAAE,QAAQ,GAAG,CACxB,KAAK,GAAG;;AAGb,SAAgB,yBAAyB,KAAsC;CAC7E,MAAM,WAA0B,EAAE;CAElC,MAAM,4CAA4B,IAAI,SAAsB;AAG5D,KAAI,IAAI,aACN,UAAS,KAAK;EAAE,MAAM;EAAU,SAA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form, op
|
|
|
202
202
|
const reqEndpoint = effective._endpointType;
|
|
203
203
|
if (match.endpoint !== void 0) {
|
|
204
204
|
if (match.endpoint !== reqEndpoint) continue;
|
|
205
|
+
if (reqEndpoint === "video" && req._videoProvider !== "byteplus" && typeof fixture.response !== "function" && require_helpers.isJSONResponse(fixture.response)) continue;
|
|
205
206
|
} else if (reqEndpoint && reqEndpoint !== "chat" && reqEndpoint !== "embedding" && !reqEndpoint.startsWith("realtime")) {
|
|
206
207
|
const r = fixture.response;
|
|
207
208
|
if (typeof r !== "function") {
|
package/dist/router.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs","names":["isImageResponse","isAudioResponse","isJSONResponse","isErrorResponse","isTranscriptionResponse","isVideoResponse"],"sources":["../src/router.ts"],"sourcesContent":["import type {\n ChatCompletionRequest,\n ChatMessage,\n ContentPart,\n Fixture,\n FixtureMatch,\n} from \"./types.js\";\nimport {\n isImageResponse,\n isAudioResponse,\n isTranscriptionResponse,\n isVideoResponse,\n isJSONResponse,\n isErrorResponse,\n} from \"./helpers.js\";\n\nexport function getLastMessageByRole(messages: ChatMessage[], role: string): ChatMessage | null {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === role) return messages[i];\n }\n return null;\n}\n\n/**\n * `hasToolResult` request-SHAPE predicate — does the CURRENT turn contain a\n * tool result message? \"Current turn\" = the messages AFTER the last `user`\n * message, so this is scoped to the turn being matched rather than the whole\n * conversation. This is what keeps leg-1 (tool call, `hasToolResult` false) vs\n * leg-2 (narration, `hasToolResult` true) fixtures working across MULTI-TURN\n * sessions: on the 2nd+ user turn the request still carries earlier turns' tool\n * results, and a whole-conversation check would force `hasToolResult=true`\n * forever, so the turn's leg-1 fixture (false) could never match again (\"No\n * fixture matched\" on every pill after the first).\n *\n * This is the SINGLE source of truth shared by the RECORD side\n * ({@link buildFixtureMatch} in recorder.ts, which STAMPS the value onto a new\n * fixture) and the MATCH side ({@link matchFixtureDiagnostic} below, which\n * CHECKS a fixture's stored value against the incoming request). The two MUST\n * agree byte-for-byte: if the recorder stamps a value the matcher would never\n * compute for the same request, a genuinely-recorded fixture can never match\n * its own request. Keeping the predicate in one function is what guarantees\n * they cannot drift.\n *\n * INVARIANT: callers MUST pass the POST-`requestTransform` (normalized)\n * messages — the same array `buildFixtureMatch` and `matchFixtureDiagnostic`\n * both feed here. Passing raw/untransformed messages on one side would let the\n * set-side and check-side diverge again and silently reopen the multi-turn bug.\n *\n * When there is no `user` message at all, `lastUserIdx` stays -1 and the scan\n * covers the whole conversation — the safe/consistent fallback for a user-less\n * request (both sides degrade identically). For a single-turn request whose\n * only tool message trails a lone user message this is identical to the old\n * whole-conversation check.\n */\nexport function currentTurnHasToolResult(messages: ChatMessage[]): boolean {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n return messages.slice(lastUserIdx + 1).some((m) => m.role === \"tool\");\n}\n\n/**\n * Concatenate the text content of every `system` role message in order.\n * Hosts that build a system context from multiple sources (persona, agent\n * context entries, tool guidance) often emit several system messages in one\n * request; this joins SEPARATE system messages with newlines so a substring\n * matcher sees the whole context as one body.\n *\n * Empty handling is symmetric with {@link getTextContent}: a system message\n * with no extractable text (`null`) contributes nothing, while a message that\n * extracts to an empty string is a present-but-empty body. We skip only the\n * `null` (no-text) case so a genuinely empty system message does not inject a\n * stray newline; this matches getTextContent treating \"no text\" and \"empty\n * text\" consistently.\n */\nexport function getSystemText(messages: ChatMessage[]): string {\n const parts: string[] = [];\n for (const m of messages) {\n if (m.role !== \"system\") continue;\n const text = getTextContent(m.content);\n if (text === null) continue;\n parts.push(text);\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * Extract the text content from a message's content field.\n * Handles both plain string content and array-of-parts content\n * (e.g. `[{type: \"text\", text: \"...\"}]` as sent by some SDKs).\n *\n * Multi-part text is joined with `\"\"` (the parts form one logical body split\n * across segments). Empty handling is symmetric with the string path: a string\n * `\"\"` returns `\"\"`, and an array containing at least one text part whose\n * combined text is empty likewise returns `\"\"` (NOT `null`). `null` is reserved\n * for \"no text content at all\" — null content, or an array with no text parts —\n * so callers can distinguish \"absent\" from \"present but empty\" the same way for\n * both content shapes.\n */\nexport function getTextContent(content: string | ContentPart[] | null): string | null {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n const texts = content\n .filter((p) => p.type === \"text\" && typeof p.text === \"string\")\n .map((p) => p.text as string);\n return texts.length > 0 ? texts.join(\"\") : null;\n }\n return null;\n}\n\n/**\n * Text of the last user message, for `userMessage` fixture matching. Normally\n * this is the text of the final `user` message. But some SDKs serialise a\n * single multimodal user turn (prompt text + attachment) into TWO consecutive\n * user messages — a text-only one FOLLOWED by an attachment-only one, e.g.\n * `[{role:\"user\", content:\"describe this\"}, {role:\"user\", content:[{type:\"image_url\",...}]}]`\n * (observed with Microsoft Agent Framework's `agent_framework_openai` image\n * path). The trailing attachment-only message has NO extractable text, so the\n * naive \"last user message\" lookup returns `null` and — because no fixture can\n * key on empty text — every such multimodal fixture misses. We therefore skip\n * trailing user messages that carry no text and use the nearest preceding user\n * message that does. This is deliberately narrow: it only skips text-LESS\n * (`null`) user messages — a message whose text extracts to an explicit empty\n * string `\"\"` is a present-but-empty body and IS returned (so a fixture can key\n * on it), while a genuine multi-message user turn (each message HAS text) is\n * unaffected and still matched on its final message. Returns the nearest\n * preceding user message whose text is non-null (including `\"\"`); returns `null`\n * only when no user message carries any text part at all.\n */\nexport function getLastUserText(messages: ChatMessage[]): string | null {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role !== \"user\") continue;\n const text = getTextContent(messages[i].content);\n if (text !== null) return text;\n }\n return null;\n}\n\n/**\n * Test a matcher RegExp against a string WITHOUT mutating the caller-supplied\n * regex. `RegExp.prototype.test` advances `lastIndex` as a side effect on\n * `/g` and `/y` regexes; fixtures hold caller-owned RegExp objects, so testing\n * them in place would clobber the caller's positional state (and a `/g` regex\n * reused across match calls would match intermittently). We test a fresh clone\n * (same source + flags) so the caller's object is never touched and every test\n * starts from index 0.\n */\nfunction regexTest(re: RegExp, text: string): boolean {\n return new RegExp(re.source, re.flags).test(text);\n}\n\n/**\n * Result of {@link matchFixtureDiagnostic}: the matched fixture (or `null`) plus\n * the number of fixtures that matched the request SHAPE (every predicate above\n * the sequenceIndex/turnIndex gates) but were rejected ONLY by the\n * sequenceIndex/turnIndex count state.\n *\n * `skippedBySequenceOrTurn > 0` with `fixture === null` distinguishes a\n * \"sequence/turn exhausted\" miss (candidate fixtures existed but their count\n * gate had moved on) from a true \"no fixture had a matching shape\" miss — used\n * to disambiguate the strict-mode 503 message.\n */\nexport interface MatchFixtureDiagnostic {\n fixture: Fixture | null;\n skippedBySequenceOrTurn: number;\n /**\n * `true` when the served fixture was selected by relaxed content-anchored\n * matching even though its `turnIndex` is defined and does NOT equal the\n * request's assistant-message count — i.e. the legacy strict turnIndex gate\n * (now opt-in via `AIMOCK_STRICT_TURN_INDEX`) WOULD HAVE rejected it. Absent /\n * falsy on canonical-position matches, non-turnIndexed matches, and misses.\n * Additive optional field — existing handler destructures are unaffected.\n */\n turnIndexRelaxed?: boolean;\n /**\n * How the served fixture was selected: `\"turnIndex\"` when its `turnIndex`\n * sits exactly at the current assistant count (canonical position),\n * `\"content\"` otherwise (a non-turnIndexed match or a relaxed off-by-N\n * match). Absent on misses. Additive optional field.\n */\n matchedBy?: \"content\" | \"turnIndex\";\n}\n\n/**\n * Optional matcher tuning.\n *\n * `strictTurnIndex` restores the legacy behaviour where `turnIndex` must equal\n * the request's assistant-message count exactly (a hard reject gate). It is set\n * by the record path, where a miss proxies upstream to capture a fresh turn; an\n * earlier-turn fixture must not shadow a longer request or the new turn would\n * never be recorded. Replay (the default, `false`) treats `turnIndex` as a\n * non-fatal disambiguator instead — see {@link selectByTurnIndex}.\n */\nexport interface MatchOptions {\n strictTurnIndex?: boolean;\n /**\n * Optional sink for the one-shot relaxed-turnIndex divergence warning. Handlers\n * pass their `defaults.logger`; the structural `{ warn }` shape avoids an\n * import cycle with logger.ts and keeps the matcher decoupled. When omitted no\n * warning is emitted (the diagnostic fields are still populated). The Logger's\n * own level gate keeps a passing programmatic run (silent default) quiet.\n */\n logger?: { warn(...args: unknown[]): void };\n}\n\n/**\n * Process-level opt-out: when `AIMOCK_STRICT_TURN_INDEX=1` (or `true`) is set,\n * REPLAY selection restores the legacy hard turnIndex gate — a content-matching\n * fixture whose `turnIndex` is defined and `!== assistantCount` is rejected,\n * reproducing origin/main semantics. Follows the `AIMOCK_ALLOW_PRIVATE_URLS`\n * precedent for parsing/precedence. Read per-call (not cached) so tests can flip\n * it. Does NOT affect the record path, which is already strict regardless.\n */\nfunction strictTurnIndexEnv(): boolean {\n const v = process.env.AIMOCK_STRICT_TURN_INDEX;\n return v === \"1\" || v === \"true\";\n}\n\n/**\n * Process-level set of fixtures for which the relaxed-turnIndex divergence\n * warning has already fired, so each divergent fixture warns at most ONCE per\n * process (throttle). Keyed by the selected fixture's OBJECT IDENTITY: the\n * `Fixture` references in the server's fixtures array are stable across replays\n * (the array is held by reference and only fully replaced on a fixtures reset),\n * so identity uniquely distinguishes divergent fixtures and warns each exactly\n * once. A `WeakSet` was chosen over the previous `JSON.stringify(match)` key for\n * two reasons: (1) stringifying the match DROPS `predicate` functions and\n * serialises any RegExp matcher to `{}`, so two distinct fixtures differing only\n * by a predicate/regex collided to one key and the second's warning was silently\n * suppressed; and (2) a string `Set` only grows, accumulating an entry per\n * divergent shape on a long-lived server, whereas a `WeakSet` auto-evicts when a\n * fixture object is released (e.g. after a fixtures reset drops the references).\n * `let` because `WeakSet` has no `.clear()`, so the test hook reassigns a fresh\n * one.\n */\nlet warnedRelaxedFixtures = new WeakSet<Fixture>();\n\n/**\n * Test-only hook to clear the throttle state between cases. Not part of the\n * public contract. `WeakSet` has no `.clear()`, so reassign a fresh instance.\n */\nexport function _resetTurnIndexRelaxWarnings(): void {\n warnedRelaxedFixtures = new WeakSet<Fixture>();\n}\n\n/**\n * Build the {@link MatchOptions} a request handler must pass to\n * {@link matchFixtureDiagnostic} / {@link matchFixture}, derived from whether\n * the handler is about to record on a miss.\n *\n * EVERY record-capable handler (OpenAI chat, Anthropic messages, Responses,\n * Gemini, Bedrock, Bedrock-Converse, Cohere, Ollama, …) must build its match\n * options through THIS helper rather than hand-rolling `{ strictTurnIndex }` at\n * the call site. Recording proxies upstream on a miss to capture a fresh turn;\n * if `strictTurnIndex` is left false during recording, an earlier-turn fixture\n * can content-shadow a longer request, the `if (!fixture)` record branch never\n * fires, and the new turn is SILENTLY never recorded. Funnelling the decision\n * through one helper makes that wiring impossible for a future handler to miss:\n * pass `recording = true` whenever the handler's own record gate is satisfied\n * (i.e. it will call `proxyAndRecord` on a miss), `false` otherwise.\n */\nexport function recordMatchOptions(\n recording: boolean,\n logger?: { warn(...args: unknown[]): void },\n): MatchOptions {\n return { strictTurnIndex: recording, logger };\n}\n\n/**\n * Match a fixture against a request, additionally reporting WHY a `null` result\n * occurred. Shares the exact predicate loop with {@link matchFixture}; a fixture\n * that passes every shape predicate but fails ONLY the sequenceIndex or\n * turnIndex gate increments `skippedBySequenceOrTurn`. {@link matchFixture} is a\n * thin wrapper that returns the `.fixture` field, so existing callers are\n * unaffected.\n */\nexport function matchFixtureDiagnostic(\n fixtures: Fixture[],\n req: ChatCompletionRequest,\n matchCounts?: Map<Fixture, number>,\n requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest,\n options?: MatchOptions,\n): MatchFixtureDiagnostic {\n // Apply transform once before matching — used for stripping dynamic data\n const effective = requestTransform ? requestTransform(req) : req;\n const useExactMatch = !!requestTransform;\n // In record mode the server proxies to the upstream on a miss, so a fixture\n // already captured for an EARLIER turn must NOT shadow a longer (later-turn)\n // request — otherwise the new turn would never be proxied and recorded.\n // There turnIndex stays a strict hard gate. Replay (the default) instead\n // treats turnIndex as a non-fatal disambiguator so a canonical multi-bubble\n // run isn't falsely rejected for an off-by-N assistant count.\n // Strict turnIndex is in force when the record path requests it OR the\n // process-level AIMOCK_STRICT_TURN_INDEX opt-out is set (which restores the\n // legacy hard gate for replay too). Record mode passes `true` explicitly; the\n // env only matters when the caller left it `false`/unset (replay).\n const strictTurnIndex = (options?.strictTurnIndex ?? false) || strictTurnIndexEnv();\n\n let skippedBySequenceOrTurn = 0;\n // Every fixture whose content / shape predicates (and sequenceIndex gate)\n // pass. turnIndex is applied afterwards as a non-fatal disambiguator.\n const contentMatches: Fixture[] = [];\n\n for (const fixture of fixtures) {\n const { match } = fixture;\n\n // predicate — if present, must return true (receives original request)\n if (match.predicate !== undefined) {\n if (!match.predicate(req)) continue;\n }\n\n // endpoint — bidirectional filtering:\n // 1. If fixture has endpoint set, only match requests of that type\n // 2. If request has _endpointType but fixture doesn't, skip fixtures\n // whose response type is incompatible (prevents generic chat fixtures\n // from matching image/speech/video requests and causing 500s)\n const reqEndpoint = effective._endpointType as string | undefined;\n if (match.endpoint !== undefined) {\n if (match.endpoint !== reqEndpoint) continue;\n } else if (\n reqEndpoint &&\n reqEndpoint !== \"chat\" &&\n reqEndpoint !== \"embedding\" &&\n !reqEndpoint.startsWith(\"realtime\")\n ) {\n // Fixture has no endpoint restriction but request is multimedia —\n // only match if the response type is compatible.\n // Function responses cannot be checked statically, so treat them as compatible.\n const r = fixture.response;\n if (typeof r !== \"function\") {\n const compatible =\n (reqEndpoint === \"image\" && isImageResponse(r)) ||\n (reqEndpoint === \"speech\" && isAudioResponse(r)) ||\n (reqEndpoint === \"elevenlabs-tts\" && isAudioResponse(r)) ||\n (reqEndpoint === \"audio-gen\" && isAudioResponse(r)) ||\n (reqEndpoint === \"fal-audio\" && isAudioResponse(r)) ||\n (reqEndpoint === \"fal\" && (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"transcription\" && isTranscriptionResponse(r)) ||\n (reqEndpoint === \"translation\" && isTranscriptionResponse(r)) ||\n (reqEndpoint === \"video\" && isVideoResponse(r));\n if (!compatible) continue;\n }\n }\n\n // context — opt-in exact match against the request's _context field.\n // If fixture specifies a context, only match requests with that exact context.\n // If fixture omits context, match any request regardless of _context.\n if (match.context !== undefined) {\n if (effective._context !== match.context) continue;\n }\n\n // userMessage — case-sensitive match against the last user message content.\n // String matching is intentionally case-sensitive so fixture authors can\n // rely on exact string values. This differs from the case-insensitive\n // matchesPattern() in helpers.ts, which is used for search/rerank/moderation\n // where exact casing rarely matters.\n if (match.userMessage !== undefined) {\n // Use the last user message that actually carries text — see\n // getLastUserText for why a trailing attachment-only user message\n // (multimodal serialisation split) must not shadow the real prompt.\n const text = getLastUserText(effective.messages);\n // `text === null` means no user message carried any text (e.g. a pure\n // attachment turn) — skip. An explicit empty-string body (`\"\"`) is a\n // present-but-empty user message and must be allowed through so a fixture\n // keyed on empty text can match it (see getLastUserText).\n if (text === null) continue;\n if (typeof match.userMessage === \"string\") {\n if (useExactMatch) {\n if (text !== match.userMessage) continue;\n } else {\n if (!text.includes(match.userMessage)) continue;\n }\n } else {\n if (!regexTest(match.userMessage, text)) continue;\n }\n }\n\n // systemMessage — case-sensitive substring, regexp, or array-of-substrings\n // match against the joined text of every system message in the request.\n // Use to gate a fixture on host-supplied context (e.g. agent-context\n // entries) so that when the calling app changes that context the fixture\n // stops matching and the request falls through to the next fixture or\n // upstream proxy.\n //\n // Array form (string[]) requires ALL substrings to be present — useful\n // when the gate must combine multiple non-adjacent tokens (e.g. a default\n // name AND a default activity list whose positions in the serialised\n // context JSON aren't stable).\n if (match.systemMessage !== undefined) {\n const sm = match.systemMessage;\n // Empty array is treated as \"no constraint\" → matches unconditionally,\n // INCLUDING requests with no system text at all. This is the documented\n // contract (same permissive behaviour as not setting systemMessage), so\n // it must be honored BEFORE the no-system-text guard below — otherwise a\n // request without a system message would be wrongly skipped. Validation\n // rejects [] at load time for JSON fixtures; programmatic callers that\n // pass [] get this permissive behaviour.\n if (Array.isArray(sm) && sm.length === 0) {\n // no constraint — fall through to the next predicate\n } else {\n const text = getSystemText(effective.messages);\n // Deliberately `!text` (not `text === null`): unlike userMessage/inputText,\n // getSystemText returns `\"\"` for BOTH \"a present but empty system message\"\n // AND \"no system message at all\", so it exposes no absent-vs-empty\n // distinction at the request level. Allowing `\"\"` through would make a\n // `systemMessage: \"\"` / `/^$/` fixture a catch-all firing on every\n // no-system-message request. There is no shipped-fixture demand for\n // matching an empty system prompt, so we keep the falsy guard here. If a\n // real need arises, add a getSystemText sibling that returns `null` when\n // absent and `\"\"` when present-empty, then switch to `text === null`.\n if (!text) continue;\n if (Array.isArray(sm)) {\n let allPresent = true;\n for (const needle of sm) {\n if (!text.includes(needle)) {\n allPresent = false;\n break;\n }\n }\n if (!allPresent) continue;\n } else if (typeof sm === \"string\") {\n if (useExactMatch) {\n if (text !== sm) continue;\n } else {\n if (!text.includes(sm)) continue;\n }\n } else {\n if (!regexTest(sm, text)) continue;\n }\n }\n }\n\n // toolCallId — a toolCallId fixture answers the model's response to a tool\n // result, which by API contract only happens when the conversation's LAST\n // message is a tool result. If a newer user (or other) turn follows the\n // tool message, the stale tool_call_id must not shadow userMessage matchers.\n if (match.toolCallId !== undefined) {\n const last = effective.messages[effective.messages.length - 1];\n if (!last || last.role !== \"tool\" || last.tool_call_id !== match.toolCallId) continue;\n }\n\n // toolResultContains — substring gate on the LAST message's text content\n // when that message is a tool result. Same last-message rule as toolCallId\n // (a tool-result fixture answers the model's next call after a tool round),\n // but discriminates on the result PAYLOAD instead of the call id — needed\n // when approve/cancel resumes share the same toolCallId and differ only\n // inside the tool-result JSON.\n if (match.toolResultContains !== undefined) {\n const last = effective.messages[effective.messages.length - 1];\n if (!last || last.role !== \"tool\") continue;\n const text = getTextContent(last.content);\n if (text === null || !text.includes(match.toolResultContains)) continue;\n }\n\n // toolName — match against any tool definition by function.name\n if (match.toolName !== undefined) {\n const tools = effective.tools ?? [];\n const found = tools.some((t) => t.function.name === match.toolName);\n if (!found) continue;\n }\n\n // inputText — case-sensitive match against the embedding input text.\n // Same rationale as userMessage above: fixture authors specify exact strings.\n if (match.inputText !== undefined) {\n const embeddingInput = effective.embeddingInput;\n // `undefined` means the request carried no embedding input (a non-embedding\n // request) — skip. An explicit empty string (`\"\"`) is a genuinely-empty\n // embedding input and must be allowed through so `inputText: \"\"` can match.\n if (embeddingInput === undefined) continue;\n if (typeof match.inputText === \"string\") {\n if (useExactMatch) {\n if (embeddingInput !== match.inputText) continue;\n } else {\n if (!embeddingInput.includes(match.inputText)) continue;\n }\n } else {\n if (!regexTest(match.inputText, embeddingInput)) continue;\n }\n }\n\n // responseFormat — exact string match against request response_format.type\n if (match.responseFormat !== undefined) {\n const reqType = effective.response_format?.type;\n if (reqType !== match.responseFormat) continue;\n }\n\n // model — exact match or prefix + dash-digit boundary for strings (so that\n // \"claude-opus-4\" matches \"claude-opus-4-20250514\" but \"gpt-4\" does NOT\n // match \"gpt-4o\" and \"gpt-4o\" does NOT match \"gpt-4o-mini\"), regexp unchanged\n if (match.model !== undefined) {\n if (typeof match.model === \"string\") {\n if (effective.model !== match.model) {\n if (!effective.model?.startsWith(match.model)) continue;\n const rest = effective.model.slice(match.model.length);\n if (!/^-\\d/.test(rest)) continue;\n }\n } else {\n if (!regexTest(match.model, effective.model ?? \"\")) continue;\n }\n }\n\n // hasToolResult — request-SHAPE predicate scoped to the CURRENT turn. Shares\n // the exact predicate with the recorder via {@link currentTurnHasToolResult}\n // so the value the matcher CHECKS can never drift from the value the recorder\n // STAMPED for the same request (see that helper's doc). Must be evaluated\n // with the other shape predicates ABOVE the sequence/turn state gates so that\n // a fixture whose shape never matched is not miscounted as \"skipped by\n // sequence/turn state\".\n if (match.hasToolResult !== undefined) {\n if (currentTurnHasToolResult(effective.messages) !== match.hasToolResult) continue;\n }\n\n // At this point every SHAPE / CONTENT predicate above has passed, so this\n // fixture is a genuine CONTENT match for the request. The sequenceIndex and\n // turnIndex constraints below are POSITION state, not request shape.\n //\n // sequenceIndex remains a hard, stateful gate: it consumes sequenced\n // siblings one call at a time (and an exhausted index intentionally falls\n // through to a later fixture). A fixture that matched the shape but fails\n // ONLY the sequenceIndex gate is a \"candidate skipped by sequence/turn\n // state\", counted separately so callers can disambiguate the strict-mode\n // 503 message.\n if (match.sequenceIndex !== undefined && matchCounts !== undefined) {\n const count = matchCounts.get(fixture) ?? 0;\n if (count !== match.sequenceIndex) {\n skippedBySequenceOrTurn++;\n continue;\n }\n }\n\n // turnIndex is normally NOT a hard gate (replay). Multi-step agents emit\n // several assistant bubbles per logical turn, so a canonical run's assistant\n // count routinely differs from a fixture's hardcoded turnIndex even when the\n // request content matches exactly. Rejecting a uniquely content-matching\n // fixture on absolute position produced false \"empty assistant response\"\n // misses. Instead we collect every content match and use turnIndex only as a\n // non-fatal DISAMBIGUATOR to choose AMONG several content-matching fixtures\n // (see selectByTurnIndex below). Content that does not match any fixture\n // still matches nothing — only the position gate is relaxed.\n //\n // Under strictTurnIndex (record mode) turnIndex stays a hard, exact gate so\n // an earlier-turn capture can't shadow a longer request; the miss then\n // proxies upstream and records the new turn.\n if (strictTurnIndex && match.turnIndex !== undefined) {\n const assistantCount = effective.messages.filter((m) => m.role === \"assistant\").length;\n if (assistantCount !== match.turnIndex) {\n skippedBySequenceOrTurn++;\n continue;\n }\n }\n\n contentMatches.push(fixture);\n }\n\n if (contentMatches.length === 0) {\n return { fixture: null, skippedBySequenceOrTurn };\n }\n\n const assistantCount = effective.messages.filter((m) => m.role === \"assistant\").length;\n const { fixture: selected, byUniquePosition } = selectByTurnIndex(contentMatches, assistantCount);\n\n // Divergence predicate: the served fixture carries a turnIndex that does NOT\n // sit at the current assistant position. Under strict matching this fixture\n // would have been rejected at the gate above, so serving it here is the (rare,\n // off-by-N) relaxed behaviour change PR #276 introduced. Computed from values\n // already in hand — no second matching pass.\n const selectedTurn = selected.match.turnIndex;\n const turnIndexRelaxed = selectedTurn !== undefined && selectedTurn !== assistantCount;\n // `matchedBy` reports \"turnIndex\" ONLY when the selection was genuinely decided\n // by a UNIQUE positional criterion (a single candidate whose turnIndex sits\n // exactly at the current assistant count). A canonical-position fixture that\n // tied with another at-position candidate, or that lost the exact-turn\n // tie-break to an earlier fallback, was decided by REGISTRATION ORDER, not by\n // position — those are \"content\". `selectByTurnIndex` reports which it was.\n const matchedBy: \"content\" | \"turnIndex\" = byUniquePosition ? \"turnIndex\" : \"content\";\n\n if (turnIndexRelaxed && options?.logger) {\n // Throttle: warn at most once per divergent fixture per process. Keyed by\n // the fixture's OBJECT IDENTITY so distinct fixtures whose match serialises\n // identically (predicate/regex collisions) each warn, and entries auto-evict\n // when the fixture is released (see warnedRelaxedFixtures above).\n if (!warnedRelaxedFixtures.has(selected)) {\n warnedRelaxedFixtures.add(selected);\n // Human-readable description for the message only (NOT the throttle key,\n // which is the fixture's object identity). `JSON.stringify(match)` is\n // unfit here: it DROPS `predicate` functions entirely and collapses any\n // RegExp matcher to `{}`, so a predicate/regex fixture's warning read\n // \"served fixture {}\" / \"{\"userMessage\":{}}\". `describeMatch` instead\n // summarizes the present matcher KEYS (annotating predicate/regex values)\n // so the warned fixture is identifiable.\n const idx = fixtures.indexOf(selected);\n const desc = describeMatch(selected.match, idx);\n options.logger.warn(\n `turnIndex relaxed: served fixture ${desc} at assistantCount=${assistantCount} ` +\n `(scripted turnIndex=${selectedTurn}); set AIMOCK_STRICT_TURN_INDEX=1 to restore strict matching`,\n );\n }\n }\n\n return { fixture: selected, skippedBySequenceOrTurn, turnIndexRelaxed, matchedBy };\n}\n\n/**\n * Build a stable, human-readable identifier for a fixture's match shape for the\n * relaxed-turnIndex warning. The previous `JSON.stringify(match)` was unfit: it\n * DROPS `predicate` functions (non-serialisable) and serialises any RegExp\n * matcher to `{}`, so a predicate- or regex-gated fixture's warning collapsed to\n * an uninformative \"served fixture {}\" / `{\"userMessage\":{}}` blob.\n *\n * Instead we list the PRESENT matcher keys in declaration order, annotating each\n * by VALUE KIND so predicates and regexes survive: `predicate(fn)`,\n * `userMessage(regex)`, `userMessage(\"hello\")`, `turnIndex=0`, etc. The\n * fixture's array `index` (when known, i.e. `>= 0`) is prefixed as the stable\n * positional identifier — the `Fixture` type carries no `id`/`name`, so its\n * registration index is the only stable handle. String/number values are shown\n * inline (truncated) so a content match remains recognisable; the whole string\n * is capped to keep the log line bounded.\n */\nfunction describeMatch(match: FixtureMatch, index: number): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(match)) {\n if (value === undefined) continue;\n if (typeof value === \"function\") {\n parts.push(`${key}(fn)`);\n } else if (value instanceof RegExp) {\n parts.push(`${key}(${value})`);\n } else if (typeof value === \"string\") {\n const v = value.length > 40 ? `${value.slice(0, 40)}…` : value;\n parts.push(`${key}(${JSON.stringify(v)})`);\n } else if (Array.isArray(value)) {\n parts.push(`${key}(${value.length} item${value.length === 1 ? \"\" : \"s\"})`);\n } else {\n parts.push(`${key}=${String(value)}`);\n }\n }\n const keys = parts.length > 0 ? parts.join(\", \") : \"no matchers\";\n const prefix = index >= 0 ? `#${index} ` : \"\";\n return `${prefix}{ ${keys} }`.slice(0, 160);\n}\n\n/**\n * Choose one fixture from a set that all CONTENT-matched the same request,\n * using `turnIndex` purely as a position disambiguator (never as a reject\n * gate).\n *\n * The selection rule is applied UNIFORMLY regardless of candidate count (a\n * single candidate is NOT special-cased), so the same request never flips its\n * answer just because an unrelated content-matching fixture was registered.\n * Within every tier ties are broken by REGISTRATION ORDER — the\n * earliest-registered eligible candidate wins — preserving the historical\n * greedy \"first matching fixture wins\" contract.\n *\n * 1. Prefer the turnIndexed candidate whose `turnIndex` is closest to\n * `assistantCount` WITHOUT exceeding it (the highest `turnIndex <=\n * assistantCount`). A behind-the-count scripted turn (turnIndex <\n * assistantCount) beats a plain fallback — an explicit position is a\n * stronger signal than an unpositioned default. A negative `turnIndex` such\n * as -1 is a valid at/behind position (the seed is `-Infinity`, never a `-1`\n * sentinel that would mis-skip it). Earlier registration breaks ties among\n * equal turnIndexes.\n * 2. EXACT-turn tie-break: when the best at/behind scripted turn sits at the\n * EXACT current position (`turnIndex === assistantCount`) a plain fallback\n * also answers \"right now\", so the two are equally eligible and REGISTRATION\n * ORDER decides — a later-registered `turnIndex:0` does NOT override an\n * earlier-registered fallback, and vice-versa.\n * 3. Otherwise every turnIndexed candidate is still AHEAD of the conversation.\n * An explicit future turn must NOT answer an earlier point, so a plain\n * fallback (eligible at every position) is the better answer — applied\n * uniformly, INCLUDING when the fallback is the sole partner of a single\n * future-turn fixture (the single/multi asymmetry this fixes).\n * 4. Otherwise (pure script, every candidate turnIndexed and all ahead) the\n * script genuinely has no earlier answer, so serve the lowest `turnIndex`\n * candidate — the false-red-kill for a lone scripted turn whose run has\n * FEWER assistant bubbles than its `turnIndex`; registration order breaks\n * ties.\n *\n * A future-turn fixture therefore NEVER answers an earlier-point request when an\n * eligible alternative (a fallback, or an at/behind scripted turn) exists — the\n * future-turn guard is enforced uniformly for single and multiple candidates.\n *\n * Returns the selected fixture alongside `byUniquePosition`: `true` ONLY when the\n * choice was decided by a UNIQUE positional criterion — the served fixture's\n * `turnIndex` sits EXACTLY at `assistantCount`, no earlier fallback overrode it\n * (tier 2), and no other candidate shared that exact position (so registration\n * order did not break a tie). `matchFixtureDiagnostic` maps this to\n * `matchedBy === \"turnIndex\"`; every other selection path (tie-break,\n * registration order, behind/ahead scripted turn, fallback) is `\"content\"`.\n */\nfunction selectByTurnIndex(\n candidates: Fixture[],\n assistantCount: number,\n): { fixture: Fixture; byUniquePosition: boolean } {\n // The first non-turnIndexed candidate is the registration-order-first plain\n // fallback (eligible at every position). Tracked by index so the exact-turn\n // tie-break can compare registration order against the chosen scripted turn.\n const fallbackIdx = candidates.findIndex((f) => f.match.turnIndex === undefined);\n\n // Tier 1: closest scripted turn at/before the current count. Strict `>`\n // preserves registration order on equal turnIndexes; `-Infinity` seed so a\n // negative turnIndex is a legitimate at/behind candidate, not a sentinel skip.\n let bestIdx = -1;\n let bestTurn = -Infinity;\n for (let i = 0; i < candidates.length; i++) {\n const t = candidates[i].match.turnIndex;\n if (t === undefined) continue;\n if (t <= assistantCount && t > bestTurn) {\n bestIdx = i;\n bestTurn = t;\n }\n }\n\n if (bestIdx !== -1) {\n // Tier 2: exact-turn tie with a fallback → earlier registration wins. A\n // fallback won the tie, so position did NOT uniquely decide → content.\n if (bestTurn === assistantCount && fallbackIdx !== -1 && fallbackIdx < bestIdx) {\n return { fixture: candidates[fallbackIdx], byUniquePosition: false };\n }\n // A UNIQUE positional decision requires the chosen turn to sit EXACTLY at\n // the current count AND to be the only candidate at that exact position —\n // otherwise registration order, not position, broke the tie.\n const atExactPosition =\n bestTurn === assistantCount &&\n candidates.filter((f) => f.match.turnIndex === assistantCount).length === 1;\n return { fixture: candidates[bestIdx], byUniquePosition: atExactPosition };\n }\n\n // Tier 3: every scripted turn is ahead. A plain fallback answers this earlier\n // point; first-registered fallback wins.\n if (fallbackIdx !== -1) return { fixture: candidates[fallbackIdx], byUniquePosition: false };\n\n // Tier 4: pure script, all turnIndexed and all ahead. Serve the lowest\n // scripted turn; registration order breaks ties (first of the lowest wins).\n let lowest = candidates[0];\n for (const f of candidates) {\n if ((f.match.turnIndex as number) < (lowest.match.turnIndex as number)) lowest = f;\n }\n return { fixture: lowest, byUniquePosition: false };\n}\n\n/**\n * Match a fixture against a request, returning the fixture or `null`. Thin\n * wrapper over {@link matchFixtureDiagnostic} that discards the skip diagnostic\n * — preserves the historical signature for all existing callers.\n */\nexport function matchFixture(\n fixtures: Fixture[],\n req: ChatCompletionRequest,\n matchCounts?: Map<Fixture, number>,\n requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest,\n options?: MatchOptions,\n): Fixture | null {\n return matchFixtureDiagnostic(fixtures, req, matchCounts, requestTransform, options).fixture;\n}\n"],"mappings":";;;AAgBA,SAAgB,qBAAqB,UAAyB,MAAkC;AAC9F,MAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,IACxC,KAAI,SAAS,GAAG,SAAS,KAAM,QAAO,SAAS;AAEjD,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCT,SAAgB,yBAAyB,UAAkC;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AAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;EAC1C,MAAM,IAAI,WAAW,GAAG,MAAM;AAC9B,MAAI,MAAM,OAAW;AACrB,MAAI,KAAK,kBAAkB,IAAI,UAAU;AACvC,aAAU;AACV,cAAW;;;AAIf,KAAI,YAAY,IAAI;AAGlB,MAAI,aAAa,kBAAkB,gBAAgB,MAAM,cAAc,QACrE,QAAO;GAAE,SAAS,WAAW;GAAc,kBAAkB;GAAO;EAKtE,MAAM,kBACJ,aAAa,kBACb,WAAW,QAAQ,MAAM,EAAE,MAAM,cAAc,eAAe,CAAC,WAAW;AAC5E,SAAO;GAAE,SAAS,WAAW;GAAU,kBAAkB;GAAiB;;AAK5E,KAAI,gBAAgB,GAAI,QAAO;EAAE,SAAS,WAAW;EAAc,kBAAkB;EAAO;CAI5F,IAAI,SAAS,WAAW;AACxB,MAAK,MAAM,KAAK,WACd,KAAK,EAAE,MAAM,YAAwB,OAAO,MAAM,UAAsB,UAAS;AAEnF,QAAO;EAAE,SAAS;EAAQ,kBAAkB;EAAO;;;;;;;AAQrD,SAAgB,aACd,UACA,KACA,aACA,kBACA,SACgB;AAChB,QAAO,uBAAuB,UAAU,KAAK,aAAa,kBAAkB,QAAQ,CAAC"}
|
|
1
|
+
{"version":3,"file":"router.cjs","names":["isJSONResponse","isImageResponse","isAudioResponse","isErrorResponse","isTranscriptionResponse","isVideoResponse"],"sources":["../src/router.ts"],"sourcesContent":["import type {\n ChatCompletionRequest,\n ChatMessage,\n ContentPart,\n Fixture,\n FixtureMatch,\n} from \"./types.js\";\nimport {\n isImageResponse,\n isAudioResponse,\n isTranscriptionResponse,\n isVideoResponse,\n isJSONResponse,\n isErrorResponse,\n} from \"./helpers.js\";\n\nexport function getLastMessageByRole(messages: ChatMessage[], role: string): ChatMessage | null {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === role) return messages[i];\n }\n return null;\n}\n\n/**\n * `hasToolResult` request-SHAPE predicate — does the CURRENT turn contain a\n * tool result message? \"Current turn\" = the messages AFTER the last `user`\n * message, so this is scoped to the turn being matched rather than the whole\n * conversation. This is what keeps leg-1 (tool call, `hasToolResult` false) vs\n * leg-2 (narration, `hasToolResult` true) fixtures working across MULTI-TURN\n * sessions: on the 2nd+ user turn the request still carries earlier turns' tool\n * results, and a whole-conversation check would force `hasToolResult=true`\n * forever, so the turn's leg-1 fixture (false) could never match again (\"No\n * fixture matched\" on every pill after the first).\n *\n * This is the SINGLE source of truth shared by the RECORD side\n * ({@link buildFixtureMatch} in recorder.ts, which STAMPS the value onto a new\n * fixture) and the MATCH side ({@link matchFixtureDiagnostic} below, which\n * CHECKS a fixture's stored value against the incoming request). The two MUST\n * agree byte-for-byte: if the recorder stamps a value the matcher would never\n * compute for the same request, a genuinely-recorded fixture can never match\n * its own request. Keeping the predicate in one function is what guarantees\n * they cannot drift.\n *\n * INVARIANT: callers MUST pass the POST-`requestTransform` (normalized)\n * messages — the same array `buildFixtureMatch` and `matchFixtureDiagnostic`\n * both feed here. Passing raw/untransformed messages on one side would let the\n * set-side and check-side diverge again and silently reopen the multi-turn bug.\n *\n * When there is no `user` message at all, `lastUserIdx` stays -1 and the scan\n * covers the whole conversation — the safe/consistent fallback for a user-less\n * request (both sides degrade identically). For a single-turn request whose\n * only tool message trails a lone user message this is identical to the old\n * whole-conversation check.\n */\nexport function currentTurnHasToolResult(messages: ChatMessage[]): boolean {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n return messages.slice(lastUserIdx + 1).some((m) => m.role === \"tool\");\n}\n\n/**\n * Concatenate the text content of every `system` role message in order.\n * Hosts that build a system context from multiple sources (persona, agent\n * context entries, tool guidance) often emit several system messages in one\n * request; this joins SEPARATE system messages with newlines so a substring\n * matcher sees the whole context as one body.\n *\n * Empty handling is symmetric with {@link getTextContent}: a system message\n * with no extractable text (`null`) contributes nothing, while a message that\n * extracts to an empty string is a present-but-empty body. We skip only the\n * `null` (no-text) case so a genuinely empty system message does not inject a\n * stray newline; this matches getTextContent treating \"no text\" and \"empty\n * text\" consistently.\n */\nexport function getSystemText(messages: ChatMessage[]): string {\n const parts: string[] = [];\n for (const m of messages) {\n if (m.role !== \"system\") continue;\n const text = getTextContent(m.content);\n if (text === null) continue;\n parts.push(text);\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * Extract the text content from a message's content field.\n * Handles both plain string content and array-of-parts content\n * (e.g. `[{type: \"text\", text: \"...\"}]` as sent by some SDKs).\n *\n * Multi-part text is joined with `\"\"` (the parts form one logical body split\n * across segments). Empty handling is symmetric with the string path: a string\n * `\"\"` returns `\"\"`, and an array containing at least one text part whose\n * combined text is empty likewise returns `\"\"` (NOT `null`). `null` is reserved\n * for \"no text content at all\" — null content, or an array with no text parts —\n * so callers can distinguish \"absent\" from \"present but empty\" the same way for\n * both content shapes.\n */\nexport function getTextContent(content: string | ContentPart[] | null): string | null {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n const texts = content\n .filter((p) => p.type === \"text\" && typeof p.text === \"string\")\n .map((p) => p.text as string);\n return texts.length > 0 ? texts.join(\"\") : null;\n }\n return null;\n}\n\n/**\n * Text of the last user message, for `userMessage` fixture matching. Normally\n * this is the text of the final `user` message. But some SDKs serialise a\n * single multimodal user turn (prompt text + attachment) into TWO consecutive\n * user messages — a text-only one FOLLOWED by an attachment-only one, e.g.\n * `[{role:\"user\", content:\"describe this\"}, {role:\"user\", content:[{type:\"image_url\",...}]}]`\n * (observed with Microsoft Agent Framework's `agent_framework_openai` image\n * path). The trailing attachment-only message has NO extractable text, so the\n * naive \"last user message\" lookup returns `null` and — because no fixture can\n * key on empty text — every such multimodal fixture misses. We therefore skip\n * trailing user messages that carry no text and use the nearest preceding user\n * message that does. This is deliberately narrow: it only skips text-LESS\n * (`null`) user messages — a message whose text extracts to an explicit empty\n * string `\"\"` is a present-but-empty body and IS returned (so a fixture can key\n * on it), while a genuine multi-message user turn (each message HAS text) is\n * unaffected and still matched on its final message. Returns the nearest\n * preceding user message whose text is non-null (including `\"\"`); returns `null`\n * only when no user message carries any text part at all.\n */\nexport function getLastUserText(messages: ChatMessage[]): string | null {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role !== \"user\") continue;\n const text = getTextContent(messages[i].content);\n if (text !== null) return text;\n }\n return null;\n}\n\n/**\n * Test a matcher RegExp against a string WITHOUT mutating the caller-supplied\n * regex. `RegExp.prototype.test` advances `lastIndex` as a side effect on\n * `/g` and `/y` regexes; fixtures hold caller-owned RegExp objects, so testing\n * them in place would clobber the caller's positional state (and a `/g` regex\n * reused across match calls would match intermittently). We test a fresh clone\n * (same source + flags) so the caller's object is never touched and every test\n * starts from index 0.\n */\nfunction regexTest(re: RegExp, text: string): boolean {\n return new RegExp(re.source, re.flags).test(text);\n}\n\n/**\n * Result of {@link matchFixtureDiagnostic}: the matched fixture (or `null`) plus\n * the number of fixtures that matched the request SHAPE (every predicate above\n * the sequenceIndex/turnIndex gates) but were rejected ONLY by the\n * sequenceIndex/turnIndex count state.\n *\n * `skippedBySequenceOrTurn > 0` with `fixture === null` distinguishes a\n * \"sequence/turn exhausted\" miss (candidate fixtures existed but their count\n * gate had moved on) from a true \"no fixture had a matching shape\" miss — used\n * to disambiguate the strict-mode 503 message.\n */\nexport interface MatchFixtureDiagnostic {\n fixture: Fixture | null;\n skippedBySequenceOrTurn: number;\n /**\n * `true` when the served fixture was selected by relaxed content-anchored\n * matching even though its `turnIndex` is defined and does NOT equal the\n * request's assistant-message count — i.e. the legacy strict turnIndex gate\n * (now opt-in via `AIMOCK_STRICT_TURN_INDEX`) WOULD HAVE rejected it. Absent /\n * falsy on canonical-position matches, non-turnIndexed matches, and misses.\n * Additive optional field — existing handler destructures are unaffected.\n */\n turnIndexRelaxed?: boolean;\n /**\n * How the served fixture was selected: `\"turnIndex\"` when its `turnIndex`\n * sits exactly at the current assistant count (canonical position),\n * `\"content\"` otherwise (a non-turnIndexed match or a relaxed off-by-N\n * match). Absent on misses. Additive optional field.\n */\n matchedBy?: \"content\" | \"turnIndex\";\n}\n\n/**\n * Optional matcher tuning.\n *\n * `strictTurnIndex` restores the legacy behaviour where `turnIndex` must equal\n * the request's assistant-message count exactly (a hard reject gate). It is set\n * by the record path, where a miss proxies upstream to capture a fresh turn; an\n * earlier-turn fixture must not shadow a longer request or the new turn would\n * never be recorded. Replay (the default, `false`) treats `turnIndex` as a\n * non-fatal disambiguator instead — see {@link selectByTurnIndex}.\n */\nexport interface MatchOptions {\n strictTurnIndex?: boolean;\n /**\n * Optional sink for the one-shot relaxed-turnIndex divergence warning. Handlers\n * pass their `defaults.logger`; the structural `{ warn }` shape avoids an\n * import cycle with logger.ts and keeps the matcher decoupled. When omitted no\n * warning is emitted (the diagnostic fields are still populated). The Logger's\n * own level gate keeps a passing programmatic run (silent default) quiet.\n */\n logger?: { warn(...args: unknown[]): void };\n}\n\n/**\n * Process-level opt-out: when `AIMOCK_STRICT_TURN_INDEX=1` (or `true`) is set,\n * REPLAY selection restores the legacy hard turnIndex gate — a content-matching\n * fixture whose `turnIndex` is defined and `!== assistantCount` is rejected,\n * reproducing origin/main semantics. Follows the `AIMOCK_ALLOW_PRIVATE_URLS`\n * precedent for parsing/precedence. Read per-call (not cached) so tests can flip\n * it. Does NOT affect the record path, which is already strict regardless.\n */\nfunction strictTurnIndexEnv(): boolean {\n const v = process.env.AIMOCK_STRICT_TURN_INDEX;\n return v === \"1\" || v === \"true\";\n}\n\n/**\n * Process-level set of fixtures for which the relaxed-turnIndex divergence\n * warning has already fired, so each divergent fixture warns at most ONCE per\n * process (throttle). Keyed by the selected fixture's OBJECT IDENTITY: the\n * `Fixture` references in the server's fixtures array are stable across replays\n * (the array is held by reference and only fully replaced on a fixtures reset),\n * so identity uniquely distinguishes divergent fixtures and warns each exactly\n * once. A `WeakSet` was chosen over the previous `JSON.stringify(match)` key for\n * two reasons: (1) stringifying the match DROPS `predicate` functions and\n * serialises any RegExp matcher to `{}`, so two distinct fixtures differing only\n * by a predicate/regex collided to one key and the second's warning was silently\n * suppressed; and (2) a string `Set` only grows, accumulating an entry per\n * divergent shape on a long-lived server, whereas a `WeakSet` auto-evicts when a\n * fixture object is released (e.g. after a fixtures reset drops the references).\n * `let` because `WeakSet` has no `.clear()`, so the test hook reassigns a fresh\n * one.\n */\nlet warnedRelaxedFixtures = new WeakSet<Fixture>();\n\n/**\n * Test-only hook to clear the throttle state between cases. Not part of the\n * public contract. `WeakSet` has no `.clear()`, so reassign a fresh instance.\n */\nexport function _resetTurnIndexRelaxWarnings(): void {\n warnedRelaxedFixtures = new WeakSet<Fixture>();\n}\n\n/**\n * Build the {@link MatchOptions} a request handler must pass to\n * {@link matchFixtureDiagnostic} / {@link matchFixture}, derived from whether\n * the handler is about to record on a miss.\n *\n * EVERY record-capable handler (OpenAI chat, Anthropic messages, Responses,\n * Gemini, Bedrock, Bedrock-Converse, Cohere, Ollama, …) must build its match\n * options through THIS helper rather than hand-rolling `{ strictTurnIndex }` at\n * the call site. Recording proxies upstream on a miss to capture a fresh turn;\n * if `strictTurnIndex` is left false during recording, an earlier-turn fixture\n * can content-shadow a longer request, the `if (!fixture)` record branch never\n * fires, and the new turn is SILENTLY never recorded. Funnelling the decision\n * through one helper makes that wiring impossible for a future handler to miss:\n * pass `recording = true` whenever the handler's own record gate is satisfied\n * (i.e. it will call `proxyAndRecord` on a miss), `false` otherwise.\n */\nexport function recordMatchOptions(\n recording: boolean,\n logger?: { warn(...args: unknown[]): void },\n): MatchOptions {\n return { strictTurnIndex: recording, logger };\n}\n\n/**\n * Match a fixture against a request, additionally reporting WHY a `null` result\n * occurred. Shares the exact predicate loop with {@link matchFixture}; a fixture\n * that passes every shape predicate but fails ONLY the sequenceIndex or\n * turnIndex gate increments `skippedBySequenceOrTurn`. {@link matchFixture} is a\n * thin wrapper that returns the `.fixture` field, so existing callers are\n * unaffected.\n */\nexport function matchFixtureDiagnostic(\n fixtures: Fixture[],\n req: ChatCompletionRequest,\n matchCounts?: Map<Fixture, number>,\n requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest,\n options?: MatchOptions,\n): MatchFixtureDiagnostic {\n // Apply transform once before matching — used for stripping dynamic data\n const effective = requestTransform ? requestTransform(req) : req;\n const useExactMatch = !!requestTransform;\n // In record mode the server proxies to the upstream on a miss, so a fixture\n // already captured for an EARLIER turn must NOT shadow a longer (later-turn)\n // request — otherwise the new turn would never be proxied and recorded.\n // There turnIndex stays a strict hard gate. Replay (the default) instead\n // treats turnIndex as a non-fatal disambiguator so a canonical multi-bubble\n // run isn't falsely rejected for an off-by-N assistant count.\n // Strict turnIndex is in force when the record path requests it OR the\n // process-level AIMOCK_STRICT_TURN_INDEX opt-out is set (which restores the\n // legacy hard gate for replay too). Record mode passes `true` explicitly; the\n // env only matters when the caller left it `false`/unset (replay).\n const strictTurnIndex = (options?.strictTurnIndex ?? false) || strictTurnIndexEnv();\n\n let skippedBySequenceOrTurn = 0;\n // Every fixture whose content / shape predicates (and sequenceIndex gate)\n // pass. turnIndex is applied afterwards as a non-fatal disambiguator.\n const contentMatches: Fixture[] = [];\n\n for (const fixture of fixtures) {\n const { match } = fixture;\n\n // predicate — if present, must return true (receives original request)\n if (match.predicate !== undefined) {\n if (!match.predicate(req)) continue;\n }\n\n // endpoint — bidirectional filtering:\n // 1. If fixture has endpoint set, only match requests of that type\n // 2. If request has _endpointType but fixture doesn't, skip fixtures\n // whose response type is incompatible (prevents generic chat fixtures\n // from matching image/speech/video requests and causing 500s)\n const reqEndpoint = effective._endpointType as string | undefined;\n if (match.endpoint !== undefined) {\n if (match.endpoint !== reqEndpoint) continue;\n // A declared endpoint used to END the shape discussion — the router\n // matched on the name and never looked at the response. That was safe\n // only while one endpoint name meant one response shape. `video` no\n // longer does: it is a SHARED namespace holding both VideoResponse\n // fixtures (Sora / Grok / Veo / OpenRouter) and RawJSONResponse Ark task\n // envelopes (BytePlus), and EVERY BytePlus fixture is required to declare\n // `endpoint: \"video\"`. One such fixture therefore became a first-class\n // candidate for all four other handlers, each of which then failed its\n // own isVideoResponse guard and returned 500 — a single BytePlus fixture\n // broke every other video provider in the same suite.\n //\n // Deliberately narrow: it filters ONLY the raw-JSON half of the shared\n // video namespace out of the non-BytePlus handlers. Every other\n // wrong-shape fixture still reaches its handler, which names the problem\n // itself (\"Fixture response is not a video type\", BytePlus's \"NOT a\n // VideoResponse\" warn) — a clearer diagnostic than a silent no-match.\n // `_videoProvider` is a routing fact of the INBOUND request, so it is\n // read off `req`, not off the post-`requestTransform` copy.\n if (\n reqEndpoint === \"video\" &&\n req._videoProvider !== \"byteplus\" &&\n typeof fixture.response !== \"function\" &&\n isJSONResponse(fixture.response)\n ) {\n continue;\n }\n } else if (\n reqEndpoint &&\n reqEndpoint !== \"chat\" &&\n reqEndpoint !== \"embedding\" &&\n !reqEndpoint.startsWith(\"realtime\")\n ) {\n // Fixture has no endpoint restriction but request is multimedia —\n // only match if the response type is compatible.\n // Function responses cannot be checked statically, so treat them as compatible.\n const r = fixture.response;\n if (typeof r !== \"function\") {\n const compatible =\n (reqEndpoint === \"image\" && isImageResponse(r)) ||\n (reqEndpoint === \"speech\" && isAudioResponse(r)) ||\n (reqEndpoint === \"elevenlabs-tts\" && isAudioResponse(r)) ||\n (reqEndpoint === \"audio-gen\" && isAudioResponse(r)) ||\n (reqEndpoint === \"fal-audio\" && isAudioResponse(r)) ||\n (reqEndpoint === \"fal\" && (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"transcription\" && isTranscriptionResponse(r)) ||\n (reqEndpoint === \"translation\" && isTranscriptionResponse(r)) ||\n (reqEndpoint === \"video\" && isVideoResponse(r));\n if (!compatible) continue;\n }\n }\n\n // context — opt-in exact match against the request's _context field.\n // If fixture specifies a context, only match requests with that exact context.\n // If fixture omits context, match any request regardless of _context.\n if (match.context !== undefined) {\n if (effective._context !== match.context) continue;\n }\n\n // userMessage — case-sensitive match against the last user message content.\n // String matching is intentionally case-sensitive so fixture authors can\n // rely on exact string values. This differs from the case-insensitive\n // matchesPattern() in helpers.ts, which is used for search/rerank/moderation\n // where exact casing rarely matters.\n if (match.userMessage !== undefined) {\n // Use the last user message that actually carries text — see\n // getLastUserText for why a trailing attachment-only user message\n // (multimodal serialisation split) must not shadow the real prompt.\n const text = getLastUserText(effective.messages);\n // `text === null` means no user message carried any text (e.g. a pure\n // attachment turn) — skip. An explicit empty-string body (`\"\"`) is a\n // present-but-empty user message and must be allowed through so a fixture\n // keyed on empty text can match it (see getLastUserText).\n if (text === null) continue;\n if (typeof match.userMessage === \"string\") {\n if (useExactMatch) {\n if (text !== match.userMessage) continue;\n } else {\n if (!text.includes(match.userMessage)) continue;\n }\n } else {\n if (!regexTest(match.userMessage, text)) continue;\n }\n }\n\n // systemMessage — case-sensitive substring, regexp, or array-of-substrings\n // match against the joined text of every system message in the request.\n // Use to gate a fixture on host-supplied context (e.g. agent-context\n // entries) so that when the calling app changes that context the fixture\n // stops matching and the request falls through to the next fixture or\n // upstream proxy.\n //\n // Array form (string[]) requires ALL substrings to be present — useful\n // when the gate must combine multiple non-adjacent tokens (e.g. a default\n // name AND a default activity list whose positions in the serialised\n // context JSON aren't stable).\n if (match.systemMessage !== undefined) {\n const sm = match.systemMessage;\n // Empty array is treated as \"no constraint\" → matches unconditionally,\n // INCLUDING requests with no system text at all. This is the documented\n // contract (same permissive behaviour as not setting systemMessage), so\n // it must be honored BEFORE the no-system-text guard below — otherwise a\n // request without a system message would be wrongly skipped. Validation\n // rejects [] at load time for JSON fixtures; programmatic callers that\n // pass [] get this permissive behaviour.\n if (Array.isArray(sm) && sm.length === 0) {\n // no constraint — fall through to the next predicate\n } else {\n const text = getSystemText(effective.messages);\n // Deliberately `!text` (not `text === null`): unlike userMessage/inputText,\n // getSystemText returns `\"\"` for BOTH \"a present but empty system message\"\n // AND \"no system message at all\", so it exposes no absent-vs-empty\n // distinction at the request level. Allowing `\"\"` through would make a\n // `systemMessage: \"\"` / `/^$/` fixture a catch-all firing on every\n // no-system-message request. There is no shipped-fixture demand for\n // matching an empty system prompt, so we keep the falsy guard here. If a\n // real need arises, add a getSystemText sibling that returns `null` when\n // absent and `\"\"` when present-empty, then switch to `text === null`.\n if (!text) continue;\n if (Array.isArray(sm)) {\n let allPresent = true;\n for (const needle of sm) {\n if (!text.includes(needle)) {\n allPresent = false;\n break;\n }\n }\n if (!allPresent) continue;\n } else if (typeof sm === \"string\") {\n if (useExactMatch) {\n if (text !== sm) continue;\n } else {\n if (!text.includes(sm)) continue;\n }\n } else {\n if (!regexTest(sm, text)) continue;\n }\n }\n }\n\n // toolCallId — a toolCallId fixture answers the model's response to a tool\n // result, which by API contract only happens when the conversation's LAST\n // message is a tool result. If a newer user (or other) turn follows the\n // tool message, the stale tool_call_id must not shadow userMessage matchers.\n if (match.toolCallId !== undefined) {\n const last = effective.messages[effective.messages.length - 1];\n if (!last || last.role !== \"tool\" || last.tool_call_id !== match.toolCallId) continue;\n }\n\n // toolResultContains — substring gate on the LAST message's text content\n // when that message is a tool result. Same last-message rule as toolCallId\n // (a tool-result fixture answers the model's next call after a tool round),\n // but discriminates on the result PAYLOAD instead of the call id — needed\n // when approve/cancel resumes share the same toolCallId and differ only\n // inside the tool-result JSON.\n if (match.toolResultContains !== undefined) {\n const last = effective.messages[effective.messages.length - 1];\n if (!last || last.role !== \"tool\") continue;\n const text = getTextContent(last.content);\n if (text === null || !text.includes(match.toolResultContains)) continue;\n }\n\n // toolName — match against any tool definition by function.name\n if (match.toolName !== undefined) {\n const tools = effective.tools ?? [];\n const found = tools.some((t) => t.function.name === match.toolName);\n if (!found) continue;\n }\n\n // inputText — case-sensitive match against the embedding input text.\n // Same rationale as userMessage above: fixture authors specify exact strings.\n if (match.inputText !== undefined) {\n const embeddingInput = effective.embeddingInput;\n // `undefined` means the request carried no embedding input (a non-embedding\n // request) — skip. An explicit empty string (`\"\"`) is a genuinely-empty\n // embedding input and must be allowed through so `inputText: \"\"` can match.\n if (embeddingInput === undefined) continue;\n if (typeof match.inputText === \"string\") {\n if (useExactMatch) {\n if (embeddingInput !== match.inputText) continue;\n } else {\n if (!embeddingInput.includes(match.inputText)) continue;\n }\n } else {\n if (!regexTest(match.inputText, embeddingInput)) continue;\n }\n }\n\n // responseFormat — exact string match against request response_format.type\n if (match.responseFormat !== undefined) {\n const reqType = effective.response_format?.type;\n if (reqType !== match.responseFormat) continue;\n }\n\n // model — exact match or prefix + dash-digit boundary for strings (so that\n // \"claude-opus-4\" matches \"claude-opus-4-20250514\" but \"gpt-4\" does NOT\n // match \"gpt-4o\" and \"gpt-4o\" does NOT match \"gpt-4o-mini\"), regexp unchanged\n if (match.model !== undefined) {\n if (typeof match.model === \"string\") {\n if (effective.model !== match.model) {\n if (!effective.model?.startsWith(match.model)) continue;\n const rest = effective.model.slice(match.model.length);\n if (!/^-\\d/.test(rest)) continue;\n }\n } else {\n if (!regexTest(match.model, effective.model ?? \"\")) continue;\n }\n }\n\n // hasToolResult — request-SHAPE predicate scoped to the CURRENT turn. Shares\n // the exact predicate with the recorder via {@link currentTurnHasToolResult}\n // so the value the matcher CHECKS can never drift from the value the recorder\n // STAMPED for the same request (see that helper's doc). Must be evaluated\n // with the other shape predicates ABOVE the sequence/turn state gates so that\n // a fixture whose shape never matched is not miscounted as \"skipped by\n // sequence/turn state\".\n if (match.hasToolResult !== undefined) {\n if (currentTurnHasToolResult(effective.messages) !== match.hasToolResult) continue;\n }\n\n // At this point every SHAPE / CONTENT predicate above has passed, so this\n // fixture is a genuine CONTENT match for the request. The sequenceIndex and\n // turnIndex constraints below are POSITION state, not request shape.\n //\n // sequenceIndex remains a hard, stateful gate: it consumes sequenced\n // siblings one call at a time (and an exhausted index intentionally falls\n // through to a later fixture). A fixture that matched the shape but fails\n // ONLY the sequenceIndex gate is a \"candidate skipped by sequence/turn\n // state\", counted separately so callers can disambiguate the strict-mode\n // 503 message.\n if (match.sequenceIndex !== undefined && matchCounts !== undefined) {\n const count = matchCounts.get(fixture) ?? 0;\n if (count !== match.sequenceIndex) {\n skippedBySequenceOrTurn++;\n continue;\n }\n }\n\n // turnIndex is normally NOT a hard gate (replay). Multi-step agents emit\n // several assistant bubbles per logical turn, so a canonical run's assistant\n // count routinely differs from a fixture's hardcoded turnIndex even when the\n // request content matches exactly. Rejecting a uniquely content-matching\n // fixture on absolute position produced false \"empty assistant response\"\n // misses. Instead we collect every content match and use turnIndex only as a\n // non-fatal DISAMBIGUATOR to choose AMONG several content-matching fixtures\n // (see selectByTurnIndex below). Content that does not match any fixture\n // still matches nothing — only the position gate is relaxed.\n //\n // Under strictTurnIndex (record mode) turnIndex stays a hard, exact gate so\n // an earlier-turn capture can't shadow a longer request; the miss then\n // proxies upstream and records the new turn.\n if (strictTurnIndex && match.turnIndex !== undefined) {\n const assistantCount = effective.messages.filter((m) => m.role === \"assistant\").length;\n if (assistantCount !== match.turnIndex) {\n skippedBySequenceOrTurn++;\n continue;\n }\n }\n\n contentMatches.push(fixture);\n }\n\n if (contentMatches.length === 0) {\n return { fixture: null, skippedBySequenceOrTurn };\n }\n\n const assistantCount = effective.messages.filter((m) => m.role === \"assistant\").length;\n const { fixture: selected, byUniquePosition } = selectByTurnIndex(contentMatches, assistantCount);\n\n // Divergence predicate: the served fixture carries a turnIndex that does NOT\n // sit at the current assistant position. Under strict matching this fixture\n // would have been rejected at the gate above, so serving it here is the (rare,\n // off-by-N) relaxed behaviour change PR #276 introduced. Computed from values\n // already in hand — no second matching pass.\n const selectedTurn = selected.match.turnIndex;\n const turnIndexRelaxed = selectedTurn !== undefined && selectedTurn !== assistantCount;\n // `matchedBy` reports \"turnIndex\" ONLY when the selection was genuinely decided\n // by a UNIQUE positional criterion (a single candidate whose turnIndex sits\n // exactly at the current assistant count). A canonical-position fixture that\n // tied with another at-position candidate, or that lost the exact-turn\n // tie-break to an earlier fallback, was decided by REGISTRATION ORDER, not by\n // position — those are \"content\". `selectByTurnIndex` reports which it was.\n const matchedBy: \"content\" | \"turnIndex\" = byUniquePosition ? \"turnIndex\" : \"content\";\n\n if (turnIndexRelaxed && options?.logger) {\n // Throttle: warn at most once per divergent fixture per process. Keyed by\n // the fixture's OBJECT IDENTITY so distinct fixtures whose match serialises\n // identically (predicate/regex collisions) each warn, and entries auto-evict\n // when the fixture is released (see warnedRelaxedFixtures above).\n if (!warnedRelaxedFixtures.has(selected)) {\n warnedRelaxedFixtures.add(selected);\n // Human-readable description for the message only (NOT the throttle key,\n // which is the fixture's object identity). `JSON.stringify(match)` is\n // unfit here: it DROPS `predicate` functions entirely and collapses any\n // RegExp matcher to `{}`, so a predicate/regex fixture's warning read\n // \"served fixture {}\" / \"{\"userMessage\":{}}\". `describeMatch` instead\n // summarizes the present matcher KEYS (annotating predicate/regex values)\n // so the warned fixture is identifiable.\n const idx = fixtures.indexOf(selected);\n const desc = describeMatch(selected.match, idx);\n options.logger.warn(\n `turnIndex relaxed: served fixture ${desc} at assistantCount=${assistantCount} ` +\n `(scripted turnIndex=${selectedTurn}); set AIMOCK_STRICT_TURN_INDEX=1 to restore strict matching`,\n );\n }\n }\n\n return { fixture: selected, skippedBySequenceOrTurn, turnIndexRelaxed, matchedBy };\n}\n\n/**\n * Build a stable, human-readable identifier for a fixture's match shape for the\n * relaxed-turnIndex warning. The previous `JSON.stringify(match)` was unfit: it\n * DROPS `predicate` functions (non-serialisable) and serialises any RegExp\n * matcher to `{}`, so a predicate- or regex-gated fixture's warning collapsed to\n * an uninformative \"served fixture {}\" / `{\"userMessage\":{}}` blob.\n *\n * Instead we list the PRESENT matcher keys in declaration order, annotating each\n * by VALUE KIND so predicates and regexes survive: `predicate(fn)`,\n * `userMessage(regex)`, `userMessage(\"hello\")`, `turnIndex=0`, etc. The\n * fixture's array `index` (when known, i.e. `>= 0`) is prefixed as the stable\n * positional identifier — the `Fixture` type carries no `id`/`name`, so its\n * registration index is the only stable handle. String/number values are shown\n * inline (truncated) so a content match remains recognisable; the whole string\n * is capped to keep the log line bounded.\n */\nfunction describeMatch(match: FixtureMatch, index: number): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(match)) {\n if (value === undefined) continue;\n if (typeof value === \"function\") {\n parts.push(`${key}(fn)`);\n } else if (value instanceof RegExp) {\n parts.push(`${key}(${value})`);\n } else if (typeof value === \"string\") {\n const v = value.length > 40 ? `${value.slice(0, 40)}…` : value;\n parts.push(`${key}(${JSON.stringify(v)})`);\n } else if (Array.isArray(value)) {\n parts.push(`${key}(${value.length} item${value.length === 1 ? \"\" : \"s\"})`);\n } else {\n parts.push(`${key}=${String(value)}`);\n }\n }\n const keys = parts.length > 0 ? parts.join(\", \") : \"no matchers\";\n const prefix = index >= 0 ? `#${index} ` : \"\";\n return `${prefix}{ ${keys} }`.slice(0, 160);\n}\n\n/**\n * Choose one fixture from a set that all CONTENT-matched the same request,\n * using `turnIndex` purely as a position disambiguator (never as a reject\n * gate).\n *\n * The selection rule is applied UNIFORMLY regardless of candidate count (a\n * single candidate is NOT special-cased), so the same request never flips its\n * answer just because an unrelated content-matching fixture was registered.\n * Within every tier ties are broken by REGISTRATION ORDER — the\n * earliest-registered eligible candidate wins — preserving the historical\n * greedy \"first matching fixture wins\" contract.\n *\n * 1. Prefer the turnIndexed candidate whose `turnIndex` is closest to\n * `assistantCount` WITHOUT exceeding it (the highest `turnIndex <=\n * assistantCount`). A behind-the-count scripted turn (turnIndex <\n * assistantCount) beats a plain fallback — an explicit position is a\n * stronger signal than an unpositioned default. A negative `turnIndex` such\n * as -1 is a valid at/behind position (the seed is `-Infinity`, never a `-1`\n * sentinel that would mis-skip it). Earlier registration breaks ties among\n * equal turnIndexes.\n * 2. EXACT-turn tie-break: when the best at/behind scripted turn sits at the\n * EXACT current position (`turnIndex === assistantCount`) a plain fallback\n * also answers \"right now\", so the two are equally eligible and REGISTRATION\n * ORDER decides — a later-registered `turnIndex:0` does NOT override an\n * earlier-registered fallback, and vice-versa.\n * 3. Otherwise every turnIndexed candidate is still AHEAD of the conversation.\n * An explicit future turn must NOT answer an earlier point, so a plain\n * fallback (eligible at every position) is the better answer — applied\n * uniformly, INCLUDING when the fallback is the sole partner of a single\n * future-turn fixture (the single/multi asymmetry this fixes).\n * 4. Otherwise (pure script, every candidate turnIndexed and all ahead) the\n * script genuinely has no earlier answer, so serve the lowest `turnIndex`\n * candidate — the false-red-kill for a lone scripted turn whose run has\n * FEWER assistant bubbles than its `turnIndex`; registration order breaks\n * ties.\n *\n * A future-turn fixture therefore NEVER answers an earlier-point request when an\n * eligible alternative (a fallback, or an at/behind scripted turn) exists — the\n * future-turn guard is enforced uniformly for single and multiple candidates.\n *\n * Returns the selected fixture alongside `byUniquePosition`: `true` ONLY when the\n * choice was decided by a UNIQUE positional criterion — the served fixture's\n * `turnIndex` sits EXACTLY at `assistantCount`, no earlier fallback overrode it\n * (tier 2), and no other candidate shared that exact position (so registration\n * order did not break a tie). `matchFixtureDiagnostic` maps this to\n * `matchedBy === \"turnIndex\"`; every other selection path (tie-break,\n * registration order, behind/ahead scripted turn, fallback) is `\"content\"`.\n */\nfunction selectByTurnIndex(\n candidates: Fixture[],\n assistantCount: number,\n): { fixture: Fixture; byUniquePosition: boolean } {\n // The first non-turnIndexed candidate is the registration-order-first plain\n // fallback (eligible at every position). Tracked by index so the exact-turn\n // tie-break can compare registration order against the chosen scripted turn.\n const fallbackIdx = candidates.findIndex((f) => f.match.turnIndex === undefined);\n\n // Tier 1: closest scripted turn at/before the current count. Strict `>`\n // preserves registration order on equal turnIndexes; `-Infinity` seed so a\n // negative turnIndex is a legitimate at/behind candidate, not a sentinel skip.\n let bestIdx = -1;\n let bestTurn = -Infinity;\n for (let i = 0; i < candidates.length; i++) {\n const t = candidates[i].match.turnIndex;\n if (t === undefined) continue;\n if (t <= assistantCount && t > bestTurn) {\n bestIdx = i;\n bestTurn = t;\n }\n }\n\n if (bestIdx !== -1) {\n // Tier 2: exact-turn tie with a fallback → earlier registration wins. A\n // fallback won the tie, so position did NOT uniquely decide → content.\n if (bestTurn === assistantCount && fallbackIdx !== -1 && fallbackIdx < bestIdx) {\n return { fixture: candidates[fallbackIdx], byUniquePosition: false };\n }\n // A UNIQUE positional decision requires the chosen turn to sit EXACTLY at\n // the current count AND to be the only candidate at that exact position —\n // otherwise registration order, not position, broke the tie.\n const atExactPosition =\n bestTurn === assistantCount &&\n candidates.filter((f) => f.match.turnIndex === assistantCount).length === 1;\n return { fixture: candidates[bestIdx], byUniquePosition: atExactPosition };\n }\n\n // Tier 3: every scripted turn is ahead. A plain fallback answers this earlier\n // point; first-registered fallback wins.\n if (fallbackIdx !== -1) return { fixture: candidates[fallbackIdx], byUniquePosition: false };\n\n // Tier 4: pure script, all turnIndexed and all ahead. Serve the lowest\n // scripted turn; registration order breaks ties (first of the lowest wins).\n let lowest = candidates[0];\n for (const f of candidates) {\n if ((f.match.turnIndex as number) < (lowest.match.turnIndex as number)) lowest = f;\n }\n return { fixture: lowest, byUniquePosition: false };\n}\n\n/**\n * Match a fixture against a request, returning the fixture or `null`. Thin\n * wrapper over {@link matchFixtureDiagnostic} that discards the skip diagnostic\n * — preserves the historical signature for all existing callers.\n */\nexport function matchFixture(\n fixtures: Fixture[],\n req: ChatCompletionRequest,\n matchCounts?: Map<Fixture, number>,\n requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest,\n options?: MatchOptions,\n): Fixture | null {\n return matchFixtureDiagnostic(fixtures, req, matchCounts, requestTransform, options).fixture;\n}\n"],"mappings":";;;AAgBA,SAAgB,qBAAqB,UAAyB,MAAkC;AAC9F,MAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,IACxC,KAAI,SAAS,GAAG,SAAS,KAAM,QAAO,SAAS;AAEjD,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCT,SAAgB,yBAAyB,UAAkC;CACzE,IAAI,cAAc;AAClB,MAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,IACxC,KAAI,SAAS,GAAG,SAAS,QAAQ;AAC/B,gBAAc;AACd;;AAGJ,QAAO,SAAS,MAAM,cAAc,EAAE,CAAC,MAAM,MAA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