@copilotkit/aimock 1.42.1 → 1.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +102 -16
  5. package/dist/agui-mock.cjs +1 -1
  6. package/dist/agui-mock.cjs.map +1 -1
  7. package/dist/agui-mock.d.cts.map +1 -1
  8. package/dist/agui-mock.d.ts.map +1 -1
  9. package/dist/agui-mock.js +1 -1
  10. package/dist/agui-mock.js.map +1 -1
  11. package/dist/agui-recorder.cjs +33 -11
  12. package/dist/agui-recorder.cjs.map +1 -1
  13. package/dist/agui-recorder.d.cts +10 -1
  14. package/dist/agui-recorder.d.cts.map +1 -1
  15. package/dist/agui-recorder.d.ts +10 -1
  16. package/dist/agui-recorder.d.ts.map +1 -1
  17. package/dist/agui-recorder.js +33 -11
  18. package/dist/agui-recorder.js.map +1 -1
  19. package/dist/agui-types.d.cts +1 -0
  20. package/dist/agui-types.d.cts.map +1 -1
  21. package/dist/agui-types.d.ts +1 -0
  22. package/dist/agui-types.d.ts.map +1 -1
  23. package/dist/aimock-cli.cjs +38 -10
  24. package/dist/aimock-cli.cjs.map +1 -1
  25. package/dist/aimock-cli.d.cts +5 -0
  26. package/dist/aimock-cli.d.cts.map +1 -1
  27. package/dist/aimock-cli.d.ts +5 -0
  28. package/dist/aimock-cli.d.ts.map +1 -1
  29. package/dist/aimock-cli.js +38 -10
  30. package/dist/aimock-cli.js.map +1 -1
  31. package/dist/batches.cjs +458 -0
  32. package/dist/batches.cjs.map +1 -0
  33. package/dist/batches.d.cts +57 -0
  34. package/dist/batches.d.cts.map +1 -0
  35. package/dist/batches.d.ts +57 -0
  36. package/dist/batches.d.ts.map +1 -0
  37. package/dist/batches.js +453 -0
  38. package/dist/batches.js.map +1 -0
  39. package/dist/bedrock-converse.cjs +12 -8
  40. package/dist/bedrock-converse.cjs.map +1 -1
  41. package/dist/bedrock-converse.d.cts.map +1 -1
  42. package/dist/bedrock-converse.d.ts.map +1 -1
  43. package/dist/bedrock-converse.js +14 -10
  44. package/dist/bedrock-converse.js.map +1 -1
  45. package/dist/bedrock.cjs +10 -8
  46. package/dist/bedrock.cjs.map +1 -1
  47. package/dist/bedrock.d.cts.map +1 -1
  48. package/dist/bedrock.d.ts.map +1 -1
  49. package/dist/bedrock.js +12 -10
  50. package/dist/bedrock.js.map +1 -1
  51. package/dist/byteplus-video.cjs +3 -3
  52. package/dist/byteplus-video.cjs.map +1 -1
  53. package/dist/byteplus-video.js +4 -4
  54. package/dist/byteplus-video.js.map +1 -1
  55. package/dist/chaos.cjs +622 -72
  56. package/dist/chaos.cjs.map +1 -1
  57. package/dist/chaos.d.cts +164 -7
  58. package/dist/chaos.d.cts.map +1 -1
  59. package/dist/chaos.d.ts +164 -7
  60. package/dist/chaos.d.ts.map +1 -1
  61. package/dist/chaos.js +613 -74
  62. package/dist/chaos.js.map +1 -1
  63. package/dist/cli.cjs +42 -23
  64. package/dist/cli.cjs.map +1 -1
  65. package/dist/cli.js +42 -23
  66. package/dist/cli.js.map +1 -1
  67. package/dist/cohere.cjs +10 -8
  68. package/dist/cohere.cjs.map +1 -1
  69. package/dist/cohere.d.cts.map +1 -1
  70. package/dist/cohere.d.ts.map +1 -1
  71. package/dist/cohere.js +12 -10
  72. package/dist/cohere.js.map +1 -1
  73. package/dist/config-loader.d.ts.map +1 -1
  74. package/dist/convert.cjs +1 -1
  75. package/dist/convert.cjs.map +1 -1
  76. package/dist/convert.js +1 -1
  77. package/dist/convert.js.map +1 -1
  78. package/dist/elevenlabs-audio.cjs +3 -3
  79. package/dist/elevenlabs-audio.cjs.map +1 -1
  80. package/dist/elevenlabs-audio.js +4 -4
  81. package/dist/elevenlabs-audio.js.map +1 -1
  82. package/dist/elevenlabs-voice.cjs +1053 -0
  83. package/dist/elevenlabs-voice.cjs.map +1 -0
  84. package/dist/elevenlabs-voice.d.cts +72 -0
  85. package/dist/elevenlabs-voice.d.cts.map +1 -0
  86. package/dist/elevenlabs-voice.d.ts +72 -0
  87. package/dist/elevenlabs-voice.d.ts.map +1 -0
  88. package/dist/elevenlabs-voice.js +1048 -0
  89. package/dist/elevenlabs-voice.js.map +1 -0
  90. package/dist/embeddings.cjs +8 -4
  91. package/dist/embeddings.cjs.map +1 -1
  92. package/dist/embeddings.d.cts.map +1 -1
  93. package/dist/embeddings.d.ts.map +1 -1
  94. package/dist/embeddings.js +9 -5
  95. package/dist/embeddings.js.map +1 -1
  96. package/dist/fal-audio.cjs +3 -3
  97. package/dist/fal-audio.cjs.map +1 -1
  98. package/dist/fal-audio.js +4 -4
  99. package/dist/fal-audio.js.map +1 -1
  100. package/dist/fal.cjs +28 -4
  101. package/dist/fal.cjs.map +1 -1
  102. package/dist/fal.d.cts +16 -1
  103. package/dist/fal.d.cts.map +1 -1
  104. package/dist/fal.d.ts +16 -1
  105. package/dist/fal.d.ts.map +1 -1
  106. package/dist/fal.js +28 -5
  107. package/dist/fal.js.map +1 -1
  108. package/dist/files.cjs +1071 -0
  109. package/dist/files.cjs.map +1 -0
  110. package/dist/files.d.cts +68 -0
  111. package/dist/files.d.cts.map +1 -0
  112. package/dist/files.d.ts +68 -0
  113. package/dist/files.d.ts.map +1 -0
  114. package/dist/files.js +1059 -0
  115. package/dist/files.js.map +1 -0
  116. package/dist/fine-tuning.cjs +1051 -0
  117. package/dist/fine-tuning.cjs.map +1 -0
  118. package/dist/fine-tuning.d.cts +96 -0
  119. package/dist/fine-tuning.d.cts.map +1 -0
  120. package/dist/fine-tuning.d.ts +96 -0
  121. package/dist/fine-tuning.d.ts.map +1 -0
  122. package/dist/fine-tuning.js +1044 -0
  123. package/dist/fine-tuning.js.map +1 -0
  124. package/dist/fixture-loader.cjs +0 -0
  125. package/dist/fixture-loader.cjs.map +1 -1
  126. package/dist/fixture-loader.d.cts +37 -5
  127. package/dist/fixture-loader.d.cts.map +1 -1
  128. package/dist/fixture-loader.d.ts +37 -5
  129. package/dist/fixture-loader.d.ts.map +1 -1
  130. package/dist/fixture-loader.js +0 -0
  131. package/dist/fixture-loader.js.map +1 -1
  132. package/dist/gemini-embeddings.cjs +2 -2
  133. package/dist/gemini-embeddings.cjs.map +1 -1
  134. package/dist/gemini-embeddings.js +3 -3
  135. package/dist/gemini-embeddings.js.map +1 -1
  136. package/dist/gemini-interactions.cjs +13 -7
  137. package/dist/gemini-interactions.cjs.map +1 -1
  138. package/dist/gemini-interactions.d.cts.map +1 -1
  139. package/dist/gemini-interactions.d.ts.map +1 -1
  140. package/dist/gemini-interactions.js +15 -9
  141. package/dist/gemini-interactions.js.map +1 -1
  142. package/dist/gemini.cjs +11 -7
  143. package/dist/gemini.cjs.map +1 -1
  144. package/dist/gemini.d.cts.map +1 -1
  145. package/dist/gemini.d.ts.map +1 -1
  146. package/dist/gemini.js +13 -9
  147. package/dist/gemini.js.map +1 -1
  148. package/dist/grok-video.cjs +14 -14
  149. package/dist/grok-video.cjs.map +1 -1
  150. package/dist/grok-video.js +15 -15
  151. package/dist/grok-video.js.map +1 -1
  152. package/dist/helpers.cjs +221 -5
  153. package/dist/helpers.cjs.map +1 -1
  154. package/dist/helpers.d.cts +38 -2
  155. package/dist/helpers.d.cts.map +1 -1
  156. package/dist/helpers.d.ts +38 -2
  157. package/dist/helpers.d.ts.map +1 -1
  158. package/dist/helpers.js +213 -6
  159. package/dist/helpers.js.map +1 -1
  160. package/dist/images.cjs +54 -123
  161. package/dist/images.cjs.map +1 -1
  162. package/dist/images.d.cts.map +1 -1
  163. package/dist/images.d.ts.map +1 -1
  164. package/dist/images.js +55 -124
  165. package/dist/images.js.map +1 -1
  166. package/dist/index.cjs +41 -8
  167. package/dist/index.d.cts +12 -7
  168. package/dist/index.d.ts +12 -7
  169. package/dist/index.js +14 -10
  170. package/dist/jest.cjs +14 -7
  171. package/dist/jest.cjs.map +1 -1
  172. package/dist/jest.d.cts +3 -2
  173. package/dist/jest.d.cts.map +1 -1
  174. package/dist/jest.d.ts +3 -2
  175. package/dist/jest.d.ts.map +1 -1
  176. package/dist/jest.js +14 -7
  177. package/dist/jest.js.map +1 -1
  178. package/dist/journal.cjs +41 -4
  179. package/dist/journal.cjs.map +1 -1
  180. package/dist/journal.d.cts +44 -3
  181. package/dist/journal.d.cts.map +1 -1
  182. package/dist/journal.d.ts +44 -3
  183. package/dist/journal.d.ts.map +1 -1
  184. package/dist/journal.js +41 -5
  185. package/dist/journal.js.map +1 -1
  186. package/dist/live-fixture.cjs +1192 -0
  187. package/dist/live-fixture.cjs.map +1 -0
  188. package/dist/live-fixture.js +1187 -0
  189. package/dist/live-fixture.js.map +1 -0
  190. package/dist/live-recorder.cjs +256 -0
  191. package/dist/live-recorder.cjs.map +1 -0
  192. package/dist/live-recorder.js +254 -0
  193. package/dist/live-recorder.js.map +1 -0
  194. package/dist/live-replay.cjs +286 -0
  195. package/dist/live-replay.cjs.map +1 -0
  196. package/dist/live-replay.js +285 -0
  197. package/dist/live-replay.js.map +1 -0
  198. package/dist/live-sanitize.cjs +196 -0
  199. package/dist/live-sanitize.cjs.map +1 -0
  200. package/dist/live-sanitize.js +196 -0
  201. package/dist/live-sanitize.js.map +1 -0
  202. package/dist/live-types.d.cts +71 -0
  203. package/dist/live-types.d.cts.map +1 -0
  204. package/dist/live-types.d.ts +71 -0
  205. package/dist/live-types.d.ts.map +1 -0
  206. package/dist/llmock.cjs +52 -41
  207. package/dist/llmock.cjs.map +1 -1
  208. package/dist/llmock.d.cts +16 -5
  209. package/dist/llmock.d.cts.map +1 -1
  210. package/dist/llmock.d.ts +16 -5
  211. package/dist/llmock.d.ts.map +1 -1
  212. package/dist/llmock.js +53 -42
  213. package/dist/llmock.js.map +1 -1
  214. package/dist/messages.cjs +11 -7
  215. package/dist/messages.cjs.map +1 -1
  216. package/dist/messages.d.cts.map +1 -1
  217. package/dist/messages.d.ts.map +1 -1
  218. package/dist/messages.js +13 -9
  219. package/dist/messages.js.map +1 -1
  220. package/dist/metrics.cjs +258 -5
  221. package/dist/metrics.cjs.map +1 -1
  222. package/dist/metrics.d.cts +3 -1
  223. package/dist/metrics.d.cts.map +1 -1
  224. package/dist/metrics.d.ts +3 -1
  225. package/dist/metrics.d.ts.map +1 -1
  226. package/dist/metrics.js +255 -6
  227. package/dist/metrics.js.map +1 -1
  228. package/dist/moderation.cjs +10 -1
  229. package/dist/moderation.cjs.map +1 -1
  230. package/dist/moderation.d.cts.map +1 -1
  231. package/dist/moderation.d.ts.map +1 -1
  232. package/dist/moderation.js +10 -1
  233. package/dist/moderation.js.map +1 -1
  234. package/dist/ollama.cjs +5 -5
  235. package/dist/ollama.cjs.map +1 -1
  236. package/dist/ollama.js +6 -6
  237. package/dist/ollama.js.map +1 -1
  238. package/dist/openrouter-video.cjs +5 -5
  239. package/dist/openrouter-video.cjs.map +1 -1
  240. package/dist/openrouter-video.js +6 -6
  241. package/dist/openrouter-video.js.map +1 -1
  242. package/dist/recorder.cjs +45 -9
  243. package/dist/recorder.cjs.map +1 -1
  244. package/dist/recorder.d.cts.map +1 -1
  245. package/dist/recorder.d.ts.map +1 -1
  246. package/dist/recorder.js +43 -11
  247. package/dist/recorder.js.map +1 -1
  248. package/dist/responses.cjs +4 -3
  249. package/dist/responses.cjs.map +1 -1
  250. package/dist/responses.js +5 -5
  251. package/dist/responses.js.map +1 -1
  252. package/dist/router.cjs +20 -33
  253. package/dist/router.cjs.map +1 -1
  254. package/dist/router.d.cts +4 -1
  255. package/dist/router.d.cts.map +1 -1
  256. package/dist/router.d.ts +4 -1
  257. package/dist/router.d.ts.map +1 -1
  258. package/dist/router.js +20 -34
  259. package/dist/router.js.map +1 -1
  260. package/dist/server.cjs +701 -625
  261. package/dist/server.cjs.map +1 -1
  262. package/dist/server.d.cts +1 -0
  263. package/dist/server.d.cts.map +1 -1
  264. package/dist/server.d.ts +1 -0
  265. package/dist/server.d.ts.map +1 -1
  266. package/dist/server.js +704 -628
  267. package/dist/server.js.map +1 -1
  268. package/dist/speech.cjs +2 -2
  269. package/dist/speech.cjs.map +1 -1
  270. package/dist/speech.js +3 -3
  271. package/dist/speech.js.map +1 -1
  272. package/dist/transcription.cjs +4 -4
  273. package/dist/transcription.cjs.map +1 -1
  274. package/dist/transcription.js +5 -5
  275. package/dist/transcription.js.map +1 -1
  276. package/dist/types.d.cts +119 -16
  277. package/dist/types.d.cts.map +1 -1
  278. package/dist/types.d.ts +119 -16
  279. package/dist/types.d.ts.map +1 -1
  280. package/dist/validate-cli.cjs +925 -0
  281. package/dist/validate-cli.cjs.map +1 -0
  282. package/dist/validate-cli.js +924 -0
  283. package/dist/validate-cli.js.map +1 -0
  284. package/dist/veo-video.cjs +13 -13
  285. package/dist/veo-video.cjs.map +1 -1
  286. package/dist/veo-video.js +14 -14
  287. package/dist/veo-video.js.map +1 -1
  288. package/dist/video.cjs +4 -4
  289. package/dist/video.cjs.map +1 -1
  290. package/dist/video.d.cts +1 -1
  291. package/dist/video.d.cts.map +1 -1
  292. package/dist/video.d.ts +1 -1
  293. package/dist/video.d.ts.map +1 -1
  294. package/dist/video.js +5 -5
  295. package/dist/video.js.map +1 -1
  296. package/dist/vitest.cjs +13 -6
  297. package/dist/vitest.cjs.map +1 -1
  298. package/dist/vitest.d.cts +2 -1
  299. package/dist/vitest.d.cts.map +1 -1
  300. package/dist/vitest.d.ts +2 -1
  301. package/dist/vitest.d.ts.map +1 -1
  302. package/dist/vitest.js +14 -7
  303. package/dist/vitest.js.map +1 -1
  304. package/dist/watcher.cjs +2 -1
  305. package/dist/watcher.cjs.map +1 -1
  306. package/dist/watcher.js +2 -1
  307. package/dist/watcher.js.map +1 -1
  308. package/dist/ws-framing.cjs +150 -35
  309. package/dist/ws-framing.cjs.map +1 -1
  310. package/dist/ws-framing.d.cts +18 -3
  311. package/dist/ws-framing.d.cts.map +1 -1
  312. package/dist/ws-framing.d.ts +18 -3
  313. package/dist/ws-framing.d.ts.map +1 -1
  314. package/dist/ws-framing.js +151 -36
  315. package/dist/ws-framing.js.map +1 -1
  316. package/dist/ws-gemini-live.cjs +2 -2
  317. package/dist/ws-gemini-live.d.ts +2 -2
  318. package/dist/ws-gemini-live.js +2 -2
  319. package/dist/ws-live.cjs +401 -0
  320. package/dist/ws-live.cjs.map +1 -0
  321. package/dist/ws-live.js +400 -0
  322. package/dist/ws-live.js.map +1 -0
  323. package/dist/ws-realtime.cjs +46 -2
  324. package/dist/ws-realtime.cjs.map +1 -1
  325. package/dist/ws-realtime.d.cts.map +1 -1
  326. package/dist/ws-realtime.d.ts +2 -2
  327. package/dist/ws-realtime.d.ts.map +1 -1
  328. package/dist/ws-realtime.js +46 -2
  329. package/dist/ws-realtime.js.map +1 -1
  330. package/dist/ws-responses.cjs +2 -2
  331. package/dist/ws-responses.js +2 -2
  332. package/dist/ws-upstream.cjs +118 -0
  333. package/dist/ws-upstream.cjs.map +1 -0
  334. package/dist/ws-upstream.js +115 -0
  335. package/dist/ws-upstream.js.map +1 -0
  336. package/fixtures/openai-live-client.json +390 -0
  337. package/fixtures/openai-live-managed.json +709 -0
  338. package/package.json +1 -1
