@copilotkit/aimock 1.43.0 → 1.45.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 (396) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +46 -0
  4. package/README.md +14 -2
  5. package/dist/agui-handler.d.ts.map +1 -1
  6. package/dist/aimock-cli.cjs +31 -5
  7. package/dist/aimock-cli.cjs.map +1 -1
  8. package/dist/aimock-cli.d.cts.map +1 -1
  9. package/dist/aimock-cli.d.ts.map +1 -1
  10. package/dist/aimock-cli.js +31 -5
  11. package/dist/aimock-cli.js.map +1 -1
  12. package/dist/bedrock-converse.cjs +344 -43
  13. package/dist/bedrock-converse.cjs.map +1 -1
  14. package/dist/bedrock-converse.d.cts.map +1 -1
  15. package/dist/bedrock-converse.d.ts.map +1 -1
  16. package/dist/bedrock-converse.js +345 -44
  17. package/dist/bedrock-converse.js.map +1 -1
  18. package/dist/bedrock.cjs +195 -42
  19. package/dist/bedrock.cjs.map +1 -1
  20. package/dist/bedrock.d.cts.map +1 -1
  21. package/dist/bedrock.d.ts.map +1 -1
  22. package/dist/bedrock.js +196 -43
  23. package/dist/bedrock.js.map +1 -1
  24. package/dist/chaos.cjs +9 -5
  25. package/dist/chaos.cjs.map +1 -1
  26. package/dist/chaos.d.cts.map +1 -1
  27. package/dist/chaos.d.ts.map +1 -1
  28. package/dist/chaos.js +10 -7
  29. package/dist/chaos.js.map +1 -1
  30. package/dist/cli.cjs +238 -9
  31. package/dist/cli.cjs.map +1 -1
  32. package/dist/cli.js +242 -13
  33. package/dist/cli.js.map +1 -1
  34. package/dist/cohere.cjs +159 -72
  35. package/dist/cohere.cjs.map +1 -1
  36. package/dist/cohere.d.cts.map +1 -1
  37. package/dist/cohere.d.ts.map +1 -1
  38. package/dist/cohere.js +160 -73
  39. package/dist/cohere.js.map +1 -1
  40. package/dist/config-loader.cjs +63 -5
  41. package/dist/config-loader.cjs.map +1 -1
  42. package/dist/config-loader.d.cts +37 -4
  43. package/dist/config-loader.d.cts.map +1 -1
  44. package/dist/config-loader.d.ts +37 -4
  45. package/dist/config-loader.d.ts.map +1 -1
  46. package/dist/config-loader.js +63 -5
  47. package/dist/config-loader.js.map +1 -1
  48. package/dist/constants.cjs +8 -0
  49. package/dist/constants.cjs.map +1 -1
  50. package/dist/constants.d.cts +6 -2
  51. package/dist/constants.d.ts +6 -2
  52. package/dist/constants.js +8 -1
  53. package/dist/constants.js.map +1 -1
  54. package/dist/echo-text.cjs +65 -0
  55. package/dist/echo-text.cjs.map +1 -0
  56. package/dist/echo-text.d.cts +22 -0
  57. package/dist/echo-text.d.cts.map +1 -0
  58. package/dist/echo-text.d.ts +22 -0
  59. package/dist/echo-text.d.ts.map +1 -0
  60. package/dist/echo-text.js +65 -0
  61. package/dist/echo-text.js.map +1 -0
  62. package/dist/embeddings.cjs +18 -1
  63. package/dist/embeddings.cjs.map +1 -1
  64. package/dist/embeddings.d.cts +1 -1
  65. package/dist/embeddings.d.cts.map +1 -1
  66. package/dist/embeddings.d.ts +1 -1
  67. package/dist/embeddings.d.ts.map +1 -1
  68. package/dist/embeddings.js +18 -1
  69. package/dist/embeddings.js.map +1 -1
  70. package/dist/fakes-plugin.cjs +131 -0
  71. package/dist/fakes-plugin.cjs.map +1 -0
  72. package/dist/fakes-plugin.d.cts +23 -0
  73. package/dist/fakes-plugin.d.cts.map +1 -0
  74. package/dist/fakes-plugin.d.ts +23 -0
  75. package/dist/fakes-plugin.d.ts.map +1 -0
  76. package/dist/fakes-plugin.js +127 -0
  77. package/dist/fakes-plugin.js.map +1 -0
  78. package/dist/files.cjs +9 -11
  79. package/dist/files.cjs.map +1 -1
  80. package/dist/files.d.cts.map +1 -1
  81. package/dist/files.d.ts.map +1 -1
  82. package/dist/files.js +10 -13
  83. package/dist/files.js.map +1 -1
  84. package/dist/fine-tuning.cjs +1 -19
  85. package/dist/fine-tuning.cjs.map +1 -1
  86. package/dist/fine-tuning.d.cts.map +1 -1
  87. package/dist/fine-tuning.d.ts.map +1 -1
  88. package/dist/fine-tuning.js +2 -20
  89. package/dist/fine-tuning.js.map +1 -1
  90. package/dist/fixture-loader-services.cjs +116 -0
  91. package/dist/fixture-loader-services.cjs.map +1 -0
  92. package/dist/fixture-loader-services.d.cts +48 -0
  93. package/dist/fixture-loader-services.d.cts.map +1 -0
  94. package/dist/fixture-loader-services.d.ts +48 -0
  95. package/dist/fixture-loader-services.d.ts.map +1 -0
  96. package/dist/fixture-loader-services.js +114 -0
  97. package/dist/fixture-loader-services.js.map +1 -0
  98. package/dist/fixture-loader.cjs +552 -29
  99. package/dist/fixture-loader.cjs.map +1 -1
  100. package/dist/fixture-loader.d.cts +140 -2
  101. package/dist/fixture-loader.d.cts.map +1 -1
  102. package/dist/fixture-loader.d.ts +140 -2
  103. package/dist/fixture-loader.d.ts.map +1 -1
  104. package/dist/fixture-loader.js +542 -31
  105. package/dist/fixture-loader.js.map +1 -1
  106. package/dist/gemini-embeddings.cjs +42 -2
  107. package/dist/gemini-embeddings.cjs.map +1 -1
  108. package/dist/gemini-embeddings.js +43 -3
  109. package/dist/gemini-embeddings.js.map +1 -1
  110. package/dist/gemini-interactions.cjs +288 -52
  111. package/dist/gemini-interactions.cjs.map +1 -1
  112. package/dist/gemini-interactions.d.cts.map +1 -1
  113. package/dist/gemini-interactions.d.ts.map +1 -1
  114. package/dist/gemini-interactions.js +289 -53
  115. package/dist/gemini-interactions.js.map +1 -1
  116. package/dist/gemini.cjs +234 -38
  117. package/dist/gemini.cjs.map +1 -1
  118. package/dist/gemini.d.cts.map +1 -1
  119. package/dist/gemini.d.ts.map +1 -1
  120. package/dist/gemini.js +235 -39
  121. package/dist/gemini.js.map +1 -1
  122. package/dist/helpers.cjs +1157 -12
  123. package/dist/helpers.cjs.map +1 -1
  124. package/dist/helpers.d.cts +85 -4
  125. package/dist/helpers.d.cts.map +1 -1
  126. package/dist/helpers.d.ts +85 -4
  127. package/dist/helpers.d.ts.map +1 -1
  128. package/dist/helpers.js +1113 -14
  129. package/dist/helpers.js.map +1 -1
  130. package/dist/images.cjs +3 -2
  131. package/dist/images.cjs.map +1 -1
  132. package/dist/images.js +3 -2
  133. package/dist/images.js.map +1 -1
  134. package/dist/index.cjs +39 -1
  135. package/dist/index.d.cts +11 -4
  136. package/dist/index.d.ts +11 -4
  137. package/dist/index.js +11 -4
  138. package/dist/jest.cjs +43 -14
  139. package/dist/jest.cjs.map +1 -1
  140. package/dist/jest.d.cts +47 -5
  141. package/dist/jest.d.cts.map +1 -1
  142. package/dist/jest.d.ts +47 -5
  143. package/dist/jest.d.ts.map +1 -1
  144. package/dist/jest.js +45 -16
  145. package/dist/jest.js.map +1 -1
  146. package/dist/journal.cjs +155 -13
  147. package/dist/journal.cjs.map +1 -1
  148. package/dist/journal.d.cts +54 -4
  149. package/dist/journal.d.cts.map +1 -1
  150. package/dist/journal.d.ts +54 -4
  151. package/dist/journal.d.ts.map +1 -1
  152. package/dist/journal.js +155 -13
  153. package/dist/journal.js.map +1 -1
  154. package/dist/live-sanitize.cjs +4 -32
  155. package/dist/live-sanitize.cjs.map +1 -1
  156. package/dist/live-sanitize.js +4 -32
  157. package/dist/live-sanitize.js.map +1 -1
  158. package/dist/llmock.cjs +204 -39
  159. package/dist/llmock.cjs.map +1 -1
  160. package/dist/llmock.d.cts +51 -1
  161. package/dist/llmock.d.cts.map +1 -1
  162. package/dist/llmock.d.ts +51 -1
  163. package/dist/llmock.d.ts.map +1 -1
  164. package/dist/llmock.js +206 -41
  165. package/dist/llmock.js.map +1 -1
  166. package/dist/mcp-fakes-mount.cjs +217 -0
  167. package/dist/mcp-fakes-mount.cjs.map +1 -0
  168. package/dist/mcp-fakes-mount.js +211 -0
  169. package/dist/mcp-fakes-mount.js.map +1 -0
  170. package/dist/mcp-fakes-report.cjs +111 -0
  171. package/dist/mcp-fakes-report.cjs.map +1 -0
  172. package/dist/mcp-fakes-report.d.cts +40 -0
  173. package/dist/mcp-fakes-report.d.cts.map +1 -0
  174. package/dist/mcp-fakes-report.d.ts +40 -0
  175. package/dist/mcp-fakes-report.d.ts.map +1 -0
  176. package/dist/mcp-fakes-report.js +107 -0
  177. package/dist/mcp-fakes-report.js.map +1 -0
  178. package/dist/mcp-fakes.cjs +1942 -0
  179. package/dist/mcp-fakes.cjs.map +1 -0
  180. package/dist/mcp-fakes.d.cts +504 -0
  181. package/dist/mcp-fakes.d.cts.map +1 -0
  182. package/dist/mcp-fakes.d.ts +504 -0
  183. package/dist/mcp-fakes.d.ts.map +1 -0
  184. package/dist/mcp-fakes.js +1937 -0
  185. package/dist/mcp-fakes.js.map +1 -0
  186. package/dist/mcp-handler.cjs +534 -27
  187. package/dist/mcp-handler.cjs.map +1 -1
  188. package/dist/mcp-handler.d.cts +49 -0
  189. package/dist/mcp-handler.d.cts.map +1 -0
  190. package/dist/mcp-handler.d.ts +49 -0
  191. package/dist/mcp-handler.d.ts.map +1 -0
  192. package/dist/mcp-handler.js +530 -28
  193. package/dist/mcp-handler.js.map +1 -1
  194. package/dist/mcp-mock.cjs +326 -47
  195. package/dist/mcp-mock.cjs.map +1 -1
  196. package/dist/mcp-mock.d.cts +97 -1
  197. package/dist/mcp-mock.d.cts.map +1 -1
  198. package/dist/mcp-mock.d.ts +97 -1
  199. package/dist/mcp-mock.d.ts.map +1 -1
  200. package/dist/mcp-mock.js +327 -48
  201. package/dist/mcp-mock.js.map +1 -1
  202. package/dist/mcp-recorder.cjs +1224 -0
  203. package/dist/mcp-recorder.cjs.map +1 -0
  204. package/dist/mcp-recorder.d.cts +108 -0
  205. package/dist/mcp-recorder.d.cts.map +1 -0
  206. package/dist/mcp-recorder.d.ts +108 -0
  207. package/dist/mcp-recorder.d.ts.map +1 -0
  208. package/dist/mcp-recorder.js +1215 -0
  209. package/dist/mcp-recorder.js.map +1 -0
  210. package/dist/mcp-stub.cjs +5 -1
  211. package/dist/mcp-stub.d.cts +3 -1
  212. package/dist/mcp-stub.d.ts +3 -1
  213. package/dist/mcp-stub.js +3 -1
  214. package/dist/mcp-types.d.cts +6 -0
  215. package/dist/mcp-types.d.ts +6 -0
  216. package/dist/message-text.cjs +192 -0
  217. package/dist/message-text.cjs.map +1 -0
  218. package/dist/message-text.d.cts +31 -0
  219. package/dist/message-text.d.cts.map +1 -0
  220. package/dist/message-text.d.ts +31 -0
  221. package/dist/message-text.d.ts.map +1 -0
  222. package/dist/message-text.js +184 -0
  223. package/dist/message-text.js.map +1 -0
  224. package/dist/messages.cjs +400 -56
  225. package/dist/messages.cjs.map +1 -1
  226. package/dist/messages.d.cts.map +1 -1
  227. package/dist/messages.d.ts.map +1 -1
  228. package/dist/messages.js +401 -58
  229. package/dist/messages.js.map +1 -1
  230. package/dist/metrics.cjs +46 -66
  231. package/dist/metrics.cjs.map +1 -1
  232. package/dist/metrics.d.cts +14 -6
  233. package/dist/metrics.d.cts.map +1 -1
  234. package/dist/metrics.d.ts +14 -6
  235. package/dist/metrics.d.ts.map +1 -1
  236. package/dist/metrics.js +32 -40
  237. package/dist/metrics.js.map +1 -1
  238. package/dist/misbehavior.cjs +1523 -0
  239. package/dist/misbehavior.cjs.map +1 -0
  240. package/dist/misbehavior.d.cts +43 -0
  241. package/dist/misbehavior.d.cts.map +1 -0
  242. package/dist/misbehavior.d.ts +43 -0
  243. package/dist/misbehavior.d.ts.map +1 -0
  244. package/dist/misbehavior.js +1511 -0
  245. package/dist/misbehavior.js.map +1 -0
  246. package/dist/ollama.cjs +315 -113
  247. package/dist/ollama.cjs.map +1 -1
  248. package/dist/ollama.d.cts.map +1 -1
  249. package/dist/ollama.d.ts.map +1 -1
  250. package/dist/ollama.js +316 -114
  251. package/dist/ollama.js.map +1 -1
  252. package/dist/openapi.cjs +3405 -0
  253. package/dist/openapi.cjs.map +1 -0
  254. package/dist/openapi.d.cts +30 -0
  255. package/dist/openapi.d.cts.map +1 -0
  256. package/dist/openapi.d.ts +30 -0
  257. package/dist/openapi.d.ts.map +1 -0
  258. package/dist/openapi.js +3404 -0
  259. package/dist/openapi.js.map +1 -0
  260. package/dist/openrouter-video.cjs +4 -4
  261. package/dist/openrouter-video.cjs.map +1 -1
  262. package/dist/openrouter-video.d.cts.map +1 -1
  263. package/dist/openrouter-video.d.ts.map +1 -1
  264. package/dist/openrouter-video.js +4 -4
  265. package/dist/openrouter-video.js.map +1 -1
  266. package/dist/record-sanitize.cjs +231 -0
  267. package/dist/record-sanitize.cjs.map +1 -0
  268. package/dist/record-sanitize.js +224 -0
  269. package/dist/record-sanitize.js.map +1 -0
  270. package/dist/recorder.cjs +115 -6
  271. package/dist/recorder.cjs.map +1 -1
  272. package/dist/recorder.d.cts +2 -1
  273. package/dist/recorder.d.cts.map +1 -1
  274. package/dist/recorder.d.ts +2 -1
  275. package/dist/recorder.d.ts.map +1 -1
  276. package/dist/recorder.js +116 -8
  277. package/dist/recorder.js.map +1 -1
  278. package/dist/responses.cjs +701 -166
  279. package/dist/responses.cjs.map +1 -1
  280. package/dist/responses.d.cts +5 -13
  281. package/dist/responses.d.cts.map +1 -1
  282. package/dist/responses.d.ts +5 -13
  283. package/dist/responses.d.ts.map +1 -1
  284. package/dist/responses.js +699 -169
  285. package/dist/responses.js.map +1 -1
  286. package/dist/route-registry.cjs +951 -0
  287. package/dist/route-registry.cjs.map +1 -0
  288. package/dist/route-registry.d.cts +33 -0
  289. package/dist/route-registry.d.cts.map +1 -0
  290. package/dist/route-registry.d.ts +33 -0
  291. package/dist/route-registry.d.ts.map +1 -0
  292. package/dist/route-registry.js +866 -0
  293. package/dist/route-registry.js.map +1 -0
  294. package/dist/router.cjs +24 -2
  295. package/dist/router.cjs.map +1 -1
  296. package/dist/router.d.cts.map +1 -1
  297. package/dist/router.d.ts.map +1 -1
  298. package/dist/router.js +25 -4
  299. package/dist/router.js.map +1 -1
  300. package/dist/server.cjs +1159 -264
  301. package/dist/server.cjs.map +1 -1
  302. package/dist/server.d.cts +4 -1
  303. package/dist/server.d.cts.map +1 -1
  304. package/dist/server.d.ts +4 -1
  305. package/dist/server.d.ts.map +1 -1
  306. package/dist/server.js +1067 -172
  307. package/dist/server.js.map +1 -1
  308. package/dist/speech.cjs +4 -2
  309. package/dist/speech.cjs.map +1 -1
  310. package/dist/speech.js +4 -2
  311. package/dist/speech.js.map +1 -1
  312. package/dist/stream-collapse.cjs +236 -34
  313. package/dist/stream-collapse.cjs.map +1 -1
  314. package/dist/stream-collapse.d.cts +39 -4
  315. package/dist/stream-collapse.d.cts.map +1 -1
  316. package/dist/stream-collapse.d.ts +39 -4
  317. package/dist/stream-collapse.d.ts.map +1 -1
  318. package/dist/stream-collapse.js +235 -35
  319. package/dist/stream-collapse.js.map +1 -1
  320. package/dist/suite.cjs +1 -1
  321. package/dist/suite.js +1 -1
  322. package/dist/transcription.cjs +2 -2
  323. package/dist/transcription.cjs.map +1 -1
  324. package/dist/transcription.d.cts.map +1 -1
  325. package/dist/transcription.d.ts.map +1 -1
  326. package/dist/transcription.js +2 -2
  327. package/dist/transcription.js.map +1 -1
  328. package/dist/types.cjs +18 -0
  329. package/dist/types.cjs.map +1 -0
  330. package/dist/types.d.cts +516 -5
  331. package/dist/types.d.cts.map +1 -1
  332. package/dist/types.d.ts +516 -5
  333. package/dist/types.d.ts.map +1 -1
  334. package/dist/types.js +17 -0
  335. package/dist/types.js.map +1 -0
  336. package/dist/validate-cli.cjs +123 -33
  337. package/dist/validate-cli.cjs.map +1 -1
  338. package/dist/validate-cli.js +125 -35
  339. package/dist/validate-cli.js.map +1 -1
  340. package/dist/vector-stores.cjs +1180 -0
  341. package/dist/vector-stores.cjs.map +1 -0
  342. package/dist/vector-stores.d.cts +106 -0
  343. package/dist/vector-stores.d.cts.map +1 -0
  344. package/dist/vector-stores.d.ts +106 -0
  345. package/dist/vector-stores.d.ts.map +1 -0
  346. package/dist/vector-stores.js +1164 -0
  347. package/dist/vector-stores.js.map +1 -0
  348. package/dist/vector-types.d.cts.map +1 -1
  349. package/dist/version.cjs +45 -0
  350. package/dist/version.cjs.map +1 -0
  351. package/dist/version.js +44 -0
  352. package/dist/version.js.map +1 -0
  353. package/dist/video.cjs +19 -0
  354. package/dist/video.cjs.map +1 -1
  355. package/dist/video.d.cts.map +1 -1
  356. package/dist/video.d.ts.map +1 -1
  357. package/dist/video.js +19 -0
  358. package/dist/video.js.map +1 -1
  359. package/dist/vitest.cjs +77 -16
  360. package/dist/vitest.cjs.map +1 -1
  361. package/dist/vitest.d.cts +38 -5
  362. package/dist/vitest.d.cts.map +1 -1
  363. package/dist/vitest.d.ts +38 -5
  364. package/dist/vitest.d.ts.map +1 -1
  365. package/dist/vitest.js +78 -17
  366. package/dist/vitest.js.map +1 -1
  367. package/dist/watcher.cjs +6 -2
  368. package/dist/watcher.cjs.map +1 -1
  369. package/dist/watcher.js +6 -2
  370. package/dist/watcher.js.map +1 -1
  371. package/dist/ws-gemini-live.cjs +210 -101
  372. package/dist/ws-gemini-live.cjs.map +1 -1
  373. package/dist/ws-gemini-live.d.cts +9 -3
  374. package/dist/ws-gemini-live.d.cts.map +1 -1
  375. package/dist/ws-gemini-live.d.ts +9 -3
  376. package/dist/ws-gemini-live.d.ts.map +1 -1
  377. package/dist/ws-gemini-live.js +211 -102
  378. package/dist/ws-gemini-live.js.map +1 -1
  379. package/dist/ws-realtime.cjs +175 -62
  380. package/dist/ws-realtime.cjs.map +1 -1
  381. package/dist/ws-realtime.d.cts +8 -3
  382. package/dist/ws-realtime.d.cts.map +1 -1
  383. package/dist/ws-realtime.d.ts +8 -3
  384. package/dist/ws-realtime.d.ts.map +1 -1
  385. package/dist/ws-realtime.js +176 -63
  386. package/dist/ws-realtime.js.map +1 -1
  387. package/dist/ws-responses.cjs +121 -16
  388. package/dist/ws-responses.cjs.map +1 -1
  389. package/dist/ws-responses.d.cts +8 -12
  390. package/dist/ws-responses.d.cts.map +1 -1
  391. package/dist/ws-responses.d.ts +8 -12
  392. package/dist/ws-responses.d.ts.map +1 -1
  393. package/dist/ws-responses.js +123 -18
  394. package/dist/ws-responses.js.map +1 -1
  395. package/package.json +13 -2
  396. package/skills/write-fixtures/SKILL.md +179 -21
