@copilotkit/aimock 1.45.1 → 1.47.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 (492) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +25 -1
  4. package/README.md +11 -2
  5. package/dist/agui-mock.cjs +25 -25
  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 +25 -25
  10. package/dist/agui-mock.js.map +1 -1
  11. package/dist/agui-types.d.cts.map +1 -1
  12. package/dist/aimock-cli.cjs +15 -1
  13. package/dist/aimock-cli.cjs.map +1 -1
  14. package/dist/aimock-cli.d.cts.map +1 -1
  15. package/dist/aimock-cli.d.ts.map +1 -1
  16. package/dist/aimock-cli.js +16 -2
  17. package/dist/aimock-cli.js.map +1 -1
  18. package/dist/api-key-auth.cjs +10 -9
  19. package/dist/api-key-auth.cjs.map +1 -1
  20. package/dist/api-key-auth.d.cts.map +1 -1
  21. package/dist/api-key-auth.d.ts.map +1 -1
  22. package/dist/api-key-auth.js +11 -10
  23. package/dist/api-key-auth.js.map +1 -1
  24. package/dist/aws-event-stream.cjs +20 -23
  25. package/dist/aws-event-stream.cjs.map +1 -1
  26. package/dist/aws-event-stream.d.cts +0 -1
  27. package/dist/aws-event-stream.d.ts +0 -1
  28. package/dist/aws-event-stream.js +20 -24
  29. package/dist/aws-event-stream.js.map +1 -1
  30. package/dist/batches.cjs +2 -4
  31. package/dist/batches.cjs.map +1 -1
  32. package/dist/batches.d.cts.map +1 -1
  33. package/dist/batches.d.ts.map +1 -1
  34. package/dist/batches.js +2 -4
  35. package/dist/batches.js.map +1 -1
  36. package/dist/bedrock-converse.cjs +139 -161
  37. package/dist/bedrock-converse.cjs.map +1 -1
  38. package/dist/bedrock-converse.d.cts.map +1 -1
  39. package/dist/bedrock-converse.d.ts.map +1 -1
  40. package/dist/bedrock-converse.js +137 -159
  41. package/dist/bedrock-converse.js.map +1 -1
  42. package/dist/bedrock.cjs +175 -216
  43. package/dist/bedrock.cjs.map +1 -1
  44. package/dist/bedrock.d.cts.map +1 -1
  45. package/dist/bedrock.d.ts.map +1 -1
  46. package/dist/bedrock.js +172 -213
  47. package/dist/bedrock.js.map +1 -1
  48. package/dist/byteplus-video.cjs +11 -10
  49. package/dist/byteplus-video.cjs.map +1 -1
  50. package/dist/byteplus-video.d.cts.map +1 -1
  51. package/dist/byteplus-video.d.ts.map +1 -1
  52. package/dist/byteplus-video.js +5 -4
  53. package/dist/byteplus-video.js.map +1 -1
  54. package/dist/chaos.cjs +5 -4
  55. package/dist/chaos.cjs.map +1 -1
  56. package/dist/chaos.d.cts.map +1 -1
  57. package/dist/chaos.d.ts.map +1 -1
  58. package/dist/chaos.js +5 -4
  59. package/dist/chaos.js.map +1 -1
  60. package/dist/cli.cjs +15 -0
  61. package/dist/cli.cjs.map +1 -1
  62. package/dist/cli.js +15 -0
  63. package/dist/cli.js.map +1 -1
  64. package/dist/cohere.cjs +107 -180
  65. package/dist/cohere.cjs.map +1 -1
  66. package/dist/cohere.d.cts.map +1 -1
  67. package/dist/cohere.d.ts.map +1 -1
  68. package/dist/cohere.js +106 -179
  69. package/dist/cohere.js.map +1 -1
  70. package/dist/config-loader.cjs +29 -1
  71. package/dist/config-loader.cjs.map +1 -1
  72. package/dist/config-loader.d.cts +7 -1
  73. package/dist/config-loader.d.cts.map +1 -1
  74. package/dist/config-loader.d.ts +7 -1
  75. package/dist/config-loader.d.ts.map +1 -1
  76. package/dist/config-loader.js +29 -2
  77. package/dist/config-loader.js.map +1 -1
  78. package/dist/count-tokens.cjs +146 -0
  79. package/dist/count-tokens.cjs.map +1 -0
  80. package/dist/count-tokens.js +146 -0
  81. package/dist/count-tokens.js.map +1 -0
  82. package/dist/elevenlabs-audio.cjs +36 -34
  83. package/dist/elevenlabs-audio.cjs.map +1 -1
  84. package/dist/elevenlabs-audio.d.cts.map +1 -1
  85. package/dist/elevenlabs-audio.d.ts.map +1 -1
  86. package/dist/elevenlabs-audio.js +33 -31
  87. package/dist/elevenlabs-audio.js.map +1 -1
  88. package/dist/elevenlabs-voice.cjs +38 -37
  89. package/dist/elevenlabs-voice.cjs.map +1 -1
  90. package/dist/elevenlabs-voice.d.cts.map +1 -1
  91. package/dist/elevenlabs-voice.d.ts.map +1 -1
  92. package/dist/elevenlabs-voice.js +33 -32
  93. package/dist/elevenlabs-voice.js.map +1 -1
  94. package/dist/embedding-request.cjs +16 -0
  95. package/dist/embedding-request.cjs.map +1 -0
  96. package/dist/embedding-request.js +14 -0
  97. package/dist/embedding-request.js.map +1 -0
  98. package/dist/embeddings.cjs +30 -20
  99. package/dist/embeddings.cjs.map +1 -1
  100. package/dist/embeddings.d.cts.map +1 -1
  101. package/dist/embeddings.d.ts.map +1 -1
  102. package/dist/embeddings.js +30 -20
  103. package/dist/embeddings.js.map +1 -1
  104. package/dist/fal-audio.cjs +45 -43
  105. package/dist/fal-audio.cjs.map +1 -1
  106. package/dist/fal-audio.d.cts.map +1 -1
  107. package/dist/fal-audio.d.ts.map +1 -1
  108. package/dist/fal-audio.js +42 -40
  109. package/dist/fal-audio.js.map +1 -1
  110. package/dist/fal.cjs +17 -15
  111. package/dist/fal.cjs.map +1 -1
  112. package/dist/fal.js +16 -14
  113. package/dist/fal.js.map +1 -1
  114. package/dist/files.cjs +2 -4
  115. package/dist/files.cjs.map +1 -1
  116. package/dist/files.d.cts.map +1 -1
  117. package/dist/files.d.ts.map +1 -1
  118. package/dist/files.js +2 -4
  119. package/dist/files.js.map +1 -1
  120. package/dist/fine-tuning.cjs +2 -4
  121. package/dist/fine-tuning.cjs.map +1 -1
  122. package/dist/fine-tuning.d.cts.map +1 -1
  123. package/dist/fine-tuning.d.ts.map +1 -1
  124. package/dist/fine-tuning.js +2 -4
  125. package/dist/fine-tuning.js.map +1 -1
  126. package/dist/fixture-loader.cjs +140 -44
  127. package/dist/fixture-loader.cjs.map +1 -1
  128. package/dist/fixture-loader.d.cts.map +1 -1
  129. package/dist/fixture-loader.d.ts.map +1 -1
  130. package/dist/fixture-loader.js +141 -46
  131. package/dist/fixture-loader.js.map +1 -1
  132. package/dist/gemini-embeddings.cjs +26 -24
  133. package/dist/gemini-embeddings.cjs.map +1 -1
  134. package/dist/gemini-embeddings.js +26 -24
  135. package/dist/gemini-embeddings.js.map +1 -1
  136. package/dist/gemini-interactions.cjs +113 -156
  137. package/dist/gemini-interactions.cjs.map +1 -1
  138. package/dist/gemini-interactions.d.cts +0 -1
  139. package/dist/gemini-interactions.d.cts.map +1 -1
  140. package/dist/gemini-interactions.d.ts +0 -1
  141. package/dist/gemini-interactions.d.ts.map +1 -1
  142. package/dist/gemini-interactions.js +113 -156
  143. package/dist/gemini-interactions.js.map +1 -1
  144. package/dist/gemini.cjs +295 -218
  145. package/dist/gemini.cjs.map +1 -1
  146. package/dist/gemini.d.cts.map +1 -1
  147. package/dist/gemini.d.ts.map +1 -1
  148. package/dist/gemini.js +295 -219
  149. package/dist/gemini.js.map +1 -1
  150. package/dist/grok-video.cjs +14 -12
  151. package/dist/grok-video.cjs.map +1 -1
  152. package/dist/grok-video.d.cts.map +1 -1
  153. package/dist/grok-video.d.ts.map +1 -1
  154. package/dist/grok-video.js +8 -6
  155. package/dist/grok-video.js.map +1 -1
  156. package/dist/helpers.cjs +411 -75
  157. package/dist/helpers.cjs.map +1 -1
  158. package/dist/helpers.d.cts +51 -1
  159. package/dist/helpers.d.cts.map +1 -1
  160. package/dist/helpers.d.ts +51 -1
  161. package/dist/helpers.d.ts.map +1 -1
  162. package/dist/helpers.js +402 -74
  163. package/dist/helpers.js.map +1 -1
  164. package/dist/images.cjs +30 -28
  165. package/dist/images.cjs.map +1 -1
  166. package/dist/images.d.cts.map +1 -1
  167. package/dist/images.d.ts.map +1 -1
  168. package/dist/images.js +27 -25
  169. package/dist/images.js.map +1 -1
  170. package/dist/index.cjs +4 -2
  171. package/dist/index.d.cts +4 -4
  172. package/dist/index.d.ts +4 -4
  173. package/dist/index.js +4 -4
  174. package/dist/journal.cjs +3 -1
  175. package/dist/journal.cjs.map +1 -1
  176. package/dist/journal.d.cts.map +1 -1
  177. package/dist/journal.d.ts.map +1 -1
  178. package/dist/journal.js +2 -1
  179. package/dist/journal.js.map +1 -1
  180. package/dist/llmock.cjs +3 -0
  181. package/dist/llmock.cjs.map +1 -1
  182. package/dist/llmock.d.cts.map +1 -1
  183. package/dist/llmock.d.ts.map +1 -1
  184. package/dist/llmock.js +3 -0
  185. package/dist/llmock.js.map +1 -1
  186. package/dist/mcp-fakes.d.cts.map +1 -1
  187. package/dist/mcp-handler.cjs +7 -3
  188. package/dist/mcp-handler.cjs.map +1 -1
  189. package/dist/mcp-handler.js +7 -3
  190. package/dist/mcp-handler.js.map +1 -1
  191. package/dist/mcp-recorder.cjs +2 -1
  192. package/dist/mcp-recorder.cjs.map +1 -1
  193. package/dist/mcp-recorder.js +3 -2
  194. package/dist/mcp-recorder.js.map +1 -1
  195. package/dist/messages.cjs +235 -202
  196. package/dist/messages.cjs.map +1 -1
  197. package/dist/messages.d.cts.map +1 -1
  198. package/dist/messages.d.ts.map +1 -1
  199. package/dist/messages.js +234 -202
  200. package/dist/messages.js.map +1 -1
  201. package/dist/metrics.cjs +5 -2
  202. package/dist/metrics.cjs.map +1 -1
  203. package/dist/metrics.d.cts.map +1 -1
  204. package/dist/metrics.d.ts.map +1 -1
  205. package/dist/metrics.js +6 -3
  206. package/dist/metrics.js.map +1 -1
  207. package/dist/misbehavior.cjs +62 -3
  208. package/dist/misbehavior.cjs.map +1 -1
  209. package/dist/misbehavior.d.cts.map +1 -1
  210. package/dist/misbehavior.d.ts.map +1 -1
  211. package/dist/misbehavior.js +63 -4
  212. package/dist/misbehavior.js.map +1 -1
  213. package/dist/model-utils.cjs +1 -0
  214. package/dist/model-utils.cjs.map +1 -1
  215. package/dist/model-utils.js +1 -1
  216. package/dist/model-utils.js.map +1 -1
  217. package/dist/moderation.cjs +15 -12
  218. package/dist/moderation.cjs.map +1 -1
  219. package/dist/moderation.js +14 -11
  220. package/dist/moderation.js.map +1 -1
  221. package/dist/ndjson-writer.cjs +21 -23
  222. package/dist/ndjson-writer.cjs.map +1 -1
  223. package/dist/ndjson-writer.d.cts +0 -1
  224. package/dist/ndjson-writer.d.cts.map +1 -1
  225. package/dist/ndjson-writer.d.ts +0 -1
  226. package/dist/ndjson-writer.d.ts.map +1 -1
  227. package/dist/ndjson-writer.js +21 -24
  228. package/dist/ndjson-writer.js.map +1 -1
  229. package/dist/ollama.cjs +276 -210
  230. package/dist/ollama.cjs.map +1 -1
  231. package/dist/ollama.d.cts.map +1 -1
  232. package/dist/ollama.d.ts.map +1 -1
  233. package/dist/ollama.js +273 -207
  234. package/dist/ollama.js.map +1 -1
  235. package/dist/openapi.cjs +323 -3
  236. package/dist/openapi.cjs.map +1 -1
  237. package/dist/openapi.d.cts.map +1 -1
  238. package/dist/openapi.d.ts.map +1 -1
  239. package/dist/openapi.js +324 -4
  240. package/dist/openapi.js.map +1 -1
  241. package/dist/openrouter-chat.cjs +11 -155
  242. package/dist/openrouter-chat.cjs.map +1 -1
  243. package/dist/openrouter-chat.js +11 -155
  244. package/dist/openrouter-chat.js.map +1 -1
  245. package/dist/openrouter-video.cjs +51 -74
  246. package/dist/openrouter-video.cjs.map +1 -1
  247. package/dist/openrouter-video.d.cts.map +1 -1
  248. package/dist/openrouter-video.d.ts.map +1 -1
  249. package/dist/openrouter-video.js +37 -60
  250. package/dist/openrouter-video.js.map +1 -1
  251. package/dist/raw-validation.cjs +177 -0
  252. package/dist/raw-validation.cjs.map +1 -0
  253. package/dist/raw-validation.js +176 -0
  254. package/dist/raw-validation.js.map +1 -0
  255. package/dist/recorder.cjs +176 -95
  256. package/dist/recorder.cjs.map +1 -1
  257. package/dist/recorder.d.cts.map +1 -1
  258. package/dist/recorder.d.ts.map +1 -1
  259. package/dist/recorder.js +176 -95
  260. package/dist/recorder.js.map +1 -1
  261. package/dist/rerank.cjs +13 -11
  262. package/dist/rerank.cjs.map +1 -1
  263. package/dist/rerank.js +12 -10
  264. package/dist/rerank.js.map +1 -1
  265. package/dist/response/catalog/anthropic-page.cjs +39 -0
  266. package/dist/response/catalog/anthropic-page.cjs.map +1 -0
  267. package/dist/response/catalog/anthropic-page.js +38 -0
  268. package/dist/response/catalog/anthropic-page.js.map +1 -0
  269. package/dist/response/catalog/collect.cjs +61 -0
  270. package/dist/response/catalog/collect.cjs.map +1 -0
  271. package/dist/response/catalog/collect.js +59 -0
  272. package/dist/response/catalog/collect.js.map +1 -0
  273. package/dist/response/catalog/gemini-page.cjs +25 -0
  274. package/dist/response/catalog/gemini-page.cjs.map +1 -0
  275. package/dist/response/catalog/gemini-page.js +24 -0
  276. package/dist/response/catalog/gemini-page.js.map +1 -0
  277. package/dist/response/catalog/render.cjs +182 -0
  278. package/dist/response/catalog/render.cjs.map +1 -0
  279. package/dist/response/catalog/render.js +171 -0
  280. package/dist/response/catalog/render.js.map +1 -0
  281. package/dist/response/deliver.cjs +144 -0
  282. package/dist/response/deliver.cjs.map +1 -0
  283. package/dist/response/deliver.js +143 -0
  284. package/dist/response/deliver.js.map +1 -0
  285. package/dist/response/errors.cjs +225 -0
  286. package/dist/response/errors.cjs.map +1 -0
  287. package/dist/response/errors.js +224 -0
  288. package/dist/response/errors.js.map +1 -0
  289. package/dist/response/finish.cjs +39 -0
  290. package/dist/response/finish.cjs.map +1 -0
  291. package/dist/response/finish.js +35 -0
  292. package/dist/response/finish.js.map +1 -0
  293. package/dist/response/frame-loop.cjs +102 -0
  294. package/dist/response/frame-loop.cjs.map +1 -0
  295. package/dist/response/frame-loop.js +100 -0
  296. package/dist/response/frame-loop.js.map +1 -0
  297. package/dist/response/lifecycle.cjs +223 -0
  298. package/dist/response/lifecycle.cjs.map +1 -0
  299. package/dist/response/lifecycle.js +211 -0
  300. package/dist/response/lifecycle.js.map +1 -0
  301. package/dist/response/policy.cjs +126 -0
  302. package/dist/response/policy.cjs.map +1 -0
  303. package/dist/response/policy.js +120 -0
  304. package/dist/response/policy.js.map +1 -0
  305. package/dist/response/profiles.cjs +69 -0
  306. package/dist/response/profiles.cjs.map +1 -0
  307. package/dist/response/profiles.js +65 -0
  308. package/dist/response/profiles.js.map +1 -0
  309. package/dist/response/proxy.cjs +71 -0
  310. package/dist/response/proxy.cjs.map +1 -0
  311. package/dist/response/proxy.js +70 -0
  312. package/dist/response/proxy.js.map +1 -0
  313. package/dist/response/raw.cjs +228 -0
  314. package/dist/response/raw.cjs.map +1 -0
  315. package/dist/response/raw.js +227 -0
  316. package/dist/response/raw.js.map +1 -0
  317. package/dist/response/timing.cjs +157 -0
  318. package/dist/response/timing.cjs.map +1 -0
  319. package/dist/response/timing.js +150 -0
  320. package/dist/response/timing.js.map +1 -0
  321. package/dist/response/usage/codecs/anthropic.cjs +52 -0
  322. package/dist/response/usage/codecs/anthropic.cjs.map +1 -0
  323. package/dist/response/usage/codecs/anthropic.js +50 -0
  324. package/dist/response/usage/codecs/anthropic.js.map +1 -0
  325. package/dist/response/usage/codecs/cohere.cjs +36 -0
  326. package/dist/response/usage/codecs/cohere.cjs.map +1 -0
  327. package/dist/response/usage/codecs/cohere.js +35 -0
  328. package/dist/response/usage/codecs/cohere.js.map +1 -0
  329. package/dist/response/usage/codecs/converse.cjs +16 -0
  330. package/dist/response/usage/codecs/converse.cjs.map +1 -0
  331. package/dist/response/usage/codecs/converse.js +15 -0
  332. package/dist/response/usage/codecs/converse.js.map +1 -0
  333. package/dist/response/usage/codecs/gemini.cjs +31 -0
  334. package/dist/response/usage/codecs/gemini.cjs.map +1 -0
  335. package/dist/response/usage/codecs/gemini.js +31 -0
  336. package/dist/response/usage/codecs/gemini.js.map +1 -0
  337. package/dist/response/usage/codecs/interactions.cjs +22 -0
  338. package/dist/response/usage/codecs/interactions.cjs.map +1 -0
  339. package/dist/response/usage/codecs/interactions.js +21 -0
  340. package/dist/response/usage/codecs/interactions.js.map +1 -0
  341. package/dist/response/usage/codecs/ollama.cjs +17 -0
  342. package/dist/response/usage/codecs/ollama.cjs.map +1 -0
  343. package/dist/response/usage/codecs/ollama.js +17 -0
  344. package/dist/response/usage/codecs/ollama.js.map +1 -0
  345. package/dist/response/usage/codecs/openai.cjs +52 -0
  346. package/dist/response/usage/codecs/openai.cjs.map +1 -0
  347. package/dist/response/usage/codecs/openai.js +50 -0
  348. package/dist/response/usage/codecs/openai.js.map +1 -0
  349. package/dist/response/usage/codecs/openrouter.cjs +68 -0
  350. package/dist/response/usage/codecs/openrouter.cjs.map +1 -0
  351. package/dist/response/usage/codecs/openrouter.js +67 -0
  352. package/dist/response/usage/codecs/openrouter.js.map +1 -0
  353. package/dist/response/usage/codecs/realtime.cjs +19 -0
  354. package/dist/response/usage/codecs/realtime.cjs.map +1 -0
  355. package/dist/response/usage/codecs/realtime.js +18 -0
  356. package/dist/response/usage/codecs/realtime.js.map +1 -0
  357. package/dist/response/usage/codecs/responses.cjs +21 -0
  358. package/dist/response/usage/codecs/responses.cjs.map +1 -0
  359. package/dist/response/usage/codecs/responses.js +20 -0
  360. package/dist/response/usage/codecs/responses.js.map +1 -0
  361. package/dist/response/usage/estimate.cjs +23 -0
  362. package/dist/response/usage/estimate.cjs.map +1 -0
  363. package/dist/response/usage/estimate.js +21 -0
  364. package/dist/response/usage/estimate.js.map +1 -0
  365. package/dist/response/usage/fields.cjs +72 -0
  366. package/dist/response/usage/fields.cjs.map +1 -0
  367. package/dist/response/usage/fields.js +70 -0
  368. package/dist/response/usage/fields.js.map +1 -0
  369. package/dist/response/usage/recording.cjs +52 -0
  370. package/dist/response/usage/recording.cjs.map +1 -0
  371. package/dist/response/usage/recording.js +52 -0
  372. package/dist/response/usage/recording.js.map +1 -0
  373. package/dist/responses.cjs +304 -196
  374. package/dist/responses.cjs.map +1 -1
  375. package/dist/responses.d.cts.map +1 -1
  376. package/dist/responses.d.ts.map +1 -1
  377. package/dist/responses.js +303 -195
  378. package/dist/responses.js.map +1 -1
  379. package/dist/route-registry.cjs +45 -0
  380. package/dist/route-registry.cjs.map +1 -1
  381. package/dist/route-registry.d.cts.map +1 -1
  382. package/dist/route-registry.d.ts.map +1 -1
  383. package/dist/route-registry.js +41 -1
  384. package/dist/route-registry.js.map +1 -1
  385. package/dist/router.cjs +24 -4
  386. package/dist/router.cjs.map +1 -1
  387. package/dist/router.d.cts +7 -1
  388. package/dist/router.d.cts.map +1 -1
  389. package/dist/router.d.ts +7 -1
  390. package/dist/router.d.ts.map +1 -1
  391. package/dist/router.js +24 -5
  392. package/dist/router.js.map +1 -1
  393. package/dist/search.cjs +13 -11
  394. package/dist/search.cjs.map +1 -1
  395. package/dist/search.js +12 -10
  396. package/dist/search.js.map +1 -1
  397. package/dist/server.cjs +293 -248
  398. package/dist/server.cjs.map +1 -1
  399. package/dist/server.d.cts.map +1 -1
  400. package/dist/server.d.ts.map +1 -1
  401. package/dist/server.js +294 -249
  402. package/dist/server.js.map +1 -1
  403. package/dist/speech.cjs +20 -18
  404. package/dist/speech.cjs.map +1 -1
  405. package/dist/speech.d.cts.map +1 -1
  406. package/dist/speech.d.ts.map +1 -1
  407. package/dist/speech.js +19 -17
  408. package/dist/speech.js.map +1 -1
  409. package/dist/sse-writer.cjs +56 -30
  410. package/dist/sse-writer.cjs.map +1 -1
  411. package/dist/sse-writer.d.cts +0 -1
  412. package/dist/sse-writer.d.cts.map +1 -1
  413. package/dist/sse-writer.d.ts +0 -1
  414. package/dist/sse-writer.d.ts.map +1 -1
  415. package/dist/sse-writer.js +55 -31
  416. package/dist/sse-writer.js.map +1 -1
  417. package/dist/stream-collapse.cjs +118 -11
  418. package/dist/stream-collapse.cjs.map +1 -1
  419. package/dist/stream-collapse.d.cts +10 -9
  420. package/dist/stream-collapse.d.cts.map +1 -1
  421. package/dist/stream-collapse.d.ts +10 -9
  422. package/dist/stream-collapse.d.ts.map +1 -1
  423. package/dist/stream-collapse.js +118 -11
  424. package/dist/stream-collapse.js.map +1 -1
  425. package/dist/transcription.cjs +31 -43
  426. package/dist/transcription.cjs.map +1 -1
  427. package/dist/transcription.d.cts.map +1 -1
  428. package/dist/transcription.d.ts.map +1 -1
  429. package/dist/transcription.js +31 -43
  430. package/dist/transcription.js.map +1 -1
  431. package/dist/types.cjs.map +1 -1
  432. package/dist/types.d.cts +231 -9
  433. package/dist/types.d.cts.map +1 -1
  434. package/dist/types.d.ts +231 -9
  435. package/dist/types.d.ts.map +1 -1
  436. package/dist/types.js.map +1 -1
  437. package/dist/vector-mock.cjs +3 -8
  438. package/dist/vector-mock.cjs.map +1 -1
  439. package/dist/vector-mock.d.cts.map +1 -1
  440. package/dist/vector-mock.d.ts.map +1 -1
  441. package/dist/vector-mock.js +3 -8
  442. package/dist/vector-mock.js.map +1 -1
  443. package/dist/vector-stores.cjs +2 -4
  444. package/dist/vector-stores.cjs.map +1 -1
  445. package/dist/vector-stores.d.cts.map +1 -1
  446. package/dist/vector-stores.d.ts.map +1 -1
  447. package/dist/vector-stores.js +2 -4
  448. package/dist/vector-stores.js.map +1 -1
  449. package/dist/veo-video.cjs +16 -14
  450. package/dist/veo-video.cjs.map +1 -1
  451. package/dist/veo-video.js +10 -8
  452. package/dist/veo-video.js.map +1 -1
  453. package/dist/video.cjs +21 -19
  454. package/dist/video.cjs.map +1 -1
  455. package/dist/video.d.cts.map +1 -1
  456. package/dist/video.d.ts.map +1 -1
  457. package/dist/video.js +20 -18
  458. package/dist/video.js.map +1 -1
  459. package/dist/ws-framing.cjs +12 -6
  460. package/dist/ws-framing.cjs.map +1 -1
  461. package/dist/ws-framing.d.cts +2 -0
  462. package/dist/ws-framing.d.cts.map +1 -1
  463. package/dist/ws-framing.d.ts +2 -0
  464. package/dist/ws-framing.d.ts.map +1 -1
  465. package/dist/ws-framing.js +12 -6
  466. package/dist/ws-framing.js.map +1 -1
  467. package/dist/ws-gemini-live.cjs +131 -96
  468. package/dist/ws-gemini-live.cjs.map +1 -1
  469. package/dist/ws-gemini-live.d.cts +0 -1
  470. package/dist/ws-gemini-live.d.cts.map +1 -1
  471. package/dist/ws-gemini-live.d.ts +0 -1
  472. package/dist/ws-gemini-live.d.ts.map +1 -1
  473. package/dist/ws-gemini-live.js +130 -95
  474. package/dist/ws-gemini-live.js.map +1 -1
  475. package/dist/ws-live.cjs +6 -5
  476. package/dist/ws-live.cjs.map +1 -1
  477. package/dist/ws-live.js +5 -4
  478. package/dist/ws-live.js.map +1 -1
  479. package/dist/ws-realtime.cjs +108 -124
  480. package/dist/ws-realtime.cjs.map +1 -1
  481. package/dist/ws-realtime.d.cts.map +1 -1
  482. package/dist/ws-realtime.d.ts.map +1 -1
  483. package/dist/ws-realtime.js +105 -121
  484. package/dist/ws-realtime.js.map +1 -1
  485. package/dist/ws-responses.cjs +80 -59
  486. package/dist/ws-responses.cjs.map +1 -1
  487. package/dist/ws-responses.d.cts.map +1 -1
  488. package/dist/ws-responses.d.ts.map +1 -1
  489. package/dist/ws-responses.js +79 -58
  490. package/dist/ws-responses.js.map +1 -1
  491. package/package.json +4 -1
  492. package/skills/write-fixtures/SKILL.md +57 -16