@@ -1 +1 @@
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,MAAM,EAAE,SAAS,OAAO;;;;;;;;;;;;;;;;AAiBvE,SAAgB,cAAc,UAAiC;CAC7D,MAAM,QAAkB,EAAE;AA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;;;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":["isLiveResponse","isJSONResponse","isImageResponse","isAudioResponse","isErrorResponse","isTranscriptionResponse","isVideoResponse","describeMatch","isOneShotError","claimOneShotError"],"sources":["../src/router.ts"],"sourcesContent":["import { claimOneShotError, isOneShotError } from \"./fixture-loader.js\";\nimport type { ChatCompletionRequest, ChatMessage, ContentPart, Fixture } from \"./types.js\";\nimport {\n describeMatch,\n isLiveResponse,\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 const response = fixture.response;\n const liveResponse = isLiveResponse(response);\n if (reqEndpoint === \"openai-live\") {\n if (\n match.endpoint !== \"openai-live\" ||\n effective.model !== \"gpt-live-1\" ||\n (typeof response !== \"function\" &&\n (!liveResponse || effective.model !== response.live.model))\n )\n continue;\n } else if (liveResponse) {\n continue;\n }\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 === \"elevenlabs-voice-design\" &&\n (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"elevenlabs-voice\" && (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"elevenlabs-voice-get\" && (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"elevenlabs-voice-delete\" &&\n (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 * 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\n/** Select for serving and reserve an injected error before the caller can await.\n * Diagnostic-only matching stays non-consuming. A competing selection retries\n * against the live queue; cancellation must release the reserved fixture.\n */\nexport function selectFixtureForServing(\n ...args: Parameters<typeof matchFixtureDiagnostic>\n): MatchFixtureDiagnostic {\n for (;;) {\n const attempt = matchFixtureDiagnostic(...args);\n if (\n attempt.fixture &&\n isOneShotError(attempt.fixture) &&\n !claimOneShotError(args[0], attempt.fixture)\n )\n continue;\n return attempt;\n }\n}\n"],"mappings":";;;;AAaA,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,MAAM,EAAE,SAAS,OAAO;;;;;;;;;;;;;;;;AAiBvE,SAAgB,cAAc,UAAiC;CAC7D,MAAM,QAAkB,EAAE;AAC1B,MAAK,MAAM,KAAK,UAAU;AACxB,MAAI,EAAE,SAAS,SAAU;EACzB,MAAM,OAAO,eAAe,EAAE,QAAQ;AACtC,MAAI,SAAS,KAAM;AACnB,QAAM,KAAK,KAAK;;AAElB,QAAO,MAAM,KAAK,KAAK;;;;;;;;;;;;;;;AAgBzB,SAAgB,eAAe,SAAuD;AAC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,KAAK,aAAa,kBAAkB,QAAQ,CAAC;;;;;;AAOvF,SAAgB,wBACd,GAAG,MACqB;AACxB,UAAS;EACP,MAAM,UAAU,uBAAuB,GAAG,KAAK;AAC/C,MACE,QAAQ,WACRC,sCAAe,QAAQ,QAAQ,IAC/B,CAACC,yCAAkB,KAAK,IAAI,QAAQ,QAAQ,CAE5C;AACF,SAAO"}
package/dist/router.d.cts CHANGED
@@ -110,7 +110,10 @@ declare function matchFixtureDiagnostic(fixtures: Fixture[], req: ChatCompletion
110
110
  * — preserves the historical signature for all existing callers.
111
111
  */
112
112
  declare function matchFixture(fixtures: Fixture[], req: ChatCompletionRequest, matchCounts?: Map<Fixture, number>, requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest, options?: MatchOptions): Fixture | null;
113
- //# sourceMappingURL=router.d.ts.map
113
+ /** Select for serving and reserve an injected error before the caller can await.
114
+ * Diagnostic-only matching stays non-consuming. A competing selection retries
115
+ * against the live queue; cancellation must release the reserved fixture.
116
+ */
114
117
  //#endregion
115
118
  export { MatchFixtureDiagnostic, getTextContent, matchFixture, matchFixtureDiagnostic };
116
119
  //# sourceMappingURL=router.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.cts","names":[],"sources":["../src/router.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;iBAuGgB,cAAA,mBAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+DhC,sBAAA;WACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BM,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmFD,sBAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT;;;;;;iBAwea,YAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT"}
1
+ {"version":3,"file":"router.d.cts","names":[],"sources":["../src/router.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;iBAoGgB,cAAA,mBAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+DhC,sBAAA;WACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BM,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmFD,sBAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT;;;;;;iBAqda,YAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT"}
package/dist/router.d.ts CHANGED
@@ -110,7 +110,10 @@ declare function matchFixtureDiagnostic(fixtures: Fixture[], req: ChatCompletion
110
110
  * — preserves the historical signature for all existing callers.
111
111
  */
112
112
  declare function matchFixture(fixtures: Fixture[], req: ChatCompletionRequest, matchCounts?: Map<Fixture, number>, requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest, options?: MatchOptions): Fixture | null;
113
- //# sourceMappingURL=router.d.ts.map
113
+ /** Select for serving and reserve an injected error before the caller can await.
114
+ * Diagnostic-only matching stays non-consuming. A competing selection retries
115
+ * against the live queue; cancellation must release the reserved fixture.
116
+ */
114
117
  //#endregion
115
118
  export { MatchFixtureDiagnostic, getTextContent, matchFixture, matchFixtureDiagnostic };
116
119
  //# sourceMappingURL=router.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.ts","names":[],"sources":["../src/router.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;iBAuGgB,cAAA,mBAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+DhC,sBAAA;WACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BM,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmFD,sBAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT;;;;;;iBAwea,YAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT"}
1
+ {"version":3,"file":"router.d.ts","names":[],"sources":["../src/router.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;iBAoGgB,cAAA,mBAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+DhC,sBAAA;WACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA8BM,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmFD,sBAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT;;;;;;iBAqda,YAAA,WACJ,gBACL,qCACS,IAAI,2CACO,0BAA0B,iCACzC,eACT"}
package/dist/router.js CHANGED
@@ -1,4 +1,5 @@
1
- import { isAudioResponse, isErrorResponse, isImageResponse, isJSONResponse, isTranscriptionResponse, isVideoResponse } from "./helpers.js";
1
+ import { describeMatch, isAudioResponse, isErrorResponse, isImageResponse, isJSONResponse, isLiveResponse, isTranscriptionResponse, isVideoResponse } from "./helpers.js";
2
+ import { claimOneShotError, isOneShotError } from "./fixture-loader.js";
2
3
 
3
4
  //#region src/router.ts
4
5
  function getLastMessageByRole(messages, role) {
@@ -200,13 +201,18 @@ function matchFixtureDiagnostic(fixtures, req, matchCounts, requestTransform, op
200
201
  if (!match.predicate(req)) continue;
201
202
  }
202
203
  const reqEndpoint = effective._endpointType;
204
+ const response = fixture.response;
205
+ const liveResponse = isLiveResponse(response);
206
+ if (reqEndpoint === "openai-live") {
207
+ if (match.endpoint !== "openai-live" || effective.model !== "gpt-live-1" || typeof response !== "function" && (!liveResponse || effective.model !== response.live.model)) continue;
208
+ } else if (liveResponse) continue;
203
209
  if (match.endpoint !== void 0) {
204
210
  if (match.endpoint !== reqEndpoint) continue;
205
211
  if (reqEndpoint === "video" && req._videoProvider !== "byteplus" && typeof fixture.response !== "function" && isJSONResponse(fixture.response)) continue;
206
212
  } else if (reqEndpoint && reqEndpoint !== "chat" && reqEndpoint !== "embedding" && !reqEndpoint.startsWith("realtime")) {
207
213
  const r = fixture.response;
208
214
  if (typeof r !== "function") {
209
- if (!(reqEndpoint === "image" && isImageResponse(r) || reqEndpoint === "speech" && isAudioResponse(r) || reqEndpoint === "elevenlabs-tts" && isAudioResponse(r) || reqEndpoint === "audio-gen" && isAudioResponse(r) || reqEndpoint === "fal-audio" && isAudioResponse(r) || reqEndpoint === "fal" && (isJSONResponse(r) || isErrorResponse(r)) || reqEndpoint === "transcription" && isTranscriptionResponse(r) || reqEndpoint === "translation" && isTranscriptionResponse(r) || reqEndpoint === "video" && isVideoResponse(r))) continue;
215
+ if (!(reqEndpoint === "image" && isImageResponse(r) || reqEndpoint === "speech" && isAudioResponse(r) || reqEndpoint === "elevenlabs-tts" && isAudioResponse(r) || reqEndpoint === "audio-gen" && isAudioResponse(r) || reqEndpoint === "fal-audio" && isAudioResponse(r) || reqEndpoint === "fal" && (isJSONResponse(r) || isErrorResponse(r)) || reqEndpoint === "elevenlabs-voice-design" && (isJSONResponse(r) || isErrorResponse(r)) || reqEndpoint === "elevenlabs-voice" && (isJSONResponse(r) || isErrorResponse(r)) || reqEndpoint === "elevenlabs-voice-get" && (isJSONResponse(r) || isErrorResponse(r)) || reqEndpoint === "elevenlabs-voice-delete" && (isJSONResponse(r) || isErrorResponse(r)) || reqEndpoint === "transcription" && isTranscriptionResponse(r) || reqEndpoint === "translation" && isTranscriptionResponse(r) || reqEndpoint === "video" && isVideoResponse(r))) continue;
210
216
  }
211
217
  }
212
218
  if (match.context !== void 0) {
@@ -316,37 +322,6 @@ function matchFixtureDiagnostic(fixtures, req, matchCounts, requestTransform, op
316
322
  };
317
323
  }
318
324
  /**
319
- * Build a stable, human-readable identifier for a fixture's match shape for the
320
- * relaxed-turnIndex warning. The previous `JSON.stringify(match)` was unfit: it
321
- * DROPS `predicate` functions (non-serialisable) and serialises any RegExp
322
- * matcher to `{}`, so a predicate- or regex-gated fixture's warning collapsed to
323
- * an uninformative "served fixture {}" / `{"userMessage":{}}` blob.
324
- *
325
- * Instead we list the PRESENT matcher keys in declaration order, annotating each
326
- * by VALUE KIND so predicates and regexes survive: `predicate(fn)`,
327
- * `userMessage(regex)`, `userMessage("hello")`, `turnIndex=0`, etc. The
328
- * fixture's array `index` (when known, i.e. `>= 0`) is prefixed as the stable
329
- * positional identifier — the `Fixture` type carries no `id`/`name`, so its
330
- * registration index is the only stable handle. String/number values are shown
331
- * inline (truncated) so a content match remains recognisable; the whole string
332
- * is capped to keep the log line bounded.
333
- */
334
- function describeMatch(match, index) {
335
- const parts = [];
336
- for (const [key, value] of Object.entries(match)) {
337
- if (value === void 0) continue;
338
- if (typeof value === "function") parts.push(`${key}(fn)`);
339
- else if (value instanceof RegExp) parts.push(`${key}(${value})`);
340
- else if (typeof value === "string") {
341
- const v = value.length > 40 ? `${value.slice(0, 40)}…` : value;
342
- parts.push(`${key}(${JSON.stringify(v)})`);
343
- } else if (Array.isArray(value)) parts.push(`${key}(${value.length} item${value.length === 1 ? "" : "s"})`);
344
- else parts.push(`${key}=${String(value)}`);
345
- }
346
- const keys = parts.length > 0 ? parts.join(", ") : "no matchers";
347
- return `${index >= 0 ? `#${index} ` : ""}{ ${keys} }`.slice(0, 160);
348
- }
349
- /**
350
325
  * Choose one fixture from a set that all CONTENT-matched the same request,
351
326
  * using `turnIndex` purely as a position disambiguator (never as a reject
352
327
  * gate).
@@ -436,7 +411,18 @@ function selectByTurnIndex(candidates, assistantCount) {
436
411
  function matchFixture(fixtures, req, matchCounts, requestTransform, options) {
437
412
  return matchFixtureDiagnostic(fixtures, req, matchCounts, requestTransform, options).fixture;
438
413
  }
414
+ /** Select for serving and reserve an injected error before the caller can await.
415
+ * Diagnostic-only matching stays non-consuming. A competing selection retries
416
+ * against the live queue; cancellation must release the reserved fixture.
417
+ */
418
+ function selectFixtureForServing(...args) {
419
+ for (;;) {
420
+ const attempt = matchFixtureDiagnostic(...args);
421
+ if (attempt.fixture && isOneShotError(attempt.fixture) && !claimOneShotError(args[0], attempt.fixture)) continue;
422
+ return attempt;
423
+ }
424
+ }
439
425
 
440
426
  //#endregion
441
- export { currentTurnHasToolResult, getLastMessageByRole, getTextContent, matchFixture, matchFixtureDiagnostic, recordMatchOptions };
427
+ export { currentTurnHasToolResult, getLastMessageByRole, getTextContent, matchFixture, matchFixtureDiagnostic, recordMatchOptions, selectFixtureForServing };
442
428
  //# sourceMappingURL=router.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","names":[],"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,MAAM,EAAE,SAAS,OAAO;;;;;;;;;;;;;;;;AAiBvE,SAAgB,cAAc,UAAiC;CAC7D,MAAM,QAAkB,EAAE;AAC1B,MAAK,MAAM,KAAK,UAAU;AACxB,MAAI,EAAE,SAAS,SAAU;EACzB,MAAM,OAAO,eAAe,EAAE,QAAQ;AACtC,MAAI,SAAS,KAAM;AACnB,QAAM,KAAK,KAAK;;AAElB,QAAO,MAAM,KAAK,KAAK;;;;;;;;;;;;;;;AAgBzB,SAAgB,eAAe,SAAuD;AACpF,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,KAAI,MAAM,QAAQ,QAAQ,EAAE;EAC1B,MAAM,QAAQ,QACX,QAAQ,MAAM,EAAE,SAAS,UAAU,OAAO,EAAE,SAAS,SAAS,CAC9D,KAAK,MAAM,EAAE,KAAe;AAC/B,SAAO,MAAM,SAAS,IAAI,MAAM,KAAK,GAAG,GAAG;;AAE7C,QAAO;;;;;;;;;;;;;;;;;;;;;AAsBT,SAAgB,gBAAgB,UAAwC;AACtE,MAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK;AAC7C,MAAI,SAAS,GAAG,SAAS,OA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src/router.ts"],"sourcesContent":["import { claimOneShotError, isOneShotError } from \"./fixture-loader.js\";\nimport type { ChatCompletionRequest, ChatMessage, ContentPart, Fixture } from \"./types.js\";\nimport {\n describeMatch,\n isLiveResponse,\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 const response = fixture.response;\n const liveResponse = isLiveResponse(response);\n if (reqEndpoint === \"openai-live\") {\n if (\n match.endpoint !== \"openai-live\" ||\n effective.model !== \"gpt-live-1\" ||\n (typeof response !== \"function\" &&\n (!liveResponse || effective.model !== response.live.model))\n )\n continue;\n } else if (liveResponse) {\n continue;\n }\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 === \"elevenlabs-voice-design\" &&\n (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"elevenlabs-voice\" && (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"elevenlabs-voice-get\" && (isJSONResponse(r) || isErrorResponse(r))) ||\n (reqEndpoint === \"elevenlabs-voice-delete\" &&\n (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 * 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\n/** Select for serving and reserve an injected error before the caller can await.\n * Diagnostic-only matching stays non-consuming. A competing selection retries\n * against the live queue; cancellation must release the reserved fixture.\n */\nexport function selectFixtureForServing(\n ...args: Parameters<typeof matchFixtureDiagnostic>\n): MatchFixtureDiagnostic {\n for (;;) {\n const attempt = matchFixtureDiagnostic(...args);\n if (\n attempt.fixture &&\n isOneShotError(attempt.fixture) &&\n !claimOneShotError(args[0], attempt.fixture)\n )\n continue;\n return attempt;\n }\n}\n"],"mappings":";;;;AAaA,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,IAA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