package/dist/helpers.js CHANGED
@@ -1,9 +1,258 @@
1
- import { DEFAULT_TEST_ID } from "./constants.js";
1
+ import { DEFAULT_TEST_ID, MCP_FAKES_ECHO_LIMIT } from "./constants.js";
2
+ import { cutText } from "./echo-text.js";
3
+ import { build, fixed, msg, quote } from "./message-text.js";
2
4
  import { isReasoningModel } from "./model-utils.js";
3
5
  import { isRecognizedApiKeyHeader } from "./api-key-auth.js";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
4
7
  import { createHash, randomBytes } from "node:crypto";
5
8
 
6
9
  //#region src/helpers.ts
10
+ /** Preserve authored text for string wires without silently repairing invalid JSON. */
11
+ function toolArgsForWire(tc) {
12
+ const raw = tc.arguments || "{}";
13
+ try {
14
+ const value = JSON.parse(raw);
15
+ return {
16
+ kind: "parsed",
17
+ value,
18
+ text: JSON.stringify(value),
19
+ raw
20
+ };
21
+ } catch {
22
+ return {
23
+ kind: "verbatim",
24
+ raw
25
+ };
26
+ }
27
+ }
28
+ /** Object wires reject the verbatim branch; string wires never need this error. */
29
+ var InvalidToolArgumentsError = class extends Error {
30
+ toolName;
31
+ parseDiagnostic;
32
+ constructor(tc) {
33
+ let parseDiagnostic = "";
34
+ try {
35
+ JSON.parse(tc.arguments || "{}");
36
+ } catch (error) {
37
+ parseDiagnostic = error instanceof Error ? error.message : String(error);
38
+ }
39
+ super(`aimock: fixture tool call "${tc.name}" has invalid JSON arguments; this wire carries arguments as an object. Use a wire that carries tool arguments as a string to test malformed JSON. (${parseDiagnostic})`);
40
+ this.name = "InvalidToolArgumentsError";
41
+ this.toolName = tc.name;
42
+ this.parseDiagnostic = parseDiagnostic;
43
+ }
44
+ };
45
+ const toolArgumentsScope = new AsyncLocalStorage();
46
+ /** Run `fn` with the `strictToolArguments` setting and logger of one request. */
47
+ function runWithToolArgumentsScope(scope, fn) {
48
+ return toolArgumentsScope.run(scope, fn);
49
+ }
50
+ /** Whether `strictToolArguments` is on for the request being served (default off). */
51
+ function strictToolArgumentsEnabled() {
52
+ return toolArgumentsScope.getStore()?.strict === true;
53
+ }
54
+ /**
55
+ * Serve the rest of this request's tool arguments as authored (the
56
+ * `strictToolArguments` behavior). An applied misbehavior fault calls this so
57
+ * that the malformed arguments it injects are not replaced with `{}`; the
58
+ * planner only applies a fault to a fixture whose own arguments are valid
59
+ * wherever the default would replace them.
60
+ */
61
+ function keepAuthoredToolArguments() {
62
+ const scope = toolArgumentsScope.getStore();
63
+ if (scope) scope.strict = true;
64
+ }
65
+ /**
66
+ * The fixture tool-call arguments a wire serves on its normal (no misbehavior)
67
+ * path. Valid JSON gives the parsed value, its re-serialized text, and the
68
+ * authored text. Invalid JSON logs one warning and, by default, is served as
69
+ * `{}` / `"{}"`, as in 1.44.0. With `strictToolArguments`, an object wire
70
+ * (`"object"`) throws {@link InvalidToolArgumentsError} and a string wire
71
+ * (`"string"`) serves the authored text unchanged.
72
+ */
73
+ function servedToolArgs(tc, wire, logger) {
74
+ const args = toolArgsForWire(tc);
75
+ if (args.kind === "parsed") return args;
76
+ const scope = toolArgumentsScope.getStore();
77
+ (logger ?? scope?.logger)?.warn(`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`);
78
+ if (scope?.strict !== true) return {
79
+ value: {},
80
+ text: "{}",
81
+ raw: "{}"
82
+ };
83
+ if (wire === "object") throw new InvalidToolArgumentsError(tc);
84
+ return {
85
+ value: void 0,
86
+ text: args.raw,
87
+ raw: args.raw
88
+ };
89
+ }
90
+ /**
91
+ * A custom (freeform) tool call reached a wire that has no faithful projection
92
+ * for it. Only the OpenAI Responses API (HTTP and WebSocket) emits custom tool
93
+ * calls, from a fixture's `customToolCalls` or a `customToolCall` block in its
94
+ * `responsesBlocks`. The handlers of the other wires raise this through
95
+ * {@link rejectResponsesOnlyToolCalls} (usually via
96
+ * {@link requireEmittedFunctionToolCalls}) before they write any content.
97
+ * Ollama `/api/generate` is the exception: it rejects every tool-call fixture
98
+ * with a 400 before this check.
99
+ */
100
+ var UnsupportedToolCallError = class extends Error {
101
+ toolName;
102
+ wire;
103
+ constructor(toolName, wire) {
104
+ super(`aimock: fixture tool call "${toolName}" is a custom tool call, which only the OpenAI Responses API supports; this request arrived on ${wire}`);
105
+ this.name = "UnsupportedToolCallError";
106
+ this.toolName = toolName;
107
+ this.wire = wire;
108
+ }
109
+ };
110
+ /**
111
+ * A fixture tool call is malformed: a `toolCalls` entry that is not an object,
112
+ * a malformed `customToolCalls` entry, or a malformed tool block in
113
+ * `responsesBlocks`. Programmatic and factory fixtures skip load validation,
114
+ * so this request-time guard is their validation for the rules
115
+ * {@link assertResponsesToolCalls} and {@link resolveResponsesBlocks} check.
116
+ * An HTTP request then fails with a 500 that carries this message and `code`;
117
+ * a WebSocket turn gets the transport's error message with the code. A
118
+ * malformed legacy `blocks` entry keeps the plain Error of
119
+ * {@link resolveFixtureBlocks}.
120
+ */
121
+ var InvalidFixtureToolCallError = class extends Error {
122
+ code = "aimock_invalid_fixture_tool_call";
123
+ constructor(index, problem, carrier = "toolCalls") {
124
+ super(carrier === "blocks" ? `Invalid fixture block at index ${index}: ${problem}` : `Invalid fixture tool call: ${problem} (${carrier}[${index}])`);
125
+ this.name = "InvalidFixtureToolCallError";
126
+ }
127
+ };
128
+ /**
129
+ * Request-time guard for one custom tool call (a `customToolCalls` entry).
130
+ * Programmatic and factory fixtures skip load validation, so this is their
131
+ * validation: an object with a non-empty string `name`, a string `input`, no
132
+ * `arguments`, a string `id` when present and a non-empty string `namespace`
133
+ * when present.
134
+ */
135
+ function assertCustomToolCall(call, index) {
136
+ const fail = (problem) => {
137
+ throw new InvalidFixtureToolCallError(index, problem, "customToolCalls");
138
+ };
139
+ if (!isPlainObject(call)) fail("expected an object");
140
+ const tc = call;
141
+ if (tc.namespace !== void 0 && (typeof tc.namespace !== "string" || tc.namespace === "")) fail("\"namespace\" must be a non-empty string when present");
142
+ if (typeof tc.name !== "string" || tc.name === "") fail("custom tool call requires a non-empty string \"name\" field");
143
+ if (typeof tc.input !== "string") fail("\"input\" must be a string for a custom tool call");
144
+ if (tc.arguments !== void 0) fail("custom tool call takes \"input\", not \"arguments\"");
145
+ if (tc.id !== void 0 && typeof tc.id !== "string") fail("custom tool call \"id\" must be a string when present");
146
+ }
147
+ /**
148
+ * Validate a response's `customToolCalls` (OpenAI Responses only) before it is
149
+ * served. Throws {@link InvalidFixtureToolCallError} on the first malformed
150
+ * entry. The key is new, so no fixture of an earlier release reaches this.
151
+ */
152
+ function assertCustomToolCalls(response) {
153
+ const list = response.customToolCalls;
154
+ if (list === void 0) return;
155
+ if (!Array.isArray(list)) throw new InvalidFixtureToolCallError(0, "customToolCalls must be an array", "customToolCalls");
156
+ list.forEach((call, i) => assertCustomToolCall(call, i));
157
+ }
158
+ /**
159
+ * Validate the custom calls among the tool calls the OpenAI Responses API is
160
+ * about to serve (see {@link servedToolCalls}). Function calls are not
161
+ * checked here: they keep the handling of earlier releases (a non-string
162
+ * `arguments` fails with the uncoded error of the Responses builders).
163
+ */
164
+ function assertResponsesToolCalls(calls) {
165
+ let customIndex = 0;
166
+ for (const tc of calls) if (isPlainObject(tc) && tc.type === "custom") assertCustomToolCall(tc, customIndex++);
167
+ }
168
+ /**
169
+ * A fixture's `toolCalls` for a wire that cannot carry custom tool calls.
170
+ * Every entry is a function call and passes through unchanged, exactly as in
171
+ * earlier releases (the builders read its `name`, `arguments` and `id`; its
172
+ * Responses-only `namespace` is not emitted). Custom calls live in
173
+ * `customToolCalls`, which {@link rejectResponsesOnlyToolCalls} rejects.
174
+ */
175
+ function requireFunctionToolCalls(calls) {
176
+ return calls;
177
+ }
178
+ /**
179
+ * Reject the Responses-only custom tool calls on a wire that cannot carry
180
+ * them: a non-empty `customToolCalls`, or a `customToolCall` block in
181
+ * `responsesBlocks`. Throws {@link UnsupportedToolCallError} naming `wire`.
182
+ * Both keys are new, so no fixture of an earlier release reaches this error.
183
+ */
184
+ function rejectResponsesOnlyToolCalls(response, wire) {
185
+ const r = response;
186
+ if (Array.isArray(r.customToolCalls) && r.customToolCalls.length > 0) {
187
+ const first = r.customToolCalls[0];
188
+ throw new UnsupportedToolCallError(isPlainObject(first) && typeof first.name === "string" ? first.name : "", wire);
189
+ }
190
+ if (Array.isArray(r.responsesBlocks)) {
191
+ for (const block of r.responsesBlocks) if (isPlainObject(block) && block.type === "customToolCall") throw new UnsupportedToolCallError(typeof block.name === "string" ? block.name : "", wire);
192
+ }
193
+ }
194
+ /**
195
+ * {@link rejectResponsesOnlyToolCalls}, then {@link requireFunctionToolCalls}
196
+ * on the response's `toolCalls` (ignoring any `blocks`).
197
+ */
198
+ function requireServedFunctionToolCalls(response, wire) {
199
+ rejectResponsesOnlyToolCalls(response, wire);
200
+ return requireFunctionToolCalls(response.toolCalls ?? []);
201
+ }
202
+ /**
203
+ * The function calls a non-Responses wire emits for this response, after
204
+ * {@link rejectResponsesOnlyToolCalls}. Non-empty ordered `blocks` are
205
+ * authoritative: the builders stream them (and validate them through
206
+ * {@link resolveFixtureBlocks}) and never emit the legacy `toolCalls`, so the
207
+ * result is empty. Without blocks, `toolCalls` is checked by
208
+ * {@link requireFunctionToolCalls}.
209
+ */
210
+ function requireEmittedFunctionToolCalls(response, wire) {
211
+ rejectResponsesOnlyToolCalls(response, wire);
212
+ if (Array.isArray(response.blocks) && response.blocks.length > 0) return [];
213
+ return requireFunctionToolCalls(response.toolCalls ?? []);
214
+ }
215
+ /** True for the fixture tool-call errors a handler surfaces as a coded 500. */
216
+ function isFixtureToolCallError(error) {
217
+ return error instanceof InvalidToolArgumentsError || error instanceof UnsupportedToolCallError || error instanceof InvalidFixtureToolCallError;
218
+ }
219
+ /** The aimock error code carried in every provider envelope for a fixture tool-call error. */
220
+ function fixtureToolCallErrorCode(error) {
221
+ if (error instanceof UnsupportedToolCallError) return "aimock_unsupported_tool_call";
222
+ if (error instanceof InvalidFixtureToolCallError) return error.code;
223
+ return "aimock_invalid_tool_arguments";
224
+ }
225
+ /**
226
+ * Google RPC error `details` carrying an aimock fixture tool-call code, for the
227
+ * Gemini, Vertex AI and Gemini Live envelopes (`google.rpc.ErrorInfo`: an
228
+ * UPPER_SNAKE `reason`, a `domain`, and string `metadata`).
229
+ */
230
+ function googleFixtureToolCallErrorDetails(code) {
231
+ return [{
232
+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",
233
+ reason: code.toUpperCase(),
234
+ domain: "aimock",
235
+ metadata: { code }
236
+ }];
237
+ }
238
+ /**
239
+ * Run a WebSocket preflight `check` that may raise a fixture tool-call error
240
+ * ({@link InvalidToolArgumentsError}, {@link UnsupportedToolCallError} or
241
+ * {@link InvalidFixtureToolCallError}).
242
+ * Such an error marks the already-journaled entry as a 500 carrying the
243
+ * message, then propagates to the transport's error handler.
244
+ */
245
+ function journalFixtureToolCallError(journalEntry, check) {
246
+ try {
247
+ return check();
248
+ } catch (error) {
249
+ if (isFixtureToolCallError(error)) {
250
+ journalEntry.response.status = 500;
251
+ journalEntry.response.error = error.message;
252
+ }
253
+ throw error;
254
+ }
255
+ }
7
256
  /**
8
257
  * Resolve effective strict mode from per-request header and server default.
9
258
  * Header values override the server default — same precedence pattern as chaos
@@ -25,6 +274,25 @@ function resolveStrictMode(serverDefault, rawHeaders) {
25
274
  }
26
275
  return serverDefault ?? false;
27
276
  }
277
+ const STRICT_INTEGER_RE = /^\d+$/;
278
+ /**
279
+ * Strict decimal-integer grammar shared by the query/list parsers that grew
280
+ * their own local copy on separate branches (files `limit`, fine-tuning
281
+ * `limit`, chaos integer fields): an unsigned digit run and nothing else — no
282
+ * sign, no exponent, no radix prefix, no surrounding whitespace (callers that
283
+ * accept padded input trim before calling).
284
+ *
285
+ * Deliberately narrower than `Number()`, which reads `0x10` as 16, `1e3` as
286
+ * 1000 and strips whitespace and a leading `+`. Returns the value, or `null`
287
+ * when the text is not a safe integer literal. Range checks and error
288
+ * messages stay with the callers — this is the grammar gate only, so sharing
289
+ * it cannot change any surface's accepted range or its 400 text.
290
+ */
291
+ function parseStrictIntegerText(text) {
292
+ if (!STRICT_INTEGER_RE.test(text)) return null;
293
+ const n = Number(text);
294
+ return Number.isSafeInteger(n) ? n : null;
295
+ }
28
296
  /**
29
297
  * Would a fixture miss on this request have been forwarded upstream? This is
30
298
  * the ONE rule behind the no-fixture chaos journal `source` label: "proxy"
@@ -161,14 +429,192 @@ function isLiveResponse(value) {
161
429
  function isResponseFactory(r) {
162
430
  return typeof r === "function";
163
431
  }
432
+ const serverFixtureLists = /* @__PURE__ */ new WeakMap();
433
+ /**
434
+ * Array methods that read elements and write them back. On a server list
435
+ * they run on the caller's array, so the extended view of an element is
436
+ * never written into it.
437
+ */
438
+ const ELEMENT_MOVING_METHODS = new Set([
439
+ "copyWithin",
440
+ "fill",
441
+ "pop",
442
+ "push",
443
+ "reverse",
444
+ "shift",
445
+ "sort",
446
+ "splice",
447
+ "unshift"
448
+ ]);
449
+ /**
450
+ * The fixture list one server reads and writes: a live view of the caller's
451
+ * `fixtures` array, with its own identity. The matcher reads the server's
452
+ * `responsesTools` mode from the list it is given, so every handler on every
453
+ * wire sees that server's mode without extra parameters, and two servers that
454
+ * share one array each keep their own mode. With `"extended"`, reading an
455
+ * element gives `extendedView(element)` (the fixture with its held keys
456
+ * applied); the caller's array and its fixtures are never changed for it.
457
+ * Writes (push, splice, `length = 0`, ...) reach the caller's array.
458
+ */
459
+ function createServerFixtureList(fixtures, mode, extendedView) {
460
+ const boundMethods = /* @__PURE__ */ new Map();
461
+ const list = new Proxy(fixtures, { get(target, key) {
462
+ const value = Reflect.get(target, key);
463
+ if (typeof value === "function") {
464
+ if (!ELEMENT_MOVING_METHODS.has(key)) return value;
465
+ let bound = boundMethods.get(key);
466
+ if (bound === void 0) {
467
+ bound = value.bind(target);
468
+ boundMethods.set(key, bound);
469
+ }
470
+ return bound;
471
+ }
472
+ if (typeof key !== "string" || mode() !== "extended") return value;
473
+ const first = key.charCodeAt(0);
474
+ if (first < 48 || first > 57 || value === null || typeof value !== "object") return value;
475
+ return extendedView(value);
476
+ } });
477
+ serverFixtureLists.set(list, {
478
+ target: fixtures,
479
+ mode
480
+ });
481
+ return list;
482
+ }
483
+ /** Fixture arrays that only their own server reads: see {@link markServerOwnedFixtures}. */
484
+ const serverOwnedFixtureArrays = /* @__PURE__ */ new WeakSet();
485
+ /**
486
+ * @internal Mark `fixtures` as an array no other server reads (LLMock's own
487
+ * array). A server may change the fixtures it makes itself (the control API)
488
+ * in place only in such an array; in a caller's array, which another server
489
+ * may share, they stay as made and an extended server reads them through its
490
+ * view.
491
+ */
492
+ function markServerOwnedFixtures(fixtures) {
493
+ serverOwnedFixtureArrays.add(fixtures);
494
+ }
495
+ /** Whether the array behind `fixtures` (a server list or an array) is server-owned. */
496
+ function isServerOwnedFixtures(fixtures) {
497
+ return serverOwnedFixtureArrays.has(fixtureListTarget(fixtures));
498
+ }
499
+ /** Whether `fixtures` is the list of a server running with `responsesTools: "extended"`. */
500
+ function isExtendedResponsesToolsList(fixtures) {
501
+ return serverFixtureLists.get(fixtures)?.mode() === "extended";
502
+ }
503
+ /** The caller's array behind a server list; any other array is itself. */
504
+ function fixtureListTarget(fixtures) {
505
+ return serverFixtureLists.get(fixtures)?.target ?? fixtures;
506
+ }
507
+ /**
508
+ * Requests matched against an extended fixture list. {@link resolveResponse}
509
+ * reads it, so the response a handler serves follows the same mode as the
510
+ * match that chose its fixture.
511
+ */
512
+ const extendedResponsesToolsRequests = /* @__PURE__ */ new WeakSet();
513
+ /** Mark `request` as matched with `responsesTools: "extended"`. */
514
+ function markExtendedResponsesToolsRequest(request) {
515
+ extendedResponsesToolsRequests.add(request);
516
+ }
517
+ /**
518
+ * Drop `customToolCalls` and `responsesBlocks`, for responses served without
519
+ * `responsesTools: "extended"`. Earlier releases ignored both keys, so a
520
+ * fixture that carries them serves exactly as before. Returns the same object
521
+ * when neither key is set.
522
+ */
523
+ function withoutResponsesToolKeys(response) {
524
+ if (!isPlainObject(response)) return response;
525
+ if (!("customToolCalls" in response) && !("responsesBlocks" in response)) return response;
526
+ const copy = { ...response };
527
+ delete copy.customToolCalls;
528
+ delete copy.responsesBlocks;
529
+ return copy;
530
+ }
164
531
  async function resolveResponse(fixture, request) {
165
- if (typeof fixture.response === "function") try {
166
- return normalizeFactoryResponse(await fixture.response(request));
167
- } catch (err) {
168
- const msg = err instanceof Error ? err.message : String(err);
169
- throw new Error(`Response factory threw: ${msg}`, { cause: err });
532
+ const served = (response) => sanitizeFixtureResponse(extendedResponsesToolsRequests.has(request) ? response : withoutResponsesToolKeys(response));
533
+ if (typeof fixture.response === "function") {
534
+ let normalized;
535
+ try {
536
+ normalized = normalizeFactoryResponse(await fixture.response(request));
537
+ } catch (err) {
538
+ const msg = err instanceof Error ? err.message : String(err);
539
+ throw new Error(`Response factory threw: ${msg}`, { cause: err });
540
+ }
541
+ return served(normalized);
170
542
  }
171
- return fixture.response;
543
+ return served(fixture.response);
544
+ }
545
+ function isPlainObject(value) {
546
+ return value !== null && typeof value === "object" && !Array.isArray(value);
547
+ }
548
+ /** A non-empty string, the only valid value of a tool call's `namespace`. */
549
+ function isValidNamespace(value) {
550
+ return typeof value === "string" && value !== "";
551
+ }
552
+ /**
553
+ * Drop the keys a served `toolCalls` entry or `toolCall` block ignores, so
554
+ * no handler reads them: on a `toolCalls` entry, `type` and `input` (a
555
+ * `toolCalls` entry is always a function call; custom calls live in
556
+ * `customToolCalls`) and an invalid `namespace` (not a non-empty string); on a
557
+ * `toolCall` block, `input` and an invalid `namespace`. Earlier releases
558
+ * ignored all of these, so fixtures that carry them serve exactly as before.
559
+ * Returns the same object when nothing needs dropping. `customToolCalls` and
560
+ * `responsesBlocks` are new keys and are validated, not sanitized.
561
+ */
562
+ function sanitizeFixtureResponse(response) {
563
+ if (!isPlainObject(response)) return response;
564
+ const r = response;
565
+ const dropKeys = (entry, keys) => {
566
+ if (!isPlainObject(entry)) return entry;
567
+ const drop = keys.filter((key) => key in entry && (key !== "namespace" || !isValidNamespace(entry.namespace)));
568
+ if (drop.length === 0) return entry;
569
+ const copy = { ...entry };
570
+ for (const key of drop) delete copy[key];
571
+ return copy;
572
+ };
573
+ const sanitizeList = (list, pick) => {
574
+ if (!Array.isArray(list)) return list;
575
+ const next = list.map(pick);
576
+ return next.some((entry, k) => entry !== list[k]) ? next : list;
577
+ };
578
+ const toolCalls = sanitizeList(r.toolCalls, (entry) => dropKeys(entry, [
579
+ "type",
580
+ "input",
581
+ "namespace"
582
+ ]));
583
+ let blocks = sanitizeList(r.blocks, (entry) => isPlainObject(entry) && entry.type === "toolCall" ? dropKeys(entry, ["input", "namespace"]) : entry);
584
+ if (!(Array.isArray(r.blocks) && r.blocks.length > 0) && Array.isArray(r.responsesBlocks) && r.responsesBlocks.length > 0 && !r.responsesBlocks.some((entry) => isPlainObject(entry) && entry.type === "customToolCall")) blocks = r.responsesBlocks;
585
+ if (toolCalls === r.toolCalls && blocks === r.blocks) return response;
586
+ const copy = { ...r };
587
+ if (toolCalls !== r.toolCalls) copy.toolCalls = toolCalls;
588
+ if (blocks !== r.blocks) copy.blocks = blocks;
589
+ return copy;
590
+ }
591
+ /**
592
+ * Drop `namespace` from every `toolCalls` entry and `toolCall` block, for
593
+ * OpenAI Responses requests served without `responsesTools: "extended"`:
594
+ * earlier releases never emitted it. (Without that mode, resolveResponse has
595
+ * already dropped `customToolCalls` and `responsesBlocks`.) Returns the same
596
+ * object when no namespace is set.
597
+ */
598
+ function withoutLegacyNamespaces(response) {
599
+ if (!isPlainObject(response)) return response;
600
+ const r = response;
601
+ const strip = (list, isTarget) => {
602
+ if (!Array.isArray(list)) return list;
603
+ if (!list.some((entry) => isPlainObject(entry) && isTarget(entry) && "namespace" in entry)) return list;
604
+ return list.map((entry) => {
605
+ if (!isPlainObject(entry) || !isTarget(entry) || !("namespace" in entry)) return entry;
606
+ const copy = { ...entry };
607
+ delete copy.namespace;
608
+ return copy;
609
+ });
610
+ };
611
+ const toolCalls = strip(r.toolCalls, () => true);
612
+ const blocks = strip(r.blocks, (entry) => entry.type === "toolCall");
613
+ if (toolCalls === r.toolCalls && blocks === r.blocks) return response;
614
+ const copy = { ...r };
615
+ if (toolCalls !== r.toolCalls) copy.toolCalls = toolCalls;
616
+ if (blocks !== r.blocks) copy.blocks = blocks;
617
+ return copy;
172
618
  }
173
619
  function normalizeFactoryResponse(raw) {
174
620
  const r = { ...raw };
@@ -187,6 +633,10 @@ function normalizeFactoryResponse(raw) {
187
633
  };
188
634
  return { ...block };
189
635
  });
