@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":"cohere.js","names":[],"sources":["../src/cohere.ts"],"sourcesContent":["/**\n * Cohere v2 Chat API endpoint support.\n *\n * Translates incoming /v2/chat requests into the ChatCompletionRequest\n * format used by the fixture router, and converts fixture responses back into\n * Cohere's typed SSE streaming (or non-streaming) format.\n *\n * Cohere uses typed SSE events (event: + data: lines), similar to the\n * Claude Messages handler in messages.ts.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n FixtureBlock,\n HandlerDefaults,\n RecordedTimings,\n ResponseOverrides,\n StreamingProfile,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n prepareOpenAIChatMisbehavior,\n resolveOpenAIChatMisbehaviorUsage,\n generateMessageId,\n generateToolCallId,\n generateDeterministicEmbedding,\n extractOverrides,\n requireEmittedFunctionToolCalls,\n isTextResponse,\n isToolCallResponse,\n isCombinedFixtureResponse,\n isEmbeddingResponse,\n isErrorResponse,\n serializeErrorResponse,\n validateChatMessages,\n validateToolsField,\n flattenHeaders,\n isJsonObject,\n getTestId,\n resolveFixtureBlockOutcome,\n resolveResponse,\n resolveStrictMode,\n resolveReasoningForModel,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n servedToolArgs,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic, recordMatchOptions } from \"./router.js\";\nimport { writeErrorResponse, delay, calculateDelay } from \"./sse-writer.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport {\n normalizeDirectToolSchema,\n planMisbehavior,\n recordMisbehaviorOutcome,\n} from \"./misbehavior.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Cohere v2 Chat request types ───────────────────────────────────────────\n\ninterface CohereToolCallDef {\n id?: string;\n type: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface CohereContentPart {\n type: string;\n text?: string;\n}\n\ninterface CohereMessage {\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n content: string | CohereContentPart[];\n tool_call_id?: string;\n tool_calls?: CohereToolCallDef[];\n}\n\n// OpenAI-style tool definition (wrapped in { type: \"function\", function: { ... } })\ninterface CohereToolDefOpenAI {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\n// Cohere v2 native tool definition (flat: { name, description, parameter_definitions })\ninterface CohereToolDefNative {\n name: string;\n description?: string;\n parameter_definitions?: object;\n}\n\ntype CohereToolDef = CohereToolDefOpenAI | CohereToolDefNative;\n\ninterface CohereRequest {\n model: string;\n messages: CohereMessage[];\n stream?: boolean;\n tools?: CohereToolDef[];\n response_format?: { type: string; json_schema?: object };\n temperature?: number;\n max_tokens?: number;\n}\n\n// ─── Cohere SSE event types ─────────────────────────────────────────────────\n\ninterface CohereSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\n// ─── Zero-value usage block ─────────────────────────────────────────────────\n\nconst ZERO_USAGE = {\n billed_units: { input_tokens: 0, output_tokens: 0, search_units: 0, classifications: 0 },\n tokens: { input_tokens: 0, output_tokens: 0 },\n};\n\n// ─── Cohere finish reason / usage mapping ──────────────────────────────────\n\nfunction cohereFinishReason(\n overrideFinishReason: string | undefined,\n defaultReason: string,\n): string {\n if (!overrideFinishReason) return defaultReason;\n if (overrideFinishReason === \"stop\") return \"COMPLETE\";\n if (overrideFinishReason === \"tool_calls\") return \"TOOL_CALL\";\n if (overrideFinishReason === \"length\") return \"MAX_TOKENS\";\n return overrideFinishReason;\n}\n\nfunction cohereUsage(overrides?: ResponseOverrides): typeof ZERO_USAGE {\n if (!overrides?.usage) return ZERO_USAGE;\n const inputTokens = overrides.usage.input_tokens ?? overrides.usage.prompt_tokens ?? 0;\n const outputTokens = overrides.usage.output_tokens ?? overrides.usage.completion_tokens ?? 0;\n return {\n billed_units: {\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n search_units: 0,\n classifications: 0,\n },\n tokens: { input_tokens: inputTokens, output_tokens: outputTokens },\n };\n}\n\n// ─── Input conversion: Cohere → ChatCompletionRequest ───────────────────────\n\n/** Extract plain text from structured content (array of { type, text } parts) or passthrough string. */\nfunction extractTextContent(content: string | CohereContentPart[] | null | undefined): string {\n if (content === null || content === undefined) return \"\";\n if (typeof content === \"string\") return content;\n return content\n .filter(\n (part) =>\n part !== null && part !== undefined && part.type === \"text\" && part.text !== undefined,\n )\n .map((part) => part.text!)\n .join(\"\");\n}\n\n/** Type guard: is this an OpenAI-style tool definition (has `function` key)? */\nfunction isOpenAIToolDef(t: CohereToolDef): t is CohereToolDefOpenAI {\n return \"function\" in t && typeof (t as CohereToolDefOpenAI).function === \"object\";\n}\n\nexport function cohereToCompletionRequest(req: CohereRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n const textContent = extractTextContent(msg.content);\n if (msg.role === \"system\") {\n messages.push({ role: \"system\", content: textContent });\n } else if (msg.role === \"user\") {\n messages.push({ role: \"user\", content: textContent });\n } else if (msg.role === \"assistant\") {\n if (msg.tool_calls && msg.tool_calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: textContent || null,\n tool_calls: msg.tool_calls.map((tc) => ({\n id: tc.id ?? generateToolCallId(),\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n })),\n });\n } else {\n messages.push({ role: \"assistant\", content: textContent });\n }\n } else if (msg.role === \"tool\") {\n messages.push({\n role: \"tool\",\n content: textContent,\n tool_call_id: msg.tool_call_id,\n });\n }\n }\n\n // Convert tools — accept both OpenAI format and Cohere v2 native format\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => {\n if (isOpenAIToolDef(t)) {\n return {\n type: \"function\" as const,\n function: {\n name: t.function.name,\n description: t.function.description,\n parameters: t.function.parameters,\n },\n };\n }\n // Preserve the native map identity before adapting to canonical JSON Schema.\n const schema = normalizeDirectToolSchema({ tools: [t] }, t.name);\n // Cohere v2 native format: { name, description, parameter_definitions }\n return {\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: schema\n ? { type: \"object\", properties: schema.properties, required: [...schema.required] }\n : undefined,\n },\n };\n });\n }\n\n return {\n model: req.model,\n messages,\n stream: req.stream,\n tools,\n ...(req.response_format && { response_format: req.response_format }),\n ...(req.temperature !== undefined && { temperature: req.temperature }),\n ...(req.max_tokens !== undefined && { max_tokens: req.max_tokens }),\n };\n}\n\n// ─── Response building: fixture → Cohere v2 Chat format ─────────────────────\n\n// Non-streaming text response\nfunction buildCohereTextResponse(\n content: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n contentBlocks.push({ type: \"text\", text: content });\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming tool call response\nfunction buildCohereToolCallResponse(\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const cohereCalls = toolCalls.map((tc) => {\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // Reasoning as a leading text block (Cohere has no native reasoning type)\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming content + tool calls response\nfunction buildCohereContentWithToolCallsResponse(\n content: string,\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): object {\n // Cohere's non-streaming response keeps text in `message.content[]` and tool\n // calls in the SEPARATE `message.tool_calls[]` field, so the relative ORDER\n // of a text vs. toolCall block is NOT observable on the wire (unlike the\n // ordered streaming events, or Anthropic/Gemini's single ordered array).\n // When `blocks` is present we therefore derive both fields FROM the blocks\n // (so a blocks-only fixture still produces correct output) but make no\n // ordering guarantee between the two fields. Legacy fixtures use the\n // `content` + `toolCalls` inputs unchanged.\n // Resolve the blocks exactly once (pure: validate + copy, no id-gen) and\n // reuse the single result for BOTH the tool-call and text derivation below.\n const outcome = blocks && blocks.length > 0 ? resolveFixtureBlockOutcome(blocks) : undefined;\n const resolvedBlocks = outcome?.ordered;\n\n const effectiveToolCalls: ToolCall[] = resolvedBlocks\n ? resolvedBlocks\n .filter((b): b is Extract<FixtureBlock, { type: \"toolCall\" }> => b.type === \"toolCall\")\n .map((b) => ({ name: b.name, arguments: b.arguments, id: b.id }))\n : toolCalls;\n\n const cohereCalls = effectiveToolCalls.map((tc) => {\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // For the blocks path, derive text only from actual text blocks. A tool-only\n // blocks fixture has no text block, so it must NOT emit a spurious empty\n // `{ type: \"text\", text: \"\" }` entry (real Cohere wouldn't). The legacy\n // (no-blocks) path is unchanged: it always emits the `content` text entry.\n const textBlocks = resolvedBlocks?.filter(\n (b): b is Extract<FixtureBlock, { type: \"text\" }> => b.type === \"text\",\n );\n const hasTextEntry = resolvedBlocks ? (textBlocks?.length ?? 0) > 0 : true;\n const effectiveContent: string = resolvedBlocks\n ? (textBlocks ?? []).map((b) => b.text).join(\"\")\n : content;\n\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n if (hasTextEntry) {\n contentBlocks.push({ type: \"text\", text: effectiveContent });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome && !outcome.hasToolCalls ? \"COMPLETE\" : \"TOOL_CALL\",\n ),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// ─── Streaming event builders ───────────────────────────────────────────────\n\nfunction buildCohereTextStreamEvents(\n content: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereToolCallStreamEvents(\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n // Reasoning as a text block before the tool plan (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: 0,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: 0,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: 0 });\n }\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereContentWithToolCallsStreamEvents(\n content: string,\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n if (blocks && blocks.length > 0) {\n // NEW path (#274): emit Cohere SSE events in the blocks' ARRAY ORDER so a\n // tool-first / interleaved fixture streams its tool call before its text.\n // Cohere v2 events are ordered, so tool-first is wire-expressible. The\n // tool-plan-delta is emitted once before the first toolCall block (Cohere\n // requires it preceding tool calls). Legacy fixtures (no blocks) skip this.\n const outcome = resolveFixtureBlockOutcome(blocks);\n const resolved = outcome.ordered;\n let toolPlanEmitted = false;\n let toolIdx = 0;\n resolved.forEach((block) => {\n if (block.type === \"toolCall\") {\n if (!toolPlanEmitted) {\n events.push({\n type: \"tool-plan-delta\",\n delta: { message: { tool_plan: \"I will use the requested tool.\" } },\n });\n toolPlanEmitted = true;\n }\n const callId = block.id || generateToolCallId();\n const args = servedToolArgs(block, \"string\", logger);\n const argsJson = args.raw;\n events.push({\n type: \"tool-call-start\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: { name: block.name, arguments: \"\" },\n },\n },\n },\n });\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n events.push({\n type: \"tool-call-delta\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: { function: { arguments: argsJson.slice(i, i + chunkSize) } },\n },\n },\n });\n }\n events.push({ type: \"tool-call-end\", index: toolIdx });\n toolIdx++;\n } else {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < block.text.length; i += chunkSize) {\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: { content: { type: \"text\", text: block.text.slice(i, i + chunkSize) } },\n },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n });\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome.hasToolCalls ? \"TOOL_CALL\" : \"COMPLETE\",\n ),\n usage: cohereUsage(overrides),\n },\n });\n return events;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n // Tool call events\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\n// ─── SSE writer for Cohere typed events ─────────────────────────────────────\n\ninterface CohereStreamOptions {\n terminalSentinel?: boolean;\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nasync function writeCohereSSEStream(\n res: http.ServerResponse,\n events: CohereSSEEvent[],\n optionsOrLatency?: number | CohereStreamOptions,\n): Promise<boolean> {\n const opts: CohereStreamOptions =\n typeof optionsOrLatency === \"number\" ? { latency: optionsOrLatency } : (optionsOrLatency ?? {});\n const latency = opts.latency ?? 0;\n const profile = opts.streamingProfile;\n const { recordedTimings, replaySpeed } = opts;\n const signal = opts.signal;\n const onChunkSent = opts.onChunkSent;\n\n if (res.writableEnded) return true;\n res.setHeader(\"Content-Type\", \"text/event-stream\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.setHeader(\"Connection\", \"keep-alive\");\n\n let chunkIndex = 0;\n for (const event of events) {\n const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);\n if (chunkDelay > 0) await delay(chunkDelay, signal);\n if (signal?.aborted) return false;\n if (res.writableEnded) return true;\n res.write(`event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`);\n onChunkSent?.();\n if (signal?.aborted) return false;\n chunkIndex++;\n }\n\n if (!res.writableEnded) {\n if (opts.terminalSentinel && !signal?.aborted) res.write(\"data: [DONE]\\n\\n\");\n res.end();\n }\n return true;\n}\n\n// ─── Request handler ────────────────────────────────────────────────────────\n\nexport async function handleCohere(\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 const { logger } = defaults;\n setCorsHeaders(res);\n\n let cohereReq: CohereRequest;\n try {\n cohereReq = JSON.parse(raw) as CohereRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\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 body: ${detail}`,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `cohereReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(cohereReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Validate required model field\n if (!cohereReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\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: \"model is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Reject wrong-typed message/tool fields before the converter dereferences\n // them — otherwise the TypeError surfaces as a 500 instead of a 400.\n let shapeError = validateChatMessages(cohereReq.messages) ?? validateToolsField(cohereReq.tools);\n if (!shapeError && Array.isArray(cohereReq.tools)) {\n const nullFunctionIndex = cohereReq.tools.findIndex(\n (tool) => \"function\" in tool && tool.function === null,\n );\n if (nullFunctionIndex !== -1) {\n shapeError = `tools[${nullFunctionIndex}].function must be an object`;\n }\n }\n if (shapeError) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\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: `Invalid request: ${shapeError}`,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = cohereToCompletionRequest(cohereReq);\n completionReq._endpointType = \"chat\";\n completionReq._context = getContext(req);\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n 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 {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictStatus = 503;\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/chat\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: strictStatus,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"cohere\",\n req.url ?? \"/v2/chat\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const resolvedResponse = await resolveResponse(fixture, completionReq);\n const misbehavior = planMisbehavior({\n wire: \"cohere\",\n fixture,\n response: resolvedResponse,\n request: completionReq,\n stream: cohereReq.stream === true,\n emitsToolCallIds: true,\n defaults,\n rawHeaders: req.headers,\n url: req.url,\n });\n if (misbehavior.kind === \"error\") {\n const entry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: misbehavior.status, fixture },\n });\n recordMisbehaviorOutcome({ entry, summary: misbehavior.summary, defaults, testId });\n if (!misbehavior.summary?.evaluations.length) logger.error(misbehavior.message);\n writeErrorResponse(\n res,\n misbehavior.status,\n JSON.stringify({ message: misbehavior.message, code: misbehavior.code }),\n );\n return;\n }\n // Cohere carries the same raw argument strings and call identities as Chat.\n // Reuse the accepted preparation so generated/duplicate IDs match metadata.\n const prepared =\n misbehavior.kind === \"applied\" ? prepareOpenAIChatMisbehavior(misbehavior) : undefined;\n const observedK5Stream =\n cohereReq.stream === true && prepared?.summary.fault === \"stop-length-mid-tool\";\n const appliedReasoning =\n prepared && \"reasoning\" in prepared.response\n ? resolveReasoningForModel(\n prepared.response.reasoning,\n cohereReq.model,\n resolveStrictMode(defaults.strict, req.headers),\n logger,\n )\n : undefined;\n const usage = prepared\n ? resolveOpenAIChatMisbehaviorUsage(prepared, completionReq, appliedReasoning !== undefined)\n : undefined;\n const response =\n prepared && usage\n ? {\n ...prepared.response,\n usage,\n ...(prepared.stop\n ? { finishReason: observedK5Stream ? \"tool_calls\" : prepared.stop }\n : {}),\n }\n : resolvedResponse;\n const summary = prepared?.summary ?? misbehavior.summary;\n const empty = prepared?.summary.fault === \"empty-response\";\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Content + tool calls response (must be checked before text/tool-only branches)\n if (isCombinedFixtureResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n const body = buildCohereContentWithToolCallsResponse(\n response.content ?? \"\",\n functionToolCalls,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereContentWithToolCallsStreamEvents(\n response.content ?? \"\",\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n terminalSentinel: observedK5Stream,\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n if (cohereReq.stream !== true) {\n const body = empty\n ? {\n ...buildCohereTextResponse(\"\", undefined, overrides),\n message: {\n role: \"assistant\",\n content: [],\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n }\n : buildCohereTextResponse(response.content, effReasoning, overrides);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereTextStreamEvents(\n response.content,\n chunkSize,\n effReasoning,\n overrides,\n ).filter((event) => !empty || event.type === \"message-start\" || event.type === \"message-end\");\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n terminalSentinel: observedK5Stream,\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n const body = buildCohereToolCallResponse(functionToolCalls, logger, effReasoning, overrides);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereToolCallStreamEvents(\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n terminalSentinel: observedK5Stream,\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Unknown response type\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n recordMisbehaviorOutcome({ entry: journalEntry, summary, defaults, testId });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n },\n }),\n );\n}\n\n// ─── Cohere v2 Embed API types ────────────────────────────────────────────\n\ninterface CohereEmbedRequest {\n texts: string[];\n model: string;\n input_type?: string;\n embedding_types?: string[];\n truncate?: string;\n}\n\ninterface CohereEmbedResponse {\n id: string;\n texts: string[];\n embeddings: Record<string, number[][]>;\n meta: { api_version: { version: string } };\n}\n\n// ─── Cohere Embed handler ─────────────────────────────────────────────────\n\nexport async function handleCohereEmbed(\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 const { logger } = defaults;\n setCorsHeaders(res);\n\n let embedReq: CohereEmbedRequest;\n try {\n embedReq = JSON.parse(raw) as CohereEmbedRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 body: ${detail}`,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `embedReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(embedReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Validate required fields\n if (!embedReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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: \"model is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (!embedReq.texts || !Array.isArray(embedReq.texts)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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: \"Invalid request: texts array is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Every text must be a string — a number reaches createHash().update() in\n // the no-fixture fallback and throws a TypeError (500) instead of a 400.\n if (!embedReq.texts.every((text) => typeof text === \"string\")) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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: \"Invalid request: texts must be an array of strings\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Concatenate all texts for fixture matching\n const combinedInput = embedReq.texts.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router\n const syntheticReq: ChatCompletionRequest = {\n model: embedReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n 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 {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n // Determine requested embedding types (default to float)\n const embeddingTypes =\n embedReq.embedding_types && embedReq.embedding_types.length > 0\n ? embedReq.embedding_types\n : [\"float\"];\n\n function rejectInvalidEmbeddingTypes(): boolean {\n if (embedReq.embedding_types == null) return false;\n const isArray = Array.isArray(embedReq.embedding_types);\n if (isArray && embedReq.embedding_types.every((type) => typeof type === \"string\")) return false;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 400, fixture: fixture ?? null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: isArray\n ? \"Invalid request: embedding_types must be an array of strings\"\n : \"Invalid request: embedding_types must be an array\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return true;\n }\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 // Embedding response — use the fixture's embedding for each input text\n if (isEmbeddingResponse(response)) {\n if (rejectInvalidEmbeddingTypes()) return;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const vectors = embedReq.texts.map(() => [...response.embedding]);\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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: {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n // No fixture match — check strict mode\n if (resolveStrictMode(defaults.strict, req.headers)) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/embed\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 },\n }),\n );\n return;\n }\n\n // Try record-and-replay proxy\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"cohere\",\n req.url ?? \"/v2/embed\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 if (rejectInvalidEmbeddingTypes()) return;\n\n // No fixture match — generate deterministic embeddings from input texts\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n const dimensions = 1024; // Cohere embed-v4.0 default\n const vectors = embedReq.texts.map((text) => generateDeterministicEmbedding(text, dimensions));\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;;;AA+HA,MAAM,aAAa;CACjB,cAAc;EAAE,cAAc;EAAG,eAAe;EAAG,cAAc;EAAG,iBAAiB;EAAG;CACxF,QAAQ;EAAE,cAAc;EAAG,eAAe;EAAG;CAC9C;AAID,SAAS,mBACP,sBACA,eACQ;AACR,KAAI,CAAC,qBAAsB,QAAO;AAClC,KAAI,yBAAyB,OAAQ,QAAO;AAC5C,KAAI,yBAAyB,aAAc,QAAO;AAClD,KAAI,yBAAyB,SAAU,QAAO;AAC9C,QAAO;;AAGT,SAAS,YAAY,WAAkD;AACrE,KAAI,CAAC,WAAW,MAAO,QAAO;CAC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BAAkB;AAChC,WAAQ,IAAI;IACV,QAAQ,IAAI,UAAU;IACtB,MAAM,IAAI,OAAO;IACjB,SAAS,eAAe,IAAI,QAAQ;IACpC,MAAM;IACN,UAAU;KAAE,QAAQ,IAAI,cAAc;KAAK,SAAS;KAAM,QAAQ;KAAS;IAC5E,CAAC;AACF;;;AAIJ,KAAI,6BAA6B,CAAE;AAGnC,QAAO,KACL,qCAAqC,cAAc,MAAM,GAAG,GAAG,CAAC,sCACjE;CACD,MAAM,aAAa;CACnB,MAAM,UAAU,SAAS,MAAM,KAAK,SAAS,+BAA+B,MAAM,WAAW,CAAC;CAC9F,MAAM,aAAyC,EAAE;AACjD,MAAK,MAAM,KAAK,eACd,YAAW,KAAK;AAGlB,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM;EACzC,CAAC;CAEF,MAAM,OAA4B;EAChC,IAAI,mBAAmB;EACvB,OAAO,SAAS;EAChB;EACA,MAAM,EAAE,aAAa,EAAE,SAAS,KAAK,EAAE;EACxC;AACD,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IAAI,KAAK,UAAU,KAAK,CAAC"}
1
+ {"version":3,"file":"cohere.js","names":["renderCohereUsage"],"sources":["../src/cohere.ts"],"sourcesContent":["/**\n * Cohere v2 Chat API endpoint support.\n *\n * Translates incoming /v2/chat requests into the ChatCompletionRequest\n * format used by the fixture router, and converts fixture responses back into\n * Cohere's typed SSE streaming (or non-streaming) format.\n *\n * Cohere uses typed SSE events (event: + data: lines), similar to the\n * Claude Messages handler in messages.ts.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n FixtureBlock,\n HandlerDefaults,\n ResponseOverrides,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n prepareOpenAIChatMisbehavior,\n resolveOpenAIChatMisbehaviorUsage,\n generateMessageId,\n generateToolCallId,\n generateDeterministicEmbedding,\n extractOverrides,\n requireEmittedFunctionToolCalls,\n isTextResponse,\n isToolCallResponse,\n isCombinedFixtureResponse,\n isEmbeddingResponse,\n isErrorResponse,\n isRawResponse,\n validateChatMessages,\n validateToolsField,\n flattenHeaders,\n isJsonObject,\n getTestId,\n resolveFixtureBlockOutcome,\n resolveResponse,\n resolveReasoningForModel,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n servedToolArgs,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic, recordMatchOptions } from \"./router.js\";\nimport { writeErrorResponse, typedSseCodec } from \"./sse-writer.js\";\nimport { deliverJson, deliverStream } from \"./response/deliver.js\";\nimport { proxyInterruption, withHangUpDetection } from \"./response/proxy.js\";\nimport { servedPayloadLength } from \"./response/timing.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport {\n normalizeDirectToolSchema,\n planMisbehavior,\n recordMisbehaviorOutcome,\n} from \"./misbehavior.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport { mapCohereFinish } from \"./response/finish.js\";\nimport { render as renderCohereUsage } from \"./response/usage/codecs/cohere.js\";\nimport { resolveRequestDecisions, strictOverrideField } from \"./response/policy.js\";\nimport { renderError } from \"./response/errors.js\";\nimport { serveRawResponse } from \"./response/raw.js\";\n\n// ─── Cohere v2 Chat request types ───────────────────────────────────────────\n\ninterface CohereToolCallDef {\n id?: string;\n type: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface CohereContentPart {\n type: string;\n text?: string;\n}\n\ninterface CohereMessage {\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n content: string | CohereContentPart[];\n tool_call_id?: string;\n tool_calls?: CohereToolCallDef[];\n}\n\n// OpenAI-style tool definition (wrapped in { type: \"function\", function: { ... } })\ninterface CohereToolDefOpenAI {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\n// Cohere v2 native tool definition (flat: { name, description, parameter_definitions })\ninterface CohereToolDefNative {\n name: string;\n description?: string;\n parameter_definitions?: object;\n}\n\ntype CohereToolDef = CohereToolDefOpenAI | CohereToolDefNative;\n\ninterface CohereRequest {\n model: string;\n messages: CohereMessage[];\n stream?: boolean;\n tools?: CohereToolDef[];\n response_format?: { type: string; json_schema?: object };\n temperature?: number;\n max_tokens?: number;\n}\n\n// ─── Cohere SSE event types ─────────────────────────────────────────────────\n\ninterface CohereSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\n// ─── Cohere finish reason / usage mapping ──────────────────────────────────\n\nfunction cohereFinishReason(\n overrideFinishReason: string | undefined,\n defaultReason: string,\n): string {\n if (!overrideFinishReason) return defaultReason;\n return mapCohereFinish(overrideFinishReason);\n}\n\nfunction cohereUsage(overrides?: ResponseOverrides): ReturnType<typeof renderCohereUsage> {\n return renderCohereUsage(overrides);\n}\n\n// ─── Input conversion: Cohere → ChatCompletionRequest ───────────────────────\n\n/** Extract plain text from structured content (array of { type, text } parts) or passthrough string. */\nfunction extractTextContent(content: string | CohereContentPart[] | null | undefined): string {\n if (content === null || content === undefined) return \"\";\n if (typeof content === \"string\") return content;\n return content\n .filter(\n (part) =>\n part !== null && part !== undefined && part.type === \"text\" && part.text !== undefined,\n )\n .map((part) => part.text!)\n .join(\"\");\n}\n\n/** Type guard: is this an OpenAI-style tool definition (has `function` key)? */\nfunction isOpenAIToolDef(t: CohereToolDef): t is CohereToolDefOpenAI {\n return \"function\" in t && typeof (t as CohereToolDefOpenAI).function === \"object\";\n}\n\nexport function cohereToCompletionRequest(req: CohereRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n const textContent = extractTextContent(msg.content);\n if (msg.role === \"system\") {\n messages.push({ role: \"system\", content: textContent });\n } else if (msg.role === \"user\") {\n messages.push({ role: \"user\", content: textContent });\n } else if (msg.role === \"assistant\") {\n if (msg.tool_calls && msg.tool_calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: textContent || null,\n tool_calls: msg.tool_calls.map((tc) => ({\n id: tc.id ?? generateToolCallId(),\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n })),\n });\n } else {\n messages.push({ role: \"assistant\", content: textContent });\n }\n } else if (msg.role === \"tool\") {\n messages.push({\n role: \"tool\",\n content: textContent,\n tool_call_id: msg.tool_call_id,\n });\n }\n }\n\n // Convert tools — accept both OpenAI format and Cohere v2 native format\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => {\n if (isOpenAIToolDef(t)) {\n return {\n type: \"function\" as const,\n function: {\n name: t.function.name,\n description: t.function.description,\n parameters: t.function.parameters,\n },\n };\n }\n // Preserve the native map identity before adapting to canonical JSON Schema.\n const schema = normalizeDirectToolSchema({ tools: [t] }, t.name);\n // Cohere v2 native format: { name, description, parameter_definitions }\n return {\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: schema\n ? { type: \"object\", properties: schema.properties, required: [...schema.required] }\n : undefined,\n },\n };\n });\n }\n\n return {\n model: req.model,\n messages,\n stream: req.stream,\n tools,\n ...(req.response_format && { response_format: req.response_format }),\n ...(req.temperature !== undefined && { temperature: req.temperature }),\n ...(req.max_tokens !== undefined && { max_tokens: req.max_tokens }),\n };\n}\n\n// ─── Response building: fixture → Cohere v2 Chat format ─────────────────────\n\n// Non-streaming text response\nfunction buildCohereTextResponse(\n content: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n contentBlocks.push({ type: \"text\", text: content });\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming tool call response\nfunction buildCohereToolCallResponse(\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const cohereCalls = toolCalls.map((tc) => {\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // Reasoning as a leading text block (Cohere has no native reasoning type)\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming content + tool calls response\nfunction buildCohereContentWithToolCallsResponse(\n content: string,\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): object {\n // Cohere's non-streaming response keeps text in `message.content[]` and tool\n // calls in the SEPARATE `message.tool_calls[]` field, so the relative ORDER\n // of a text vs. toolCall block is NOT observable on the wire (unlike the\n // ordered streaming events, or Anthropic/Gemini's single ordered array).\n // When `blocks` is present we therefore derive both fields FROM the blocks\n // (so a blocks-only fixture still produces correct output) but make no\n // ordering guarantee between the two fields. Legacy fixtures use the\n // `content` + `toolCalls` inputs unchanged.\n // Resolve the blocks exactly once (pure: validate + copy, no id-gen) and\n // reuse the single result for BOTH the tool-call and text derivation below.\n const outcome = blocks && blocks.length > 0 ? resolveFixtureBlockOutcome(blocks) : undefined;\n const resolvedBlocks = outcome?.ordered;\n\n const effectiveToolCalls: ToolCall[] = resolvedBlocks\n ? resolvedBlocks\n .filter((b): b is Extract<FixtureBlock, { type: \"toolCall\" }> => b.type === \"toolCall\")\n .map((b) => ({ name: b.name, arguments: b.arguments, id: b.id }))\n : toolCalls;\n\n const cohereCalls = effectiveToolCalls.map((tc) => {\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // For the blocks path, derive text only from actual text blocks. A tool-only\n // blocks fixture has no text block, so it must NOT emit a spurious empty\n // `{ type: \"text\", text: \"\" }` entry (real Cohere wouldn't). The legacy\n // (no-blocks) path is unchanged: it always emits the `content` text entry.\n const textBlocks = resolvedBlocks?.filter(\n (b): b is Extract<FixtureBlock, { type: \"text\" }> => b.type === \"text\",\n );\n const hasTextEntry = resolvedBlocks ? (textBlocks?.length ?? 0) > 0 : true;\n const effectiveContent: string = resolvedBlocks\n ? (textBlocks ?? []).map((b) => b.text).join(\"\")\n : content;\n\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n if (hasTextEntry) {\n contentBlocks.push({ type: \"text\", text: effectiveContent });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome && !outcome.hasToolCalls ? \"COMPLETE\" : \"TOOL_CALL\",\n ),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// ─── Streaming event builders ───────────────────────────────────────────────\n\nfunction buildCohereTextStreamEvents(\n content: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereToolCallStreamEvents(\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n // Reasoning as a text block before the tool plan (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: 0,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: 0,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: 0 });\n }\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereContentWithToolCallsStreamEvents(\n content: string,\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n if (blocks && blocks.length > 0) {\n // NEW path (#274): emit Cohere SSE events in the blocks' ARRAY ORDER so a\n // tool-first / interleaved fixture streams its tool call before its text.\n // Cohere v2 events are ordered, so tool-first is wire-expressible. The\n // tool-plan-delta is emitted once before the first toolCall block (Cohere\n // requires it preceding tool calls). Legacy fixtures (no blocks) skip this.\n const outcome = resolveFixtureBlockOutcome(blocks);\n const resolved = outcome.ordered;\n let toolPlanEmitted = false;\n let toolIdx = 0;\n resolved.forEach((block) => {\n if (block.type === \"toolCall\") {\n if (!toolPlanEmitted) {\n events.push({\n type: \"tool-plan-delta\",\n delta: { message: { tool_plan: \"I will use the requested tool.\" } },\n });\n toolPlanEmitted = true;\n }\n const callId = block.id || generateToolCallId();\n const args = servedToolArgs(block, \"string\", logger);\n const argsJson = args.raw;\n events.push({\n type: \"tool-call-start\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: { name: block.name, arguments: \"\" },\n },\n },\n },\n });\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n events.push({\n type: \"tool-call-delta\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: { function: { arguments: argsJson.slice(i, i + chunkSize) } },\n },\n },\n });\n }\n events.push({ type: \"tool-call-end\", index: toolIdx });\n toolIdx++;\n } else {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < block.text.length; i += chunkSize) {\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: { content: { type: \"text\", text: block.text.slice(i, i + chunkSize) } },\n },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n });\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome.hasToolCalls ? \"TOOL_CALL\" : \"COMPLETE\",\n ),\n usage: cohereUsage(overrides),\n },\n });\n return events;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n // Tool call events\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\n// ─── Request handler ────────────────────────────────────────────────────────\n\nexport async function handleCohere(\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 const { logger } = defaults;\n setCorsHeaders(res);\n\n let cohereReq: CohereRequest;\n try {\n cohereReq = JSON.parse(raw) as CohereRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Malformed JSON body: ${detail}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `cohereReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(cohereReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Validate required model field\n if (!cohereReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"model is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject wrong-typed message/tool fields before the converter dereferences\n // them — otherwise the TypeError surfaces as a 500 instead of a 400.\n let shapeError = validateChatMessages(cohereReq.messages) ?? validateToolsField(cohereReq.tools);\n if (!shapeError && Array.isArray(cohereReq.tools)) {\n const nullFunctionIndex = cohereReq.tools.findIndex(\n (tool) => \"function\" in tool && tool.function === null,\n );\n if (nullFunctionIndex !== -1) {\n shapeError = `tools[${nullFunctionIndex}].function must be an object`;\n }\n }\n if (shapeError) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Invalid request: ${shapeError}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = cohereToCompletionRequest(cohereReq);\n completionReq._endpointType = \"chat\";\n completionReq._context = getContext(req);\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n { ...recordMatchOptions(!!defaults.record, defaults.logger), wire: \"cohere\" },\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n 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 {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss;\n if (effectiveStrict) {\n const strictStatus = 503;\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/chat\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: strictStatus,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n strictStatus,\n renderError(\"cohere\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n if (defaults.record) {\n const { outcome, clientHungUp } = await withHangUpDetection(req, res, () =>\n proxyAndRecord(\n req,\n res,\n completionReq,\n \"cohere\",\n req.url ?? \"/v2/chat\",\n fixtures,\n defaults,\n raw,\n ),\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: res.statusCode ?? 200,\n fixture: null,\n source: \"proxy\",\n ...proxyInterruption(res, clientHungUp),\n },\n });\n return;\n }\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n renderError(\"cohere\", \"fixture-miss\", {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n const resolvedResponse = await resolveResponse(fixture, completionReq);\n const misbehavior = planMisbehavior({\n wire: \"cohere\",\n fixture,\n response: resolvedResponse,\n request: completionReq,\n stream: cohereReq.stream === true,\n emitsToolCallIds: true,\n defaults,\n rawHeaders: req.headers,\n url: req.url,\n });\n if (misbehavior.kind === \"error\") {\n const entry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: misbehavior.status, fixture },\n });\n recordMisbehaviorOutcome({ entry, summary: misbehavior.summary, defaults, testId });\n if (!misbehavior.summary?.evaluations.length) logger.error(misbehavior.message);\n writeErrorResponse(\n res,\n misbehavior.status,\n renderError(\"cohere\", \"misbehavior\", {\n message: misbehavior.message,\n code: misbehavior.code,\n }).body,\n );\n return;\n }\n\n // Raw passthrough (#549): the authored events or JSON, framed for this wire.\n if (isRawResponse(resolvedResponse)) {\n await serveRawResponse({\n wire: \"cohere\",\n stream: cohereReq.stream === true,\n req,\n res,\n fixture,\n response: resolvedResponse,\n body: completionReq,\n journal,\n defaults,\n testId,\n misbehaviorSummary: misbehavior.summary,\n errorWire: \"cohere\",\n });\n return;\n }\n\n // Cohere carries the same raw argument strings and call identities as Chat.\n // Reuse the accepted preparation so generated/duplicate IDs match metadata.\n const prepared =\n misbehavior.kind === \"applied\" ? prepareOpenAIChatMisbehavior(misbehavior) : undefined;\n const observedK5Stream =\n cohereReq.stream === true && prepared?.summary.fault === \"stop-length-mid-tool\";\n const appliedReasoning =\n prepared && \"reasoning\" in prepared.response\n ? resolveReasoningForModel(\n prepared.response.reasoning,\n cohereReq.model,\n resolveRequestDecisions(defaults.strict, req.headers).reasoningSuppression,\n logger,\n )\n : undefined;\n const usage = prepared\n ? resolveOpenAIChatMisbehaviorUsage(prepared, completionReq, appliedReasoning !== undefined)\n : undefined;\n const response =\n prepared && usage\n ? {\n ...prepared.response,\n usage,\n ...(prepared.stop\n ? { finishReason: observedK5Stream ? \"tool_calls\" : prepared.stop }\n : {}),\n }\n : resolvedResponse;\n const summary = prepared?.summary ?? misbehavior.summary;\n const empty = prepared?.summary.fault === \"empty-response\";\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n const replaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;\n const streamTiming = {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed,\n };\n const codec = typedSseCodec<CohereSSEEvent>({ terminalSentinel: observedK5Stream });\n // Cohere has no separate misbehavior reply: an applied plan is merged into\n // `response` above and served by the branches below, so every non-streaming\n // site sizes its wait from the served payload and carries the K4 flag.\n const jsonOpts = (payloadLength: number) => ({\n surface: \"other\" as const,\n payloadLength,\n chunkSize,\n recordedTimings: fixture.recordedTimings,\n duplicateId: !!prepared?.duplicateId,\n replaySpeed,\n });\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n writeErrorResponse(res, status, renderError(\"openai\", \"fixture\", response.error).body, {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Content + tool calls response (must be checked before text/tool-only branches)\n if (isCombinedFixtureResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n await deliverJson(\n res,\n journalEntry,\n fixture,\n () =>\n buildCohereContentWithToolCallsResponse(\n response.content ?? \"\",\n functionToolCalls,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n ),\n jsonOpts(servedPayloadLength(response, effReasoning)),\n );\n } else {\n const events = buildCohereContentWithToolCallsStreamEvents(\n response.content ?? \"\",\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n );\n await deliverStream(res, journalEntry, fixture, codec, events, streamTiming);\n }\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n if (cohereReq.stream !== true) {\n await deliverJson(\n res,\n journalEntry,\n fixture,\n () =>\n empty\n ? {\n ...buildCohereTextResponse(\"\", undefined, overrides),\n message: {\n role: \"assistant\",\n content: [],\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n }\n : buildCohereTextResponse(response.content, effReasoning, overrides),\n jsonOpts(servedPayloadLength(response, effReasoning)),\n );\n } else {\n const events = buildCohereTextStreamEvents(\n response.content,\n chunkSize,\n effReasoning,\n overrides,\n ).filter((event) => !empty || event.type === \"message-start\" || event.type === \"message-end\");\n await deliverStream(res, journalEntry, fixture, codec, events, streamTiming);\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n await deliverJson(\n res,\n journalEntry,\n fixture,\n () => buildCohereToolCallResponse(functionToolCalls, logger, effReasoning, overrides),\n jsonOpts(servedPayloadLength(response, effReasoning)),\n );\n } else {\n const events = buildCohereToolCallStreamEvents(\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n );\n await deliverStream(res, journalEntry, fixture, codec, events, streamTiming);\n }\n return;\n }\n\n // Unknown response type\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n recordMisbehaviorOutcome({ entry: journalEntry, summary, defaults, testId });\n writeErrorResponse(\n res,\n 500,\n renderError(\"cohere\", \"unknown-response\", {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n }).body,\n );\n}\n\n// ─── Cohere v2 Embed API types ────────────────────────────────────────────\n\ninterface CohereEmbedRequest {\n texts: string[];\n model: string;\n input_type?: string;\n embedding_types?: string[];\n truncate?: string;\n}\n\ninterface CohereEmbedResponse {\n id: string;\n texts: string[];\n embeddings: Record<string, number[][]>;\n meta: { api_version: { version: string } };\n}\n\n// ─── Cohere Embed handler ─────────────────────────────────────────────────\n\nexport async function handleCohereEmbed(\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 const { logger } = defaults;\n setCorsHeaders(res);\n\n let embedReq: CohereEmbedRequest;\n try {\n embedReq = JSON.parse(raw) as CohereEmbedRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Malformed JSON body: ${detail}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `embedReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(embedReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Validate required fields\n if (!embedReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"model is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n if (!embedReq.texts || !Array.isArray(embedReq.texts)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Invalid request: texts array is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Every text must be a string — a number reaches createHash().update() in\n // the no-fixture fallback and throws a TypeError (500) instead of a 400.\n if (!embedReq.texts.every((text) => typeof text === \"string\")) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Invalid request: texts must be an array of strings\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Concatenate all texts for fixture matching\n const combinedInput = embedReq.texts.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router\n const syntheticReq: ChatCompletionRequest = {\n model: embedReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n 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 {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n // Determine requested embedding types (default to float)\n const embeddingTypes =\n embedReq.embedding_types && embedReq.embedding_types.length > 0\n ? embedReq.embedding_types\n : [\"float\"];\n\n function rejectInvalidEmbeddingTypes(): boolean {\n if (embedReq.embedding_types == null) return false;\n const isArray = Array.isArray(embedReq.embedding_types);\n if (isArray && embedReq.embedding_types.every((type) => typeof type === \"string\")) return false;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 400, fixture: fixture ?? null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: isArray\n ? \"Invalid request: embedding_types must be an array of strings\"\n : \"Invalid request: embedding_types must be an array\",\n type: \"invalid_request_error\",\n }).body,\n );\n return true;\n }\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 // Embedding response — use the fixture's embedding for each input text\n if (isEmbeddingResponse(response)) {\n if (rejectInvalidEmbeddingTypes()) return;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const vectors = embedReq.texts.map(() => [...response.embedding]);\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n renderError(\"cohere\", \"unknown-response\", {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n }).body,\n );\n return;\n }\n\n // No fixture match — check strict mode\n if (resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/embed\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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(\"cohere\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Try record-and-replay proxy\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"cohere\",\n req.url ?? \"/v2/embed\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 if (rejectInvalidEmbeddingTypes()) return;\n\n // No fixture match — generate deterministic embeddings from input texts\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n const dimensions = 1024; // Cohere embed-v4.0 default\n const vectors = embedReq.texts.map((text) => generateDeterministicEmbedding(text, dimensions));\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;;;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ACF;;;AAIJ,KAAI,6BAA6B,CAAE;AAGnC,QAAO,KACL,qCAAqC,cAAc,MAAM,GAAG,GAAG,CAAC,sCACjE;CACD,MAAM,aAAa;CACnB,MAAM,UAAU,SAAS,MAAM,KAAK,SAAS,+BAA+B,MAAM,WAAW,CAAC;CAC9F,MAAM,aAAyC,EAAE;AACjD,MAAK,MAAM,KAAK,eACd,YAAW,KAAK;AAGlB,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM;EACzC,CAAC;CAEF,MAAM,OAA4B;EAChC,IAAI,mBAAmB;EACvB,OAAO,SAAS;EAChB;EACA,MAAM,EAAE,aAAa,EAAE,SAAS,KAAK,EAAE;EACxC;AACD,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IAAI,KAAK,UAAU,KAAK,CAAC"}
@@ -1,5 +1,6 @@
1
1
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
2
  const require_api_key_auth = require('./api-key-auth.cjs');
3
+ const require_policy = require('./response/policy.cjs');
3
4
  const require_a2a_mock = require('./a2a-mock.cjs');
4
5
  const require_agui_handler = require('./agui-handler.cjs');
5
6
  const require_misbehavior = require('./misbehavior.cjs');
@@ -30,8 +31,33 @@ function loadConfig(configPath) {
30
31
  function hasMcpRecordMount(mcp) {
31
32
  return typeof mcp === "object" && mcp !== null && !Array.isArray(mcp) && Object.keys(mcp).length > 0;
32
33
  }
34
+ /** Both CLI entry points use the shared policy parser and treat failures as usage errors. */
35
+ function parsePolicyFlags(entries) {
36
+ const policy = {};
37
+ for (const entry of entries) {
38
+ const separator = entry.indexOf("=");
39
+ if (separator < 0) return {
40
+ ok: false,
41
+ error: `Invalid --policy ${JSON.stringify(entry)}: expected key=value.`
42
+ };
43
+ const parsed = require_policy.parsePolicyEntry(entry.slice(0, separator), entry.slice(separator + 1));
44
+ if (!parsed.ok) return {
45
+ ok: false,
46
+ error: `Invalid --policy ${JSON.stringify(entry)}: ${parsed.reason} Use key=value.`
47
+ };
48
+ require_policy.assignPolicyEntry(policy, parsed);
49
+ }
50
+ return {
51
+ ok: true,
52
+ policy
53
+ };
54
+ }
33
55
  async function startFromConfig(config, overrides) {
34
56
  const logger = new require_logger.Logger("info");
57
+ const policy = {
58
+ ...require_policy.parsePolicy(config.llm?.policy, (message) => logger.warn(message)),
59
+ ...require_policy.parsePolicy(overrides?.policy, (message) => logger.warn(message))
60
+ };
35
61
  const booleanOptIn = (key) => {
36
62
  const value = config.llm?.[key];
37
63
  if (value === void 0 || typeof value === "boolean") return value;
@@ -76,7 +102,8 @@ async function startFromConfig(config, overrides) {
76
102
  metrics: config.metrics,
77
103
  strict: config.strict,
78
104
  strictToolArguments: overrides?.strictToolArguments ?? configStrictToolArguments,
79
- responsesTools: overrides?.responsesTools ?? responsesTools
105
+ responsesTools: overrides?.responsesTools ?? responsesTools,
106
+ policy
80
107
  }, resolvedAuth);
81
108
  const configMounts = /* @__PURE__ */ new Map();
82
109
  if (config.llm?.fixtures) {
@@ -209,5 +236,6 @@ async function startFromConfig(config, overrides) {
209
236
 
210
237
  //#endregion
211
238
  exports.loadConfig = loadConfig;
239
+ exports.parsePolicyFlags = parsePolicyFlags;
212
240
  exports.startFromConfig = startFromConfig;
213
241
  //# sourceMappingURL=config-loader.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-loader.cjs","names":["fs","Logger","parseMisbehavior","resolveInboundAuth","selectInboundAuthSource","createLLMockWithResolvedAuth","path","MCPMock","A2AMock","AGUIMock","buildTextResponse","VectorMock"],"sources":["../src/config-loader.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { LLMock, createLLMockWithResolvedAuth } from \"./llmock.js\";\nimport { resolveInboundAuth, selectInboundAuthSource } from \"./api-key-auth.js\";\nimport { MCPMock } from \"./mcp-mock.js\";\nimport { configToolHandlers } from \"./mcp-handler.js\";\nimport { A2AMock } from \"./a2a-mock.js\";\nimport { AGUIMock } from \"./agui-mock.js\";\nimport type {\n ApiKeyAuthConfig,\n ChaosConfig,\n McpRecordConfig,\n MisbehaviorConfig,\n MisbehaviorFaultId,\n Mountable,\n RecordConfig,\n ResponsesToolsMode,\n} from \"./types.js\";\nimport { parseMisbehavior } from \"./misbehavior.js\";\nimport type { MCPToolDefinition, MCPPromptDefinition } from \"./mcp-types.js\";\nimport type { A2AAgentDefinition, A2APart, A2AArtifact, A2AStreamEvent } from \"./a2a-types.js\";\nimport type { AGUIEvent } from \"./agui-types.js\";\nimport { buildTextResponse } from \"./agui-handler.js\";\nimport { VectorMock } from \"./vector-mock.js\";\nimport type { QueryResult } from \"./vector-types.js\";\nimport { Logger } from \"./logger.js\";\nimport { wireMcpRecording } from \"./mcp-recorder.js\";\n\nexport interface MCPConfigTool extends MCPToolDefinition {\n result?: string;\n}\n\nexport interface MCPConfigResource {\n uri: string;\n name: string;\n mimeType?: string;\n description?: string;\n text?: string;\n blob?: string;\n}\n\nexport interface MCPConfigPrompt extends MCPPromptDefinition {\n result?: {\n messages: Array<{ role: string; content: { type: string; text: string } }>;\n };\n}\n\nexport interface MCPConfig {\n path?: string;\n serverInfo?: { name: string; version: string };\n tools?: MCPConfigTool[];\n resources?: MCPConfigResource[];\n prompts?: MCPConfigPrompt[];\n}\n\nexport interface A2AConfigPattern {\n pattern: string;\n parts?: A2APart[];\n artifacts?: A2AArtifact[];\n events?: A2AStreamEvent[];\n delayMs?: number;\n}\n\nexport interface A2AConfigAgent extends A2AAgentDefinition {\n messages?: A2AConfigPattern[];\n tasks?: A2AConfigPattern[];\n streamingTasks?: A2AConfigPattern[];\n}\n\nexport interface A2AConfig {\n path?: string;\n agents?: A2AConfigAgent[];\n}\n\nexport interface AGUIConfigFixture {\n match: { message?: string; toolCallId?: string; toolName?: string; stateKey?: string };\n text?: string; // shorthand: uses buildTextResponse\n events?: AGUIEvent[]; // raw events\n delayMs?: number;\n}\n\nexport interface AGUIConfig {\n path?: string; // mount path, default \"/agui\"\n fixtures?: AGUIConfigFixture[];\n}\n\nexport interface VectorConfigCollection {\n name: string;\n dimension: number;\n vectors?: Array<{\n id: string;\n values: number[];\n metadata?: Record<string, unknown>;\n }>;\n queryResults?: QueryResult[];\n}\n\nexport interface VectorConfig {\n path?: string;\n collections?: VectorConfigCollection[];\n}\n\n/** `llm.record` in a config file: the LLM `RecordConfig`, plus MCP record mounts (C10). */\nexport interface AimockRecordConfig extends RecordConfig {\n /** MR1: mount path → upstream URL, or a full MCP record config. */\n mcp?: Record<string, string | McpRecordConfig>;\n}\n\nexport interface AimockConfig {\n auth?: ApiKeyAuthConfig;\n llm?: {\n fixtures?: string;\n latency?: number;\n chunkSize?: number;\n replaySpeed?: number;\n logLevel?: \"silent\" | \"warn\" | \"info\" | \"debug\";\n chaos?: ChaosConfig;\n /**\n * Server-wide misbehavior defaults. Read only when misbehavior is enabled\n * (`llm.enableMisbehavior: true` or `aimock --misbehavior`); otherwise the\n * key is ignored with a warning, as 1.44.0 ignored it.\n */\n misbehavior?: MisbehaviorConfig | MisbehaviorFaultId;\n /** See `MockServerOptions.enableMisbehavior`. */\n enableMisbehavior?: boolean;\n record?: AimockRecordConfig;\n /**\n * Turns on `llm.record.mcp`. Without it the key is ignored with a warning,\n * as 1.44.0 ignored it.\n */\n enableMcpRecording?: boolean;\n /** See `MockServerOptions.strictToolArguments`. */\n strictToolArguments?: boolean;\n /** See `MockServerOptions.responsesTools`. */\n responsesTools?: ResponsesToolsMode;\n };\n mcp?: MCPConfig;\n a2a?: A2AConfig;\n agui?: AGUIConfig;\n vector?: VectorConfig;\n services?: { search?: boolean; rerank?: boolean; moderate?: boolean };\n metrics?: boolean;\n strict?: boolean;\n port?: number;\n host?: string;\n}\n\n/** C10: the LLM part of `llm.record`. `mcp` is MCP-only; no `providers` means no LLM recording. */\nfunction llmRecordOf(record: AimockRecordConfig | undefined): RecordConfig | undefined {\n if (!record) return undefined;\n const { mcp: _mcp, ...llm } = record;\n void _mcp; // repo pattern for an intentionally unused binding (byteplus-video.ts:1379-1380)\n return llm.providers === undefined ? undefined : llm;\n}\n\nexport function loadConfig(configPath: string): AimockConfig {\n const raw = fs.readFileSync(configPath, \"utf-8\");\n return JSON.parse(raw) as AimockConfig;\n}\n\n/** C3: `llm.record.mcp` is an object with at least one mount. */\nfunction hasMcpRecordMount(mcp: unknown): boolean {\n return (\n typeof mcp === \"object\" && mcp !== null && !Array.isArray(mcp) && Object.keys(mcp).length > 0\n );\n}\n\n/**\n * Command-line overrides for `startFromConfig`. The opt-in flags win over the\n * matching `llm.*` config keys.\n */\nexport interface StartFromConfigOverrides {\n port?: number;\n host?: string;\n /** `aimock --misbehavior`: overrides `llm.enableMisbehavior`. */\n enableMisbehavior?: boolean;\n /** `aimock --strict-tool-arguments`: overrides `llm.strictToolArguments`. */\n strictToolArguments?: boolean;\n /** `aimock --responses-tools`: overrides `llm.responsesTools`. */\n responsesTools?: ResponsesToolsMode;\n}\n\nexport async function startFromConfig(\n config: AimockConfig,\n overrides?: StartFromConfigOverrides,\n): Promise<{ llmock: LLMock; url: string }> {\n const logger = new Logger(\"info\");\n // 1.44.0 ignored these keys, so a non-boolean value (such as the string\n // \"true\") is ignored with a warning, as `llm.misbehavior` is, and the\n // option stays off unless a CLI flag turns it on (`llm.enableMcpRecording`\n // has no CLI flag).\n const booleanOptIn = (\n key: \"enableMisbehavior\" | \"enableMcpRecording\" | \"strictToolArguments\",\n ): boolean | undefined => {\n const value: unknown = config.llm?.[key];\n if (value === undefined || typeof value === \"boolean\") return value;\n logger.warn(\n `Ignoring llm.${key} because it must be true or false, got ${JSON.stringify(value)}.`,\n );\n return undefined;\n };\n const configEnableMisbehavior = booleanOptIn(\"enableMisbehavior\");\n const configStrictToolArguments = booleanOptIn(\"strictToolArguments\");\n // MCP recording also needs an explicit opt-in. 1.44.0 ignored\n // `llm.record.mcp`, so without `llm.enableMcpRecording: true` the key is\n // ignored (with a warning): nothing is mounted or validated and the log level\n // is unchanged. With the opt-in, an invalid value fails startup.\n const enableMcpRecording = booleanOptIn(\"enableMcpRecording\") === true;\n const mcpRecord = enableMcpRecording ? config.llm?.record?.mcp : undefined;\n // Misbehavior needs an explicit opt-in that a 1.44.0 config cannot contain.\n // 1.44.0 ignored `llm.misbehavior`, so without the opt-in the key is ignored\n // (with a warning) and the server serves exactly what 1.44.0 served. With the\n // opt-in, an invalid value fails startup like any other enabled-mode error.\n const enableMisbehavior = (overrides?.enableMisbehavior ?? configEnableMisbehavior) === true;\n let misbehavior: MisbehaviorConfig | undefined;\n if (config.llm?.misbehavior !== undefined) {\n if (!enableMisbehavior) {\n logger.warn(\n \"Ignoring llm.misbehavior because misbehavior is not enabled. Set llm.enableMisbehavior: true or pass --misbehavior to use it.\",\n );\n } else {\n const parsed = parseMisbehavior(config.llm.misbehavior, \"llm.misbehavior\");\n if (!parsed.ok) {\n throw new TypeError(`${parsed.issue.rule}: ${parsed.issue.path}: ${parsed.issue.message}`);\n }\n misbehavior = parsed.config;\n }\n }\n if (config.llm?.record?.mcp !== undefined && !enableMcpRecording) {\n logger.warn(\n \"Ignoring llm.record.mcp because MCP recording is not enabled. Set llm.enableMcpRecording: true to use it.\",\n );\n }\n\n // 1.44.0 ignored `llm.responsesTools`, so an invalid value is ignored with a\n // warning (as `llm.misbehavior` is) and the server runs in \"legacy\" mode,\n // unless `--responses-tools` sets the mode. The warning names the mode that\n // actually runs.\n let responsesTools = config.llm?.responsesTools;\n if (\n responsesTools !== undefined &&\n responsesTools !== \"legacy\" &&\n responsesTools !== \"extended\"\n ) {\n const effective =\n overrides?.responsesTools !== undefined\n ? `\"${overrides.responsesTools}\" from --responses-tools`\n : '\"legacy\"';\n logger.warn(\n `Ignoring llm.responsesTools because it must be \"legacy\" or \"extended\", got ${JSON.stringify(responsesTools)}. Using ${effective}.`,\n );\n responsesTools = undefined;\n }\n\n // A non-positive replaySpeed fails calculateDelay's `speed > 0` check and applies the\n // full delay rather than none. Mirrors the fixture-level guard in fixture-loader.ts.\n let replaySpeed = config.llm?.replaySpeed;\n if (replaySpeed != null && (!Number.isFinite(replaySpeed) || replaySpeed <= 0)) {\n logger.warn(`llm.replaySpeed must be a positive number, got ${replaySpeed}. Ignoring.`);\n replaySpeed = undefined;\n }\n\n // Load fixtures if specified\n const resolvedAuth = resolveInboundAuth(selectInboundAuthSource(config.auth));\n const llmock = createLLMockWithResolvedAuth(\n {\n port: overrides?.port ?? config.port ?? 0,\n host: overrides?.host ?? config.host ?? \"127.0.0.1\",\n latency: config.llm?.latency,\n chunkSize: config.llm?.chunkSize,\n replaySpeed,\n // llm.record.mcp reports skipped or failed recordings only as MCP-RECORD: warnings,\n // so an enabled config with at least one mount defaults to \"warn\" rather than the silent\n // default. An empty llm.record.mcp records nothing. An explicit logLevel wins.\n logLevel: config.llm?.logLevel ?? (hasMcpRecordMount(mcpRecord) ? \"warn\" : undefined),\n chaos: config.llm?.chaos,\n misbehavior,\n ...(enableMisbehavior ? { enableMisbehavior: true } : {}),\n record: llmRecordOf(config.llm?.record),\n metrics: config.metrics,\n strict: config.strict,\n strictToolArguments: overrides?.strictToolArguments ?? configStrictToolArguments,\n responsesTools: overrides?.responsesTools ?? responsesTools,\n },\n resolvedAuth,\n );\n\n // What this function mounted, by path (MR1: llm.record.mcp records through an MCP mount).\n const configMounts = new Map<string, Mountable>();\n\n if (config.llm?.fixtures) {\n const fixturePath = path.resolve(config.llm.fixtures);\n const stat = fs.statSync(fixturePath);\n if (stat.isDirectory()) {\n llmock.loadFixtureDir(fixturePath);\n } else {\n llmock.loadFixtureFile(fixturePath);\n }\n }\n\n // MCP\n if (config.mcp) {\n const mcpConfig = config.mcp;\n const mcp = new MCPMock({\n serverInfo: mcpConfig.serverInfo,\n });\n\n if (mcpConfig.tools) {\n for (const tool of mcpConfig.tools) {\n const { result, ...def } = tool;\n mcp.addTool(def);\n if (result !== undefined) {\n const answer = () => result;\n configToolHandlers.add(answer);\n mcp.onToolCall(def.name, answer);\n }\n }\n }\n\n if (mcpConfig.resources) {\n for (const res of mcpConfig.resources) {\n mcp.addResource(\n { uri: res.uri, name: res.name, mimeType: res.mimeType, description: res.description },\n res.text !== undefined || res.blob !== undefined\n ? { text: res.text, blob: res.blob, mimeType: res.mimeType }\n : undefined,\n );\n }\n }\n\n if (mcpConfig.prompts) {\n for (const prompt of mcpConfig.prompts) {\n const { result, ...def } = prompt;\n if (result) {\n mcp.addPrompt(def, () => result as import(\"./mcp-types.js\").MCPPromptResult);\n } else {\n mcp.addPrompt(def);\n }\n }\n }\n\n const mcpPath = mcpConfig.path ?? \"/mcp\";\n llmock.mount(mcpPath, mcp);\n configMounts.set(mcpPath, mcp);\n logger.info(`MCPMock mounted at ${mcpPath}`);\n }\n\n // A2A\n if (config.a2a) {\n const a2aConfig = config.a2a;\n const a2a = new A2AMock();\n\n if (a2aConfig.agents) {\n for (const agentConfig of a2aConfig.agents) {\n const { messages, tasks, streamingTasks, ...def } = agentConfig;\n a2a.registerAgent(def);\n\n if (messages) {\n for (const m of messages) {\n a2a.onMessage(def.name, m.pattern, m.parts ?? [{ text: \"\" }]);\n }\n }\n\n if (tasks) {\n for (const t of tasks) {\n a2a.onTask(def.name, t.pattern, t.artifacts ?? []);\n }\n }\n\n if (streamingTasks) {\n for (const s of streamingTasks) {\n a2a.onStreamingTask(def.name, s.pattern, s.events ?? [], s.delayMs);\n }\n }\n }\n }\n\n const a2aPath = a2aConfig.path ?? \"/a2a\";\n llmock.mount(a2aPath, a2a);\n configMounts.set(a2aPath, a2a);\n logger.info(`A2AMock mounted at ${a2aPath}`);\n }\n\n // AG-UI\n if (config.agui) {\n const aguiConfig = config.agui;\n const agui = new AGUIMock();\n\n if (aguiConfig.fixtures) {\n for (const f of aguiConfig.fixtures) {\n if (f.match.toolCallId && f.text && !f.events) {\n logger.warn(\n `AG-UI fixture uses text shorthand with toolCallId — text shorthand ignores toolCallId matching; use events[] instead (match: ${JSON.stringify(f.match)})`,\n );\n }\n if (f.text) {\n if (f.match.message !== undefined) {\n agui.onMessage(f.match.message, f.text, { delayMs: f.delayMs });\n } else {\n // No message pattern — register via addFixture so it only matches\n // on other criteria (toolCallId, toolName, stateKey) instead of\n // becoming a catch-all that matches every request.\n agui.addFixture({\n match: {\n toolCallId: f.match.toolCallId,\n toolName: f.match.toolName,\n stateKey: f.match.stateKey,\n },\n events: buildTextResponse(f.text),\n delayMs: f.delayMs,\n });\n }\n } else if (f.events) {\n agui.addFixture({\n match: {\n message: f.match.message,\n toolCallId: f.match.toolCallId,\n toolName: f.match.toolName,\n stateKey: f.match.stateKey,\n },\n events: f.events,\n delayMs: f.delayMs,\n });\n } else {\n logger.warn(\n `AG-UI fixture has neither text nor events — it will be skipped (match: ${JSON.stringify(f.match)})`,\n );\n }\n }\n }\n\n const aguiPath = aguiConfig.path ?? \"/agui\";\n llmock.mount(aguiPath, agui);\n configMounts.set(aguiPath, agui);\n logger.info(`AGUIMock mounted at ${aguiPath}`);\n }\n\n // Vector\n if (config.vector) {\n const vectorConfig = config.vector;\n const vector = new VectorMock();\n\n if (vectorConfig.collections) {\n for (const col of vectorConfig.collections) {\n vector.addCollection(col.name, { dimension: col.dimension });\n\n if (col.vectors && col.vectors.length > 0) {\n vector.upsert(col.name, col.vectors);\n }\n\n if (col.queryResults) {\n vector.onQuery(col.name, col.queryResults);\n }\n }\n }\n\n const vectorPath = vectorConfig.path ?? \"/vector\";\n llmock.mount(vectorPath, vector);\n configMounts.set(vectorPath, vector);\n logger.info(`VectorMock mounted at ${vectorPath}`);\n }\n\n // MR1: llm.record.mcp — record mounts (auto-mount an MCPMock where none is).\n // Read only with llm.enableMcpRecording: true. Any value that is present is then\n // validated, so null, false, 0 and \"\" fail at start too.\n if (mcpRecord !== undefined) {\n wireMcpRecording(llmock, mcpRecord, {\n mounted: configMounts,\n mcpMock: MCPMock,\n fixtures: config.llm?.fixtures,\n fixturePath: config.llm?.record?.fixturePath,\n strict: config.strict,\n env: process.env,\n });\n }\n\n // Services — configure default catch-all responses\n if (config.services) {\n if (config.services.search) {\n llmock.onSearch(/.*/, []);\n logger.info(\"Search service enabled with default empty results\");\n }\n if (config.services.rerank) {\n llmock.onRerank(/.*/, []);\n logger.info(\"Rerank service enabled with default empty results\");\n }\n if (config.services.moderate) {\n llmock.onModerate(/.*/, { flagged: false, categories: {} });\n logger.info(\"Moderation service enabled with default unflagged results\");\n }\n }\n\n const url = await llmock.start();\n return { llmock, url };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoJA,SAAS,YAAY,QAAkE;AACrF,KAAI,CAAC,OAAQ,QAAO;CACpB,MAAM,EAAE,KAAK,MAAM,GAAG,QAAQ;AAE9B,QAAO,IAAI,cAAc,SAAY,SAAY;;AAGnD,SAAgB,WAAW,YAAkC;CAC3D,MAAM,MAAMA,QAAG,aAAa,YAAY,QAAQ;AAChD,QAAO,KAAK,MAAM,IAAI;;;AAIxB,SAAS,kBAAkB,KAAuB;AAChD,QACE,OAAO,QAAQ,YAAY,QAAQ,QAAQ,CAAC,MAAM,QAAQ,IAAI,IAAI,OAAO,KAAK,IAAI,CAAC,SAAS;;AAmBhG,eAAsB,gBACpB,QACA,WAC0C;CAC1C,MAAM,SAAS,IAAIC,sBAAO,OAAO;CAKjC,MAAM,gBACJ,QACwB;EACxB,MAAM,QAAiB,OAAO,MAAM;AACpC,MAAI,UAAU,UAAa,OAAO,UAAU,UAAW,QAAO;AAC9D,SAAO,KACL,gBAAgB,IAAI,yCAAyC,KAAK,UAAU,MAAM,CAAC,GACpF;;CAGH,MAAM,0BAA0B,aAAa,oBAAoB;CACjE,MAAM,4BAA4B,aAAa,sBAAsB;CAKrE,MAAM,qBAAqB,aAAa,qBAAqB,KAAK;CAClE,MAAM,YAAY,qBAAqB,OAAO,KAAK,QAAQ,MAAM;CAKjE,MAAM,qBAAqB,WAAW,qBAAqB,6BAA6B;CACxF,IAAI;AACJ,KAAI,OAAO,KAAK,gBAAgB,OAC9B,KAA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L,MAAM,OAAO,OAAO;EACV"}
1
+ {"version":3,"file":"config-loader.cjs","names":["fs","parsePolicyEntry","Logger","parsePolicy","parseMisbehavior","resolveInboundAuth","selectInboundAuthSource","createLLMockWithResolvedAuth","path","MCPMock","A2AMock","AGUIMock","buildTextResponse","VectorMock"],"sources":["../src/config-loader.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { LLMock, createLLMockWithResolvedAuth } from \"./llmock.js\";\nimport { resolveInboundAuth, selectInboundAuthSource } from \"./api-key-auth.js\";\nimport { MCPMock } from \"./mcp-mock.js\";\nimport { configToolHandlers } from \"./mcp-handler.js\";\nimport { A2AMock } from \"./a2a-mock.js\";\nimport { AGUIMock } from \"./agui-mock.js\";\nimport type {\n AimockPolicy,\n ApiKeyAuthConfig,\n ChaosConfig,\n McpRecordConfig,\n MisbehaviorConfig,\n MisbehaviorFaultId,\n Mountable,\n RecordConfig,\n ResponsesToolsMode,\n} from \"./types.js\";\nimport { parseMisbehavior } from \"./misbehavior.js\";\nimport type { MCPToolDefinition, MCPPromptDefinition } from \"./mcp-types.js\";\nimport type { A2AAgentDefinition, A2APart, A2AArtifact, A2AStreamEvent } from \"./a2a-types.js\";\nimport type { AGUIEvent } from \"./agui-types.js\";\nimport { buildTextResponse } from \"./agui-handler.js\";\nimport { VectorMock } from \"./vector-mock.js\";\nimport type { QueryResult } from \"./vector-types.js\";\nimport { Logger } from \"./logger.js\";\nimport { wireMcpRecording } from \"./mcp-recorder.js\";\nimport { assignPolicyEntry, parsePolicy, parsePolicyEntry } from \"./response/policy.js\";\n\nexport interface MCPConfigTool extends MCPToolDefinition {\n result?: string;\n}\n\nexport interface MCPConfigResource {\n uri: string;\n name: string;\n mimeType?: string;\n description?: string;\n text?: string;\n blob?: string;\n}\n\nexport interface MCPConfigPrompt extends MCPPromptDefinition {\n result?: {\n messages: Array<{ role: string; content: { type: string; text: string } }>;\n };\n}\n\nexport interface MCPConfig {\n path?: string;\n serverInfo?: { name: string; version: string };\n tools?: MCPConfigTool[];\n resources?: MCPConfigResource[];\n prompts?: MCPConfigPrompt[];\n}\n\nexport interface A2AConfigPattern {\n pattern: string;\n parts?: A2APart[];\n artifacts?: A2AArtifact[];\n events?: A2AStreamEvent[];\n delayMs?: number;\n}\n\nexport interface A2AConfigAgent extends A2AAgentDefinition {\n messages?: A2AConfigPattern[];\n tasks?: A2AConfigPattern[];\n streamingTasks?: A2AConfigPattern[];\n}\n\nexport interface A2AConfig {\n path?: string;\n agents?: A2AConfigAgent[];\n}\n\nexport interface AGUIConfigFixture {\n match: { message?: string; toolCallId?: string; toolName?: string; stateKey?: string };\n text?: string; // shorthand: uses buildTextResponse\n events?: AGUIEvent[]; // raw events\n delayMs?: number;\n}\n\nexport interface AGUIConfig {\n path?: string; // mount path, default \"/agui\"\n fixtures?: AGUIConfigFixture[];\n}\n\nexport interface VectorConfigCollection {\n name: string;\n dimension: number;\n vectors?: Array<{\n id: string;\n values: number[];\n metadata?: Record<string, unknown>;\n }>;\n queryResults?: QueryResult[];\n}\n\nexport interface VectorConfig {\n path?: string;\n collections?: VectorConfigCollection[];\n}\n\n/** `llm.record` in a config file: the LLM `RecordConfig`, plus MCP record mounts (C10). */\nexport interface AimockRecordConfig extends RecordConfig {\n /** MR1: mount path → upstream URL, or a full MCP record config. */\n mcp?: Record<string, string | McpRecordConfig>;\n}\n\nexport interface AimockConfig {\n auth?: ApiKeyAuthConfig;\n llm?: {\n fixtures?: string;\n latency?: number;\n chunkSize?: number;\n replaySpeed?: number;\n logLevel?: \"silent\" | \"warn\" | \"info\" | \"debug\";\n chaos?: ChaosConfig;\n /**\n * Server-wide misbehavior defaults. Read only when misbehavior is enabled\n * (`llm.enableMisbehavior: true` or `aimock --misbehavior`); otherwise the\n * key is ignored with a warning, as 1.44.0 ignored it.\n */\n misbehavior?: MisbehaviorConfig | MisbehaviorFaultId;\n /** See `MockServerOptions.enableMisbehavior`. */\n enableMisbehavior?: boolean;\n record?: AimockRecordConfig;\n /**\n * Turns on `llm.record.mcp`. Without it the key is ignored with a warning,\n * as 1.44.0 ignored it.\n */\n enableMcpRecording?: boolean;\n /** See `MockServerOptions.strictToolArguments`. */\n strictToolArguments?: boolean;\n /** See `MockServerOptions.responsesTools`. */\n responsesTools?: ResponsesToolsMode;\n /** See `MockServerOptions.policy`. Independent of `strict`. */\n policy?: AimockPolicy;\n };\n mcp?: MCPConfig;\n a2a?: A2AConfig;\n agui?: AGUIConfig;\n vector?: VectorConfig;\n services?: { search?: boolean; rerank?: boolean; moderate?: boolean };\n metrics?: boolean;\n strict?: boolean;\n port?: number;\n host?: string;\n}\n\n/** C10: the LLM part of `llm.record`. `mcp` is MCP-only; no `providers` means no LLM recording. */\nfunction llmRecordOf(record: AimockRecordConfig | undefined): RecordConfig | undefined {\n if (!record) return undefined;\n const { mcp: _mcp, ...llm } = record;\n void _mcp; // repo pattern for an intentionally unused binding (byteplus-video.ts:1379-1380)\n return llm.providers === undefined ? undefined : llm;\n}\n\nexport function loadConfig(configPath: string): AimockConfig {\n const raw = fs.readFileSync(configPath, \"utf-8\");\n return JSON.parse(raw) as AimockConfig;\n}\n\n/** C3: `llm.record.mcp` is an object with at least one mount. */\nfunction hasMcpRecordMount(mcp: unknown): boolean {\n return (\n typeof mcp === \"object\" && mcp !== null && !Array.isArray(mcp) && Object.keys(mcp).length > 0\n );\n}\n\n/**\n * Command-line overrides for `startFromConfig`. The opt-in flags win over the\n * matching `llm.*` config keys.\n */\nexport interface StartFromConfigOverrides {\n port?: number;\n host?: string;\n /** `aimock --misbehavior`: overrides `llm.enableMisbehavior`. */\n enableMisbehavior?: boolean;\n /** `aimock --strict-tool-arguments`: overrides `llm.strictToolArguments`. */\n strictToolArguments?: boolean;\n /** `aimock --responses-tools`: overrides `llm.responsesTools`. */\n responsesTools?: ResponsesToolsMode;\n /** `aimock --policy`: overrides individual keys from `llm.policy`. */\n policy?: AimockPolicy;\n}\n\n/** Both CLI entry points use the shared policy parser and treat failures as usage errors. */\nexport function parsePolicyFlags(entries: string[]) {\n const policy: AimockPolicy = {};\n for (const entry of entries) {\n const separator = entry.indexOf(\"=\");\n if (separator < 0) {\n return {\n ok: false,\n error: `Invalid --policy ${JSON.stringify(entry)}: expected key=value.`,\n } as const;\n }\n const parsed = parsePolicyEntry(entry.slice(0, separator), entry.slice(separator + 1));\n if (!parsed.ok) {\n return {\n ok: false,\n error: `Invalid --policy ${JSON.stringify(entry)}: ${parsed.reason} Use key=value.`,\n } as const;\n }\n assignPolicyEntry(policy, parsed);\n }\n return { ok: true, policy } as const;\n}\n\nexport async function startFromConfig(\n config: AimockConfig,\n overrides?: StartFromConfigOverrides,\n): Promise<{ llmock: LLMock; url: string }> {\n const logger = new Logger(\"info\");\n const policy = {\n ...parsePolicy(config.llm?.policy, (message) => logger.warn(message)),\n ...parsePolicy(overrides?.policy, (message) => logger.warn(message)),\n };\n // 1.44.0 ignored these keys, so a non-boolean value (such as the string\n // \"true\") is ignored with a warning, as `llm.misbehavior` is, and the\n // option stays off unless a CLI flag turns it on (`llm.enableMcpRecording`\n // has no CLI flag).\n const booleanOptIn = (\n key: \"enableMisbehavior\" | \"enableMcpRecording\" | \"strictToolArguments\",\n ): boolean | undefined => {\n const value: unknown = config.llm?.[key];\n if (value === undefined || typeof value === \"boolean\") return value;\n logger.warn(\n `Ignoring llm.${key} because it must be true or false, got ${JSON.stringify(value)}.`,\n );\n return undefined;\n };\n const configEnableMisbehavior = booleanOptIn(\"enableMisbehavior\");\n const configStrictToolArguments = booleanOptIn(\"strictToolArguments\");\n // MCP recording also needs an explicit opt-in. 1.44.0 ignored\n // `llm.record.mcp`, so without `llm.enableMcpRecording: true` the key is\n // ignored (with a warning): nothing is mounted or validated and the log level\n // is unchanged. With the opt-in, an invalid value fails startup.\n const enableMcpRecording = booleanOptIn(\"enableMcpRecording\") === true;\n const mcpRecord = enableMcpRecording ? config.llm?.record?.mcp : undefined;\n // Misbehavior needs an explicit opt-in that a 1.44.0 config cannot contain.\n // 1.44.0 ignored `llm.misbehavior`, so without the opt-in the key is ignored\n // (with a warning) and the server serves exactly what 1.44.0 served. With the\n // opt-in, an invalid value fails startup like any other enabled-mode error.\n const enableMisbehavior = (overrides?.enableMisbehavior ?? configEnableMisbehavior) === true;\n let misbehavior: MisbehaviorConfig | undefined;\n if (config.llm?.misbehavior !== undefined) {\n if (!enableMisbehavior) {\n logger.warn(\n \"Ignoring llm.misbehavior because misbehavior is not enabled. Set llm.enableMisbehavior: true or pass --misbehavior to use it.\",\n );\n } else {\n const parsed = parseMisbehavior(config.llm.misbehavior, \"llm.misbehavior\");\n if (!parsed.ok) {\n throw new TypeError(`${parsed.issue.rule}: ${parsed.issue.path}: ${parsed.issue.message}`);\n }\n misbehavior = parsed.config;\n }\n }\n if (config.llm?.record?.mcp !== undefined && !enableMcpRecording) {\n logger.warn(\n \"Ignoring llm.record.mcp because MCP recording is not enabled. Set llm.enableMcpRecording: true to use it.\",\n );\n }\n\n // 1.44.0 ignored `llm.responsesTools`, so an invalid value is ignored with a\n // warning (as `llm.misbehavior` is) and the server runs in \"legacy\" mode,\n // unless `--responses-tools` sets the mode. The warning names the mode that\n // actually runs.\n let responsesTools = config.llm?.responsesTools;\n if (\n responsesTools !== undefined &&\n responsesTools !== \"legacy\" &&\n responsesTools !== \"extended\"\n ) {\n const effective =\n overrides?.responsesTools !== undefined\n ? `\"${overrides.responsesTools}\" from --responses-tools`\n : '\"legacy\"';\n logger.warn(\n `Ignoring llm.responsesTools because it must be \"legacy\" or \"extended\", got ${JSON.stringify(responsesTools)}. Using ${effective}.`,\n );\n responsesTools = undefined;\n }\n\n // A non-positive replaySpeed fails calculateDelay's `speed > 0` check and applies the\n // full delay rather than none. Mirrors the fixture-level guard in fixture-loader.ts.\n let replaySpeed = config.llm?.replaySpeed;\n if (replaySpeed != null && (!Number.isFinite(replaySpeed) || replaySpeed <= 0)) {\n logger.warn(`llm.replaySpeed must be a positive number, got ${replaySpeed}. Ignoring.`);\n replaySpeed = undefined;\n }\n\n // Load fixtures if specified\n const resolvedAuth = resolveInboundAuth(selectInboundAuthSource(config.auth));\n const llmock = createLLMockWithResolvedAuth(\n {\n port: overrides?.port ?? config.port ?? 0,\n host: overrides?.host ?? config.host ?? \"127.0.0.1\",\n latency: config.llm?.latency,\n chunkSize: config.llm?.chunkSize,\n replaySpeed,\n // llm.record.mcp reports skipped or failed recordings only as MCP-RECORD: warnings,\n // so an enabled config with at least one mount defaults to \"warn\" rather than the silent\n // default. An empty llm.record.mcp records nothing. An explicit logLevel wins.\n logLevel: config.llm?.logLevel ?? (hasMcpRecordMount(mcpRecord) ? \"warn\" : undefined),\n chaos: config.llm?.chaos,\n misbehavior,\n ...(enableMisbehavior ? { enableMisbehavior: true } : {}),\n record: llmRecordOf(config.llm?.record),\n metrics: config.metrics,\n strict: config.strict,\n strictToolArguments: overrides?.strictToolArguments ?? configStrictToolArguments,\n responsesTools: overrides?.responsesTools ?? responsesTools,\n policy,\n },\n resolvedAuth,\n );\n\n // What this function mounted, by path (MR1: llm.record.mcp records through an MCP mount).\n const configMounts = new Map<string, Mountable>();\n\n if (config.llm?.fixtures) {\n const fixturePath = path.resolve(config.llm.fixtures);\n const stat = fs.statSync(fixturePath);\n if (stat.isDirectory()) {\n llmock.loadFixtureDir(fixturePath);\n } else {\n llmock.loadFixtureFile(fixturePath);\n }\n }\n\n // MCP\n if (config.mcp) {\n const mcpConfig = config.mcp;\n const mcp = new MCPMock({\n serverInfo: mcpConfig.serverInfo,\n });\n\n if (mcpConfig.tools) {\n for (const tool of mcpConfig.tools) {\n const { result, ...def } = tool;\n mcp.addTool(def);\n if (result !== undefined) {\n const answer = () => result;\n configToolHandlers.add(answer);\n mcp.onToolCall(def.name, answer);\n }\n }\n }\n\n if (mcpConfig.resources) {\n for (const res of mcpConfig.resources) {\n mcp.addResource(\n { uri: res.uri, name: res.name, mimeType: res.mimeType, description: res.description },\n res.text !== undefined || res.blob !== undefined\n ? { text: res.text, blob: res.blob, mimeType: res.mimeType }\n : undefined,\n );\n }\n }\n\n if (mcpConfig.prompts) {\n for (const prompt of mcpConfig.prompts) {\n const { result, ...def } = prompt;\n if (result) {\n mcp.addPrompt(def, () => result as import(\"./mcp-types.js\").MCPPromptResult);\n } else {\n mcp.addPrompt(def);\n }\n }\n }\n\n const mcpPath = mcpConfig.path ?? \"/mcp\";\n llmock.mount(mcpPath, mcp);\n configMounts.set(mcpPath, mcp);\n logger.info(`MCPMock mounted at ${mcpPath}`);\n }\n\n // A2A\n if (config.a2a) {\n const a2aConfig = config.a2a;\n const a2a = new A2AMock();\n\n if (a2aConfig.agents) {\n for (const agentConfig of a2aConfig.agents) {\n const { messages, tasks, streamingTasks, ...def } = agentConfig;\n a2a.registerAgent(def);\n\n if (messages) {\n for (const m of messages) {\n a2a.onMessage(def.name, m.pattern, m.parts ?? [{ text: \"\" }]);\n }\n }\n\n if (tasks) {\n for (const t of tasks) {\n a2a.onTask(def.name, t.pattern, t.artifacts ?? []);\n }\n }\n\n if (streamingTasks) {\n for (const s of streamingTasks) {\n a2a.onStreamingTask(def.name, s.pattern, s.events ?? [], s.delayMs);\n }\n }\n }\n }\n\n const a2aPath = a2aConfig.path ?? \"/a2a\";\n llmock.mount(a2aPath, a2a);\n configMounts.set(a2aPath, a2a);\n logger.info(`A2AMock mounted at ${a2aPath}`);\n }\n\n // AG-UI\n if (config.agui) {\n const aguiConfig = config.agui;\n const agui = new AGUIMock();\n\n if (aguiConfig.fixtures) {\n for (const f of aguiConfig.fixtures) {\n if (f.match.toolCallId && f.text && !f.events) {\n logger.warn(\n `AG-UI fixture uses text shorthand with toolCallId — text shorthand ignores toolCallId matching; use events[] instead (match: ${JSON.stringify(f.match)})`,\n );\n }\n if (f.text) {\n if (f.match.message !== undefined) {\n agui.onMessage(f.match.message, f.text, { delayMs: f.delayMs });\n } else {\n // No message pattern — register via addFixture so it only matches\n // on other criteria (toolCallId, toolName, stateKey) instead of\n // becoming a catch-all that matches every request.\n agui.addFixture({\n match: {\n toolCallId: f.match.toolCallId,\n toolName: f.match.toolName,\n stateKey: f.match.stateKey,\n },\n events: buildTextResponse(f.text),\n delayMs: f.delayMs,\n });\n }\n } else if (f.events) {\n agui.addFixture({\n match: {\n message: f.match.message,\n toolCallId: f.match.toolCallId,\n toolName: f.match.toolName,\n stateKey: f.match.stateKey,\n },\n events: f.events,\n delayMs: f.delayMs,\n });\n } else {\n logger.warn(\n `AG-UI fixture has neither text nor events — it will be skipped (match: ${JSON.stringify(f.match)})`,\n );\n }\n }\n }\n\n const aguiPath = aguiConfig.path ?? \"/agui\";\n llmock.mount(aguiPath, agui);\n configMounts.set(aguiPath, agui);\n logger.info(`AGUIMock mounted at ${aguiPath}`);\n }\n\n // Vector\n if (config.vector) {\n const vectorConfig = config.vector;\n const vector = new VectorMock();\n\n if (vectorConfig.collections) {\n for (const col of vectorConfig.collections) {\n vector.addCollection(col.name, { dimension: col.dimension });\n\n if (col.vectors && col.vectors.length > 0) {\n vector.upsert(col.name, col.vectors);\n }\n\n if (col.queryResults) {\n vector.onQuery(col.name, col.queryResults);\n }\n }\n }\n\n const vectorPath = vectorConfig.path ?? \"/vector\";\n llmock.mount(vectorPath, vector);\n configMounts.set(vectorPath, vector);\n logger.info(`VectorMock mounted at ${vectorPath}`);\n }\n\n // MR1: llm.record.mcp — record mounts (auto-mount an MCPMock where none is).\n // Read only with llm.enableMcpRecording: true. Any value that is present is then\n // validated, so null, false, 0 and \"\" fail at start too.\n if (mcpRecord !== undefined) {\n wireMcpRecording(llmock, mcpRecord, {\n mounted: configMounts,\n mcpMock: MCPMock,\n fixtures: config.llm?.fixtures,\n fixturePath: config.llm?.record?.fixturePath,\n strict: config.strict,\n env: process.env,\n });\n }\n\n // Services — configure default catch-all responses\n if (config.services) {\n if (config.services.search) {\n llmock.onSearch(/.*/, []);\n logger.info(\"Search service enabled with default empty results\");\n }\n if (config.services.rerank) {\n llmock.onRerank(/.*/, []);\n logger.info(\"Rerank service enabled with default empty results\");\n }\n if (config.services.moderate) {\n llmock.onModerate(/.*/, { flagged: false, categories: {} });\n logger.info(\"Moderation service enabled with default unflagged results\");\n }\n }\n\n const url = await llmock.start();\n return { llmock, url };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwJA,SAAS,YAAY,QAAkE;AACrF,KAAI,CAAC,OAAQ,QAAO;CACpB,MAAM,EAAE,KAAK,MAAM,GAAG,QAAQ;AAE9B,QAAO,IAAI,cAAc,SAAY,SAAY;;AAGnD,SAAgB,WAAW,YAAkC;CAC3D,MAAM,MAAMA,QAAG,aAAa,YAAY,QAAQ;AAChD,QAAO,KAAK,MAAM,IAAI;;;AAIxB,SAAS,kBAAkB,KAAuB;AAChD,QACE,OAAO,QAAQ,YAAY,QAAQ,QAAQ,CAAC,MAAM,QAAQ,IAAI,IAAI,OAAO,KAAK,IAAI,CAAC,SAAS;;;AAsBhG,SAAgB,iBAAiB,SAAmB;CAClD,MAAM,SAAuB,EAAE;AAC/B,MAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,YAAY,MAAM,QAAQ,IAAI;AACpC,MAAI,YAAY,EACd,QAAO;GACL,IAAI;GACJ,OAAO,oBAAoB,KAAK,UAAU,MAAM,CAAC;GAClD;EAEH,MAAM,SAASC,gCAAiB,MAAM,MAAM,GAAG,UAAU,EAAE,MAAM,MAAM,YAAY,EAAE,CAAC;AACtF,MAAI,CAAC,OAAO,GACV,QAAO;GACL,IAAI;GACJ,OAAO,oBAAoB,KAAK,UAAU,MAAM,CAAC,IAAI,OAAO,OAAO;GACpE;AAEH,mCAAkB,QAAQ,OAAO;;AAEnC,QAAO;EAAE,IAAI;EAAM;EAAQ;;AAG7B,eAAsB,gBACpB,QACA,WAC0C;CAC1C,MAAM,SAAS,IAAIC,sBAAO,OAAO;CACjC,MAAM,SAAS;EACb,GAAGC,2BAAY,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,QAAQ,CAAC;EACrE,GAAGA,2BAAY,WAAW,SAAS,YAAY,OAAO,KAAK,QAAQ,CAAC;EACrE;CAKD,MA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,KAAK,QAAQ;EACjC,QAAQ,OAAO;EACf,KAAK,QAAQ;EACd,CAAC;AAIJ,KAAI,OAAO,UAAU;AACnB,MAAI,OAAO,SAAS,QAAQ;AAC1B,UAAO,SAAS,MAAM,EAAE,CAAC;AACzB,UAAO,KAAK,oDAAoD;;AAElE,MAAI,OAAO,SAAS,QAAQ;AAC1B,UAAO,SAAS,MAAM,EAAE,CAAC;AACzB,UAAO,KAAK,oDAAoD;;AAElE,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAO,WAAW,MAAM;IAAE,SAAS;IAAO,YAAY,EAAE;IAAE,CAAC;AAC3D,UAAO,KAAK,4DAA4D;;;AAK5E,QAAO;EAAE;EAAQ,KADL,MAAM,OAAO,OAAO;EACV"}
@@ -1,4 +1,4 @@
1
- import { ApiKeyAuthConfig, ChaosConfig, McpRecordConfig, MisbehaviorConfig, MisbehaviorFaultId, RecordConfig, ResponsesToolsMode } from "./types.cjs";
1
+ import { AimockPolicy, ApiKeyAuthConfig, ChaosConfig, McpRecordConfig, MisbehaviorConfig, MisbehaviorFaultId, RecordConfig, ResponsesToolsMode } from "./types.cjs";
2
2
  import { A2AAgentDefinition, A2AArtifact, A2APart, A2AStreamEvent } from "./a2a-types.cjs";
3
3
  import { AGUIEvent } from "./agui-types.cjs";
4
4
  import { LLMock } from "./llmock.cjs";
@@ -115,6 +115,8 @@ interface AimockConfig {
115
115
  strictToolArguments?: boolean;
116
116
  /** See `MockServerOptions.responsesTools`. */
117
117
  responsesTools?: ResponsesToolsMode;
118
+ /** See `MockServerOptions.policy`. Independent of `strict`. */
119
+ policy?: AimockPolicy;
118
120
  };
119
121
  mcp?: MCPConfig;
120
122
  a2a?: A2AConfig;
@@ -144,7 +146,11 @@ interface StartFromConfigOverrides {
144
146
  strictToolArguments?: boolean;
145
147
  /** `aimock --responses-tools`: overrides `llm.responsesTools`. */
146
148
  responsesTools?: ResponsesToolsMode;
149
+ /** `aimock --policy`: overrides individual keys from `llm.policy`. */
150
+ policy?: AimockPolicy;
147
151
  }
152
+ /** Both CLI entry points use the shared policy parser and treat failures as usage errors. */
153
+
148
154
  declare function startFromConfig(config: AimockConfig, overrides?: StartFromConfigOverrides): Promise<{
149
155
  llmock: LLMock;
150
156
  url: string;
@@ -1 +1 @@
1
- {"version":3,"file":"config-loader.d.cts","names":[],"sources":["../src/config-loader.ts"],"sourcesContent":[],"mappings":";;;;;;;;UA4BiB,aAAA,SAAsB;;AAAvC;AAIiB,UAAA,iBAAA,CAAiB;EASjB,GAAA,EAAA,MAAA;EAAgB,IAAA,EAAA,MAAA;UAEnB,CAAA,EAAA,MAAA;aAF2B,CAAA,EAAA,MAAA;EAAmB,IAAA,CAAA,EAAA,MAAA;EAM3C,IAAA,CAAA,EAAA,MAAS;;AAGhB,UATO,eAAA,SAAwB,mBAS/B,CAAA;QACI,CAAA,EAAA;IACF,QAAA,EATE,KASF,CAAA;MAAe,IAAA,EAAA,MAAA;MAGV,OAAA,EAAA;QAAgB,IAAA,EAAA,MAAA;QAEvB,IAAA,EAAA,MAAA;MACI,CAAA;IACH,CAAA,CAAA;EAAc,CAAA;AAIzB;AAAgC,UAhBf,SAAA,CAgBe;MACnB,CAAA,EAAA,MAAA;YACH,CAAA,EAAA;IACS,IAAA,EAAA,MAAA;IAHqB,OAAA,EAAA,MAAA;EAAkB,CAAA;EAMzC,KAAA,CAAA,EAnBP,aAmBgB,EAEf;EAGM,SAAA,CAAA,EAvBH,iBAuBoB,EAGvB;EAIM,OAAA,CAAA,EA7BL,eA+BC,EAAA;AAGb;AAAuC,UA/BtB,gBAAA,CA+BsB;SAMxB,EAAA,MAAA;OAHH,CAAA,EAhCF,OAgCE,EAAA;WAKK,CAAA,EApCH,WAoCG,EAAA;EAAW,MAAA,CAAA,EAnCjB,cAmCiB,EAAA;EAGX,OAAA,CAAA,EAAA,MAAY;AAM7B;AAAoC,UAxCnB,cAAA,SAAuB,kBAwCJ,CAAA;UAEJ,CAAA,EAzCnB,gBAyCmB,EAAA;OAAxB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