@@ -1 +1 @@
1
- {"version":3,"file":"images.js","names":[],"sources":["../src/images.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordProviderKey,\n} from \"./types.js\";\nimport {\n isImageResponse,\n isErrorResponse,\n isJsonObject,\n serializeErrorResponse,\n flattenHeaders,\n getContext,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport { extractBoundary, extractFormField } from \"./transcription.js\";\n\n/**\n * Model used for fixture matching when the caller sends no `model`.\n *\n * `dall-e-2`/`dall-e-3` were removed from the OpenAI API on 2026-05-12;\n * `gpt-image-1` is OpenAI's documented replacement for both. A request that\n * names a model still has that model echoed through unchanged.\n */\nconst DEFAULT_IMAGE_MODEL = \"gpt-image-1\";\n\ninterface OpenAIImageRequest {\n model?: string;\n prompt: string;\n n?: number;\n size?: string;\n response_format?: \"url\" | \"b64_json\";\n [key: string]: unknown;\n}\n\ninterface GeminiPredictRequest {\n instances: Array<{ prompt: string }>;\n parameters?: { sampleCount?: number };\n [key: string]: unknown;\n}\n\nfunction buildSyntheticRequest(\n model: string,\n prompt: string,\n context?: string,\n): ChatCompletionRequest {\n return {\n model,\n messages: [{ role: \"user\", content: prompt }],\n _endpointType: \"image\",\n ...(context !== undefined && { _context: context }),\n };\n}\n\nexport async function handleImages(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n format: \"openai\" | \"gemini\" = \"openai\",\n geminiModel?: string,\n /**\n * Provider key this request records under. Defaults to `\"openai\"` — the\n * value hardcoded here before BytePlus Ark needed images attribution — so the\n * Gemini `:predict` call site keeps today's behavior by omitting it. Only the\n * OpenAI-images call site passes it, and only with a non-default value behind\n * server.ts's configuration gate (a byteplus upstream must be configured AND\n * the request must carry the /api/v3 prefix).\n */\n recordProviderKey?: RecordProviderKey,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/images/generations\";\n const method = req.method ?? \"POST\";\n\n let model: string;\n let prompt: string;\n\n let body: unknown;\n try {\n body = JSON.parse(raw);\n // Reject bodies that parsed but are not a JSON object (e.g. `null`) before\n // touching fields — without this the TypeError below lands in the\n // malformed-JSON branch with a misleading message.\n if (!isJsonObject(body)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n if (format === \"gemini\") {\n const geminiReq = body as GeminiPredictRequest;\n prompt = geminiReq.instances?.[0]?.prompt ?? \"\";\n model = geminiModel ?? \"imagen\";\n } else {\n const openaiReq = body as OpenAIImageRequest;\n prompt = openaiReq.prompt ?? \"\";\n model = openaiReq.model ?? DEFAULT_IMAGE_MODEL;\n }\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n },\n }),\n );\n return;\n }\n\n const promptValue: unknown = prompt;\n if (\n !promptValue ||\n (typeof promptValue !== \"string\" &&\n !(\n Array.isArray(promptValue) &&\n promptValue.length > 0 &&\n promptValue.every(\n (part: unknown) =>\n isJsonObject(part) &&\n typeof part.type === \"string\" &&\n (part.text === undefined || typeof part.text === \"string\"),\n )\n ))\n ) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: !prompt\n ? \"Missing required parameter: 'prompt'\"\n : \"Invalid parameter: 'prompt' must be a string or non-empty content-parts array\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const syntheticReq = buildSyntheticRequest(model, prompt, getContext(req));\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n format === \"gemini\" ? \"gemini\" : (recordProviderKey ?? \"openai\"),\n req.url ?? \"/v1/images/generations\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isImageResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response is not an image type\", type: \"server_error\" },\n }),\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n // Normalize to array of image items\n const items = response.images ?? (response.image ? [response.image] : []);\n\n if (format === \"gemini\") {\n const predictions = items.map((item) => ({\n bytesBase64Encoded: item.b64Json ?? \"\",\n mimeType: \"image/png\" as const,\n }));\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ predictions }));\n } else {\n serializeOpenAIImageResponse(res, items);\n }\n}\n\n/**\n * Write the standard OpenAI image response envelope (`{ created, data }`).\n * Shared by generations, edit, and variations endpoints.\n */\nfunction serializeOpenAIImageResponse(\n res: http.ServerResponse,\n items: Array<{ url?: string; b64Json?: string; revisedPrompt?: string }>,\n): void {\n const data = items.map((item) => {\n const entry: Record<string, string> = {};\n if (item.url) entry.url = item.url;\n if (item.b64Json) entry.b64_json = item.b64Json;\n if (item.revisedPrompt) entry.revised_prompt = item.revisedPrompt;\n return entry;\n });\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ created: Math.floor(Date.now() / 1000), data }));\n}\n\n/**\n * Handle POST /v1/images/edits — OpenAI Image Edit API.\n *\n * Request uses multipart/form-data. We extract text fields (`prompt`, `model`,\n * `n`, `size`, `response_format`) and ignore binary fields (`image`, `mask`)\n * since aimock doesn't process actual image data.\n *\n * The response envelope is identical to /v1/images/generations.\n */\nexport async function handleImageEdit(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/images/edits\";\n const method = req.method ?? \"POST\";\n\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n const boundary = extractBoundary(contentType);\n\n const prompt = extractFormField(raw, \"prompt\", boundary) ?? \"\";\n const model = extractFormField(raw, \"model\", boundary) ?? DEFAULT_IMAGE_MODEL;\n\n if (!prompt) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: { message: \"Missing required parameter: 'prompt'\", type: \"invalid_request_error\" },\n }),\n );\n return;\n }\n\n const syntheticReq = buildSyntheticRequest(model, prompt, getContext(req));\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"openai\",\n req.url ?? \"/v1/images/edits\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isImageResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: { message: \"Fixture response is not an image type\", type: \"server_error\" },\n }),\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const items = response.images ?? (response.image ? [response.image] : []);\n serializeOpenAIImageResponse(res, items);\n}\n\n/**\n * Handle POST /v1/images/variations — REMOVED upstream.\n *\n * `/v1/images/variations` only ever served `dall-e-2`. OpenAI removed\n * `dall-e-2` on 2026-05-12 and removed the endpoint with it: the path no\n * longer routes at all. Per aimock's deprecation policy\n * (https://aimock.copilotkit.dev/deprecation-policy/) a removed upstream\n * surface is mocked as REMOVED — aimock replays the rejection the real API\n * returns today, so the removal surfaces in the caller's tests instead of in\n * production. The route stays registered on purpose: it is the thing that\n * makes the removal explicit (and journaled) rather than silently falling\n * through to aimock's generic unknown-path 404, which carries a different body.\n *\n * Wire behaviour observed firsthand against `https://api.openai.com` on\n * 2026-09-15, both KEYLESS and with a live key, POST and OPTIONS:\n *\n * HTTP/2 404\n * server: cloudflare\n * (zero-byte body, NO content-type, NO openai-version/x-request-id header)\n *\n * The 404 lands at the edge BEFORE authentication — a keyless request to\n * `/v1/images/variations` 404s while a keyless `/v1/images/generations` 401s —\n * and is byte-for-byte what a made-up path (`/v1/images/bogus`) returns. So\n * this is a removed ENDPOINT, not a live endpoint rejecting a dead model:\n * there is no JSON error envelope to replay, because the real API sends none.\n *\n * The `model` form field is irrelevant upstream (the request never reaches\n * model validation), so it is irrelevant here too.\n *\n * aimock's own CORS headers are still set — unlike the CDN 404, which carries\n * none — so a browser-based caller sees the 404 rather than a CORS failure\n * masking it. Status, empty body and absent `Content-Type` are the observed\n * values; the CORS headers are aimock's, and are the one deliberate departure.\n */\nexport function handleImageVariations(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n void raw;\n void fixtures;\n setCorsHeaders(res);\n\n defaults.logger.warn(\n `POST /v1/images/variations is removed upstream (the endpoint 404s at api.openai.com; it only ever served dall-e-2, removed 2026-05-12) — replaying the real 404. See https://aimock.copilotkit.dev/deprecation-policy/`,\n );\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/images/variations\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 404, fixture: null, source: \"internal\" },\n });\n\n // Written raw, NOT through writeErrorResponse(): the real API sends a\n // zero-byte body with no Content-Type, and writeErrorResponse() would\n // force `Content-Type: application/json` and a JSON envelope.\n res.writeHead(404);\n res.end();\n return Promise.resolve();\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmCA,MAAM,sBAAsB;AAiB5B,SAAS,sBACP,OACA,QACA,SACuB;AACvB,QAAO;EACL;EACA,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS;GAAQ,CAAC;EAC7C,eAAe;EACf,GAAI,YAAY,UAAa,EAAE,UAAU,SAAS;EACnD;;AAGH,eAAsB,aACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,SAA8B,UAC9B,aASA,mBACe;AACf,gBAAe,IAAI;CACnB,MAAM,OAAO,IAAI,OAAO;CACxB,MAAM,SAAS,IAAI,UAAU;CAE7B,IAAI;CACJ,IAAI;CAEJ,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,MAAM,IAAI;AAItB,MAAI,CAAC,aAAa,KAAK,EAAE;AACvB,WAAQ,IAAI;IACV;IACA;IACA,SAAS,eAAe,IAAI,QAAQ;IACpC,MAAM;IACN,UAAU;KAAE,QAAQ;KAAK,SAAS;KAAM;IACzC,CAAC;AACF,sBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;IACL,SAAS;IACT,MAAM;IACP,EACF,CAAC,CACH;AACD;;AAEF,MAAI,WAAW,UAAU;AAEvB,YADkB,KACC,YAAY,IAAI,UAAU;AAC7C,WAAQ,eAAe;SAClB;GACL,MAAM,YAAY;AAClB,YAAS,UAAU,UAAU;AAC7B,WAAQ,UAAU,SAAS;;UAEtB,UAAU;EACjB,MAAM,SAAS,oBAAoB,QAAQ,SAAS,UAAU;AAC9D,UAAQ,IAAI;GACV;GACA;GACA,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK,SAAS;IAAM;GACzC,CAAC;AACF,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS,mBAAmB;GAC5B,MAAM;GACN,MA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F,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GAAE,SAAS;GAAyC,MAAM;GAAgB,EAClF,CAAC,CACH;AACD;;AAGF,SAAQ,IAAI;EACV;EACA;EACA,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK;GAAS;EACnC,CAAC;AAGF,8BAA6B,KADf,SAAS,WAAW,SAAS,QAAQ,CAAC,SAAS,MAAM,GAAG,EAAE,EAChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqC1C,SAAgB,sBACd,KACA,KACA,KACA,UACA,SACA,UACA,gBACe;AAGf,gBAAe,IAAI;AAEnB,UAAS,OAAO,KACd,yNACD;AAED,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM,QAAQ;GAAY;EAC7D,CAAC;AAKF,KAAI,UAAU,IAAI;AAClB,KAAI,KAAK;AACT,QAAO,QAAQ,SAAS"}
1
+ {"version":3,"file":"images.js","names":[],"sources":["../src/images.ts"],"sourcesContent":["import { renderError } from \"./response/errors.js\";\nimport { resolveRequestDecisions, strictOverrideField } from \"./response/policy.js\";\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n HandlerDefaults,\n RecordProviderKey,\n} from \"./types.js\";\nimport {\n isImageResponse,\n isErrorResponse,\n isJsonObject,\n flattenHeaders,\n getContext,\n getTestId,\n resolveResponse,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport { extractBoundary, extractFormField } from \"./transcription.js\";\n\n/**\n * Model used for fixture matching when the caller sends no `model`.\n *\n * `dall-e-2`/`dall-e-3` were removed from the OpenAI API on 2026-05-12;\n * `gpt-image-1` is OpenAI's documented replacement for both. A request that\n * names a model still has that model echoed through unchanged.\n */\nconst DEFAULT_IMAGE_MODEL = \"gpt-image-1\";\n\ninterface OpenAIImageRequest {\n model?: string;\n prompt: string;\n n?: number;\n size?: string;\n response_format?: \"url\" | \"b64_json\";\n [key: string]: unknown;\n}\n\ninterface GeminiPredictRequest {\n instances: Array<{ prompt: string }>;\n parameters?: { sampleCount?: number };\n [key: string]: unknown;\n}\n\nfunction buildSyntheticRequest(\n model: string,\n prompt: string,\n context?: string,\n): ChatCompletionRequest {\n return {\n model,\n messages: [{ role: \"user\", content: prompt }],\n _endpointType: \"image\",\n ...(context !== undefined && { _context: context }),\n };\n}\n\nexport async function handleImages(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n format: \"openai\" | \"gemini\" = \"openai\",\n geminiModel?: string,\n /**\n * Provider key this request records under. Defaults to `\"openai\"` — the\n * value hardcoded here before BytePlus Ark needed images attribution — so the\n * Gemini `:predict` call site keeps today's behavior by omitting it. Only the\n * OpenAI-images call site passes it, and only with a non-default value behind\n * server.ts's configuration gate (a byteplus upstream must be configured AND\n * the request must carry the /api/v3 prefix).\n */\n recordProviderKey?: RecordProviderKey,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/images/generations\";\n const method = req.method ?? \"POST\";\n\n let model: string;\n let prompt: string;\n\n let body: unknown;\n try {\n body = JSON.parse(raw);\n // Reject bodies that parsed but are not a JSON object (e.g. `null`) before\n // touching fields — without this the TypeError below lands in the\n // malformed-JSON branch with a misleading message.\n if (!isJsonObject(body)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"openai\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n if (format === \"gemini\") {\n const geminiReq = body as GeminiPredictRequest;\n prompt = geminiReq.instances?.[0]?.prompt ?? \"\";\n model = geminiModel ?? \"imagen\";\n } else {\n const openaiReq = body as OpenAIImageRequest;\n prompt = openaiReq.prompt ?? \"\";\n model = openaiReq.model ?? DEFAULT_IMAGE_MODEL;\n }\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"openai\", \"validation\", {\n message: `Malformed JSON: ${detail}`,\n type: \"invalid_request_error\",\n code: \"invalid_json\",\n }).body,\n );\n return;\n }\n\n const promptValue: unknown = prompt;\n if (\n !promptValue ||\n (typeof promptValue !== \"string\" &&\n !(\n Array.isArray(promptValue) &&\n promptValue.length > 0 &&\n promptValue.every(\n (part: unknown) =>\n isJsonObject(part) &&\n typeof part.type === \"string\" &&\n (part.text === undefined || typeof part.text === \"string\"),\n )\n ))\n ) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"openai\", \"validation\", {\n message: !prompt\n ? \"Missing required parameter: 'prompt'\"\n : \"Invalid parameter: 'prompt' must be a string or non-empty content-parts array\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n const syntheticReq = buildSyntheticRequest(model, prompt, getContext(req));\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss;\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n renderError(\"openai\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n format === \"gemini\" ? \"gemini\" : (recordProviderKey ?? \"openai\"),\n req.url ?? \"/v1/images/generations\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n renderError(\"openai\", \"fixture-miss\", {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, renderError(\"openai\", \"fixture\", response.error).body, {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isImageResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n renderError(\"openai\", \"unknown-response\", {\n message: \"Fixture response is not an image type\",\n type: \"server_error\",\n }).body,\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n // Normalize to array of image items\n const items = response.images ?? (response.image ? [response.image] : []);\n\n if (format === \"gemini\") {\n const predictions = items.map((item) => ({\n bytesBase64Encoded: item.b64Json ?? \"\",\n mimeType: \"image/png\" as const,\n }));\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ predictions }));\n } else {\n serializeOpenAIImageResponse(res, items);\n }\n}\n\n/**\n * Write the standard OpenAI image response envelope (`{ created, data }`).\n * Shared by generations, edit, and variations endpoints.\n */\nfunction serializeOpenAIImageResponse(\n res: http.ServerResponse,\n items: Array<{ url?: string; b64Json?: string; revisedPrompt?: string }>,\n): void {\n const data = items.map((item) => {\n const entry: Record<string, string> = {};\n if (item.url) entry.url = item.url;\n if (item.b64Json) entry.b64_json = item.b64Json;\n if (item.revisedPrompt) entry.revised_prompt = item.revisedPrompt;\n return entry;\n });\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ created: Math.floor(Date.now() / 1000), data }));\n}\n\n/**\n * Handle POST /v1/images/edits — OpenAI Image Edit API.\n *\n * Request uses multipart/form-data. We extract text fields (`prompt`, `model`,\n * `n`, `size`, `response_format`) and ignore binary fields (`image`, `mask`)\n * since aimock doesn't process actual image data.\n *\n * The response envelope is identical to /v1/images/generations.\n */\nexport async function handleImageEdit(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n setCorsHeaders(res);\n const path = req.url ?? \"/v1/images/edits\";\n const method = req.method ?? \"POST\";\n\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n const boundary = extractBoundary(contentType);\n\n const prompt = extractFormField(raw, \"prompt\", boundary) ?? \"\";\n const model = extractFormField(raw, \"model\", boundary) ?? DEFAULT_IMAGE_MODEL;\n\n if (!prompt) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"openai\", \"validation\", {\n message: \"Missing required parameter: 'prompt'\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n const syntheticReq = buildSyntheticRequest(model, prompt, getContext(req));\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss;\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n renderError(\"openai\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"openai\",\n req.url ?? \"/v1/images/edits\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n renderError(\"openai\", \"fixture-miss\", {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n }).body,\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, renderError(\"openai\", \"fixture\", response.error).body, {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isImageResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n renderError(\"openai\", \"unknown-response\", {\n message: \"Fixture response is not an image type\",\n type: \"server_error\",\n }).body,\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const items = response.images ?? (response.image ? [response.image] : []);\n serializeOpenAIImageResponse(res, items);\n}\n\n/**\n * Handle POST /v1/images/variations — REMOVED upstream.\n *\n * `/v1/images/variations` only ever served `dall-e-2`. OpenAI removed\n * `dall-e-2` on 2026-05-12 and removed the endpoint with it: the path no\n * longer routes at all. Per aimock's deprecation policy\n * (https://aimock.copilotkit.dev/deprecation-policy/) a removed upstream\n * surface is mocked as REMOVED — aimock replays the rejection the real API\n * returns today, so the removal surfaces in the caller's tests instead of in\n * production. The route stays registered on purpose: it is the thing that\n * makes the removal explicit (and journaled) rather than silently falling\n * through to aimock's generic unknown-path 404, which carries a different body.\n *\n * Wire behaviour observed firsthand against `https://api.openai.com` on\n * 2026-09-15, both KEYLESS and with a live key, POST and OPTIONS:\n *\n * HTTP/2 404\n * server: cloudflare\n * (zero-byte body, NO content-type, NO openai-version/x-request-id header)\n *\n * The 404 lands at the edge BEFORE authentication — a keyless request to\n * `/v1/images/variations` 404s while a keyless `/v1/images/generations` 401s —\n * and is byte-for-byte what a made-up path (`/v1/images/bogus`) returns. So\n * this is a removed ENDPOINT, not a live endpoint rejecting a dead model:\n * there is no JSON error envelope to replay, because the real API sends none.\n *\n * The `model` form field is irrelevant upstream (the request never reaches\n * model validation), so it is irrelevant here too.\n *\n * aimock's own CORS headers are still set — unlike the CDN 404, which carries\n * none — so a browser-based caller sees the 404 rather than a CORS failure\n * masking it. Status, empty body and absent `Content-Type` are the observed\n * values; the CORS headers are aimock's, and are the one deliberate departure.\n */\nexport function handleImageVariations(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n void raw;\n void fixtures;\n setCorsHeaders(res);\n\n defaults.logger.warn(\n `POST /v1/images/variations is removed upstream (the endpoint 404s at api.openai.com; it only ever served dall-e-2, removed 2026-05-12) — replaying the real 404. See https://aimock.copilotkit.dev/deprecation-policy/`,\n );\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v1/images/variations\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 404, fixture: null, source: \"internal\" },\n });\n\n // Written raw, NOT through writeErrorResponse(): the real API sends a\n // zero-byte body with no Content-Type, and writeErrorResponse() would\n // force `Content-Type: application/json` and a JSON envelope.\n res.writeHead(404);\n res.end();\n return Promise.resolve();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCA,MAAM,sBAAsB;AAiB5B,SAAS,sBACP,OACA,QACA,SACuB;AACvB,QAAO;EACL;EACA,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS;GAAQ,CAAC;EAC7C,eAAe;EACf,GAAI,YAAY,UAAa,EAAE,UAAU,SAAS;EACnD;;AAGH,eAAsB,aACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,SAA8B,UAC9B,aASA,mBACe;AACf,gBAAe,IAAI;CACnB,MAAM,OAAO,IAAI,OAAO;CACxB,MAAM,SAAS,IAAI,UAAU;CAE7B,IAAI;CACJ,IAAI;CAEJ,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,MAAM,IAAI;AAItB,MAAI,CAAC,aAAa,KAAK,EAAE;AACvB,WAAQ,IAAI;IACV;IACA;IACA,SAAS,eAAe,IAAI,QAAQ;IACpC,MAAM;IACN,UAAU;KAAE,QAAQ;KAAK,SAAS;KAAM;IACzC,CAAC;AACF,sBACE,KACA,KACA,YAAY,UAAU,cAAc;IAClC,SAAS;IACT,MAAM;IACP,CAAC,CAAC,KACJ;AACD;;AAEF,MAAI,WAAW,UAAU;AAEvB,YADkB,KACC,YAAY,IAAI,UAAU;AAC7C,WAAQ,eAAe;SAClB;GACL,MAAM,YAAY;AAClB,YAAS,UAAU,UAAU;AAC7B,WAAQ,UAAU,SAAS;;UAEtB,UAAU;EACjB,MAAM,SAAS,oBAAoB,QAAQ,SAAS,UAAU;AAC9D,UAAQ,IAAI;GACV;GACA;GACA,SAAS,eAAe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AM,EACrF,YAAY,SAAS,YACtB,CAAC;AACF;;AAGF,KAAI,CAAC,gBAAgB,SAAS,EAAE;AAC9B,UAAQ,IAAI;GACV;GACA;GACA,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK;IAAS;GACnC,CAAC;AACF,qBACE,KACA,KACA,YAAY,UAAU,oBAAoB;GACxC,SAAS;GACT,MAAM;GACP,CAAC,CAAC,KACJ;AACD;;AAGF,SAAQ,IAAI;EACV;EACA;EACA,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK;GAAS;EACnC,CAAC;AAGF,8BAA6B,KADf,SAAS,WAAW,SAAS,QAAQ,CAAC,SAAS,MAAM,GAAG,EAAE,EAChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqC1C,SAAgB,sBACd,KACA,KACA,KACA,UACA,SACA,UACA,gBACe;AAGf,gBAAe,IAAI;AAEnB,UAAS,OAAO,KACd,yNACD;AAED,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM,QAAQ;GAAY;EAC7D,CAAC;AAKF,KAAI,UAAU,IAAI;AAClB,KAAI,KAAK;AACT,QAAO,QAAQ,SAAS"}
package/dist/index.cjs CHANGED
@@ -16,10 +16,11 @@ const require_logger = require('./logger.cjs');
16
16
  const require_agui_mock = require('./agui-mock.cjs');
17
17
  const require_journal = require('./journal.cjs');
18
18
  const require_interruption = require('./interruption.cjs');
19
+ const require_aws_event_stream = require('./aws-event-stream.cjs');
20
+ const require_ndjson_writer = require('./ndjson-writer.cjs');
19
21
  const require_responses = require('./responses.cjs');
20
22
  const require_messages = require('./messages.cjs');
21
23
  const require_gemini = require('./gemini.cjs');
22
- const require_aws_event_stream = require('./aws-event-stream.cjs');
23
24
  const require_bedrock = require('./bedrock.cjs');
24
25
  const require_bedrock_converse = require('./bedrock-converse.cjs');
25
26
  const require_gemini_interactions = require('./gemini-interactions.cjs');
@@ -36,7 +37,6 @@ const require_grok_video = require('./grok-video.cjs');
36
37
  const require_byteplus_video = require('./byteplus-video.cjs');
37
38
  const require_elevenlabs_audio = require('./elevenlabs-audio.cjs');
38
39
  const require_elevenlabs_voice = require('./elevenlabs-voice.cjs');
39
- const require_ndjson_writer = require('./ndjson-writer.cjs');
40
40
  const require_ollama = require('./ollama.cjs');
41
41
  const require_cohere = require('./cohere.cjs');
42
42
  const require_search = require('./search.cjs');
@@ -80,6 +80,7 @@ exports.FalQueueStateMap = require_fal.FalQueueStateMap;
80
80
  exports.FixtureLoadError = require_fixture_loader.FixtureLoadError;
81
81
  exports.GROK_VIDEO_MAX_ENTRIES = require_grok_video.GROK_VIDEO_MAX_ENTRIES;
82
82
  exports.GrokVideoJobMap = require_grok_video.GrokVideoJobMap;
83
+ exports.InvalidFixtureOutputError = require_helpers.InvalidFixtureOutputError;
83
84
  exports.InvalidFixtureToolCallError = require_helpers.InvalidFixtureToolCallError;
84
85
  exports.Journal = require_journal.Journal;
85
86
  exports.LLMock = require_llmock.LLMock;
@@ -93,6 +94,7 @@ exports.OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES = require_openrouter_video.OP
93
94
  exports.OPENROUTER_VIDEO_MAX_ENTRIES = require_openrouter_video.OPENROUTER_VIDEO_MAX_ENTRIES;
94
95
  exports.OpenRouterVideoJobMap = require_openrouter_video.OpenRouterVideoJobMap;
95
96
  exports.ROUTE_DEFINITIONS = require_route_registry.ROUTE_DEFINITIONS;
97
+ exports.UnsupportedGeneratedFileError = require_helpers.UnsupportedGeneratedFileError;
96
98
  exports.UnsupportedToolCallError = require_helpers.UnsupportedToolCallError;
97
99
  exports.VEO_VIDEO_MAX_ENTRIES = require_veo_video.VEO_VIDEO_MAX_ENTRIES;
98
100
  exports.VectorMock = require_vector_mock.VectorMock;
package/dist/index.d.cts CHANGED
@@ -7,7 +7,7 @@ import { ROUTE_DEFINITIONS, RouteDefinition } from "./route-registry.cjs";
7
7
  import { MetricsRegistry, createMetricsRegistry, normalizePathLabel } from "./metrics.cjs";
8
8
  import { FixtureLoadError, FixtureLoadErrorJSON, MisbehaviorConfigError, MisbehaviorConfigErrorJSON, ValidationRef, ValidationResult, loadFixtureFile, loadFixturesFromDir, normalizeResponse, renderValidationRef, validateFixtures } from "./fixture-loader.cjs";
9
9
  import { McpFakeAddOrigin, McpFakeAddResult, McpFakeBlockSnapshot, McpFakeDeclaredEntry, McpFakeIssue, McpFakeReportEvent, McpFakeReportPart, McpFakesAddError, McpFakesAddErrorJSON, RecordReplayLoadRule } from "./mcp-fakes.cjs";
10
- import { ApiKeyAuthConfig, AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, CustomToolCall, CustomToolCallMessage, CustomToolDefinition, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureFile, FixtureFileContentWithToolCallsResponse, FixtureFileCustomToolCall, FixtureFileEntry, FixtureFileResponse, FixtureFileResponsesBlock, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, FixtureToolCall, ImageItem, ImageResponse, JournalBody, JournalEntry, MCP_FAKE_ERROR_CODES, McpFakeAnnotations, McpFakeBlock, McpFakeCall, McpFakeCallAnswer, McpFakeCallMatch, McpFakeContentBlock, McpFakeDeepReadonly, McpFakeErrorCode, McpFakeFullResult, McpFakeIcon, McpFakeIdentity, McpFakeNotification, McpFakeOutcome, McpFakeRecorded, McpFakeResourceContents, McpFakeResult, McpFakeScope, McpFakeSource, McpFakeStructuredResult, McpFakeTool, McpFakeUndeclaredPolicy, McpRecordConfig, MisbehaviorConfig, MisbehaviorFault, MisbehaviorFaultId, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, ResponseOverrides, ResponsesFixtureBlock, ResponsesToolsMode, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse, VoiceDesignPreview, VoiceDesignResponse } from "./types.cjs";
10
+ import { AimockPolicy, ApiKeyAuthConfig, AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionAnnotation, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, CustomToolCall, CustomToolCallMessage, CustomToolDefinition, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureCitation, FixtureFile, FixtureFileCitation, FixtureFileContentWithToolCallsResponse, FixtureFileCustomToolCall, FixtureFileEntry, FixtureFileResponse, FixtureFileResponsesBlock, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureGeneratedFile, FixtureMatch, FixtureOpts, FixtureResponse, FixtureToolCall, FixtureUrlCitation, ImageItem, ImageResponse, JournalBody, JournalEntry, MCP_FAKE_ERROR_CODES, McpFakeAnnotations, McpFakeBlock, McpFakeCall, McpFakeCallAnswer, McpFakeCallMatch, McpFakeContentBlock, McpFakeDeepReadonly, McpFakeErrorCode, McpFakeFullResult, McpFakeIcon, McpFakeIdentity, McpFakeNotification, McpFakeOutcome, McpFakeRecorded, McpFakeResourceContents, McpFakeResult, McpFakeScope, McpFakeSource, McpFakeStructuredResult, McpFakeTool, McpFakeUndeclaredPolicy, McpRecordConfig, MisbehaviorConfig, MisbehaviorFault, MisbehaviorFaultId, MockServerOptions, Mountable, RawJSONResponse, RawResponse, RawWireId, RecordConfig, RecordProviderKey, ResponseOverrides, ResponsesFixtureBlock, ResponsesToolsMode, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse, VoiceDesignPreview, VoiceDesignResponse, WireId } from "./types.cjs";
11
11
  import { A2AAgentDefinition, A2AArtifact, A2AMessage, A2AMockOptions, A2APart, A2ARole, A2AStreamEvent, A2ATask, A2ATaskResponse, A2ATaskState } from "./a2a-types.cjs";
12
12
  import { A2AMock } from "./a2a-mock.cjs";
13
13
  import { AGUIActivityDeltaEvent, AGUIActivitySnapshotEvent, AGUIBaseEvent, AGUICustomEvent, AGUIEvent, AGUIEventType, AGUIFixture, AGUIFixtureMatch, AGUIInterrupt, AGUIMessage, AGUIMessageContentPart, AGUIMessageRole, AGUIMessagesSnapshotEvent, AGUIMockOptions, AGUIRawEvent, AGUIReasoningEncryptedValueEvent, AGUIReasoningEncryptedValueSubtype, AGUIReasoningEndEvent, AGUIReasoningMessageChunkEvent, AGUIReasoningMessageContentEvent, AGUIReasoningMessageEndEvent, AGUIReasoningMessageStartEvent, AGUIReasoningStartEvent, AGUIRecordConfig, AGUIResumeEntry, AGUIRunAgentInput, AGUIRunErrorEvent, AGUIRunFinishedEvent, AGUIRunFinishedOutcome, AGUIRunStartedEvent, AGUIStateDeltaEvent, AGUIStateSnapshotEvent, AGUIStepFinishedEvent, AGUIStepStartedEvent, AGUISubagentErrorEvent, AGUISubagentFinishedEvent, AGUISubagentFinishedOutcome, AGUISubagentStartedEvent, AGUITextMessageChunkEvent, AGUITextMessageContentEvent, AGUITextMessageEndEvent, AGUITextMessageRole, AGUITextMessageStartEvent, AGUIThinkingEndEvent, AGUIThinkingStartEvent, AGUIThinkingTextMessageContentEvent, AGUIThinkingTextMessageEndEvent, AGUIThinkingTextMessageStartEvent, AGUITokenUsage, AGUIToolCall, AGUIToolCallArgsEvent, AGUIToolCallChunkEvent, AGUIToolCallEndEvent, AGUIToolCallResultEvent, AGUIToolCallStartEvent, AGUIToolDefinition } from "./agui-types.cjs";
@@ -36,6 +36,7 @@ import { handleEmbeddings } from "./embeddings.cjs";
36
36
  import { bedrockToCompletionRequest, handleBedrock, handleBedrockStream } from "./bedrock.cjs";
37
37
  import { converseToCompletionRequest, handleConverse, handleConverseStream } from "./bedrock-converse.cjs";
38
38
  import { geminiInteractionsToCompletionRequest, handleGeminiInteractions } from "./gemini-interactions.cjs";
39
+ import { WebSocketConnection, WebSocketLimits, computeAcceptKey, upgradeToWebSocket } from "./ws-framing.cjs";
39
40
  import { encodeEventStreamFrame, encodeEventStreamMessage, writeEventStream } from "./aws-event-stream.cjs";
40
41
  import { NDJSONStreamOptions, writeNDJSONStream } from "./ndjson-writer.cjs";
41
42
  import { handleOllama, handleOllamaGenerate, ollamaToCompletionRequest } from "./ollama.cjs";
@@ -45,7 +46,6 @@ import { BatchObject, clearBatchStore, handleBatchesCancel, handleBatchesCreate,
45
46
  import { FileObject, clearFileStore, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve } from "./files.cjs";
46
47
  import { FineTuningJob, FineTuningJobError, FineTuningJobEvent, FineTuningJobHyperparameters, FineTuningJobStatus, clearFineTuningStore, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve } from "./fine-tuning.cjs";
47
48
  import { VectorFileBatchObject, VectorFileBatchStatus, VectorSearchResult, VectorStoreFileObject, VectorStoreFileStatus, VectorStoreObject, VectorStoreStatus, clearVectorStoreStore, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch } from "./vector-stores.cjs";
48
- import { WebSocketConnection, WebSocketLimits, computeAcceptKey, upgradeToWebSocket } from "./ws-framing.cjs";
49
49
  import { handleWebSocketResponses } from "./ws-responses.cjs";
50
50
  import { handleWebSocketRealtime } from "./ws-realtime.cjs";
51
51
  import { handleWebSocketGeminiLive } from "./ws-gemini-live.cjs";
@@ -56,7 +56,7 @@ import { handleElevenLabsAudio } from "./elevenlabs-audio.cjs";
56
56
  import { clearElevenLabsVoices, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, voiceDesignToJson } from "./elevenlabs-voice.cjs";
57
57
  import { handleFalQueue } from "./fal-audio.cjs";
58
58
  import { FalQueueStateMap, handleFal } from "./fal.cjs";
59
- import { EmbeddingAPIResponse, FORMAT_TO_CONTENT_TYPE, FunctionFixtureBlock, InvalidFixtureToolCallError, UnsupportedToolCallError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, requireFunctionToolCalls, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, strictNoMatchLogLine, strictNoMatchMessage } from "./helpers.cjs";
59
+ import { EmbeddingAPIResponse, FORMAT_TO_CONTENT_TYPE, FunctionFixtureBlock, InvalidFixtureOutputError, InvalidFixtureToolCallError, UnsupportedGeneratedFileError, UnsupportedToolCallError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, requireFunctionToolCalls, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, strictNoMatchLogLine, strictNoMatchMessage } from "./helpers.cjs";
60
60
  import { InterruptionControl, createInterruptionSignal } from "./interruption.cjs";
61
61
  import { ErrorResponseOptions, StreamOptions, calculateDelay, delay, writeErrorResponse, writeSSEStream } from "./sse-writer.cjs";
62
62
  import { ChaosAsyncOutcome, applyChaosAsync, applyChaosDeprecated, evaluateChaos, resolveChaosLatencyMs } from "./chaos.cjs";
@@ -68,4 +68,4 @@ import { AimockFakesReportError, AimockTestIdCollisionError, McpFakesReport, ass
68
68
  import { VectorMock } from "./vector-mock.cjs";
69
69
  import { JsonRpcDispatcherOptions, JsonRpcResponse, MethodHandler, createJsonRpcDispatcher } from "./jsonrpc.cjs";
70
70
  import { MockSuite, MockSuiteOptions, createMockSuite } from "./suite.cjs";
71
- export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUISubagentErrorEvent, type AGUISubagentFinishedEvent, type AGUISubagentFinishedOutcome, type AGUISubagentStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUITokenUsage, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, AimockFakesReportError, AimockTestIdCollisionError, type ApiKeyAuthConfig, type AudioResponse, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, type BatchObject, BytePlusVideoJobMap, CATALOG_ROUTES, type CatalogRoute, type ChaosAction, type ChaosAsyncOutcome, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, type CustomToolCall, type CustomToolCallMessage, type CustomToolDefinition, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type FileObject, type FineTuningJob, type FineTuningJobError, type FineTuningJobEvent, type FineTuningJobHyperparameters, type FineTuningJobStatus, type Fixture, type FixtureBlock, type FixtureFile, type FixtureFileContentWithToolCallsResponse, type FixtureFileCustomToolCall, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileResponsesBlock, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, FixtureLoadError, type FixtureLoadErrorJSON, type FixtureMatch, type FixtureOpts, type FixtureResponse, type FixtureToolCall, type FixturesWithServices, type FunctionFixtureBlock, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, InvalidFixtureToolCallError, Journal, type JournalBody, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LiveBinding, type LiveEntry, type LiveFailureCategory, type LiveFixtureResponse, type LiveJson, type LiveMode, type LiveObject, type LiveOptions, type LivePosition, type LiveTranscript, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, MCP_FAKE_ERROR_CODES, type MatchFixtureDiagnostic, type McpFakeAddOrigin, type McpFakeAddResult, type McpFakeAnnotations, type McpFakeBlock, type McpFakeBlockSnapshot, type McpFakeCall, type McpFakeCallAnswer, type McpFakeCallMatch, type McpFakeContentBlock, type McpFakeDeclaredEntry, type McpFakeDeepReadonly, type McpFakeErrorCode, type McpFakeFullResult, type McpFakeIcon, type McpFakeIdentity, type McpFakeIssue, type McpFakeNotification, type McpFakeOutcome, type McpFakeRecorded, type McpFakeReportEvent, type McpFakeReportPart, type McpFakeResourceContents, type McpFakeResult, type McpFakeScope, type McpFakeSource, type McpFakeStructuredResult, type McpFakeTool, type McpFakeUndeclaredPolicy, McpFakesAddError, type McpFakesAddErrorJSON, type McpFakesReport, type McpRecordConfig, type MethodHandler, type MetricsRegistry, type MisbehaviorConfig, MisbehaviorConfigError, type MisbehaviorConfigErrorJSON, type MisbehaviorFault, type MisbehaviorFaultId, type MisbehaviorRule, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, ROUTE_DEFINITIONS, type RawJSONResponse, type RecordConfig, type RecordProviderKey, type RecordReplayLoadRule, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesFixtureBlock, type ResponsesSSEEvent, type ResponsesToolsMode, type RouteDefinition, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, UnsupportedToolCallError, VEO_VIDEO_MAX_ENTRIES, type ValidationRef, type ValidationResult, type VectorCollection, type VectorEntry, type VectorFileBatchObject, type VectorFileBatchStatus, VectorMock, type VectorMockOptions, type VectorQuery, type VectorSearchResult, type VectorStoreFileObject, type VectorStoreFileStatus, type VectorStoreObject, type VectorStoreStatus, VeoVideoJobMap, type VideoResponse, VideoStateMap, type VoiceDesignPreview, type VoiceDesignResponse, WebSocketConnection, type WebSocketLimits, applyChaosDeprecated as applyChaos, applyChaosAsync, assertFakesReport, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildOpenApiDocument, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, clearVectorStoreStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixtureFileWithServices, loadFixturesFromDir, loadFixturesFromDirWithServices, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, requireFunctionToolCalls, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
71
+ export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUISubagentErrorEvent, type AGUISubagentFinishedEvent, type AGUISubagentFinishedOutcome, type AGUISubagentStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUITokenUsage, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, AimockFakesReportError, type AimockPolicy, AimockTestIdCollisionError, type ApiKeyAuthConfig, type AudioResponse, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, type BatchObject, BytePlusVideoJobMap, CATALOG_ROUTES, type CatalogRoute, type ChaosAction, type ChaosAsyncOutcome, type ChaosConfig, type ChatCompletion, type ChatCompletionAnnotation, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, type CustomToolCall, type CustomToolCallMessage, type CustomToolDefinition, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type FileObject, type FineTuningJob, type FineTuningJobError, type FineTuningJobEvent, type FineTuningJobHyperparameters, type FineTuningJobStatus, type Fixture, type FixtureBlock, type FixtureCitation, type FixtureFile, type FixtureFileCitation, type FixtureFileContentWithToolCallsResponse, type FixtureFileCustomToolCall, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileResponsesBlock, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, type FixtureGeneratedFile, FixtureLoadError, type FixtureLoadErrorJSON, type FixtureMatch, type FixtureOpts, type FixtureResponse, type FixtureToolCall, type FixtureUrlCitation, type FixturesWithServices, type FunctionFixtureBlock, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, InvalidFixtureOutputError, InvalidFixtureToolCallError, Journal, type JournalBody, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LiveBinding, type LiveEntry, type LiveFailureCategory, type LiveFixtureResponse, type LiveJson, type LiveMode, type LiveObject, type LiveOptions, type LivePosition, type LiveTranscript, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, MCP_FAKE_ERROR_CODES, type MatchFixtureDiagnostic, type McpFakeAddOrigin, type McpFakeAddResult, type McpFakeAnnotations, type McpFakeBlock, type McpFakeBlockSnapshot, type McpFakeCall, type McpFakeCallAnswer, type McpFakeCallMatch, type McpFakeContentBlock, type McpFakeDeclaredEntry, type McpFakeDeepReadonly, type McpFakeErrorCode, type McpFakeFullResult, type McpFakeIcon, type McpFakeIdentity, type McpFakeIssue, type McpFakeNotification, type McpFakeOutcome, type McpFakeRecorded, type McpFakeReportEvent, type McpFakeReportPart, type McpFakeResourceContents, type McpFakeResult, type McpFakeScope, type McpFakeSource, type McpFakeStructuredResult, type McpFakeTool, type McpFakeUndeclaredPolicy, McpFakesAddError, type McpFakesAddErrorJSON, type McpFakesReport, type McpRecordConfig, type MethodHandler, type MetricsRegistry, type MisbehaviorConfig, MisbehaviorConfigError, type MisbehaviorConfigErrorJSON, type MisbehaviorFault, type MisbehaviorFaultId, type MisbehaviorRule, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, ROUTE_DEFINITIONS, type RawJSONResponse, type RawResponse, type RawWireId, type RecordConfig, type RecordProviderKey, type RecordReplayLoadRule, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesFixtureBlock, type ResponsesSSEEvent, type ResponsesToolsMode, type RouteDefinition, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, UnsupportedGeneratedFileError, UnsupportedToolCallError, VEO_VIDEO_MAX_ENTRIES, type ValidationRef, type ValidationResult, type VectorCollection, type VectorEntry, type VectorFileBatchObject, type VectorFileBatchStatus, VectorMock, type VectorMockOptions, type VectorQuery, type VectorSearchResult, type VectorStoreFileObject, type VectorStoreFileStatus, type VectorStoreObject, type VectorStoreStatus, VeoVideoJobMap, type VideoResponse, VideoStateMap, type VoiceDesignPreview, type VoiceDesignResponse, WebSocketConnection, type WebSocketLimits, type WireId, applyChaosDeprecated as applyChaos, applyChaosAsync, assertFakesReport, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildOpenApiDocument, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, clearVectorStoreStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixtureFileWithServices, loadFixturesFromDir, loadFixturesFromDirWithServices, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, requireFunctionToolCalls, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ import { ROUTE_DEFINITIONS, RouteDefinition } from "./route-registry.js";
7
7
  import { MetricsRegistry, createMetricsRegistry, normalizePathLabel } from "./metrics.js";
8
8
  import { FixtureLoadError, FixtureLoadErrorJSON, MisbehaviorConfigError, MisbehaviorConfigErrorJSON, ValidationRef, ValidationResult, loadFixtureFile, loadFixturesFromDir, normalizeResponse, renderValidationRef, validateFixtures } from "./fixture-loader.js";
9
9
  import { McpFakeAddOrigin, McpFakeAddResult, McpFakeBlockSnapshot, McpFakeDeclaredEntry, McpFakeIssue, McpFakeReportEvent, McpFakeReportPart, McpFakesAddError, McpFakesAddErrorJSON, RecordReplayLoadRule } from "./mcp-fakes.js";
10
- import { ApiKeyAuthConfig, AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, CustomToolCall, CustomToolCallMessage, CustomToolDefinition, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureFile, FixtureFileContentWithToolCallsResponse, FixtureFileCustomToolCall, FixtureFileEntry, FixtureFileResponse, FixtureFileResponsesBlock, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, FixtureToolCall, ImageItem, ImageResponse, JournalBody, JournalEntry, MCP_FAKE_ERROR_CODES, McpFakeAnnotations, McpFakeBlock, McpFakeCall, McpFakeCallAnswer, McpFakeCallMatch, McpFakeContentBlock, McpFakeDeepReadonly, McpFakeErrorCode, McpFakeFullResult, McpFakeIcon, McpFakeIdentity, McpFakeNotification, McpFakeOutcome, McpFakeRecorded, McpFakeResourceContents, McpFakeResult, McpFakeScope, McpFakeSource, McpFakeStructuredResult, McpFakeTool, McpFakeUndeclaredPolicy, McpRecordConfig, MisbehaviorConfig, MisbehaviorFault, MisbehaviorFaultId, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, ResponseOverrides, ResponsesFixtureBlock, ResponsesToolsMode, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse, VoiceDesignPreview, VoiceDesignResponse } from "./types.js";
10
+ import { AimockPolicy, ApiKeyAuthConfig, AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionAnnotation, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, CustomToolCall, CustomToolCallMessage, CustomToolDefinition, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, Fixture, FixtureBlock, FixtureCitation, FixtureFile, FixtureFileCitation, FixtureFileContentWithToolCallsResponse, FixtureFileCustomToolCall, FixtureFileEntry, FixtureFileResponse, FixtureFileResponsesBlock, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureGeneratedFile, FixtureMatch, FixtureOpts, FixtureResponse, FixtureToolCall, FixtureUrlCitation, ImageItem, ImageResponse, JournalBody, JournalEntry, MCP_FAKE_ERROR_CODES, McpFakeAnnotations, McpFakeBlock, McpFakeCall, McpFakeCallAnswer, McpFakeCallMatch, McpFakeContentBlock, McpFakeDeepReadonly, McpFakeErrorCode, McpFakeFullResult, McpFakeIcon, McpFakeIdentity, McpFakeNotification, McpFakeOutcome, McpFakeRecorded, McpFakeResourceContents, McpFakeResult, McpFakeScope, McpFakeSource, McpFakeStructuredResult, McpFakeTool, McpFakeUndeclaredPolicy, McpRecordConfig, MisbehaviorConfig, MisbehaviorFault, MisbehaviorFaultId, MockServerOptions, Mountable, RawJSONResponse, RawResponse, RawWireId, RecordConfig, RecordProviderKey, ResponseOverrides, ResponsesFixtureBlock, ResponsesToolsMode, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse, VoiceDesignPreview, VoiceDesignResponse, WireId } from "./types.js";
11
11
  import { A2AAgentDefinition, A2AArtifact, A2AMessage, A2AMockOptions, A2APart, A2ARole, A2AStreamEvent, A2ATask, A2ATaskResponse, A2ATaskState } from "./a2a-types.js";
12
12
  import { A2AMock } from "./a2a-mock.js";
13
13
  import { AGUIActivityDeltaEvent, AGUIActivitySnapshotEvent, AGUIBaseEvent, AGUICustomEvent, AGUIEvent, AGUIEventType, AGUIFixture, AGUIFixtureMatch, AGUIInterrupt, AGUIMessage, AGUIMessageContentPart, AGUIMessageRole, AGUIMessagesSnapshotEvent, AGUIMockOptions, AGUIRawEvent, AGUIReasoningEncryptedValueEvent, AGUIReasoningEncryptedValueSubtype, AGUIReasoningEndEvent, AGUIReasoningMessageChunkEvent, AGUIReasoningMessageContentEvent, AGUIReasoningMessageEndEvent, AGUIReasoningMessageStartEvent, AGUIReasoningStartEvent, AGUIRecordConfig, AGUIResumeEntry, AGUIRunAgentInput, AGUIRunErrorEvent, AGUIRunFinishedEvent, AGUIRunFinishedOutcome, AGUIRunStartedEvent, AGUIStateDeltaEvent, AGUIStateSnapshotEvent, AGUIStepFinishedEvent, AGUIStepStartedEvent, AGUISubagentErrorEvent, AGUISubagentFinishedEvent, AGUISubagentFinishedOutcome, AGUISubagentStartedEvent, AGUITextMessageChunkEvent, AGUITextMessageContentEvent, AGUITextMessageEndEvent, AGUITextMessageRole, AGUITextMessageStartEvent, AGUIThinkingEndEvent, AGUIThinkingStartEvent, AGUIThinkingTextMessageContentEvent, AGUIThinkingTextMessageEndEvent, AGUIThinkingTextMessageStartEvent, AGUITokenUsage, AGUIToolCall, AGUIToolCallArgsEvent, AGUIToolCallChunkEvent, AGUIToolCallEndEvent, AGUIToolCallResultEvent, AGUIToolCallStartEvent, AGUIToolDefinition } from "./agui-types.js";
@@ -36,6 +36,7 @@ import { handleEmbeddings } from "./embeddings.js";
36
36
  import { bedrockToCompletionRequest, handleBedrock, handleBedrockStream } from "./bedrock.js";
37
37
  import { converseToCompletionRequest, handleConverse, handleConverseStream } from "./bedrock-converse.js";
38
38
  import { geminiInteractionsToCompletionRequest, handleGeminiInteractions } from "./gemini-interactions.js";
39
+ import { WebSocketConnection, WebSocketLimits, computeAcceptKey, upgradeToWebSocket } from "./ws-framing.js";
39
40
  import { encodeEventStreamFrame, encodeEventStreamMessage, writeEventStream } from "./aws-event-stream.js";
40
41
  import { NDJSONStreamOptions, writeNDJSONStream } from "./ndjson-writer.js";
41
42
  import { handleOllama, handleOllamaGenerate, ollamaToCompletionRequest } from "./ollama.js";
@@ -45,7 +46,6 @@ import { BatchObject, clearBatchStore, handleBatchesCancel, handleBatchesCreate,
45
46
  import { FileObject, clearFileStore, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve } from "./files.js";
46
47
  import { FineTuningJob, FineTuningJobError, FineTuningJobEvent, FineTuningJobHyperparameters, FineTuningJobStatus, clearFineTuningStore, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve } from "./fine-tuning.js";
47
48
  import { VectorFileBatchObject, VectorFileBatchStatus, VectorSearchResult, VectorStoreFileObject, VectorStoreFileStatus, VectorStoreObject, VectorStoreStatus, clearVectorStoreStore, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch } from "./vector-stores.js";
48
- import { WebSocketConnection, WebSocketLimits, computeAcceptKey, upgradeToWebSocket } from "./ws-framing.js";
49
49
  import { handleWebSocketResponses } from "./ws-responses.js";
50
50
  import { handleWebSocketRealtime } from "./ws-realtime.js";
51
51
  import { handleWebSocketGeminiLive } from "./ws-gemini-live.js";
@@ -56,7 +56,7 @@ import { handleElevenLabsAudio } from "./elevenlabs-audio.js";
56
56
  import { clearElevenLabsVoices, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, voiceDesignToJson } from "./elevenlabs-voice.js";
57
57
  import { handleFalQueue } from "./fal-audio.js";
58
58
  import { FalQueueStateMap, handleFal } from "./fal.js";
59
- import { EmbeddingAPIResponse, FORMAT_TO_CONTENT_TYPE, FunctionFixtureBlock, InvalidFixtureToolCallError, UnsupportedToolCallError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, requireFunctionToolCalls, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, strictNoMatchLogLine, strictNoMatchMessage } from "./helpers.js";
59
+ import { EmbeddingAPIResponse, FORMAT_TO_CONTENT_TYPE, FunctionFixtureBlock, InvalidFixtureOutputError, InvalidFixtureToolCallError, UnsupportedGeneratedFileError, UnsupportedToolCallError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, requireFunctionToolCalls, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, strictNoMatchLogLine, strictNoMatchMessage } from "./helpers.js";
60
60
  import { InterruptionControl, createInterruptionSignal } from "./interruption.js";
61
61
  import { ErrorResponseOptions, StreamOptions, calculateDelay, delay, writeErrorResponse, writeSSEStream } from "./sse-writer.js";
62
62
  import { ChaosAsyncOutcome, applyChaosAsync, applyChaosDeprecated, evaluateChaos, resolveChaosLatencyMs } from "./chaos.js";
@@ -68,4 +68,4 @@ import { AimockFakesReportError, AimockTestIdCollisionError, McpFakesReport, ass
68
68
  import { VectorMock } from "./vector-mock.js";
69
69
  import { JsonRpcDispatcherOptions, JsonRpcResponse, MethodHandler, createJsonRpcDispatcher } from "./jsonrpc.js";
70
70
  import { MockSuite, MockSuiteOptions, createMockSuite } from "./suite.js";
71
- export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUISubagentErrorEvent, type AGUISubagentFinishedEvent, type AGUISubagentFinishedOutcome, type AGUISubagentStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUITokenUsage, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, AimockFakesReportError, AimockTestIdCollisionError, type ApiKeyAuthConfig, type AudioResponse, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, type BatchObject, BytePlusVideoJobMap, CATALOG_ROUTES, type CatalogRoute, type ChaosAction, type ChaosAsyncOutcome, type ChaosConfig, type ChatCompletion, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, type CustomToolCall, type CustomToolCallMessage, type CustomToolDefinition, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type FileObject, type FineTuningJob, type FineTuningJobError, type FineTuningJobEvent, type FineTuningJobHyperparameters, type FineTuningJobStatus, type Fixture, type FixtureBlock, type FixtureFile, type FixtureFileContentWithToolCallsResponse, type FixtureFileCustomToolCall, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileResponsesBlock, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, FixtureLoadError, type FixtureLoadErrorJSON, type FixtureMatch, type FixtureOpts, type FixtureResponse, type FixtureToolCall, type FixturesWithServices, type FunctionFixtureBlock, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, InvalidFixtureToolCallError, Journal, type JournalBody, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LiveBinding, type LiveEntry, type LiveFailureCategory, type LiveFixtureResponse, type LiveJson, type LiveMode, type LiveObject, type LiveOptions, type LivePosition, type LiveTranscript, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, MCP_FAKE_ERROR_CODES, type MatchFixtureDiagnostic, type McpFakeAddOrigin, type McpFakeAddResult, type McpFakeAnnotations, type McpFakeBlock, type McpFakeBlockSnapshot, type McpFakeCall, type McpFakeCallAnswer, type McpFakeCallMatch, type McpFakeContentBlock, type McpFakeDeclaredEntry, type McpFakeDeepReadonly, type McpFakeErrorCode, type McpFakeFullResult, type McpFakeIcon, type McpFakeIdentity, type McpFakeIssue, type McpFakeNotification, type McpFakeOutcome, type McpFakeRecorded, type McpFakeReportEvent, type McpFakeReportPart, type McpFakeResourceContents, type McpFakeResult, type McpFakeScope, type McpFakeSource, type McpFakeStructuredResult, type McpFakeTool, type McpFakeUndeclaredPolicy, McpFakesAddError, type McpFakesAddErrorJSON, type McpFakesReport, type McpRecordConfig, type MethodHandler, type MetricsRegistry, type MisbehaviorConfig, MisbehaviorConfigError, type MisbehaviorConfigErrorJSON, type MisbehaviorFault, type MisbehaviorFaultId, type MisbehaviorRule, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, ROUTE_DEFINITIONS, type RawJSONResponse, type RecordConfig, type RecordProviderKey, type RecordReplayLoadRule, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesFixtureBlock, type ResponsesSSEEvent, type ResponsesToolsMode, type RouteDefinition, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, UnsupportedToolCallError, VEO_VIDEO_MAX_ENTRIES, type ValidationRef, type ValidationResult, type VectorCollection, type VectorEntry, type VectorFileBatchObject, type VectorFileBatchStatus, VectorMock, type VectorMockOptions, type VectorQuery, type VectorSearchResult, type VectorStoreFileObject, type VectorStoreFileStatus, type VectorStoreObject, type VectorStoreStatus, VeoVideoJobMap, type VideoResponse, VideoStateMap, type VoiceDesignPreview, type VoiceDesignResponse, WebSocketConnection, type WebSocketLimits, applyChaosDeprecated as applyChaos, applyChaosAsync, assertFakesReport, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildOpenApiDocument, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, clearVectorStoreStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixtureFileWithServices, loadFixturesFromDir, loadFixturesFromDirWithServices, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, requireFunctionToolCalls, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
71
+ export { type A2AAgentDefinition, type A2AArtifact, type A2AMessage, A2AMock, type A2AMockOptions, type A2APart, type A2ARole, type A2AStreamEvent, type A2ATask, type A2ATaskResponse, type A2ATaskState, type AGUIActivityDeltaEvent, type AGUIActivitySnapshotEvent, type AGUIBaseEvent, type AGUIBuildOpts, type AGUICustomEvent, type AGUIEvent, type AGUIEventType, type AGUIFixture, type AGUIFixtureMatch, type AGUIInterrupt, type AGUIMessage, type AGUIMessageContentPart, type AGUIMessageRole, type AGUIMessagesSnapshotEvent, AGUIMock, type AGUIMockOptions, type AGUIRawEvent, type AGUIReasoningEncryptedValueEvent, type AGUIReasoningEncryptedValueSubtype, type AGUIReasoningEndEvent, type AGUIReasoningMessageChunkEvent, type AGUIReasoningMessageContentEvent, type AGUIReasoningMessageEndEvent, type AGUIReasoningMessageStartEvent, type AGUIReasoningStartEvent, type AGUIRecordConfig, type AGUIResumeEntry, type AGUIRunAgentInput, type AGUIRunErrorEvent, type AGUIRunFinishedEvent, type AGUIRunFinishedOutcome, type AGUIRunStartedEvent, type AGUIStateDeltaEvent, type AGUIStateSnapshotEvent, type AGUIStepFinishedEvent, type AGUIStepStartedEvent, type AGUISubagentErrorEvent, type AGUISubagentFinishedEvent, type AGUISubagentFinishedOutcome, type AGUISubagentStartedEvent, type AGUITextMessageChunkEvent, type AGUITextMessageContentEvent, type AGUITextMessageEndEvent, type AGUITextMessageRole, type AGUITextMessageStartEvent, type AGUIThinkingEndEvent, type AGUIThinkingStartEvent, type AGUIThinkingTextMessageContentEvent, type AGUIThinkingTextMessageEndEvent, type AGUIThinkingTextMessageStartEvent, type AGUITokenUsage, type AGUIToolCall, type AGUIToolCallArgsEvent, type AGUIToolCallChunkEvent, type AGUIToolCallEndEvent, type AGUIToolCallResultEvent, type AGUIToolCallStartEvent, type AGUIToolDefinition, AGUI_RECORD_BUFFER_HARD_CEILING, type AimockConfig, AimockFakesReportError, type AimockPolicy, AimockTestIdCollisionError, type ApiKeyAuthConfig, type AudioResponse, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, type BatchObject, BytePlusVideoJobMap, CATALOG_ROUTES, type CatalogRoute, type ChaosAction, type ChaosAsyncOutcome, type ChaosConfig, type ChatCompletion, type ChatCompletionAnnotation, type ChatCompletionChoice, type ChatCompletionMessage, type ChatCompletionRequest, type ChatMessage, type CollapseResult, type ContentPart, type ContentWithToolCallsResponse, type CustomToolCall, type CustomToolCallMessage, type CustomToolDefinition, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, type EmbeddingAPIResponse, type EmbeddingFixtureOpts, type EmbeddingResponse, type ErrorResponse, type ErrorResponseOptions, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, type FileObject, type FineTuningJob, type FineTuningJobError, type FineTuningJobEvent, type FineTuningJobHyperparameters, type FineTuningJobStatus, type Fixture, type FixtureBlock, type FixtureCitation, type FixtureFile, type FixtureFileCitation, type FixtureFileContentWithToolCallsResponse, type FixtureFileCustomToolCall, type FixtureFileEntry, type FixtureFileResponse, type FixtureFileResponsesBlock, type FixtureFileTextResponse, type FixtureFileToolCall, type FixtureFileToolCallResponse, type FixtureGeneratedFile, FixtureLoadError, type FixtureLoadErrorJSON, type FixtureMatch, type FixtureOpts, type FixtureResponse, type FixtureToolCall, type FixtureUrlCitation, type FixturesWithServices, type FunctionFixtureBlock, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, type ImageItem, type ImageResponse, type InterruptionControl, InvalidFixtureOutputError, InvalidFixtureToolCallError, Journal, type JournalBody, type JournalEntry, type JsonRpcDispatcherOptions, type JsonRpcResponse, LLMock, type LiveBinding, type LiveEntry, type LiveFailureCategory, type LiveFixtureResponse, type LiveJson, type LiveMode, type LiveObject, type LiveOptions, type LivePosition, type LiveTranscript, type LogLevel, Logger, MAX_COLLAPSE_STRING_LENGTH, type MCPContent, MCPMock, type MCPMockOptions, type MCPPromptDefinition, type MCPPromptResult, type MCPResourceContent, type MCPResourceDefinition, type MCPSession, type MCPToolDefinition, MCP_FAKE_ERROR_CODES, type MatchFixtureDiagnostic, type McpFakeAddOrigin, type McpFakeAddResult, type McpFakeAnnotations, type McpFakeBlock, type McpFakeBlockSnapshot, type McpFakeCall, type McpFakeCallAnswer, type McpFakeCallMatch, type McpFakeContentBlock, type McpFakeDeclaredEntry, type McpFakeDeepReadonly, type McpFakeErrorCode, type McpFakeFullResult, type McpFakeIcon, type McpFakeIdentity, type McpFakeIssue, type McpFakeNotification, type McpFakeOutcome, type McpFakeRecorded, type McpFakeReportEvent, type McpFakeReportPart, type McpFakeResourceContents, type McpFakeResult, type McpFakeScope, type McpFakeSource, type McpFakeStructuredResult, type McpFakeTool, type McpFakeUndeclaredPolicy, McpFakesAddError, type McpFakesAddErrorJSON, type McpFakesReport, type McpRecordConfig, type MethodHandler, type MetricsRegistry, type MisbehaviorConfig, MisbehaviorConfigError, type MisbehaviorConfigErrorJSON, type MisbehaviorFault, type MisbehaviorFaultId, type MisbehaviorRule, type MockServerOptions, type MockSuite, type MockSuiteOptions, type ModerationFixture, type ModerationResult, type Mountable, type NDJSONStreamOptions, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, type QueryHandler, type QueryResult, ROUTE_DEFINITIONS, type RawJSONResponse, type RawResponse, type RawWireId, type RecordConfig, type RecordProviderKey, type RecordReplayLoadRule, type RerankFixture, type RerankResult, type ResponseOverrides, type ResponsesFixtureBlock, type ResponsesSSEEvent, type ResponsesToolsMode, type RouteDefinition, type SSEChoice, type SSEChunk, type SSEDelta, type SSEToolCallDelta, type SearchFixture, type SearchResult, type ServerInstance, type ServiceFixtures, type StreamOptions, type StreamingProfile, type TextResponse, type ToolCall, type ToolCallMessage, type ToolCallResponse, type ToolDefinition, type TranscriptionResponse, UnsupportedGeneratedFileError, UnsupportedToolCallError, VEO_VIDEO_MAX_ENTRIES, type ValidationRef, type ValidationResult, type VectorCollection, type VectorEntry, type VectorFileBatchObject, type VectorFileBatchStatus, VectorMock, type VectorMockOptions, type VectorQuery, type VectorSearchResult, type VectorStoreFileObject, type VectorStoreFileStatus, type VectorStoreObject, type VectorStoreStatus, VeoVideoJobMap, type VideoResponse, VideoStateMap, type VoiceDesignPreview, type VoiceDesignResponse, WebSocketConnection, type WebSocketLimits, type WireId, applyChaosDeprecated as applyChaos, applyChaosAsync, assertFakesReport, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildOpenApiDocument, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, clearVectorStoreStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixtureFileWithServices, loadFixturesFromDir, loadFixturesFromDirWithServices, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, requireFunctionToolCalls, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_TEST_ID } from "./constants.js";
2
- import { FORMAT_TO_CONTENT_TYPE, InvalidFixtureToolCallError, UnsupportedToolCallError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, requireFunctionToolCalls, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, strictNoMatchLogLine, strictNoMatchMessage } from "./helpers.js";
2
+ import { FORMAT_TO_CONTENT_TYPE, InvalidFixtureOutputError, InvalidFixtureToolCallError, UnsupportedGeneratedFileError, UnsupportedToolCallError, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildEmbeddingResponse, buildTextChunks, buildTextCompletion, buildToolCallChunks, buildToolCallCompletion, extractOverrides, flattenHeaders, formatToMime, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, isAudioResponse, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, requireFunctionToolCalls, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, strictNoMatchLogLine, strictNoMatchMessage } from "./helpers.js";
3
3
  import { createJsonRpcDispatcher } from "./jsonrpc.js";
4
4
  import { A2AMock } from "./a2a-mock.js";
5
5
  import { buildActivityDelta, buildActivityResponse, buildCompositeResponse, buildCustomEvent, buildErrorResponse, buildMessagesSnapshot, buildRawEvent, buildReasoningChunk, buildReasoningEncryptedValue, buildReasoningResponse, buildStateDelta, buildStateUpdate, buildStepWithText, buildTextChunkResponse, buildTextResponse, buildToolCallChunk, buildToolCallResponse, extractLastUserMessage, findFixture, getLastMessageIfToolResult, matchesFixture, writeAGUIEventStream } from "./agui-handler.js";
@@ -15,10 +15,11 @@ import { Logger } from "./logger.js";
15
15
  import { AGUIMock } from "./agui-mock.js";
16
16
  import { Journal, isChatCompletionBody } from "./journal.js";
17
17
  import { createInterruptionSignal } from "./interruption.js";
18
+ import { encodeEventStreamFrame, encodeEventStreamMessage, writeEventStream } from "./aws-event-stream.js";
19
+ import { writeNDJSONStream } from "./ndjson-writer.js";
18
20
  import { buildContentWithToolCallsStreamEvents, buildTextStreamEvents, buildToolCallStreamEvents, handleResponses } from "./responses.js";
19
21
  import { handleMessages } from "./messages.js";
20
22
  import { handleGemini } from "./gemini.js";
21
- import { encodeEventStreamFrame, encodeEventStreamMessage, writeEventStream } from "./aws-event-stream.js";
22
23
  import { bedrockToCompletionRequest, handleBedrock, handleBedrockStream } from "./bedrock.js";
23
24
  import { converseToCompletionRequest, handleConverse, handleConverseStream } from "./bedrock-converse.js";
24
25
  import { geminiInteractionsToCompletionRequest, handleGeminiInteractions } from "./gemini-interactions.js";
@@ -35,7 +36,6 @@ import { GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, handleGrokVideoCreate, handleG
35
36
  import { BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, BytePlusVideoJobMap, buildBytePlusMatchText, handleBytePlusVideoCreate, handleBytePlusVideoStatus } from "./byteplus-video.js";
36
37
  import { handleElevenLabsAudio } from "./elevenlabs-audio.js";
37
38
  import { clearElevenLabsVoices, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, voiceDesignToJson } from "./elevenlabs-voice.js";
38
- import { writeNDJSONStream } from "./ndjson-writer.js";
39
39
  import { handleOllama, handleOllamaGenerate, ollamaToCompletionRequest } from "./ollama.js";
40
40
  import { cohereToCompletionRequest, handleCohere } from "./cohere.js";
41
41
  import { handleSearch } from "./search.js";
@@ -63,4 +63,4 @@ import { VectorMock } from "./vector-mock.js";
63
63
  import { loadConfig, startFromConfig } from "./config-loader.js";
64
64
  import { createMockSuite } from "./suite.js";
65
65
 
66
- export { A2AMock, AGUIMock, AGUI_RECORD_BUFFER_HARD_CEILING, AimockFakesReportError, AimockTestIdCollisionError, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, BytePlusVideoJobMap, CATALOG_ROUTES, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, FixtureLoadError, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, InvalidFixtureToolCallError, Journal, LLMock, Logger, MAX_COLLAPSE_STRING_LENGTH, MCPMock, MCP_FAKE_ERROR_CODES, McpFakesAddError, MisbehaviorConfigError, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, ROUTE_DEFINITIONS, UnsupportedToolCallError, VEO_VIDEO_MAX_ENTRIES, VectorMock, VeoVideoJobMap, VideoStateMap, WebSocketConnection, applyChaosDeprecated as applyChaos, applyChaosAsync, assertFakesReport, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildOpenApiDocument, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, clearVectorStoreStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixtureFileWithServices, loadFixturesFromDir, loadFixturesFromDirWithServices, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, requireFunctionToolCalls, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
66
+ export { A2AMock, AGUIMock, AGUI_RECORD_BUFFER_HARD_CEILING, AimockFakesReportError, AimockTestIdCollisionError, BYTEPLUS_VIDEO_MAX_ENTRIES, BYTEPLUS_VIDEO_TASKS_PATH, BytePlusVideoJobMap, CATALOG_ROUTES, DEFAULT_AGUI_RECORD_BUFFER_BYTES, DEFAULT_TEST_ID, FORMAT_TO_CONTENT_TYPE, FalQueueStateMap, FixtureLoadError, GROK_VIDEO_MAX_ENTRIES, GrokVideoJobMap, InvalidFixtureOutputError, InvalidFixtureToolCallError, Journal, LLMock, Logger, MAX_COLLAPSE_STRING_LENGTH, MCPMock, MCP_FAKE_ERROR_CODES, McpFakesAddError, MisbehaviorConfigError, OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES, OPENROUTER_VIDEO_MAX_ENTRIES, OpenRouterVideoJobMap, ROUTE_DEFINITIONS, UnsupportedGeneratedFileError, UnsupportedToolCallError, VEO_VIDEO_MAX_ENTRIES, VectorMock, VeoVideoJobMap, VideoStateMap, WebSocketConnection, applyChaosDeprecated as applyChaos, applyChaosAsync, assertFakesReport, bedrockToCompletionRequest, buildActivityDelta as buildAGUIActivityDelta, buildActivityResponse as buildAGUIActivityResponse, buildCompositeResponse as buildAGUICompositeResponse, buildCustomEvent as buildAGUICustomEvent, buildErrorResponse as buildAGUIErrorResponse, buildMessagesSnapshot as buildAGUIMessagesSnapshot, buildRawEvent as buildAGUIRawEvent, buildReasoningChunk as buildAGUIReasoningChunk, buildReasoningEncryptedValue as buildAGUIReasoningEncryptedValue, buildReasoningResponse as buildAGUIReasoningResponse, buildStateDelta as buildAGUIStateDelta, buildStateUpdate as buildAGUIStateUpdate, buildStepWithText as buildAGUIStepWithText, buildTextChunkResponse as buildAGUITextChunkResponse, buildTextResponse as buildAGUITextResponse, buildToolCallChunk as buildAGUIToolCallChunk, buildToolCallResponse as buildAGUIToolCallResponse, buildBytePlusMatchText, buildContentWithToolCallsChunks, buildContentWithToolCallsCompletion, buildContentWithToolCallsStreamEvents, buildEmbeddingResponse, buildOpenApiDocument, buildTextChunks, buildTextCompletion, buildTextStreamEvents, buildToolCallChunks, buildToolCallCompletion, buildToolCallStreamEvents, calculateDelay, clearBatchStore, clearElevenLabsVoices, clearFileStore, clearFineTuningStore, clearVectorStoreStore, cohereToCompletionRequest, collapseAnthropicSSE, collapseBedrockEventStream, collapseCohereSSE, collapseGeminiInteractionsSSE, collapseGeminiSSE, collapseOllamaNDJSON, collapseOpenAISSE, collapseStreamingResponse, computeAcceptKey, converseToCompletionRequest, createInterruptionSignal, createJsonRpcDispatcher, createMetricsRegistry, createMockSuite, createServer, delay, encodeEventStreamFrame, encodeEventStreamMessage, evaluateChaos, extractLastUserMessage as extractAGUILastUserMessage, extractOverrides, findFixture as findAGUIFixture, flattenHeaders, formatToMime, geminiInteractionsToCompletionRequest, generateDeterministicEmbedding, generateId, generateMessageId, generateToolCallId, generateToolUseId, getLastMessageIfToolResult as getAGUILastMessageIfToolResult, getTextContent, handleBatchesCancel, handleBatchesCreate, handleBatchesList, handleBatchesRetrieve, handleBedrock, handleBedrockStream, handleBytePlusVideoCreate, handleBytePlusVideoStatus, handleCohere, handleConverse, handleConverseStream, handleElevenLabsAudio, handleElevenLabsVoiceCreate, handleElevenLabsVoiceDelete, handleElevenLabsVoiceDesign, handleElevenLabsVoiceGet, handleEmbeddings, handleFal, handleFalQueue, handleFilesContent, handleFilesCreate, handleFilesDelete, handleFilesList, handleFilesRetrieve, handleFineTuningCancel, handleFineTuningCreate, handleFineTuningEvents, handleFineTuningList, handleFineTuningRetrieve, handleGemini, handleGeminiInteractions, handleGrokVideoCreate, handleGrokVideoStatus, handleImages, handleMessages, handleModeration, handleOllama, handleOllamaGenerate, handleOpenRouterVideoContent, handleOpenRouterVideoCreate, handleOpenRouterVideoModels, handleOpenRouterVideoStatus, handleRerank, handleResponses, handleSearch, handleSpeech, handleTranscription, handleVectorFileBatchesCancel, handleVectorFileBatchesCreate, handleVectorFileBatchesFiles, handleVectorFileBatchesRetrieve, handleVectorStoreFilesCreate, handleVectorStoreFilesDelete, handleVectorStoreFilesList, handleVectorStoreFilesRetrieve, handleVectorStoresCreate, handleVectorStoresDelete, handleVectorStoresList, handleVectorStoresModify, handleVectorStoresRetrieve, handleVectorStoresSearch, handleVeoVideoCreate, handleVeoVideoStatus, handleVideoCreate, handleVideoStatus, handleWebSocketGeminiLive, handleWebSocketRealtime, handleWebSocketResponses, isAudioResponse, isChatCompletionBody, isContentWithToolCallsResponse, isEmbeddingResponse, isErrorResponse, isImageResponse, isLiveResponse, isTextResponse, isToolCallResponse, isTranscriptionResponse, isVideoResponse, loadConfig, loadFixtureFile, loadFixtureFileWithServices, loadFixturesFromDir, loadFixturesFromDirWithServices, matchFixture, matchFixtureDiagnostic, matchesFixture as matchesAGUIFixture, normalizePathLabel, normalizeResponse, ollamaToCompletionRequest, proxyAndRecord, proxyAndRecordAGUI, renderValidationRef, requireFunctionToolCalls, resolveChaosLatencyMs, resolveFixtureBlocks, resolveRequestId, resolveResponsesBlocks, resolveUpstreamUrl, setAGUIRecordBufferCeilingForTests, setCollapseStringLimitForTests, startFromConfig, strictNoMatchLogLine, strictNoMatchMessage, upgradeToWebSocket, validateFixtures, voiceDesignToJson, writeAGUIEventStream, writeErrorResponse, writeEventStream, writeNDJSONStream, writeSSEStream };
package/dist/journal.cjs CHANGED
@@ -1,5 +1,7 @@
1
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
1
2
  const require_constants = require('./constants.cjs');
2
3
  const require_helpers = require('./helpers.cjs');
4
+ let node_util = require("node:util");
3
5
 
4
6
  //#region src/journal.ts
5
7
  /**
@@ -76,7 +78,7 @@ function systemMessageEqual(a, b) {
76
78
  * (ignoring sequenceIndex). Used to group sequenced fixtures.
77
79
  */
78
80
  function matchCriteriaEqual(a, b) {
79
- return fieldEqual(a.userMessage, b.userMessage) && systemMessageEqual(a.systemMessage, b.systemMessage) && fieldEqual(a.inputText, b.inputText) && fieldEqual(a.toolCallId, b.toolCallId) && fieldEqual(a.toolName, b.toolName) && fieldEqual(a.toolNamespace, b.toolNamespace) && fieldEqual(a.model, b.model) && fieldEqual(a.responseFormat, b.responseFormat) && fieldEqual(a.predicate, b.predicate) && fieldEqual(a.endpoint, b.endpoint) && fieldEqual(a.turnIndex, b.turnIndex) && fieldEqual(a.hasToolResult, b.hasToolResult) && fieldEqual(a.toolResultContains, b.toolResultContains) && fieldEqual(a.context, b.context);
81
+ return fieldEqual(a.userMessage, b.userMessage) && systemMessageEqual(a.systemMessage, b.systemMessage) && fieldEqual(a.inputText, b.inputText) && (0, node_util.isDeepStrictEqual)(a.embeddingRequest, b.embeddingRequest) && fieldEqual(a.toolCallId, b.toolCallId) && fieldEqual(a.toolName, b.toolName) && fieldEqual(a.toolNamespace, b.toolNamespace) && fieldEqual(a.model, b.model) && fieldEqual(a.responseFormat, b.responseFormat) && fieldEqual(a.predicate, b.predicate) && fieldEqual(a.endpoint, b.endpoint) && fieldEqual(a.turnIndex, b.turnIndex) && fieldEqual(a.hasToolResult, b.hasToolResult) && fieldEqual(a.toolResultContains, b.toolResultContains) && fieldEqual(a.context, b.context);
80
82
  }
81
83
  /** Count-map keys resolve through `identity`, so every alias of a fixture finds its caller entry. */
82
84
  var FixtureCountMap = class extends Map {
@@ -1 +1 @@
1
- {"version":3,"file":"journal.cjs","names":["DEFAULT_TEST_ID","generateId"],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n MisbehaviorCounterKey,\n MisbehaviorCounters,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.toolNamespace, b.toolNamespace) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\n/** Count-map keys resolve through `identity`, so every alias of a fixture finds its caller entry. */\nclass FixtureCountMap extends Map<Fixture, number> {\n constructor(private readonly identity: (fixture: Fixture) => Fixture) {\n super();\n }\n\n override get(key: Fixture): number | undefined {\n return super.get(this.identity(key));\n }\n\n override has(key: Fixture): boolean {\n return super.has(this.identity(key));\n }\n\n override set(key: Fixture, value: number): this {\n return super.set(this.identity(key), value);\n }\n\n override delete(key: Fixture): boolean {\n return super.delete(this.identity(key));\n }\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained across fixture match-count\n * and misbehavior counters. When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal implements MisbehaviorCounters {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n /** The fixture a request was served from, where the entry names its caller fixture instead. */\n private readonly servedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n /** An extended server's view of a fixture to the caller's fixture (configureFixtureViewSource). */\n private fixtureViewSource = (fixture: Fixture): Fixture => fixture;\n private fixtureCountIdentity = (fixture: Fixture): Fixture => fixture;\n /** The key a fixture is counted under: the caller's object behind any view or copy. */\n private readonly fixtureCountKey = (fixture: Fixture): Fixture =>\n this.fixtureCountIdentity(this.fixtureViewSource(fixture));\n private createFixtureCountMap = (): Map<Fixture, number> => new Map();\n private fixtureCountIdentityConfigured = false;\n private fixtureViewSourceConfigured = false;\n private readonly counterTestIds = new Set<string>();\n private readonly misbehaviorCountersByTestId = new Map<\n string,\n Map<string, Map<number, { ordinal: number; firings: number }>>\n >();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /**\n * The per-test-id cap on fixture match-count maps, for an MCP mount to pass\n * to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`\n * meaning unbounded, and never throws, whatever option was passed:\n * omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above\n * `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more\n * is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values\n * it is the number of test ids the journal keeps.\n *\n * An option between 0 and 1 is the exception. The journal keeps no test id\n * (each new count map is evicted as soon as it is made, so counts never\n * advance), and a store cap cannot say \"keep none\" because `0` is\n * unbounded. The getter returns `1`, the smallest bounded cap, so a store\n * given it keeps 1 test id where the journal keeps 0.\n */\n get fixtureCountsMaxTestIdsCap(): number {\n const cap = this.fixtureCountsMaxTestIds;\n if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;\n return Math.max(1, Math.floor(cap));\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n // A request is served from an extended server's view of a fixture, or\n // from LLMock's per-addition copy with misbehavior enabled; the entry\n // names the caller's fixture behind it, as in 1.44.0.\n const fixture = full.response.fixture;\n const source = fixture ? this.fixtureCountKey(fixture) : fixture;\n if (fixture && source !== fixture) {\n full.response = { ...full.response, fixture: source };\n this.servedFixtures.set(full, fixture);\n }\n if (matchedFixture) this.matchedFixtures.set(full, this.fixtureCountKey(matchedFixture));\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n const key = this.fixtureCountKey(fixture);\n return this.entries.filter((e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === key);\n }\n\n /**\n * @internal The fixture `entry`'s request was served from: the extended\n * view or the per-addition copy when the entry names the caller's fixture\n * behind it, otherwise `entry.response.fixture`. The journal JSON shows it.\n */\n servedFixture(entry: JournalEntry): Fixture | null {\n return this.servedFixtures.get(entry) ?? entry.response.fixture;\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? this.createFixtureCountMap();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = this.createFixtureCountMap();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n this.admitCounterTestId(testId);\n }\n return counts;\n }\n\n /** Match and fault mutations share one admission order and capacity. */\n private admitCounterTestId(testId: string): void {\n this.counterTestIds.add(testId);\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.counterTestIds.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.counterTestIds.values().next().value;\n if (oldest !== undefined) {\n this.counterTestIds.delete(oldest);\n this.fixtureMatchCountsByTestId.delete(oldest);\n this.misbehaviorCountersByTestId.delete(oldest);\n }\n }\n }\n\n private getOrCreateMisbehaviorCounter(key: MisbehaviorCounterKey) {\n let sources = this.misbehaviorCountersByTestId.get(key.testId);\n if (!sources) {\n sources = new Map();\n this.misbehaviorCountersByTestId.set(key.testId, sources);\n this.admitCounterTestId(key.testId);\n }\n let entries = sources.get(key.sourceKey);\n if (!entries) {\n entries = new Map();\n sources.set(key.sourceKey, entries);\n }\n let counter = entries.get(key.entryIndex);\n if (!counter) {\n counter = { ordinal: 0, firings: 0 };\n entries.set(key.entryIndex, counter);\n }\n return counter;\n }\n\n getFiringCount(key: MisbehaviorCounterKey): number {\n return (\n this.misbehaviorCountersByTestId.get(key.testId)?.get(key.sourceKey)?.get(key.entryIndex)\n ?.firings ?? 0\n );\n }\n\n nextOrdinal(key: MisbehaviorCounterKey): number {\n return this.getOrCreateMisbehaviorCounter(key).ordinal++;\n }\n\n recordFiring(key: MisbehaviorCounterKey): void {\n this.getOrCreateMisbehaviorCounter(key).firings++;\n }\n\n clearMisbehaviorCounters(testId?: string): void {\n if (testId !== undefined) {\n this.misbehaviorCountersByTestId.delete(testId);\n if (!this.fixtureMatchCountsByTestId.has(testId)) this.counterTestIds.delete(testId);\n } else {\n this.misbehaviorCountersByTestId.clear();\n for (const id of this.counterTestIds) {\n if (!this.fixtureMatchCountsByTestId.has(id)) this.counterTestIds.delete(id);\n }\n }\n }\n\n /** @internal LLMock configures caller count identity before serving requests. */\n configureFixtureCountIdentity(identity: (fixture: Fixture) => Fixture): void {\n if (this.fixtureCountIdentityConfigured || this.fixtureMatchCountsByTestId.size > 0) {\n throw new Error(\"Fixture count identity must be configured once before counting\");\n }\n this.fixtureCountIdentity = identity;\n this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);\n this.fixtureCountIdentityConfigured = true;\n }\n\n /**\n * @internal A server with `responsesTools: \"extended\"` matches each fixture\n * through its extended view. `source` maps a view back to the caller's\n * fixture, so counts, `findByFixture` and `JournalEntry.response.fixture`\n * keep the caller's object. Configured once, before counting.\n */\n configureFixtureViewSource(source: (fixture: Fixture) => Fixture): void {\n if (this.fixtureViewSourceConfigured || this.fixtureMatchCountsByTestId.size > 0) {\n throw new Error(\"Fixture view source must be configured once before counting\");\n }\n this.fixtureViewSource = source;\n this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);\n this.fixtureViewSourceConfigured = true;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (this.fixtureCountKey(sibling) === this.fixtureCountKey(fixture)) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n this.clearMisbehaviorCounters(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n this.clearMisbehaviorCounters();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.clearMatchCounts();\n }\n\n get size(): number {\n return this.entries.length;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,MAAM,yBAAyB,KAAK;;;;;;;;;;;AAYpC,SAAS,QAAQ,MAA8C;AAC7D,KAAI,SAAS,KAAM,QAAO;CAC1B,MAAM,aAAa,KAAK,UAAU,KAAK;AACvC,KAAI,OAAO,WAAW,YAAY,OAAO,IAAI,uBAAwB,QAAO;AAG5E,QAAO;EACL,oBAAoB;EACpB,kBAAkB,OAAO,WAAW,YAAY,OAAO;EACvD,MAAM;EACP;;;;;;;;;;;;;;;;AAiBH,SAAgB,qBACd,MAC+B;AAC/B,QACE,SAAS,QACT,SAAS,UACT,MAAM,QAAS,KAAgC,SAAS,IACxD,OAAQ,KAA6B,UAAU;;;;;AAOnD,SAAS,WAAW,GAAY,GAAqB;AACnD,KAAI,aAAa,UAAU,aAAa,OACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAChD,QAAO,MAAM;;;;;;AAOf,SAAS,mBACP,GACA,GACS;AACT,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,SAAU,QAAO,MAAM;AACjE,KAAI,MAAM,QAAQ,EAAE,IAAI,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":"journal.cjs","names":["DEFAULT_TEST_ID","generateId"],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n MisbehaviorCounterKey,\n MisbehaviorCounters,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n isDeepStrictEqual(a.embeddingRequest, b.embeddingRequest) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.toolNamespace, b.toolNamespace) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\n/** Count-map keys resolve through `identity`, so every alias of a fixture finds its caller entry. */\nclass FixtureCountMap extends Map<Fixture, number> {\n constructor(private readonly identity: (fixture: Fixture) => Fixture) {\n super();\n }\n\n override get(key: Fixture): number | undefined {\n return super.get(this.identity(key));\n }\n\n override has(key: Fixture): boolean {\n return super.has(this.identity(key));\n }\n\n override set(key: Fixture, value: number): this {\n return super.set(this.identity(key), value);\n }\n\n override delete(key: Fixture): boolean {\n return super.delete(this.identity(key));\n }\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained across fixture match-count\n * and misbehavior counters. When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal implements MisbehaviorCounters {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n /** The fixture a request was served from, where the entry names its caller fixture instead. */\n private readonly servedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n /** An extended server's view of a fixture to the caller's fixture (configureFixtureViewSource). */\n private fixtureViewSource = (fixture: Fixture): Fixture => fixture;\n private fixtureCountIdentity = (fixture: Fixture): Fixture => fixture;\n /** The key a fixture is counted under: the caller's object behind any view or copy. */\n private readonly fixtureCountKey = (fixture: Fixture): Fixture =>\n this.fixtureCountIdentity(this.fixtureViewSource(fixture));\n private createFixtureCountMap = (): Map<Fixture, number> => new Map();\n private fixtureCountIdentityConfigured = false;\n private fixtureViewSourceConfigured = false;\n private readonly counterTestIds = new Set<string>();\n private readonly misbehaviorCountersByTestId = new Map<\n string,\n Map<string, Map<number, { ordinal: number; firings: number }>>\n >();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /**\n * The per-test-id cap on fixture match-count maps, for an MCP mount to pass\n * to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`\n * meaning unbounded, and never throws, whatever option was passed:\n * omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above\n * `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more\n * is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values\n * it is the number of test ids the journal keeps.\n *\n * An option between 0 and 1 is the exception. The journal keeps no test id\n * (each new count map is evicted as soon as it is made, so counts never\n * advance), and a store cap cannot say \"keep none\" because `0` is\n * unbounded. The getter returns `1`, the smallest bounded cap, so a store\n * given it keeps 1 test id where the journal keeps 0.\n */\n get fixtureCountsMaxTestIdsCap(): number {\n const cap = this.fixtureCountsMaxTestIds;\n if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;\n return Math.max(1, Math.floor(cap));\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n // A request is served from an extended server's view of a fixture, or\n // from LLMock's per-addition copy with misbehavior enabled; the entry\n // names the caller's fixture behind it, as in 1.44.0.\n const fixture = full.response.fixture;\n const source = fixture ? this.fixtureCountKey(fixture) : fixture;\n if (fixture && source !== fixture) {\n full.response = { ...full.response, fixture: source };\n this.servedFixtures.set(full, fixture);\n }\n if (matchedFixture) this.matchedFixtures.set(full, this.fixtureCountKey(matchedFixture));\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n const key = this.fixtureCountKey(fixture);\n return this.entries.filter((e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === key);\n }\n\n /**\n * @internal The fixture `entry`'s request was served from: the extended\n * view or the per-addition copy when the entry names the caller's fixture\n * behind it, otherwise `entry.response.fixture`. The journal JSON shows it.\n */\n servedFixture(entry: JournalEntry): Fixture | null {\n return this.servedFixtures.get(entry) ?? entry.response.fixture;\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? this.createFixtureCountMap();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = this.createFixtureCountMap();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n this.admitCounterTestId(testId);\n }\n return counts;\n }\n\n /** Match and fault mutations share one admission order and capacity. */\n private admitCounterTestId(testId: string): void {\n this.counterTestIds.add(testId);\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.counterTestIds.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.counterTestIds.values().next().value;\n if (oldest !== undefined) {\n this.counterTestIds.delete(oldest);\n this.fixtureMatchCountsByTestId.delete(oldest);\n this.misbehaviorCountersByTestId.delete(oldest);\n }\n }\n }\n\n private getOrCreateMisbehaviorCounter(key: MisbehaviorCounterKey) {\n let sources = this.misbehaviorCountersByTestId.get(key.testId);\n if (!sources) {\n sources = new Map();\n this.misbehaviorCountersByTestId.set(key.testId, sources);\n this.admitCounterTestId(key.testId);\n }\n let entries = sources.get(key.sourceKey);\n if (!entries) {\n entries = new Map();\n sources.set(key.sourceKey, entries);\n }\n let counter = entries.get(key.entryIndex);\n if (!counter) {\n counter = { ordinal: 0, firings: 0 };\n entries.set(key.entryIndex, counter);\n }\n return counter;\n }\n\n getFiringCount(key: MisbehaviorCounterKey): number {\n return (\n this.misbehaviorCountersByTestId.get(key.testId)?.get(key.sourceKey)?.get(key.entryIndex)\n ?.firings ?? 0\n );\n }\n\n nextOrdinal(key: MisbehaviorCounterKey): number {\n return this.getOrCreateMisbehaviorCounter(key).ordinal++;\n }\n\n recordFiring(key: MisbehaviorCounterKey): void {\n this.getOrCreateMisbehaviorCounter(key).firings++;\n }\n\n clearMisbehaviorCounters(testId?: string): void {\n if (testId !== undefined) {\n this.misbehaviorCountersByTestId.delete(testId);\n if (!this.fixtureMatchCountsByTestId.has(testId)) this.counterTestIds.delete(testId);\n } else {\n this.misbehaviorCountersByTestId.clear();\n for (const id of this.counterTestIds) {\n if (!this.fixtureMatchCountsByTestId.has(id)) this.counterTestIds.delete(id);\n }\n }\n }\n\n /** @internal LLMock configures caller count identity before serving requests. */\n configureFixtureCountIdentity(identity: (fixture: Fixture) => Fixture): void {\n if (this.fixtureCountIdentityConfigured || this.fixtureMatchCountsByTestId.size > 0) {\n throw new Error(\"Fixture count identity must be configured once before counting\");\n }\n this.fixtureCountIdentity = identity;\n this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);\n this.fixtureCountIdentityConfigured = true;\n }\n\n /**\n * @internal A server with `responsesTools: \"extended\"` matches each fixture\n * through its extended view. `source` maps a view back to the caller's\n * fixture, so counts, `findByFixture` and `JournalEntry.response.fixture`\n * keep the caller's object. Configured once, before counting.\n */\n configureFixtureViewSource(source: (fixture: Fixture) => Fixture): void {\n if (this.fixtureViewSourceConfigured || this.fixtureMatchCountsByTestId.size > 0) {\n throw new Error(\"Fixture view source must be configured once before counting\");\n }\n this.fixtureViewSource = source;\n this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);\n this.fixtureViewSourceConfigured = true;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (this.fixtureCountKey(sibling) === this.fixtureCountKey(fixture)) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n this.clearMisbehaviorCounters(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n this.clearMisbehaviorCounters();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.clearMatchCounts();\n }\n\n get size(): number {\n return this.entries.length;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,MAAM,yBAAyB,KAAK;;;;;;;;;;;AAYpC,SAAS,QAAQ,MAA8C;AAC7D,KAAI,SAAS,KAAM,QAAO;CAC1B,MAAM,aAAa,KAAK,UAAU,KAAK;AACvC,KAAI,OAAO,WAAW,YAAY,OAAO,IAAI,uBAAwB,QAAO;AAG5E,QAAO;EACL,oBAAoB;EACpB,kBAAkB,OAAO,WAAW,YAAY,OAAO;EACvD,MAAM;EACP;;;;;;;;;;;;;;;;AAiBH,SAAgB,qBACd,MAC+B;AAC/B,QACE,SAAS,QACT,SAAS,UACT,MAAM,QAAS,KAAgC,SAAS,IACxD,OAAQ,KAA6B,UAAU;;;;;AAOnD,SAAS,WAAW,GAAY,GAAqB;AACnD,KAAI,aAAa,UAAU,aAAa,OACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAChD,QAAO,MAAM;;;;;;AAOf,SAAS,mBACP,GACA,GACS;AACT,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,SAAU,QAAO,MAAM;AACjE,KAAI,MAAM,QAAQ,EAAE,IAAI,MAAM,QAAQ,EAAE,CACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,MAAM,EAAE,GAAG;AAC/D,KAAI,aAAa,UAAU,aAAa,OACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAChD,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