636
+ if (Array.isArray(r.responsesBlocks)) r.responsesBlocks = r.responsesBlocks.map((block) => isPlainObject(block) && block.type === "toolCall" && typeof block.arguments === "object" && block.arguments !== null ? {
637
+ ...block,
638
+ arguments: JSON.stringify(block.arguments)
639
+ } : block);
190
640
  return r;
191
641
  }
192
642
  function generateId(prefix = "chatcmpl") {
@@ -258,6 +708,12 @@ function isTextResponse(r) {
258
708
  function isToolCallResponse(r) {
259
709
  return "toolCalls" in r && Array.isArray(r.toolCalls) && !("content" in r && typeof r.content === "string");
260
710
  }
711
+ /**
712
+ * Whether `r` is a combined content + tool calls response: a string `content`
713
+ * with a `toolCalls` array, or a non-empty `blocks` array. Public, with the
714
+ * 1.44.0 result for every input; `responsesBlocks` does not count. aimock's
715
+ * own handlers use {@link isCombinedFixtureResponse}, which also counts it.
716
+ */
261
717
  function isContentWithToolCallsResponse(r) {
262
718
  const o = r;
263
719
  const hasContentAndToolCalls = "content" in r && typeof o.content === "string" && "toolCalls" in r && Array.isArray(o.toolCalls);
@@ -265,6 +721,19 @@ function isContentWithToolCallsResponse(r) {
265
721
  return hasContentAndToolCalls || hasNonEmptyBlocks;
266
722
  }
267
723
  /**
724
+ * @internal The combined-response guard aimock's handlers, validation and
725
+ * misbehavior use: {@link isContentWithToolCallsResponse} plus a non-empty
726
+ * `responsesBlocks`. In legacy mode those keys are dropped before serving, so
727
+ * only `responsesTools: "extended"` sees the extra clause.
728
+ */
729
+ function isCombinedFixtureResponse(r) {
730
+ const o = r;
731
+ const hasContentAndToolCalls = "content" in r && typeof o.content === "string" && "toolCalls" in r && Array.isArray(o.toolCalls);
732
+ const hasNonEmptyBlocks = Array.isArray(o.blocks) && o.blocks.length > 0;
733
+ const hasNonEmptyResponsesBlocks = Array.isArray(o.responsesBlocks) && o.responsesBlocks.length > 0;
734
+ return hasContentAndToolCalls || hasNonEmptyBlocks || hasNonEmptyResponsesBlocks;
735
+ }
736
+ /**
268
737
  * Validate and pass through the ordered `blocks` field of a combined
269
738
  * content+toolCalls fixture. Used ONLY on the new block-iteration path (when a
270
739
  * fixture explicitly sets `blocks`); it is NOT a legacy-order reconstructor —
@@ -291,7 +760,9 @@ function isContentWithToolCallsResponse(r) {
291
760
  * optional string `id`. The return type guarantees `arguments: string` — every
292
761
  * caller relies on that. Throws on a malformed array or entry — same fail-fast
293
762
  * idiom as the other fixture validators in this module (see e.g. the factory
294
- * guard at {@link resolveResponse}).
763
+ * guard at {@link resolveResponse}). A `customToolCall` block is not a
764
+ * `blocks` entry (it belongs in `responsesBlocks`, see
765
+ * {@link resolveResponsesBlocks}) and fails as an unknown type.
295
766
  */
296
767
  function resolveFixtureBlocks(blocks) {
297
768
  if (!Array.isArray(blocks)) throw new Error(`Invalid fixture blocks: expected an array, got ${typeof blocks}`);
@@ -321,6 +792,130 @@ function resolveFixtureBlocks(blocks) {
321
792
  } else throw new Error(`Invalid fixture block at index ${i}: unknown type ${JSON.stringify(b.type)} (expected "text" or "toolCall")`);
322
793
  });
323
794
  }
795
+ /**
796
+ * Validate and normalize a fixture's `responsesBlocks` (OpenAI Responses
797
+ * only). Same rules and normalized copy as {@link resolveFixtureBlocks}, plus:
798
+ * a `customToolCall` block with a non-empty string `name`, a string `input`
799
+ * (never parsed or stringified), no `arguments` and an optional string `id`;
800
+ * on either tool block, `namespace` must be a non-empty string when present,
801
+ * and a `toolCall` block carries no `input`. The key is new, so a malformed
802
+ * tool block throws the coded {@link InvalidFixtureToolCallError}; a malformed
803
+ * text block or an unknown type throws a plain Error.
804
+ */
805
+ function resolveResponsesBlocks(blocks) {
806
+ if (!Array.isArray(blocks)) throw new Error(`Invalid fixture responsesBlocks: expected an array, got ${typeof blocks}`);
807
+ return blocks.map((block, i) => {
808
+ if (!isPlainObject(block)) throw new Error(`Invalid fixture block at index ${i}: expected an object`);
809
+ const b = block;
810
+ const failToolCall = (problem) => {
811
+ throw new InvalidFixtureToolCallError(i, problem, "blocks");
812
+ };
813
+ if ((b.type === "toolCall" || b.type === "customToolCall") && b.namespace !== void 0 && (typeof b.namespace !== "string" || b.namespace === "")) failToolCall("\"namespace\" must be a non-empty string when present");
814
+ const namespace = typeof b.namespace === "string" ? { namespace: b.namespace } : {};
815
+ const id = typeof b.id === "string" ? { id: b.id } : {};
816
+ if (b.type === "text") {
817
+ if (typeof b.text !== "string") throw new Error(`Invalid fixture block at index ${i}: "text" block requires a string "text" field`);
818
+ return {
819
+ type: "text",
820
+ text: b.text
821
+ };
822
+ }
823
+ if (b.type === "toolCall") {
824
+ if (b.input !== void 0) failToolCall("\"input\" is only valid on a \"customToolCall\" block");
825
+ if (typeof b.name !== "string") failToolCall("\"toolCall\" block requires a string \"name\" field");
826
+ if (b.id !== void 0 && typeof b.id !== "string") failToolCall("\"toolCall\" block \"id\" must be a string when present");
827
+ const args = typeof b.arguments === "object" && b.arguments !== null ? JSON.stringify(b.arguments) : b.arguments;
828
+ if (typeof args !== "string") failToolCall("\"toolCall\" block requires a string or object \"arguments\" field");
829
+ return {
830
+ type: "toolCall",
831
+ name: b.name,
832
+ arguments: args,
833
+ ...id,
834
+ ...namespace
835
+ };
836
+ }
837
+ if (b.type === "customToolCall") {
838
+ if (typeof b.name !== "string" || b.name === "") failToolCall("\"customToolCall\" block requires a non-empty string \"name\" field");
839
+ if (typeof b.input !== "string") failToolCall("\"customToolCall\" block requires a string \"input\" field");
840
+ if (b.arguments !== void 0) failToolCall("\"customToolCall\" block takes \"input\", not \"arguments\"");
841
+ if (b.id !== void 0 && typeof b.id !== "string") failToolCall("\"customToolCall\" block \"id\" must be a string when present");
842
+ return {
843
+ type: "customToolCall",
844
+ name: b.name,
845
+ input: b.input,
846
+ ...id,
847
+ ...namespace
848
+ };
849
+ }
850
+ throw new Error(`Invalid fixture block at index ${i}: unknown type ${JSON.stringify(b.type)} (expected "text", "toolCall" or "customToolCall")`);
851
+ });
852
+ }
853
+ /** Allocate the exact OpenAI call identities once for both wire output and observations. */
854
+ function prepareOpenAIChatMisbehavior(plan) {
855
+ const response = plan.response;
856
+ const combined = isCombinedFixtureResponse(response);
857
+ const outcome = combined ? resolveServedBlockOutcome(response) : void 0;
858
+ const calls = outcome?.toolCalls ?? (combined || isToolCallResponse(response) ? servedToolCalls(response) : []);
859
+ const duplicate = plan.duplicateId;
860
+ const toolCalls = calls.map((call, index) => ({
861
+ ...call,
862
+ ...index === duplicate?.destinationIndex ? {} : { id: call.id || generateToolCallId() }
863
+ }));
864
+ if (duplicate) toolCalls[duplicate.destinationIndex].id = toolCalls[duplicate.sourceIndex].id;
865
+ let preparedResponse = { ...response };
866
+ if ("usage" in preparedResponse) delete preparedResponse.usage;
867
+ if (plan.stop === "length") preparedResponse = {
868
+ ...preparedResponse,
869
+ finishReason: "length"
870
+ };
871
+ if (outcome) preparedResponse = withServedToolCalls({
872
+ ...preparedResponse,
873
+ content: outcome.content
874
+ }, toolCalls, rebuildOrderedBlocks(outcome.ordered, toolCalls));
875
+ else if (combined || isToolCallResponse(response)) preparedResponse = withServedToolCalls(preparedResponse, toolCalls);
876
+ return {
877
+ ...plan,
878
+ response: preparedResponse,
879
+ summary: {
880
+ ...plan.summary,
881
+ servedToolCalls: toolCalls.map(servedMisbehaviorToolCall)
882
+ }
883
+ };
884
+ }
885
+ /**
886
+ * The journaled form of a served misbehavior tool call: `{ name, arguments,
887
+ * id }`. A Responses custom tool call adds `type: "custom"` and carries its
888
+ * free-text `input` in `arguments`; `namespace` is recorded only when set.
889
+ */
890
+ function servedMisbehaviorToolCall(call) {
891
+ const namespace = call.namespace !== void 0 ? { namespace: call.namespace } : {};
892
+ return call.type === "custom" ? {
893
+ type: "custom",
894
+ name: call.name,
895
+ arguments: call.input,
896
+ id: call.id,
897
+ ...namespace
898
+ } : {
899
+ name: call.name,
900
+ arguments: call.arguments,
901
+ id: call.id,
902
+ ...namespace
903
+ };
904
+ }
905
+ /** The text a tool call contributes to an estimated completion: name plus arguments or input. */
906
+ function toolCallUsageText(call) {
907
+ return call.name + (call.type === "custom" ? call.input : call.arguments);
908
+ }
909
+ /** Estimate once from the full applied output, before any delivery interruption. */
910
+ function resolveOpenAIChatMisbehaviorUsage(plan, request, exposeReasoning = true) {
911
+ const response = plan.response;
912
+ const combined = isCombinedFixtureResponse(response);
913
+ const outcome = combined ? resolveServedBlockOutcome(response) : void 0;
914
+ const calls = outcome?.toolCalls ?? (combined || isToolCallResponse(response) ? servedToolCalls(response) : []);
915
+ const content = outcome?.content ?? ("content" in response && typeof response.content === "string" ? response.content : "");
916
+ const reasoning = plan.reasoning ?? ("reasoning" in response && typeof response.reasoning === "string" ? response.reasoning : "");
917
+ return resolveUsage(void 0, request.messages.map((message) => typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.map((part) => part.text ?? "").join("") : "").join(""), content + calls.map(toolCallUsageText).join("") + (plan.refusal ?? "") + (exposeReasoning ? reasoning : ""));
918
+ }
324
919
  /** Project normalized ordered blocks without changing the fixture or generating ids. */
325
920
  function resolveFixtureBlockOutcome(blocks) {
326
921
  const ordered = resolveFixtureBlocks(blocks);
@@ -339,6 +934,118 @@ function resolveFixtureBlockOutcome(blocks) {
339
934
  hasToolCalls: toolCalls.length > 0
340
935
  };
341
936
  }
937
+ /**
938
+ * Every tool call a response serves, in order: the function calls of
939
+ * `toolCalls`, then the custom calls of `customToolCalls` (each tagged
940
+ * `type: "custom"`). Only the OpenAI Responses API may serve the custom ones;
941
+ * the other wires reject a non-empty `customToolCalls` first
942
+ * ({@link rejectResponsesOnlyToolCalls}).
943
+ */
944
+ function servedToolCalls(response) {
945
+ const calls = [...response.toolCalls ?? []];
946
+ for (const call of Array.isArray(response.customToolCalls) ? response.customToolCalls : []) calls.push(isPlainObject(call) ? {
947
+ ...call,
948
+ type: "custom"
949
+ } : call);
950
+ return calls;
951
+ }
952
+ /**
953
+ * Resolve the ordered blocks a response serves, with each tool block projected
954
+ * to its {@link FixtureToolCall}: a non-empty `responsesBlocks` (OpenAI
955
+ * Responses only, through {@link resolveResponsesBlocks}), else a non-empty
956
+ * legacy `blocks` (through {@link resolveFixtureBlocks}, which rejects a
957
+ * `customToolCall` block with the error of earlier releases). Undefined when
958
+ * the response has neither.
959
+ */
960
+ function resolveServedBlockOutcome(response) {
961
+ const r = response;
962
+ let ordered;
963
+ let source;
964
+ if (Array.isArray(r.responsesBlocks) && r.responsesBlocks.length > 0) {
965
+ ordered = resolveResponsesBlocks(r.responsesBlocks);
966
+ source = "responsesBlocks";
967
+ } else if (Array.isArray(r.blocks) && r.blocks.length > 0) {
968
+ ordered = resolveFixtureBlocks(r.blocks);
969
+ source = "blocks";
970
+ } else return void 0;
971
+ let content = "";
972
+ const toolCalls = [];
973
+ for (const block of ordered) if (block.type === "text") content += block.text;
974
+ else toolCalls.push(fixtureBlockToolCall(block));
975
+ return {
976
+ ordered,
977
+ content,
978
+ toolCalls,
979
+ hasToolCalls: toolCalls.length > 0,
980
+ source
981
+ };
982
+ }
983
+ /**
984
+ * Write rewritten served tool calls (and, with `ordered`, rebuilt ordered
985
+ * blocks) back into a copy of `response`, split by carrier: function calls go
986
+ * to `toolCalls`, custom calls to `customToolCalls`, and the blocks to
987
+ * `responsesBlocks` when the response served those, else to `blocks`.
988
+ */
989
+ function withServedToolCalls(response, toolCalls, ordered) {
990
+ const functionCalls = [];
991
+ const customCalls = [];
992
+ for (const call of toolCalls) if (call.type === "custom") customCalls.push(call);
993
+ else functionCalls.push(call);
994
+ const out = {
995
+ ...response,
996
+ toolCalls: functionCalls
997
+ };
998
+ if (customCalls.length > 0 || "customToolCalls" in response) out.customToolCalls = customCalls;
999
+ if (ordered) {
1000
+ const r = response;
1001
+ if (Array.isArray(r.responsesBlocks) && r.responsesBlocks.length > 0) out.responsesBlocks = ordered;
1002
+ else out.blocks = ordered;
1003
+ }
1004
+ return out;
1005
+ }
1006
+ /** Project one normalized tool block to the matching served tool call. */
1007
+ function fixtureBlockToolCall(block) {
1008
+ const id = block.id !== void 0 ? { id: block.id } : {};
1009
+ const namespace = block.namespace !== void 0 ? { namespace: block.namespace } : {};
1010
+ return block.type === "customToolCall" ? {
1011
+ type: "custom",
1012
+ name: block.name,
1013
+ input: block.input,
1014
+ ...id,
1015
+ ...namespace
1016
+ } : {
1017
+ name: block.name,
1018
+ arguments: block.arguments,
1019
+ ...id,
1020
+ ...namespace
1021
+ };
1022
+ }
1023
+ /** Project one served tool call back to its ordered tool block. */
1024
+ function toolCallFixtureBlock(call) {
1025
+ const id = call.id !== void 0 ? { id: call.id } : {};
1026
+ const namespace = call.namespace !== void 0 ? { namespace: call.namespace } : {};
1027
+ return call.type === "custom" ? {
1028
+ type: "customToolCall",
1029
+ name: call.name,
1030
+ input: call.input,
1031
+ ...id,
1032
+ ...namespace
1033
+ } : {
1034
+ type: "toolCall",
1035
+ name: call.name,
1036
+ arguments: call.arguments,
1037
+ ...id,
1038
+ ...namespace
1039
+ };
1040
+ }
1041
+ /**
1042
+ * Rebuild ordered blocks after their tool calls were rewritten one-for-one:
1043
+ * text blocks are copied and the Nth tool block becomes `toolCalls[N]`.
1044
+ */
1045
+ function rebuildOrderedBlocks(ordered, toolCalls) {
1046
+ let callIndex = 0;
1047
+ return ordered.map((block) => block.type === "text" ? { ...block } : toolCallFixtureBlock(toolCalls[callIndex++]));
1048
+ }
342
1049
  function isErrorResponse(r) {
343
1050
  return "error" in r && r.error !== null && typeof r.error === "object" && "message" in r.error && typeof r.error.message === "string";
344
1051
  }
@@ -416,6 +1123,17 @@ function estimateTokens(text) {
416
1123
  return Math.max(1, Math.ceil(text.length / 4));
417
1124
  }
418
1125
  /**
1126
+ * Estimate prompt tokens from a request's messages array.
1127
+ */
1128
+ function estimatePromptTokens(messages) {
1129
+ let totalChars = 0;
1130
+ for (const msg of messages) if (typeof msg.content === "string") totalChars += msg.content.length;
1131
+ else if (Array.isArray(msg.content)) {
1132
+ for (const part of msg.content) if (part.text) totalChars += part.text.length;
1133
+ }
1134
+ return Math.max(1, Math.ceil(totalChars / 4));
1135
+ }
1136
+ /**
419
1137
  * Build usage object: use explicit overrides if provided, otherwise estimate.
420
1138
  *
421
1139
  * Shared by BOTH the non-streaming completion builders (below) and the
@@ -530,6 +1248,140 @@ function buildTextChunks(content, model, chunkSize, reasoning, overrides) {
530
1248
  });
531
1249
  return chunks;
532
1250
  }
1251
+ /** K9 exposure is selected by the provider path, never the echoed response model. */
1252
+ function buildOpenAIReasoningChunks(reasoning, model, chunkSize, exposeReasoning, overrides) {
1253
+ return buildTextChunks(exposeReasoning ? reasoning : "", model, chunkSize, void 0, {
1254
+ ...overrides,
1255
+ role: "assistant",
1256
+ finishReason: "length"
1257
+ }).map((chunk) => ({
1258
+ ...chunk,
1259
+ choices: chunk.choices.map((choice) => ({
1260
+ ...choice,
1261
+ delta: choice.delta.role !== void 0 ? {
1262
+ role: "assistant",
1263
+ content: null
1264
+ } : typeof choice.delta.content === "string" ? {
1265
+ role: "assistant",
1266
+ content: "",
1267
+ reasoning: choice.delta.content,
1268
+ reasoning_details: [{
1269
+ type: "reasoning.text",
1270
+ text: choice.delta.content,
1271
+ format: "unknown",
1272
+ index: 0
1273
+ }]
1274
+ } : {}
1275
+ }))
1276
+ }));
1277
+ }
1278
+ /** Render exposed reasoning or native OpenAI's empty length completion. */
1279
+ function buildOpenAIReasoningCompletion(reasoning, model, exposeReasoning, overrides, requestMessages) {
1280
+ const visible = exposeReasoning ? reasoning : "";
1281
+ const completion = buildTextCompletion(visible, model, void 0, {
1282
+ ...overrides,
1283
+ role: "assistant",
1284
+ finishReason: "length",
1285
+ usage: void 0
1286
+ }, requestMessages);
1287
+ return {
1288
+ ...completion,
1289
+ choices: completion.choices.map((choice) => ({
1290
+ ...choice,
1291
+ message: {
1292
+ role: "assistant",
1293
+ content: null,
1294
+ refusal: null,
1295
+ ...exposeReasoning ? {
1296
+ reasoning: visible,
1297
+ reasoning_details: [{
1298
+ type: "reasoning.text",
1299
+ text: visible,
1300
+ format: "unknown",
1301
+ index: 0
1302
+ }]
1303
+ } : {}
1304
+ }
1305
+ }))
1306
+ };
1307
+ }
1308
+ /** Render withheld output with only the role and native content-filter terminal. */
1309
+ function buildOpenAIContentFilterChunks(model, overrides) {
1310
+ return buildTextChunks("", model, 1, void 0, {
1311
+ ...overrides,
1312
+ role: "assistant",
1313
+ finishReason: "content_filter"
1314
+ }).map((chunk) => ({
1315
+ ...chunk,
1316
+ choices: chunk.choices.map((choice) => ({
1317
+ ...choice,
1318
+ delta: choice.delta.role !== void 0 ? {
1319
+ role: "assistant",
1320
+ content: null
1321
+ } : {}
1322
+ }))
1323
+ }));
1324
+ }
1325
+ /** Non-streaming filtered output contains no answer, refusal text, reasoning, or calls. */
1326
+ function buildOpenAIContentFilterCompletion(model, overrides, requestMessages) {
1327
+ const completion = buildTextCompletion("", model, void 0, {
1328
+ ...overrides,
1329
+ role: "assistant",
1330
+ finishReason: "content_filter",
1331
+ usage: void 0
1332
+ }, requestMessages);
1333
+ return {
1334
+ ...completion,
1335
+ choices: completion.choices.map((choice) => ({
1336
+ ...choice,
1337
+ message: {
1338
+ role: "assistant",
1339
+ content: null,
1340
+ refusal: null
1341
+ }
1342
+ }))
1343
+ };
1344
+ }
1345
+ /** Render an applied refusal on its own channel without ordinary content or reasoning. */
1346
+ function buildOpenAIRefusalChunks(refusal, model, chunkSize, overrides) {
1347
+ return buildTextChunks(refusal, model, chunkSize, void 0, {
1348
+ ...overrides,
1349
+ role: "assistant",
1350
+ finishReason: "stop"
1351
+ }).map((chunk) => ({
1352
+ ...chunk,
1353
+ choices: chunk.choices.map((choice) => {
1354
+ const delta = choice.delta.role !== void 0 ? {
1355
+ role: "assistant",
1356
+ content: null
1357
+ } : typeof choice.delta.content === "string" ? { refusal: choice.delta.content } : {};
1358
+ return {
1359
+ ...choice,
1360
+ delta
1361
+ };
1362
+ })
1363
+ }));
1364
+ }
1365
+ /** Refusal-only counterpart of the ordinary text completion builder. */
1366
+ function buildOpenAIRefusalCompletion(refusal, model, overrides, requestMessages) {
1367
+ const completion = buildTextCompletion(refusal, model, void 0, {
1368
+ ...overrides,
1369
+ role: "assistant",
1370
+ finishReason: "stop",
1371
+ usage: void 0
1372
+ }, requestMessages);
1373
+ return {
1374
+ ...completion,
1375
+ choices: completion.choices.map((choice) => ({
1376
+ ...choice,
1377
+ message: {
1378
+ role: "assistant",
1379
+ content: null,
1380
+ refusal
1381
+ }
1382
+ }))
1383
+ };
1384
+ }
533
1385
  function buildToolCallChunks(toolCalls, model, chunkSize, reasoning, overrides) {
534
1386
  const id = overrides?.id ?? generateId();
535
1387
  const created = overrides?.created ?? Math.floor(Date.now() / 1e3);
@@ -1070,11 +1922,14 @@ function matchesPattern(text, pattern) {
1070
1922
  return result;
1071
1923
  }
1072
1924
  /**
1073
- * The ONE definition of "which test does this traffic belong to": the
1074
- * `X-Test-Id` header wins, then `?testId=` in the query string, then
1075
- * `DEFAULT_TEST_ID`. Every per-test axis (fixture match-counts, the journal
1076
- * filter, chaos scoping) resolves through this, so a caller that tags one way
1077
- * can never land in two different scopes.
1925
+ * Which test LLM and other HTTP-route traffic belongs to: the `X-Test-Id`
1926
+ * header (raw, not percent-decoded) wins, then `?testId=` in the query string
1927
+ * (read through `URLSearchParams`, so percent-decoded and with `+` as a
1928
+ * space), then `DEFAULT_TEST_ID`. Every per-test axis of those routes
1929
+ * (fixture match-counts, the journal filter, chaos scoping) resolves through
1930
+ * this. MCP mounts resolve the test id with {@link resolveMcpIdentity}
1931
+ * instead, which percent-decodes the header, so `X-Test-Id: a%20b` is `a%20b`
1932
+ * here and `a b` there. Both read a `+` in the query as a space.
1078
1933
  */
1079
1934
  function resolveTestId(headers, url) {
1080
1935
  const headerValue = headers["x-test-id"];
@@ -1098,6 +1953,237 @@ function getContext(req) {
1098
1953
  } else if (typeof headerValue === "string" && headerValue) return headerValue;
1099
1954
  }
1100
1955
  /**
1956
+ * Decode one MCP identity value: an `X-Test-Id` / `X-AIMock-Context` header
1957
+ * value, and also each query name and (through {@link decodeMcpQueryValue})
1958
+ * each `?testId=` / `?context=` / `?undeclared=` query value. Clients send `encodeURIComponent(id)` because
1959
+ * `fetch` rejects characters such as `›` in a header. A value that is not
1960
+ * valid percent-encoding (a raw `applies 50% discount`) is used as-is, with
1961
+ * `fellBack: true` so the caller can log the fallback. Only that `URIError`
1962
+ * is caught; any other throw propagates. MCP requests only: LLM routes read
1963
+ * the header raw and the query through `URLSearchParams` (see
1964
+ * {@link resolveTestId}).
1965
+ */
1966
+ function decodeMcpHeaderValue(raw) {
1967
+ try {
1968
+ return {
1969
+ value: decodeURIComponent(raw),
1970
+ fellBack: false
1971
+ };
1972
+ } catch (err) {
1973
+ if (!(err instanceof URIError)) throw err;
1974
+ return {
1975
+ value: raw,
1976
+ fellBack: true
1977
+ };
1978
+ }
1979
+ }
1980
+ /**
1981
+ * Decode one MCP query value (`?testId=`, `?context=`, `?undeclared=`) the way
1982
+ * `URLSearchParams` reads it (spec I1): a `+` is a space, then the value is
1983
+ * percent-decoded by the {@link decodeMcpHeaderValue} rule. So a query built
1984
+ * with `URL.searchParams.set(...)` (a space sent as `+`) and one built with
1985
+ * `encodeURIComponent` both resolve to the id itself. A value that is not
1986
+ * valid percent-encoding is used as-is (its `+` still a space), with
1987
+ * `fellBack: true`.
1988
+ */
1989
+ function decodeMcpQueryValue(raw) {
1990
+ return decodeMcpHeaderValue(raw.replace(/\+/g, " "));
1991
+ }
1992
+ /**
1993
+ * Every value of the header `name`, one per header line: `[]` when absent.
1994
+ * Node joins a repeated header into one comma-joined `req.headers` string, so
1995
+ * the values come from `req.headersDistinct` (one element per line) when the
1996
+ * request has it. A caller without it (a hand-built request) is read from
1997
+ * `req.headers`: one element for a string, each element for an array.
1998
+ */
1999
+ function headerValues(req, name) {
2000
+ const distinct = req.headersDistinct?.[name];
2001
+ if (distinct !== void 0) return distinct;
2002
+ const value = req.headers[name];
2003
+ if (value === void 0) return [];
2004
+ return Array.isArray(value) ? value : [value];
2005
+ }
2006
+ /**
2007
+ * Every pair of a query string, in order, each name decoded by the
2008
+ * `decodeMcpHeaderValue` rule. A bare `name` with no `=` counts as an
2009
+ * occurrence with an empty value, so `?testId&testId=t1` has two. Each value
2010
+ * is left raw for the caller to decode with {@link decodeMcpQueryValue}.
2011
+ * A name that is not valid percent-encoding (`test%Id`) gets `name: null`: it
2012
+ * matches no field, and the caller counts it.
2013
+ */
2014
+ function queryPairs(query) {
2015
+ if (query === "") return [];
2016
+ return query.split("&").map((pair) => {
2017
+ const eq = pair.indexOf("=");
2018
+ const key = decodeMcpHeaderValue(eq === -1 ? pair : pair.slice(0, eq));
2019
+ return {
2020
+ name: key.fellBack ? null : key.value,
2021
+ value: eq === -1 ? "" : pair.slice(eq + 1)
2022
+ };
2023
+ });
2024
+ }
2025
+ /**
2026
+ * A request value as a message part, the way the message builder quotes every
2027
+ * user string: JSON-quoted (quotes and control characters escaped), then cut
2028
+ * once as JSON text, so the whole echo, quotes, escapes and the
2029
+ * `… (<n> more chars)` count included, fits in `MCP_FAKES_ECHO_LIMIT` and the
2030
+ * cut never splits a JSON escape or a surrogate pair.
2031
+ */
2032
+ function echoIdentityValue(value) {
2033
+ return quote(value, MCP_FAKES_ECHO_LIMIT);
2034
+ }
2035
+ const MCP_IDENTITY_INPUTS = {
2036
+ testId: {
2037
+ header: "x-test-id",
2038
+ query: "testId",
2039
+ label: "X-Test-Id"
2040
+ },
2041
+ context: {
2042
+ header: "x-aimock-context",
2043
+ query: "context",
2044
+ label: "X-AIMock-Context"
2045
+ },
2046
+ undeclared: {
2047
+ header: "x-aimock-mcp-undeclared",
2048
+ query: "undeclared",
2049
+ label: "X-AIMock-MCP-Undeclared"
2050
+ }
2051
+ };
2052
+ /**
2053
+ * Resolve the identity (test id, context, undeclared override) of one MCP request.
2054
+ * Each field resolves on its own, first of: the header, the query parameter,
2055
+ * the session value bound at `initialize`. A field sent more than once on
2056
+ * either path (more than one header line, read from `headersDistinct` because
2057
+ * Node joins repeated lines into one `headers` string; a header array from a
2058
+ * hand-built request; a repeated query name) is an error
2059
+ * (`MCP_DUPLICATE_IDENTITY`), even when the other path also carries it. For
2060
+ * the test id and the context, a header value is decoded with
2061
+ * `decodeURIComponent` (raw value on failure, with `fellBack` set) and a query
2062
+ * value the way `URLSearchParams` reads it (spec I1): a `+` is a space, then
2063
+ * the same `decodeURIComponent` rule. So `encodeURIComponent` output (what
2064
+ * clients send) and a query built with `URL.searchParams` both decode to the
2065
+ * id itself, while a raw `+` is a `+` in the header and a space in the query.
2066
+ * When both paths carry a test id or a context, the header is used and the
2067
+ * query value is ignored, even if the two differ, but an ignored query value
2068
+ * that does not decode still sets `fellBack`. The undeclared header is not
2069
+ * percent-decoded; its query value is, by the same query rule. Both are
2070
+ * trimmed and compared case-insensitively. `supplied` says whether the
2071
+ * request itself carried a non-empty header or query value for the field,
2072
+ * never `resolveTestId`'s result (which returns `"__default__"` when nothing
2073
+ * is sent). Blank values: an empty value is not supplied and falls through;
2074
+ * it is never rejected. A whitespace-only value is not supplied for the
2075
+ * undeclared override (it is trimmed), but is a real value for the test id
2076
+ * and the context, which match exactly and are never trimmed (Node trims a
2077
+ * header value, so only the query or a hand-built request can carry one). A
2078
+ * lone query name with no `=` carries no value. An empty session value counts
2079
+ * as none, and a missing `req.url` as `/`. A field with no value anywhere is
2080
+ * `null`. An unrecognized undeclared override on the header or the query is
2081
+ * an error (`ok: false`), not a fall-through: both are checked before the
2082
+ * header one is used, so a valid header does not hide a mistyped query value.
2083
+ * Bad percent-encoding is never silent: a test id or context value that does
2084
+ * not decode sets `fellBack`, on either path, used or ignored; an undeclared
2085
+ * query value that does not decode is that error, with the message saying
2086
+ * so; and a query name that does not decode matches no field and is counted
2087
+ * in `undecodedQueryNames`. `resolveTestId` / `getContext` stay unchanged for
2088
+ * LLM routes.
2089
+ */
2090
+ function resolveMcpIdentity(req, session) {
2091
+ const url = req.url ?? "/";
2092
+ const qIdx = url.indexOf("?");
2093
+ const pairs = queryPairs(qIdx === -1 ? "" : url.slice(qIdx + 1));
2094
+ const raw = {};
2095
+ for (const field of [
2096
+ "testId",
2097
+ "context",
2098
+ "undeclared"
2099
+ ]) {
2100
+ const input = MCP_IDENTITY_INPUTS[field];
2101
+ const sent = [["header", headerValues(req, input.header)], ["query", pairs.filter((p) => p.name === input.query).map((p) => p.value)]];
2102
+ for (const [source, values] of sent) if (values.length > 1) {
2103
+ const label = source === "header" ? msg`${fixed(input.label)} header` : msg`?${fixed(input.query)}= query parameter`;
2104
+ return {
2105
+ ok: false,
2106
+ error: {
2107
+ code: "MCP_DUPLICATE_IDENTITY",
2108
+ status: 400,
2109
+ field,
2110
+ source,
2111
+ count: values.length,
2112
+ message: build(msg`Duplicate ${label}: ${values.length} values sent, expected one`)
2113
+ }
2114
+ };
2115
+ }
2116
+ raw[field] = {
2117
+ header: sent[0][1][0],
2118
+ query: sent[1][1][0]
2119
+ };
2120
+ }
2121
+ const fromRequest = (field) => {
2122
+ const { header, query: q } = raw[field];
2123
+ const fromQuery = q ? decodeMcpQueryValue(q) : null;
2124
+ if (header) {
2125
+ const used = decodeMcpHeaderValue(header);
2126
+ return {
2127
+ value: used.value,
2128
+ fellBack: used.fellBack || (fromQuery?.fellBack ?? false)
2129
+ };
2130
+ }
2131
+ return fromQuery ?? {
2132
+ value: null,
2133
+ fellBack: false
2134
+ };
2135
+ };
2136
+ const testId = fromRequest("testId");
2137
+ const context = fromRequest("context");
2138
+ let undeclared = null;
2139
+ for (const source of ["header", "query"]) {
2140
+ const sent = raw.undeclared[source];
2141
+ if (sent === void 0) continue;
2142
+ const decoded = source === "header" ? {
2143
+ value: sent,
2144
+ fellBack: false
2145
+ } : decodeMcpQueryValue(sent);
2146
+ if (decoded.value.trim() === "") continue;
2147
+ const parsed = parseMcpUndeclared(decoded.value);
2148
+ if (parsed === null) {
2149
+ const echoed = echoIdentityValue(sent);
2150
+ const label = source === "header" ? msg`X-AIMock-MCP-Undeclared header` : msg`?undeclared= query parameter`;
2151
+ const note = decoded.fellBack ? msg` (not valid percent-encoding)` : msg``;
2152
+ return {
2153
+ ok: false,
2154
+ error: {
2155
+ code: "MCP_INVALID_UNDECLARED",
2156
+ status: 400,
2157
+ field: "undeclared",
2158
+ source,
2159
+ raw: cutText(sent),
2160
+ message: build(msg`Invalid ${label} value ${echoed}${note}: expected allow or deny`)
2161
+ }
2162
+ };
2163
+ }
2164
+ undeclared ??= parsed;
2165
+ }
2166
+ const undecodedQueryNames = pairs.filter((p) => p.name === null).length;
2167
+ return {
2168
+ ok: true,
2169
+ identity: {
2170
+ testId: testId.value ?? (session?.testId || null),
2171
+ context: context.value ?? (session?.context || null),
2172
+ undeclared: undeclared ?? session?.undeclared ?? null
2173
+ },
2174
+ supplied: {
2175
+ testId: testId.value !== null,
2176
+ context: context.value !== null,
2177
+ undeclared: undeclared !== null
2178
+ },
2179
+ fellBack: {
2180
+ testId: testId.fellBack,
2181
+ context: context.fellBack
2182
+ },
2183
+ ...undecodedQueryNames > 0 ? { undecodedQueryNames } : {}
2184
+ };
2185
+ }
2186
+ /**
1101
2187
  * Convert a test ID (e.g. Playwright titlePath) into a filesystem-safe slug
1102
2188
  * suitable for use as a directory name in snapshot-style recording.
1103
2189
  */
@@ -1328,7 +2414,20 @@ function describeMatch(match, index) {
1328
2414
  const cut = head.lastIndexOf(", ");
1329
2415
  return `${cut > 0 ? head.slice(0, cut) : head}, … }`;
1330
2416
  }
2417
+ /**
2418
+ * Parse an `X-AIMock-MCP-Undeclared` header or `?undeclared=` value.
2419
+ * Modeled on {@link resolveStrictMode}: case-insensitive, surrounding
2420
+ * whitespace trimmed. Returns `null` when unrecognised; unlike the strict
2421
+ * header, {@link resolveMcpIdentity} turns that into an error rather than a
2422
+ * fall-through, because falling through would turn a mistyped `deny` into
2423
+ * the permissive default.
2424
+ */
2425
+ function parseMcpUndeclared(raw) {
2426
+ const val = raw.trim().toLowerCase();
2427
+ if (val === "allow" || val === "deny") return val;
2428
+ return null;
2429
+ }
1331
2430
 
1332
2431
  //#endregion
1333
- export { FORMAT_TO_CONTENT_TYPE, MAX_EMBEDDING_DIMENSIONS, RequestBodyTooLargeError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, buildUsageChunk, describeMatch, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getContext, getTestId, hasMintedRequestId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isJSONResponse, isJsonObject, isLiveResponse, isResponseFactory, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, markMintedRequestId, matchesPattern, normalizeEmbeddingInput, normalizeTextInput, readBody, readBodyBufferBounded, resolveFixtureBlockOutcome, resolveFixtureBlocks, resolveReasoningArtifactsForModel, resolveReasoningForModel, resolveRequestId, resolveResponse, resolveStrictMode, resolveTestId, resolveUsage, serializeErrorResponse, slugifyContext, slugifyTestId, strictNoMatchLogLine, strictNoMatchMessage, strictOverrideField, validateChatMessages, validateEmbeddingDimensions, validateToolsField, wouldProxyMiss };
2432
+ export { FORMAT_TO_CONTENT_TYPE, InvalidFixtureToolCallError, InvalidToolArgumentsError, MAX_EMBEDDING_DIMENSIONS, RequestBodyTooLargeError, UnsupportedToolCallError, assertCustomToolCalls, assertResponsesToolCalls, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildOpenAIContentFilterChunks, buildOpenAIContentFilterCompletion, buildOpenAIReasoningChunks, buildOpenAIReasoningCompletion, buildOpenAIRefusalChunks, buildOpenAIRefusalCompletion, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, buildUsageChunk, createServerFixtureList, decodeMcpHeaderValue, describeMatch, estimatePromptTokens, estimateTokens, extractOverrides, fixtureListTarget, fixtureToolCallErrorCode, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getContext, getTestId, googleFixtureToolCallErrorDetails, hasMintedRequestId, isAudioResponse, isCombinedFixtureResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isExtendedResponsesToolsList, isFixtureToolCallError, isImageResponse, isJSONResponse, isJsonObject, isLiveResponse, isResponseFactory, isServerOwnedFixtures, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, journalFixtureToolCallError, keepAuthoredToolArguments, markExtendedResponsesToolsRequest, markMintedRequestId, markServerOwnedFixtures, matchesPattern, normalizeEmbeddingInput, normalizeTextInput, parseStrictIntegerText, prepareOpenAIChatMisbehavior, readBody, readBodyBufferBounded, rebuildOrderedBlocks, rejectResponsesOnlyToolCalls, requireEmittedFunctionToolCalls, requireFunctionToolCalls, requireServedFunctionToolCalls, resolveFixtureBlockOutcome, resolveFixtureBlocks, resolveMcpIdentity, resolveOpenAIChatMisbehaviorUsage, resolveReasoningArtifactsForModel, resolveReasoningForModel, resolveRequestId, resolveResponse, resolveResponsesBlocks, resolveServedBlockOutcome, resolveStrictMode, resolveTestId, resolveUsage, runWithToolArgumentsScope, serializeErrorResponse, servedToolArgs, servedToolCalls, slugifyContext, slugifyTestId, strictNoMatchLogLine, strictNoMatchMessage, strictOverrideField, strictToolArgumentsEnabled, toolArgsForWire, toolCallFixtureBlock, validateChatMessages, validateEmbeddingDimensions, validateToolsField, withServedToolCalls, withoutLegacyNamespaces, withoutResponsesToolKeys, wouldProxyMiss };
1334
2433
  //# sourceMappingURL=helpers.js.map