@zyro-sec/ai 0.0.0-stage → 1.0.1

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 (828) hide show
  1. package/AGENTS.md +23 -0
  2. package/README.md +1810 -2
  3. package/example/tutorial.ts +284 -0
  4. package/package.json +40 -4
  5. package/script/pack.ts +5 -0
  6. package/script/recording-cost-report.ts +250 -0
  7. package/script/setup-recording-env.ts +602 -0
  8. package/src/ai-client.ts +28 -0
  9. package/src/cache-policy.ts +249 -0
  10. package/src/decision-client.ts +88 -0
  11. package/src/decision.ts +335 -0
  12. package/src/effect.ts +44 -0
  13. package/src/effort-updates.ts +25 -0
  14. package/src/embedding-client.ts +46 -0
  15. package/src/embedding.ts +167 -0
  16. package/src/experimental/cloudflare-run-extraction.ts +112 -0
  17. package/src/experimental/extraction.ts +190 -0
  18. package/src/experimental/realtime.ts +211 -0
  19. package/src/experimental.ts +51 -0
  20. package/src/generation.ts +210 -0
  21. package/src/image-client.ts +89 -0
  22. package/src/image.ts +236 -0
  23. package/src/index.ts +363 -0
  24. package/src/llm.ts +364 -0
  25. package/src/loop.ts +214 -0
  26. package/src/media-client.ts +94 -0
  27. package/src/media-model.ts +129 -0
  28. package/src/media.ts +408 -0
  29. package/src/protocols/alibaba-chat.ts +95 -0
  30. package/src/protocols/alibaba-images.ts +126 -0
  31. package/src/protocols/alibaba-messages.ts +49 -0
  32. package/src/protocols/alibaba-responses.ts +86 -0
  33. package/src/protocols/anthropic-messages.ts +1664 -0
  34. package/src/protocols/assemblyai-transcription.ts +209 -0
  35. package/src/protocols/bedrock-converse.ts +984 -0
  36. package/src/protocols/bedrock-event-stream.ts +147 -0
  37. package/src/protocols/cartesia-speech.ts +182 -0
  38. package/src/protocols/cloudflare-run-decisions.ts +55 -0
  39. package/src/protocols/cloudflare-workers-ai-images.ts +124 -0
  40. package/src/protocols/cohere-chat.ts +353 -0
  41. package/src/protocols/deepgram-speech.ts +148 -0
  42. package/src/protocols/deepgram-transcription.ts +179 -0
  43. package/src/protocols/elevenlabs-speech.ts +207 -0
  44. package/src/protocols/elevenlabs-transcription.ts +211 -0
  45. package/src/protocols/gemini.ts +908 -0
  46. package/src/protocols/google-decisions.ts +179 -0
  47. package/src/protocols/google-embed-content.ts +165 -0
  48. package/src/protocols/google-images.ts +255 -0
  49. package/src/protocols/google-interactions-video.ts +264 -0
  50. package/src/protocols/google-interactions.ts +904 -0
  51. package/src/protocols/google-speech.ts +157 -0
  52. package/src/protocols/google-transcription.ts +206 -0
  53. package/src/protocols/google-vertex-predict-embeddings.ts +104 -0
  54. package/src/protocols/index.ts +21 -0
  55. package/src/protocols/meta-images.ts +162 -0
  56. package/src/protocols/meta-messages.ts +67 -0
  57. package/src/protocols/meta-responses.ts +249 -0
  58. package/src/protocols/minimax-images.ts +215 -0
  59. package/src/protocols/minimax-video.ts +406 -0
  60. package/src/protocols/mistral-chat.ts +768 -0
  61. package/src/protocols/open-responses-channel.ts +198 -0
  62. package/src/protocols/open-responses-continuation.ts +218 -0
  63. package/src/protocols/open-responses.ts +1636 -0
  64. package/src/protocols/openai-chat.ts +1431 -0
  65. package/src/protocols/openai-compatible-chat.ts +22 -0
  66. package/src/protocols/openai-compatible-responses.ts +21 -0
  67. package/src/protocols/openai-decisions.ts +174 -0
  68. package/src/protocols/openai-embeddings.ts +105 -0
  69. package/src/protocols/openai-freeform.ts +287 -0
  70. package/src/protocols/openai-images.ts +442 -0
  71. package/src/protocols/openai-responses.ts +442 -0
  72. package/src/protocols/openai-speech.ts +164 -0
  73. package/src/protocols/openai-transcription.ts +295 -0
  74. package/src/protocols/openrouter-video.ts +215 -0
  75. package/src/protocols/seedance-video.ts +301 -0
  76. package/src/protocols/shared.ts +552 -0
  77. package/src/protocols/system-one.ts +335 -0
  78. package/src/protocols/utils/bedrock-auth.ts +147 -0
  79. package/src/protocols/utils/bedrock-cache.ts +56 -0
  80. package/src/protocols/utils/bedrock-media.ts +121 -0
  81. package/src/protocols/utils/cache.ts +44 -0
  82. package/src/protocols/utils/claude-model.ts +19 -0
  83. package/src/protocols/utils/gateway-protocol.ts +92 -0
  84. package/src/protocols/utils/gemini-generate-content.ts +172 -0
  85. package/src/protocols/utils/gemini-json-schema.ts +77 -0
  86. package/src/protocols/utils/image-sizing.ts +117 -0
  87. package/src/protocols/utils/lifecycle.ts +120 -0
  88. package/src/protocols/utils/media-input.ts +98 -0
  89. package/src/protocols/utils/mistral-tool-id.ts +34 -0
  90. package/src/protocols/utils/open-responses-options.ts +82 -0
  91. package/src/protocols/utils/partial-json-options.ts +62 -0
  92. package/src/protocols/utils/partial-json.ts +283 -0
  93. package/src/protocols/utils/responses-checkpoint.ts +115 -0
  94. package/src/protocols/utils/responses-compaction.ts +210 -0
  95. package/src/protocols/utils/responses-hosted-tools.ts +104 -0
  96. package/src/protocols/utils/speaker-turns.ts +10 -0
  97. package/src/protocols/utils/speech-stream.ts +111 -0
  98. package/src/protocols/utils/tool-schema.ts +115 -0
  99. package/src/protocols/utils/tool-stream.ts +240 -0
  100. package/src/protocols/venice-chat.ts +356 -0
  101. package/src/protocols/xai-images.ts +137 -0
  102. package/src/protocols/xai-responses.ts +106 -0
  103. package/src/protocols/xai-video.ts +232 -0
  104. package/src/protocols/zai-chat.ts +71 -0
  105. package/src/protocols/zai-images.ts +120 -0
  106. package/src/protocols/zai-messages.ts +34 -0
  107. package/src/protocols.ts +1 -0
  108. package/src/provider-error.ts +291 -0
  109. package/src/provider-package.ts +32 -0
  110. package/src/providers/alibaba/chat.ts +1 -0
  111. package/src/providers/alibaba/embeddings.ts +2 -0
  112. package/src/providers/alibaba/images.ts +2 -0
  113. package/src/providers/alibaba/messages.ts +3 -0
  114. package/src/providers/alibaba/responses.ts +3 -0
  115. package/src/providers/alibaba.ts +177 -0
  116. package/src/providers/amazon-bedrock/mantle/chat.ts +2 -0
  117. package/src/providers/amazon-bedrock/mantle/messages.ts +2 -0
  118. package/src/providers/amazon-bedrock/mantle/responses.ts +2 -0
  119. package/src/providers/amazon-bedrock/mantle.ts +2 -0
  120. package/src/providers/amazon-bedrock-mantle.ts +192 -0
  121. package/src/providers/amazon-bedrock.ts +81 -0
  122. package/src/providers/anthropic-compatible.ts +80 -0
  123. package/src/providers/anthropic.ts +66 -0
  124. package/src/providers/assemblyai.ts +32 -0
  125. package/src/providers/azure/chat.ts +2 -0
  126. package/src/providers/azure/embeddings.ts +2 -0
  127. package/src/providers/azure/images.ts +2 -0
  128. package/src/providers/azure/messages.ts +2 -0
  129. package/src/providers/azure/responses.ts +2 -0
  130. package/src/providers/azure.ts +240 -0
  131. package/src/providers/baseten/decisions.ts +2 -0
  132. package/src/providers/baseten.ts +88 -0
  133. package/src/providers/byteplus/videos.ts +2 -0
  134. package/src/providers/byteplus.ts +39 -0
  135. package/src/providers/cartesia.ts +28 -0
  136. package/src/providers/cerebras.ts +56 -0
  137. package/src/providers/cloudflare-ai-gateway/decisions.ts +2 -0
  138. package/src/providers/cloudflare-ai-gateway.ts +199 -0
  139. package/src/providers/cloudflare-shared.ts +29 -0
  140. package/src/providers/cloudflare-workers-ai/decisions.ts +2 -0
  141. package/src/providers/cloudflare-workers-ai/images.ts +2 -0
  142. package/src/providers/cloudflare-workers-ai.ts +104 -0
  143. package/src/providers/cohere/chat.ts +8 -0
  144. package/src/providers/cohere/embeddings.ts +2 -0
  145. package/src/providers/cohere.ts +72 -0
  146. package/src/providers/deepgram.ts +33 -0
  147. package/src/providers/deepinfra/embeddings.ts +2 -0
  148. package/src/providers/deepinfra.ts +76 -0
  149. package/src/providers/deepseek.ts +54 -0
  150. package/src/providers/digitalocean/decisions.ts +2 -0
  151. package/src/providers/digitalocean/embeddings.ts +2 -0
  152. package/src/providers/digitalocean/images.ts +2 -0
  153. package/src/providers/digitalocean/responses.ts +4 -0
  154. package/src/providers/digitalocean.ts +144 -0
  155. package/src/providers/elevenlabs.ts +35 -0
  156. package/src/providers/fireworks/embeddings.ts +2 -0
  157. package/src/providers/fireworks.ts +66 -0
  158. package/src/providers/google/decisions.ts +2 -0
  159. package/src/providers/google/embeddings.ts +2 -0
  160. package/src/providers/google/images.ts +2 -0
  161. package/src/providers/google/interactions.ts +13 -0
  162. package/src/providers/google/videos.ts +2 -0
  163. package/src/providers/google-vertex/chat.ts +2 -0
  164. package/src/providers/google-vertex/embeddings.ts +2 -0
  165. package/src/providers/google-vertex/gemini.ts +2 -0
  166. package/src/providers/google-vertex/images.ts +2 -0
  167. package/src/providers/google-vertex/interactions.ts +2 -0
  168. package/src/providers/google-vertex/messages.ts +2 -0
  169. package/src/providers/google-vertex/mistral.ts +2 -0
  170. package/src/providers/google-vertex/responses.ts +2 -0
  171. package/src/providers/google-vertex-chat.ts +63 -0
  172. package/src/providers/google-vertex-interactions.ts +104 -0
  173. package/src/providers/google-vertex-messages.ts +99 -0
  174. package/src/providers/google-vertex-mistral.ts +79 -0
  175. package/src/providers/google-vertex-responses.ts +64 -0
  176. package/src/providers/google-vertex-shared.ts +176 -0
  177. package/src/providers/google-vertex.ts +228 -0
  178. package/src/providers/google.ts +121 -0
  179. package/src/providers/groq.ts +98 -0
  180. package/src/providers/index.ts +45 -0
  181. package/src/providers/meta/chat.ts +2 -0
  182. package/src/providers/meta/images.ts +2 -0
  183. package/src/providers/meta/messages.ts +2 -0
  184. package/src/providers/meta/responses.ts +2 -0
  185. package/src/providers/meta.ts +161 -0
  186. package/src/providers/minimax/chat.ts +8 -0
  187. package/src/providers/minimax/images.ts +4 -0
  188. package/src/providers/minimax/messages.ts +1 -0
  189. package/src/providers/minimax/responses.ts +8 -0
  190. package/src/providers/minimax/videos.ts +4 -0
  191. package/src/providers/minimax.ts +162 -0
  192. package/src/providers/mistral.ts +40 -0
  193. package/src/providers/moonshot/chat.ts +1 -0
  194. package/src/providers/moonshot/messages.ts +8 -0
  195. package/src/providers/moonshot/responses.ts +8 -0
  196. package/src/providers/moonshot.ts +134 -0
  197. package/src/providers/open-responses-options.ts +4 -0
  198. package/src/providers/openai/chat.ts +2 -0
  199. package/src/providers/openai/embeddings.ts +2 -0
  200. package/src/providers/openai/images.ts +2 -0
  201. package/src/providers/openai/responses.ts +2 -0
  202. package/src/providers/openai-compatible/decisions.ts +2 -0
  203. package/src/providers/openai-compatible/embeddings.ts +2 -0
  204. package/src/providers/openai-compatible/images.ts +2 -0
  205. package/src/providers/openai-compatible/responses.ts +1 -0
  206. package/src/providers/openai-compatible-responses.ts +52 -0
  207. package/src/providers/openai-compatible.ts +108 -0
  208. package/src/providers/openai-options.ts +66 -0
  209. package/src/providers/openai.ts +207 -0
  210. package/src/providers/opencode/decisions.ts +2 -0
  211. package/src/providers/opencode.ts +45 -0
  212. package/src/providers/openrouter/decisions.ts +2 -0
  213. package/src/providers/openrouter/embeddings.ts +2 -0
  214. package/src/providers/openrouter/images.ts +2 -0
  215. package/src/providers/openrouter/responses.ts +3 -0
  216. package/src/providers/openrouter/videos.ts +2 -0
  217. package/src/providers/openrouter.ts +347 -0
  218. package/src/providers/settings.ts +54 -0
  219. package/src/providers/togetherai.ts +53 -0
  220. package/src/providers/typesafe-ai/decisions.ts +2 -0
  221. package/src/providers/typesafe-ai.ts +45 -0
  222. package/src/providers/venice/responses.ts +4 -0
  223. package/src/providers/venice.ts +93 -0
  224. package/src/providers/vercel-ai-gateway/chat.ts +2 -0
  225. package/src/providers/vercel-ai-gateway/decisions.ts +2 -0
  226. package/src/providers/vercel-ai-gateway/embeddings.ts +2 -0
  227. package/src/providers/vercel-ai-gateway/images.ts +2 -0
  228. package/src/providers/vercel-ai-gateway/messages.ts +2 -0
  229. package/src/providers/vercel-ai-gateway/responses.ts +2 -0
  230. package/src/providers/vercel-ai-gateway.ts +300 -0
  231. package/src/providers/volcengine/videos.ts +2 -0
  232. package/src/providers/volcengine.ts +39 -0
  233. package/src/providers/xai/images.ts +2 -0
  234. package/src/providers/xai/videos.ts +2 -0
  235. package/src/providers/xai.ts +125 -0
  236. package/src/providers/zai/chat.ts +1 -0
  237. package/src/providers/zai/images.ts +2 -0
  238. package/src/providers/zai-coding-plan/chat.ts +1 -0
  239. package/src/providers/zai-coding-plan/messages.ts +8 -0
  240. package/src/providers/zai-coding-plan/responses.ts +8 -0
  241. package/src/providers/zai-coding-plan.ts +86 -0
  242. package/src/providers/zai.ts +73 -0
  243. package/src/providers.ts +1 -0
  244. package/src/public.ts +204 -0
  245. package/src/route/auth-options.ts +62 -0
  246. package/src/route/auth.ts +164 -0
  247. package/src/route/client.ts +700 -0
  248. package/src/route/decision.ts +150 -0
  249. package/src/route/embedding.ts +175 -0
  250. package/src/route/endpoint.ts +63 -0
  251. package/src/route/executor-service.ts +191 -0
  252. package/src/route/executor.ts +361 -0
  253. package/src/route/framing.ts +112 -0
  254. package/src/route/index.ts +47 -0
  255. package/src/route/media-protocol.ts +321 -0
  256. package/src/route/media.ts +507 -0
  257. package/src/route/protocol.ts +97 -0
  258. package/src/route/transport/http.ts +103 -0
  259. package/src/route/transport/index.ts +59 -0
  260. package/src/route/transport/websocket-channel.ts +51 -0
  261. package/src/route/transport/websocket.ts +443 -0
  262. package/src/route.ts +1 -0
  263. package/src/schema/errors.ts +246 -0
  264. package/src/schema/events.ts +744 -0
  265. package/src/schema/ids.ts +24 -0
  266. package/src/schema/index.ts +5 -0
  267. package/src/schema/messages.ts +529 -0
  268. package/src/schema/options.ts +445 -0
  269. package/src/speech-client.ts +25 -0
  270. package/src/speech.ts +211 -0
  271. package/src/testing.ts +218 -0
  272. package/src/tool-history.ts +91 -0
  273. package/src/tool-runtime.ts +107 -0
  274. package/src/tool-updates.ts +139 -0
  275. package/src/tool.ts +281 -0
  276. package/src/transcription-client.ts +19 -0
  277. package/src/transcription.ts +234 -0
  278. package/src/utils/bytes.ts +9 -0
  279. package/src/utils/json.ts +5 -0
  280. package/src/utils/media-type.ts +93 -0
  281. package/src/utils/provider-codes.ts +43 -0
  282. package/src/utils/record.ts +3 -0
  283. package/src/utils/sanitize.ts +33 -0
  284. package/src/video-client.ts +66 -0
  285. package/src/video.ts +181 -0
  286. package/test/adapter.test.ts +180 -0
  287. package/test/auth-options.types.ts +283 -0
  288. package/test/auth.test.ts +112 -0
  289. package/test/cache-policy.test.ts +578 -0
  290. package/test/compaction-http.test.ts +96 -0
  291. package/test/compaction.test.ts +107 -0
  292. package/test/compile.test.ts +600 -0
  293. package/test/continuation-scenarios.ts +115 -0
  294. package/test/decision.test.ts +983 -0
  295. package/test/decision.types.ts +117 -0
  296. package/test/effort-updates.test.ts +574 -0
  297. package/test/embedding.test.ts +455 -0
  298. package/test/endpoint.test.ts +58 -0
  299. package/test/error-partial.test.ts +140 -0
  300. package/test/executor.test.ts +1095 -0
  301. package/test/exports.test.ts +222 -0
  302. package/test/extraction.test.ts +227 -0
  303. package/test/fixtures/audio/dialog.mp3 +0 -0
  304. package/test/fixtures/audio/hello.mp3 +0 -0
  305. package/test/fixtures/images/edit-source.jpg +0 -0
  306. package/test/fixtures/media/restroom.png +0 -0
  307. package/test/fixtures/recordings/alibaba-chat/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
  308. package/test/fixtures/recordings/alibaba-chat/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
  309. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-flash-reads-image-bytes.json +34 -0
  310. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
  311. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
  312. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-returns-a-json-object.json +34 -0
  313. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-default-effort.json +36 -0
  314. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-high-effort.json +36 -0
  315. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-low-effort.json +36 -0
  316. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-max-effort.json +36 -0
  317. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-medium-effort.json +36 -0
  318. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-minimal-effort.json +36 -0
  319. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-none-effort.json +36 -0
  320. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-xhigh-effort.json +36 -0
  321. package/test/fixtures/recordings/alibaba-images/edits-an-image.json +33 -0
  322. package/test/fixtures/recordings/alibaba-images/generates-qwen-image-images.json +33 -0
  323. package/test/fixtures/recordings/alibaba-images/generates-wan-images.json +33 -0
  324. package/test/fixtures/recordings/alibaba-messages/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
  325. package/test/fixtures/recordings/alibaba-messages/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
  326. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-flash-reads-image-bytes.json +34 -0
  327. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-follows-a-json-schema.json +34 -0
  328. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
  329. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
  330. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-default-effort.json +36 -0
  331. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-high-effort.json +36 -0
  332. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-low-effort.json +36 -0
  333. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-max-effort.json +36 -0
  334. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-medium-effort.json +36 -0
  335. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-xhigh-effort.json +36 -0
  336. package/test/fixtures/recordings/alibaba-responses/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
  337. package/test/fixtures/recordings/alibaba-responses/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
  338. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-flash-reads-image-bytes.json +34 -0
  339. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-continues-a-stored-response.json +53 -0
  340. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
  341. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
  342. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-default-effort.json +36 -0
  343. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-high-effort.json +36 -0
  344. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-low-effort.json +36 -0
  345. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-max-effort.json +36 -0
  346. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-medium-effort.json +36 -0
  347. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-minimal-effort.json +36 -0
  348. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-none-effort.json +36 -0
  349. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-xhigh-effort.json +36 -0
  350. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-uses-hosted-code-interpreter.json +35 -0
  351. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-uses-hosted-web-search-and-extraction.json +36 -0
  352. package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-text.json +40 -0
  353. package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-tool-call.json +41 -0
  354. package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-tool-loop.json +60 -0
  355. package/test/fixtures/recordings/anthropic-messages/anthropic-opus-4-7-image-tool-result.json +43 -0
  356. package/test/fixtures/recordings/anthropic-messages-cache/keeps-a-long-tool-turn-inside-the-cache-lookback.json +48 -0
  357. package/test/fixtures/recordings/anthropic-messages-cache/writes-then-reads-cache-control-on-identical-second-call.json +48 -0
  358. package/test/fixtures/recordings/assemblyai-transcription/uploads-submits-and-polls-a-transcript.json +98 -0
  359. package/test/fixtures/recordings/azure/chat-streams-text-from-a-foundry-models-url.json +31 -0
  360. package/test/fixtures/recordings/azure/chat-streams-text.json +28 -0
  361. package/test/fixtures/recordings/azure/messages-calls-a-tool.json +31 -0
  362. package/test/fixtures/recordings/azure/messages-streams-text.json +31 -0
  363. package/test/fixtures/recordings/azure/responses-calls-a-tool.json +31 -0
  364. package/test/fixtures/recordings/azure/responses-continues-after-a-tool-result.json +31 -0
  365. package/test/fixtures/recordings/azure/responses-streams-text.json +31 -0
  366. package/test/fixtures/recordings/baseten-decision/decides-choice-score-and-predicate-questions.json +33 -0
  367. package/test/fixtures/recordings/bedrock-converse/continues-after-parallel-tool-results.json +36 -0
  368. package/test/fixtures/recordings/bedrock-converse/drives-a-tool-loop.json +55 -0
  369. package/test/fixtures/recordings/bedrock-converse/streams-a-tool-call.json +29 -0
  370. package/test/fixtures/recordings/bedrock-converse/streams-text.json +29 -0
  371. package/test/fixtures/recordings/bedrock-converse-cache/writes-then-reads-cachepoint-on-identical-second-call.json +48 -0
  372. package/test/fixtures/recordings/bedrock-converse-options/constrains-claude-output-to-a-json-schema.json +33 -0
  373. package/test/fixtures/recordings/bedrock-converse-options/sends-claude-effort-with-adaptive-thinking-service-tier-and-request-metadata.json +34 -0
  374. package/test/fixtures/recordings/bedrock-converse-options/sends-gpt-oss-reasoning-effort-with-the-priority-tier.json +34 -0
  375. package/test/fixtures/recordings/bedrock-converse-options/sends-nova-2-reasoning-effort.json +34 -0
  376. package/test/fixtures/recordings/bedrock-converse-thinking-binding/accepts-the-default-binding-with-no-thinking-configured.json +34 -0
  377. package/test/fixtures/recordings/bedrock-converse-thinking-binding/keeps-a-session-working-after-the-system-prompt-changes.json +71 -0
  378. package/test/fixtures/recordings/bedrock-mantle/streams-text.json +33 -0
  379. package/test/fixtures/recordings/bedrock-mantle-messages/applies-mid-conversation-effort-updates-and-thinking-block-binding-on-opus-5-5.json +57 -0
  380. package/test/fixtures/recordings/bedrock-mantle-messages/lowers-system-updates-to-wrapped-user-text-on-haiku-4-5-with-budget-thinking.json +37 -0
  381. package/test/fixtures/recordings/bedrock-mantle-messages/replays-signed-thinking-through-a-tool-loop-and-native-system-update.json +59 -0
  382. package/test/fixtures/recordings/bedrock-mantle-messages/strips-unsupported-mid-conversation-effort-updates-on-opus-5-0.json +37 -0
  383. package/test/fixtures/recordings/cartesia-speech/generates-speech.json +34 -0
  384. package/test/fixtures/recordings/cartesia-speech/streams-speech-with-timestamps.json +33 -0
  385. package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-text.json +32 -0
  386. package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-tool-call.json +32 -0
  387. package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-tool-loop.json +50 -0
  388. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-claude-haiku-4-5-text.json +38 -0
  389. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-claude-haiku-4-5-tool-loop.json +58 -0
  390. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-openai-gpt-5-nano-text.json +37 -0
  391. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-openai-gpt-5-nano-tool-loop.json +56 -0
  392. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  393. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-llama-3-1-8b-text.json +32 -0
  394. package/test/fixtures/recordings/cloudflare-ai-gateway-decision/decides-choice-score-and-predicate-questions.json +33 -0
  395. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  396. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-llama-3-1-8b-text.json +32 -0
  397. package/test/fixtures/recordings/cloudflare-workers-ai-decision/decides-choice-score-and-predicate-questions.json +33 -0
  398. package/test/fixtures/recordings/cloudflare-workers-ai-extraction/extracts-invoice-fields.json +33 -0
  399. package/test/fixtures/recordings/cloudflare-workers-ai-images/generates-a-flux-2-image-from-multipart-fields.json +32 -0
  400. package/test/fixtures/recordings/cloudflare-workers-ai-images/generates-a-raw-binary-image.json +33 -0
  401. package/test/fixtures/recordings/cohere/continues-a-native-tool-call.json +49 -0
  402. package/test/fixtures/recordings/cohere/streams-compatible-chat-reasoning.json +31 -0
  403. package/test/fixtures/recordings/cohere/streams-native-text-and-usage.json +31 -0
  404. package/test/fixtures/recordings/cohere/streams-native-thinking-with-a-budget.json +31 -0
  405. package/test/fixtures/recordings/cohere-embedding/embeds-text-through-the-compatibility-api.json +33 -0
  406. package/test/fixtures/recordings/deepgram-speech/generates-speech.json +36 -0
  407. package/test/fixtures/recordings/deepgram-speech/streams-speech.json +36 -0
  408. package/test/fixtures/recordings/deepgram-transcription/splits-utterances-at-speaker-changes.json +32 -0
  409. package/test/fixtures/recordings/deepgram-transcription/transcribes-raw-audio-with-speakers-and-word-timestamps.json +50 -0
  410. package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-text.json +32 -0
  411. package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-tool-call.json +32 -0
  412. package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-tool-loop.json +50 -0
  413. package/test/fixtures/recordings/digitalocean-chat/gpt-nano-continues-a-tool-call-with-cache-markers.json +54 -0
  414. package/test/fixtures/recordings/digitalocean-chat/gpt-nano-reuses-a-cached-prompt.json +53 -0
  415. package/test/fixtures/recordings/digitalocean-chat/haiku-continues-a-tool-call-with-cache-markers.json +54 -0
  416. package/test/fixtures/recordings/digitalocean-chat/haiku-reuses-a-cached-prompt.json +53 -0
  417. package/test/fixtures/recordings/digitalocean-decision/decides-choice-score-and-predicate-questions.json +33 -0
  418. package/test/fixtures/recordings/digitalocean-responses/calls-a-freeform-text-tool.json +35 -0
  419. package/test/fixtures/recordings/digitalocean-responses/continues-a-tool-call.json +53 -0
  420. package/test/fixtures/recordings/digitalocean-responses/streams-text.json +35 -0
  421. package/test/fixtures/recordings/elevenlabs-speech/generates-speech.json +35 -0
  422. package/test/fixtures/recordings/elevenlabs-speech/streams-speech-with-timestamps.json +34 -0
  423. package/test/fixtures/recordings/elevenlabs-transcription/groups-diarized-words-into-speaker-turns.json +32 -0
  424. package/test/fixtures/recordings/elevenlabs-transcription/transcribes-audio-with-word-timestamps.json +50 -0
  425. package/test/fixtures/recordings/gemini/gemini-2-5-flash-image.json +32 -0
  426. package/test/fixtures/recordings/gemini-cache/reports-cachedcontenttokencount-on-identical-second-call.json +46 -0
  427. package/test/fixtures/recordings/google-decision/decides-choice-score-and-predicate-questions.json +33 -0
  428. package/test/fixtures/recordings/google-embedding/embeds-an-image-and-text-into-one-vector-each.json +32 -0
  429. package/test/fixtures/recordings/google-embedding/embeds-text-through-batchembedcontents.json +32 -0
  430. package/test/fixtures/recordings/google-embedding/maps-inputtype-to-a-task-type-for-gemini-embedding-001.json +50 -0
  431. package/test/fixtures/recordings/google-images/edits-an-image.json +28 -0
  432. package/test/fixtures/recordings/google-images/generates-an-image.json +28 -0
  433. package/test/fixtures/recordings/google-interactions/continues-tool-results-with-previous-interaction-id.json +66 -0
  434. package/test/fixtures/recordings/google-interactions/replays-native-tool-results-and-signatures-statelessly.json +50 -0
  435. package/test/fixtures/recordings/google-interactions/streams-reasoning-and-retains-thought-signatures.json +32 -0
  436. package/test/fixtures/recordings/google-interactions/streams-text-and-reports-usage.json +32 -0
  437. package/test/fixtures/recordings/google-interactions-video/generates-a-video.json +96 -0
  438. package/test/fixtures/recordings/google-speech/generates-speech.json +32 -0
  439. package/test/fixtures/recordings/google-speech/streams-speech.json +32 -0
  440. package/test/fixtures/recordings/google-transcription/streams-speaker-turns.json +32 -0
  441. package/test/fixtures/recordings/google-transcription/transcribes-with-speakers-and-word-timestamps.json +32 -0
  442. package/test/fixtures/recordings/google-vertex/calls-a-tool.json +32 -0
  443. package/test/fixtures/recordings/google-vertex/continues-after-a-tool-result.json +32 -0
  444. package/test/fixtures/recordings/google-vertex/streams-text.json +32 -0
  445. package/test/fixtures/recordings/google-vertex-embedding/embeds-gemini-embedding-001-one-text-per-predict-request.json +50 -0
  446. package/test/fixtures/recordings/google-vertex-embedding/embeds-text-through-predict.json +32 -0
  447. package/test/fixtures/recordings/groq-chat/continues-qwen-parallel-tool-calls.json +47 -0
  448. package/test/fixtures/recordings/groq-chat/replays-gpt-oss-reasoning-through-a-tool-loop.json +47 -0
  449. package/test/fixtures/recordings/groq-chat/streams-qwen-parsed-reasoning.json +29 -0
  450. package/test/fixtures/recordings/groq-chat/streams-text-with-usage.json +29 -0
  451. package/test/fixtures/recordings/meta-chat/continues-a-generated-tool-call.json +56 -0
  452. package/test/fixtures/recordings/meta-chat/streams-text-with-default-reasoning.json +37 -0
  453. package/test/fixtures/recordings/meta-chat/streams-text-with-high-reasoning.json +29 -0
  454. package/test/fixtures/recordings/meta-chat/streams-text-with-low-reasoning.json +29 -0
  455. package/test/fixtures/recordings/meta-chat/streams-text-with-max-reasoning.json +29 -0
  456. package/test/fixtures/recordings/meta-chat/streams-text-with-medium-reasoning.json +37 -0
  457. package/test/fixtures/recordings/meta-chat/streams-text-with-minimal-reasoning.json +37 -0
  458. package/test/fixtures/recordings/meta-chat/streams-text-with-xhigh-reasoning.json +29 -0
  459. package/test/fixtures/recordings/meta-images/edits-image-bytes-and-returns-png.json +29 -0
  460. package/test/fixtures/recordings/meta-images/generates-default-webp-bytes.json +29 -0
  461. package/test/fixtures/recordings/meta-images/replays-a-signed-image-handle-for-a-responses-edit.json +55 -0
  462. package/test/fixtures/recordings/meta-messages/replays-encrypted-thinking-through-a-tool-loop.json +54 -0
  463. package/test/fixtures/recordings/meta-messages/streams-text-with-adaptive-thinking.json +36 -0
  464. package/test/fixtures/recordings/meta-messages/streams-text-with-enabled-thinking.json +36 -0
  465. package/test/fixtures/recordings/meta-responses/replays-encrypted-reasoning-through-a-tool-loop.json +56 -0
  466. package/test/fixtures/recordings/meta-responses/streams-text-with-default-reasoning.json +37 -0
  467. package/test/fixtures/recordings/meta-responses/streams-text-with-high-reasoning.json +37 -0
  468. package/test/fixtures/recordings/meta-responses/streams-text-with-low-reasoning.json +37 -0
  469. package/test/fixtures/recordings/meta-responses/streams-text-with-max-reasoning.json +37 -0
  470. package/test/fixtures/recordings/meta-responses/streams-text-with-medium-reasoning.json +37 -0
  471. package/test/fixtures/recordings/meta-responses/streams-text-with-minimal-reasoning.json +37 -0
  472. package/test/fixtures/recordings/meta-responses/streams-text-with-xhigh-reasoning.json +37 -0
  473. package/test/fixtures/recordings/meta-search/searches-and-replays-grounded-messages.json +56 -0
  474. package/test/fixtures/recordings/meta-search/searches-and-replays-grounded-responses.json +56 -0
  475. package/test/fixtures/recordings/minimax-chat/m3-continues-a-tool-loop-with-default-thinking.json +56 -0
  476. package/test/fixtures/recordings/minimax-chat/m3-streams-text-with-thinking-disabled.json +36 -0
  477. package/test/fixtures/recordings/minimax-images/generates-an-image.json +32 -0
  478. package/test/fixtures/recordings/minimax-images/generates-from-a-subject-reference.json +32 -0
  479. package/test/fixtures/recordings/minimax-messages/m2-7-streams-default-thinking.json +36 -0
  480. package/test/fixtures/recordings/minimax-messages/m3-continues-a-tool-loop-with-adaptive-thinking.json +56 -0
  481. package/test/fixtures/recordings/minimax-messages/m3-generates-a-named-tool-call-with-default-thinking-off.json +36 -0
  482. package/test/fixtures/recordings/minimax-messages/m3-streams-adaptive-thinking.json +36 -0
  483. package/test/fixtures/recordings/minimax-messages/m3-streams-text-with-thinking-disabled.json +36 -0
  484. package/test/fixtures/recordings/minimax-responses/m3-continues-a-tool-loop-with-effort-minimal.json +56 -0
  485. package/test/fixtures/recordings/minimax-responses/m3-streams-text-with-effort-none.json +36 -0
  486. package/test/fixtures/recordings/minimax-video/generates-a-hailuo-video-from-a-first-frame.json +176 -0
  487. package/test/fixtures/recordings/minimax-video/generates-an-h3-video.json +96 -0
  488. package/test/fixtures/recordings/mistral-chat/drives-a-tool-loop.json +54 -0
  489. package/test/fixtures/recordings/mistral-chat/replays-native-reasoning.json +47 -0
  490. package/test/fixtures/recordings/mistral-chat/streams-text-with-usage.json +29 -0
  491. package/test/fixtures/recordings/mistral-chat-glm/streams-an-indexed-tool-call.json +36 -0
  492. package/test/fixtures/recordings/moonshot-chat/k3-reads-image-bytes.json +29 -0
  493. package/test/fixtures/recordings/moonshot-chat/k3-respects-tool-choice-none.json +29 -0
  494. package/test/fixtures/recordings/moonshot-chat/k3-respects-tool-choice-required.json +29 -0
  495. package/test/fixtures/recordings/moonshot-chat/k3-returns-native-structured-output.json +29 -0
  496. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-default-effort.json +29 -0
  497. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-high-effort.json +29 -0
  498. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-low-effort.json +29 -0
  499. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-max-effort.json +29 -0
  500. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  501. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-default-thinking.json +29 -0
  502. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-disabled-thinking.json +29 -0
  503. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-enabled-thinking.json +29 -0
  504. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-highspeed-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  505. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-highspeed-streams-text-with-default-thinking.json +29 -0
  506. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  507. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-streams-text-with-default-thinking.json +29 -0
  508. package/test/fixtures/recordings/moonshot-chat/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  509. package/test/fixtures/recordings/moonshot-messages/k3-reads-image-bytes.json +36 -0
  510. package/test/fixtures/recordings/moonshot-messages/k3-respects-tool-choice-none.json +36 -0
  511. package/test/fixtures/recordings/moonshot-messages/k3-respects-tool-choice-required.json +36 -0
  512. package/test/fixtures/recordings/moonshot-messages/k3-returns-native-structured-output.json +35 -0
  513. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-default-effort.json +36 -0
  514. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-high-effort.json +36 -0
  515. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-low-effort.json +36 -0
  516. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-max-effort.json +36 -0
  517. package/test/fixtures/recordings/moonshot-messages/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  518. package/test/fixtures/recordings/moonshot-responses/k3-reads-image-bytes.json +36 -0
  519. package/test/fixtures/recordings/moonshot-responses/k3-rejects-unsupported-tool-choice-none.json +36 -0
  520. package/test/fixtures/recordings/moonshot-responses/k3-rejects-unsupported-tool-choice-required.json +36 -0
  521. package/test/fixtures/recordings/moonshot-responses/k3-returns-native-structured-output.json +35 -0
  522. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-default-effort.json +36 -0
  523. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-high-effort.json +36 -0
  524. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-low-effort.json +36 -0
  525. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-max-effort.json +36 -0
  526. package/test/fixtures/recordings/moonshot-responses/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  527. package/test/fixtures/recordings/openai-compatible-chat/gemini-parallel-tool-signatures.json +54 -0
  528. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-text.json +28 -0
  529. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-tool-call.json +28 -0
  530. package/test/fixtures/recordings/openai-decision/decides-choice-score-and-predicate-questions-about-json-state.json +33 -0
  531. package/test/fixtures/recordings/openai-embedding/embeds-text-with-requested-dimensions.json +33 -0
  532. package/test/fixtures/recordings/openai-images/edits-an-image.json +28 -0
  533. package/test/fixtures/recordings/openai-images/generates-an-image.json +28 -0
  534. package/test/fixtures/recordings/openai-images/streams-a-partial-image-before-the-final-image.json +32 -0
  535. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-image-tool-result.json +42 -0
  536. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning-continuation.json +58 -0
  537. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning.json +38 -0
  538. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-tool-loop.json +57 -0
  539. package/test/fixtures/recordings/openai-responses-cache/caches-the-system-prompt-on-gpt-6-2-sol.json +51 -0
  540. package/test/fixtures/recordings/openai-responses-cache/reports-cached-tokens-on-identical-second-call.json +51 -0
  541. package/test/fixtures/recordings/openai-responses-images/generates-and-edits-an-image-with-the-hosted-tool.json +50 -0
  542. package/test/fixtures/recordings/openai-responses-websocket/continues-a-tool-call-over-one-socket.json +588 -0
  543. package/test/fixtures/recordings/openai-responses-websocket/reconstructs-full-context-after-reconnect.json +167 -0
  544. package/test/fixtures/recordings/openai-responses-websocket/recovers-from-explicit-continuation-rejection.json +167 -0
  545. package/test/fixtures/recordings/openai-speech/generates-speech.json +33 -0
  546. package/test/fixtures/recordings/openai-speech/streams-speech.json +32 -0
  547. package/test/fixtures/recordings/openai-transcription/diarizes-speakers-into-segments.json +32 -0
  548. package/test/fixtures/recordings/openai-transcription/returns-whisper-word-timestamps.json +32 -0
  549. package/test/fixtures/recordings/openai-transcription/streams-text-deltas.json +32 -0
  550. package/test/fixtures/recordings/openai-transcription/transcribes-with-a-language-hint.json +32 -0
  551. package/test/fixtures/recordings/opencode-decision/decides-choice-score-and-predicate-questions.json +33 -0
  552. package/test/fixtures/recordings/openrouter-decision/decides-choice-score-and-predicate-questions.json +33 -0
  553. package/test/fixtures/recordings/openrouter-images/edits-an-image-through-input-references.json +32 -0
  554. package/test/fixtures/recordings/openrouter-images/renders-flux-3-from-an-aspect-ratio-and-tier.json +32 -0
  555. package/test/fixtures/recordings/openrouter-images/renders-gemini-at-the-requested-2k-tier.json +32 -0
  556. package/test/fixtures/recordings/openrouter-reasoning-tool-loop.json +55 -0
  557. package/test/fixtures/recordings/openrouter-reasoning.json +29 -0
  558. package/test/fixtures/recordings/openrouter-responses/calls-a-freeform-text-tool.json +35 -0
  559. package/test/fixtures/recordings/openrouter-responses/continues-a-tool-call.json +53 -0
  560. package/test/fixtures/recordings/openrouter-responses/streams-text.json +35 -0
  561. package/test/fixtures/recordings/openrouter-video/generates-a-video.json +113 -0
  562. package/test/fixtures/recordings/pdf/anthropic-tool-result.json +28 -0
  563. package/test/fixtures/recordings/pdf/anthropic-user-input.json +28 -0
  564. package/test/fixtures/recordings/pdf/bedrock-tool-result.json +29 -0
  565. package/test/fixtures/recordings/pdf/bedrock-user-input.json +29 -0
  566. package/test/fixtures/recordings/pdf/gemini-tool-result.json +53 -0
  567. package/test/fixtures/recordings/pdf/gemini-user-input.json +28 -0
  568. package/test/fixtures/recordings/pdf/openai-tool-result.json +35 -0
  569. package/test/fixtures/recordings/pdf/openai-user-input.json +34 -0
  570. package/test/fixtures/recordings/pdf/xai-tool-result.json +35 -0
  571. package/test/fixtures/recordings/pdf/xai-user-input.json +34 -0
  572. package/test/fixtures/recordings/typesafe-decision/decides-choice-score-and-predicate-questions.json +33 -0
  573. package/test/fixtures/recordings/venice-chat/claude-opus-4-8-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  574. package/test/fixtures/recordings/venice-chat/deepseek-v4-flash-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  575. package/test/fixtures/recordings/venice-chat/gemini-3-1-pro-preview-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  576. package/test/fixtures/recordings/venice-chat/gemini-preserves-per-call-signatures-through-parallel-tools.json +71 -0
  577. package/test/fixtures/recordings/venice-chat/openai-gpt-54-mini-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  578. package/test/fixtures/recordings/venice-chat/qwen-disables-reasoning.json +35 -0
  579. package/test/fixtures/recordings/venice-chat/surfaces-venice-model-errors.json +33 -0
  580. package/test/fixtures/recordings/venice-responses/calls-a-freeform-text-tool.json +35 -0
  581. package/test/fixtures/recordings/venice-responses/continues-a-tool-call.json +53 -0
  582. package/test/fixtures/recordings/venice-responses/streams-text.json +35 -0
  583. package/test/fixtures/recordings/vercel-ai-gateway-images/generates-an-image.json +32 -0
  584. package/test/fixtures/recordings/vercel-ai-gateway-images/sizes-grok-through-xai-provider-options.json +32 -0
  585. package/test/fixtures/recordings/vercel-ai-gateway-reasoning-tool-loop.json +55 -0
  586. package/test/fixtures/recordings/vercel-ai-gateway-reasoning.json +29 -0
  587. package/test/fixtures/recordings/vercel-native/automatically-caches-distinct-claude-system-blocks.json +49 -0
  588. package/test/fixtures/recordings/vercel-native/continues-chat-claude-reasoning-and-tools.json +49 -0
  589. package/test/fixtures/recordings/vercel-native/continues-chat-muse-reasoning-and-tools.json +49 -0
  590. package/test/fixtures/recordings/vercel-native/continues-messages-claude-reasoning-and-tools.json +49 -0
  591. package/test/fixtures/recordings/vercel-native/continues-messages-deepseek-reasoning-and-tools.json +49 -0
  592. package/test/fixtures/recordings/vercel-native/continues-messages-gemini-reasoning-and-tools.json +49 -0
  593. package/test/fixtures/recordings/vercel-native/continues-responses-gpt-reasoning-and-tools.json +49 -0
  594. package/test/fixtures/recordings/vercel-native/continues-responses-grok-reasoning-and-tools.json +49 -0
  595. package/test/fixtures/recordings/vercel-native/rejects-invalid-credentials-without-retryable-classification.json +31 -0
  596. package/test/fixtures/recordings/xai-images/edits-an-image.json +28 -0
  597. package/test/fixtures/recordings/xai-images/generates-an-image.json +28 -0
  598. package/test/fixtures/recordings/xai-video/generates-a-video.json +129 -0
  599. package/test/fixtures/recordings/zai-chat/glm-4-5-calls-a-tool-without-streaming-arguments.json +28 -0
  600. package/test/fixtures/recordings/zai-chat/glm-4-7-streams-thinking-disabled.json +28 -0
  601. package/test/fixtures/recordings/zai-chat/glm-4-7-streams-thinking-enabled.json +28 -0
  602. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-high-effort.json +28 -0
  603. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-low-effort.json +28 -0
  604. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-max-effort.json +28 -0
  605. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-medium-effort.json +28 -0
  606. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-minimal-effort.json +28 -0
  607. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-none-effort.json +28 -0
  608. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-thinking-disabled.json +28 -0
  609. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-thinking-enabled.json +28 -0
  610. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-xhigh-effort.json +28 -0
  611. package/test/fixtures/recordings/zai-chat/glm-5-3-flash-reads-image-bytes.json +28 -0
  612. package/test/fixtures/recordings/zai-chat/glm-5-3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +64 -0
  613. package/test/fixtures/recordings/zai-chat/glm-5-3-rejects-disabled-thinking.json +27 -0
  614. package/test/fixtures/recordings/zai-chat/glm-5-3-returns-a-json-object.json +28 -0
  615. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-default-effort.json +28 -0
  616. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-high-effort.json +28 -0
  617. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-low-effort.json +28 -0
  618. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-max-effort.json +28 -0
  619. package/test/fixtures/recordings/zai-images/generates-an-image.json +28 -0
  620. package/test/generate-object.test.ts +281 -0
  621. package/test/generation.test.ts +191 -0
  622. package/test/google-interactions-video.test.ts +351 -0
  623. package/test/http-hooks.test.ts +137 -0
  624. package/test/http-timeout.test.ts +287 -0
  625. package/test/image-job.test.ts +199 -0
  626. package/test/image-sizing.test.ts +47 -0
  627. package/test/image.test.ts +1114 -0
  628. package/test/image.types.ts +203 -0
  629. package/test/keyless-auth.test.ts +85 -0
  630. package/test/lib/effect.ts +50 -0
  631. package/test/lib/env.ts +30 -0
  632. package/test/lib/http.ts +141 -0
  633. package/test/lib/image.ts +29 -0
  634. package/test/lib/openai-chunks.ts +27 -0
  635. package/test/lib/sse.ts +20 -0
  636. package/test/lib/tool-runtime.ts +152 -0
  637. package/test/llm-option-types.types.ts +153 -0
  638. package/test/llm.test.ts +286 -0
  639. package/test/loop-steps.test.ts +77 -0
  640. package/test/loop-tools.types.ts +79 -0
  641. package/test/loop.test.ts +425 -0
  642. package/test/media-input.test.ts +98 -0
  643. package/test/media-usage.test.ts +13 -0
  644. package/test/media.test.ts +340 -0
  645. package/test/minimax-video.test.ts +553 -0
  646. package/test/openai-freeform.test.ts +252 -0
  647. package/test/openrouter-video.test.ts +294 -0
  648. package/test/partial-json.test.ts +58 -0
  649. package/test/promise-parity.types.ts +83 -0
  650. package/test/promise.test.ts +632 -0
  651. package/test/provider/alibaba-capabilities.recorded.test.ts +253 -0
  652. package/test/provider/alibaba-images.recorded.test.ts +71 -0
  653. package/test/provider/alibaba-images.test.ts +199 -0
  654. package/test/provider/alibaba.recorded.test.ts +165 -0
  655. package/test/provider/alibaba.test.ts +419 -0
  656. package/test/provider/anthropic-compaction.test.ts +171 -0
  657. package/test/provider/anthropic-messages-cache.recorded.test.ts +111 -0
  658. package/test/provider/anthropic-messages.recorded.test.ts +45 -0
  659. package/test/provider/anthropic-messages.test.ts +2609 -0
  660. package/test/provider/anthropic-thinking-binding.test.ts +65 -0
  661. package/test/provider/assemblyai-transcription.recorded.test.ts +39 -0
  662. package/test/provider/azure.recorded.test.ts +139 -0
  663. package/test/provider/azure.test.ts +48 -0
  664. package/test/provider/bedrock-converse-cache.recorded.test.ts +61 -0
  665. package/test/provider/bedrock-converse-cache.test.ts +168 -0
  666. package/test/provider/bedrock-converse-options.recorded.test.ts +119 -0
  667. package/test/provider/bedrock-converse-options.test.ts +149 -0
  668. package/test/provider/bedrock-converse-thinking-binding.recorded.test.ts +103 -0
  669. package/test/provider/bedrock-converse-thinking-binding.test.ts +107 -0
  670. package/test/provider/bedrock-converse.test.ts +2548 -0
  671. package/test/provider/bedrock-mantle.test.ts +444 -0
  672. package/test/provider/bedrock-mistral-ids.test.ts +86 -0
  673. package/test/provider/cartesia-speech.recorded.test.ts +47 -0
  674. package/test/provider/checkpoint.test.ts +324 -0
  675. package/test/provider/cloudflare-workers-ai-images.recorded.test.ts +57 -0
  676. package/test/provider/cloudflare-workers-ai-images.test.ts +155 -0
  677. package/test/provider/cloudflare.test.ts +330 -0
  678. package/test/provider/cohere.recorded.test.ts +94 -0
  679. package/test/provider/cohere.test.ts +301 -0
  680. package/test/provider/compaction-websocket.test.ts +50 -0
  681. package/test/provider/compaction.recorded.test.ts +89 -0
  682. package/test/provider/compaction.test.ts +178 -0
  683. package/test/provider/conversation-lowering.test.ts +31 -0
  684. package/test/provider/decision.recorded.test.ts +211 -0
  685. package/test/provider/deepgram-speech.recorded.test.ts +41 -0
  686. package/test/provider/deepgram-transcription.recorded.test.ts +47 -0
  687. package/test/provider/digitalocean.recorded.test.ts +78 -0
  688. package/test/provider/digitalocean.test.ts +123 -0
  689. package/test/provider/elevenlabs-speech.recorded.test.ts +54 -0
  690. package/test/provider/elevenlabs-transcription.recorded.test.ts +50 -0
  691. package/test/provider/embedding.recorded.test.ts +109 -0
  692. package/test/provider/empty-tool-choice.test.ts +80 -0
  693. package/test/provider/error-retention.test.ts +158 -0
  694. package/test/provider/explicit-compaction.test.ts +503 -0
  695. package/test/provider/extraction.recorded.test.ts +46 -0
  696. package/test/provider/freeform-tools.test.ts +446 -0
  697. package/test/provider/gemini-cache.recorded.test.ts +49 -0
  698. package/test/provider/gemini-openai-chat.recorded.test.ts +69 -0
  699. package/test/provider/gemini.test.ts +2336 -0
  700. package/test/provider/golden.recorded.test.ts +287 -0
  701. package/test/provider/google-images.recorded.test.ts +53 -0
  702. package/test/provider/google-interactions-video.recorded.test.ts +48 -0
  703. package/test/provider/google-interactions.recorded.test.ts +169 -0
  704. package/test/provider/google-interactions.test.ts +593 -0
  705. package/test/provider/google-speech.recorded.test.ts +45 -0
  706. package/test/provider/google-transcription.recorded.test.ts +54 -0
  707. package/test/provider/google-vertex-interactions.test.ts +307 -0
  708. package/test/provider/google-vertex.recorded.test.ts +75 -0
  709. package/test/provider/google-vertex.test.ts +595 -0
  710. package/test/provider/groq.recorded.test.ts +187 -0
  711. package/test/provider/groq.test.ts +134 -0
  712. package/test/provider/image-detail.test.ts +58 -0
  713. package/test/provider/media-entrypoints.test.ts +618 -0
  714. package/test/provider/meta-capabilities.test.ts +216 -0
  715. package/test/provider/meta-images.recorded.test.ts +119 -0
  716. package/test/provider/meta-messages.recorded.test.ts +121 -0
  717. package/test/provider/meta-search.recorded.test.ts +97 -0
  718. package/test/provider/meta.recorded.test.ts +182 -0
  719. package/test/provider/meta.test.ts +140 -0
  720. package/test/provider/minimax-images.recorded.test.ts +52 -0
  721. package/test/provider/minimax-images.test.ts +236 -0
  722. package/test/provider/minimax-video.recorded.test.ts +83 -0
  723. package/test/provider/minimax.recorded.test.ts +257 -0
  724. package/test/provider/minimax.test.ts +110 -0
  725. package/test/provider/missing-tool-input.test.ts +73 -0
  726. package/test/provider/mistral-chat.test.ts +757 -0
  727. package/test/provider/mistral.recorded.test.ts +170 -0
  728. package/test/provider/moonshot-capabilities.recorded.test.ts +131 -0
  729. package/test/provider/moonshot.recorded.test.ts +191 -0
  730. package/test/provider/moonshot.test.ts +218 -0
  731. package/test/provider/native-providers.test.ts +299 -0
  732. package/test/provider/open-responses-errors.test.ts +141 -0
  733. package/test/provider/open-responses-finals.test.ts +209 -0
  734. package/test/provider/open-responses-lifecycle.test.ts +526 -0
  735. package/test/provider/open-responses-replay.test.ts +120 -0
  736. package/test/provider/openai-chat-reasoning.recorded.test.ts +154 -0
  737. package/test/provider/openai-chat.test.ts +2505 -0
  738. package/test/provider/openai-compatible-chat.test.ts +819 -0
  739. package/test/provider/openai-compatible-responses.test.ts +1139 -0
  740. package/test/provider/openai-images.recorded.test.ts +91 -0
  741. package/test/provider/openai-responses-cache.recorded.test.ts +68 -0
  742. package/test/provider/openai-responses-images.recorded.test.ts +66 -0
  743. package/test/provider/openai-responses-websocket.recorded.test.ts +221 -0
  744. package/test/provider/openai-responses.test.ts +5414 -0
  745. package/test/provider/openai-speech.recorded.test.ts +38 -0
  746. package/test/provider/openai-transcription.recorded.test.ts +91 -0
  747. package/test/provider/openrouter-images.recorded.test.ts +76 -0
  748. package/test/provider/openrouter-video.recorded.test.ts +53 -0
  749. package/test/provider/openrouter.test.ts +656 -0
  750. package/test/provider/pdf.recorded.test.ts +211 -0
  751. package/test/provider/queued-recording.ts +10 -0
  752. package/test/provider/responses-routes.recorded.test.ts +91 -0
  753. package/test/provider/seedance-video.recorded.test.ts +52 -0
  754. package/test/provider/speech-recording.ts +19 -0
  755. package/test/provider/transcription-recording.ts +41 -0
  756. package/test/provider/venice.recorded.test.ts +237 -0
  757. package/test/provider/venice.test.ts +373 -0
  758. package/test/provider/vercel-ai-gateway-images.recorded.test.ts +55 -0
  759. package/test/provider/vercel-ai-gateway.recorded.test.ts +125 -0
  760. package/test/provider/vercel-ai-gateway.test.ts +303 -0
  761. package/test/provider/xai-images.recorded.test.ts +54 -0
  762. package/test/provider/xai-images.test.ts +109 -0
  763. package/test/provider/xai-responses.test.ts +339 -0
  764. package/test/provider/xai-video.recorded.test.ts +54 -0
  765. package/test/provider/zai-capabilities.recorded.test.ts +156 -0
  766. package/test/provider/zai-images.recorded.test.ts +33 -0
  767. package/test/provider/zai-images.test.ts +163 -0
  768. package/test/provider/zai.recorded.test.ts +115 -0
  769. package/test/provider/zai.test.ts +374 -0
  770. package/test/provider-api-methods.types.ts +8 -0
  771. package/test/provider-error.test.ts +800 -0
  772. package/test/provider-model.types.ts +37 -0
  773. package/test/provider-options/alibaba.types.ts +46 -0
  774. package/test/provider-options/amazon-bedrock.types.ts +33 -0
  775. package/test/provider-options/anthropic-compatible.types.ts +13 -0
  776. package/test/provider-options/anthropic.types.ts +30 -0
  777. package/test/provider-options/azure.types.ts +13 -0
  778. package/test/provider-options/checkpoint.types.ts +150 -0
  779. package/test/provider-options/cloudflare.types.ts +13 -0
  780. package/test/provider-options/compaction.types.ts +146 -0
  781. package/test/provider-options/google-vertex-chat.types.ts +7 -0
  782. package/test/provider-options/google-vertex-interactions.types.ts +29 -0
  783. package/test/provider-options/google-vertex-messages.types.ts +13 -0
  784. package/test/provider-options/google-vertex-responses.types.ts +14 -0
  785. package/test/provider-options/google-vertex.types.ts +17 -0
  786. package/test/provider-options/google.types.ts +43 -0
  787. package/test/provider-options/minimax.types.ts +33 -0
  788. package/test/provider-options/mistral.types.ts +24 -0
  789. package/test/provider-options/moonshot.types.ts +45 -0
  790. package/test/provider-options/openai-compatible-responses.types.ts +17 -0
  791. package/test/provider-options/openai-compatible.types.ts +13 -0
  792. package/test/provider-options/openai.types.ts +27 -0
  793. package/test/provider-options/openrouter.types.ts +55 -0
  794. package/test/provider-options/venice.types.ts +39 -0
  795. package/test/provider-options/vercel-ai-gateway.types.ts +30 -0
  796. package/test/provider-options/xai.types.ts +14 -0
  797. package/test/provider-options/zai.types.ts +42 -0
  798. package/test/provider-package.test.ts +586 -0
  799. package/test/raw-events.test.ts +75 -0
  800. package/test/realtime.test.ts +172 -0
  801. package/test/recorded-golden.ts +104 -0
  802. package/test/recorded-runner.ts +101 -0
  803. package/test/recorded-scenarios.ts +468 -0
  804. package/test/recorded-test.ts +127 -0
  805. package/test/recorded-utils.ts +56 -0
  806. package/test/request-encoding.test.ts +57 -0
  807. package/test/request-transport.test.ts +74 -0
  808. package/test/response.test.ts +203 -0
  809. package/test/route.test.ts +225 -0
  810. package/test/sanitize.test.ts +80 -0
  811. package/test/schema.test.ts +412 -0
  812. package/test/seedance-video.test.ts +418 -0
  813. package/test/speech.test.ts +297 -0
  814. package/test/speech.types.ts +33 -0
  815. package/test/testing.test.ts +372 -0
  816. package/test/tool-history.test.ts +162 -0
  817. package/test/tool-runtime.test.ts +926 -0
  818. package/test/tool-schema-projection.test.ts +427 -0
  819. package/test/tool-stream.test.ts +252 -0
  820. package/test/tool-updates.test.ts +849 -0
  821. package/test/tool.types.ts +131 -0
  822. package/test/transcription.test.ts +618 -0
  823. package/test/transcription.types.ts +44 -0
  824. package/test/video.test.ts +447 -0
  825. package/test/video.types.ts +110 -0
  826. package/tsconfig.build.json +8 -0
  827. package/tsconfig.json +17 -0
  828. package/tsconfig.types.json +16 -0
@@ -0,0 +1,1431 @@
1
+ import { Effect, Option, Schema } from "effect"
2
+ import { Tool } from "@zyro-sec/schema/tool"
3
+ import { Route } from "../route/client.js"
4
+ import { Auth } from "../route/auth.js"
5
+ import { Endpoint } from "../route/endpoint.js"
6
+ import { Framing } from "../route/framing.js"
7
+ import { HttpTransport } from "../route/transport/index.js"
8
+ import { Protocol } from "../route/protocol.js"
9
+ import {
10
+ AIError,
11
+ AIErrorReason,
12
+ InvalidProviderOutputError,
13
+ LLMEvent,
14
+ ProviderInternalError,
15
+ UnknownProviderError,
16
+ Usage,
17
+ type FinishReasonDetails,
18
+ type AssistantMessage,
19
+ type CacheHint,
20
+ type LLMRequest,
21
+ type MediaPart,
22
+ type ReasoningPart,
23
+ type ToolCallPart,
24
+ type ToolDefinition,
25
+ type ToolMessage,
26
+ type UserMessage,
27
+ } from "../schema/index.js"
28
+ import { classifyProviderFailure } from "../provider-error.js"
29
+ import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
30
+ import { placesMarkers, requestTTL } from "../cache-policy.js"
31
+ import * as Cache from "./utils/cache.js"
32
+ import { resolveParallelToolCalls } from "./open-responses.js"
33
+ import { OpenResponsesOptions } from "./utils/open-responses-options.js"
34
+ import { Lifecycle } from "./utils/lifecycle.js"
35
+ import { ToolStream } from "./utils/tool-stream.js"
36
+ import { OpenAIFreeform } from "./openai-freeform.js"
37
+
38
+ const ADAPTER = "openai-chat"
39
+ const RESERVED_REASONING_FIELDS = new Set(["role", "content", "refusal", "tool_calls"])
40
+ export const DEFAULT_BASE_URL = "https://api.openai.com/v1"
41
+ export const PATH = "/chat/completions"
42
+
43
+ // =============================================================================
44
+ // Request Body Schema
45
+ // =============================================================================
46
+ // The body schema is the provider-native JSON body. `fromRequest` below builds
47
+ // this shape from the common `LLMRequest`, then `Route.make` validates and
48
+ // JSON-encodes it before transport.
49
+ const OpenAIChatCacheControl = Schema.Struct({
50
+ type: Schema.Literal("ephemeral"),
51
+ ttl: Schema.optional(Schema.String),
52
+ })
53
+ type OpenAIChatCacheControl = Schema.Schema.Type<typeof OpenAIChatCacheControl>
54
+
55
+ const OpenAIChatTool = Schema.Union([
56
+ Schema.Struct({
57
+ type: Schema.tag("function"),
58
+ function: Schema.Struct({
59
+ name: Schema.String,
60
+ description: Schema.String,
61
+ parameters: JsonObject,
62
+ strict: Schema.optional(Schema.Boolean),
63
+ }),
64
+ cache_control: Schema.optional(OpenAIChatCacheControl),
65
+ }),
66
+ Schema.Struct({
67
+ type: Schema.tag("custom"),
68
+ custom: Schema.Struct({
69
+ name: Schema.String,
70
+ description: Schema.String,
71
+ format: Schema.Union([
72
+ Schema.Struct({ type: Schema.tag("text") }),
73
+ Schema.Struct({
74
+ type: Schema.tag("grammar"),
75
+ grammar: Schema.Struct({ syntax: Schema.Literals(["lark", "regex"]), definition: Schema.String }),
76
+ }),
77
+ ]),
78
+ }),
79
+ cache_control: Schema.optional(OpenAIChatCacheControl),
80
+ }),
81
+ ])
82
+ type OpenAIChatTool = Schema.Schema.Type<typeof OpenAIChatTool>
83
+
84
+ // Gemini's OpenAI-compatible surface carries thought signatures in tool call
85
+ // `extra_content` and rejects replayed parallel calls without them:
86
+ // https://ai.google.dev/gemini-api/docs/thinking#signatures
87
+ const ExtraContent = Schema.Struct({
88
+ google: Schema.Struct({ thought_signature: Schema.String }),
89
+ })
90
+ const decodeExtraContent = (value: unknown) => Option.getOrUndefined(Schema.decodeUnknownOption(ExtraContent)(value))
91
+
92
+ export const OpenAIChatAssistantToolCall = Schema.Struct({
93
+ id: Schema.String,
94
+ type: Schema.tag("function"),
95
+ function: Schema.Struct({
96
+ name: Schema.String,
97
+ arguments: Schema.String,
98
+ }),
99
+ extra_content: Schema.optional(ExtraContent),
100
+ })
101
+
102
+ export const OpenAIChatAssistantCustomToolCall = Schema.Struct({
103
+ id: Schema.String,
104
+ type: Schema.tag("custom"),
105
+ custom: Schema.Struct({
106
+ name: Schema.String,
107
+ input: Schema.String,
108
+ }),
109
+ })
110
+ type OpenAIChatAssistantToolCall = Schema.Schema.Type<
111
+ typeof OpenAIChatAssistantToolCall | typeof OpenAIChatAssistantCustomToolCall
112
+ >
113
+
114
+ // `reasoning_details` carries two dialects. OpenRouter's `reasoning.*` entries
115
+ // must be replayed unmodified (`index` included), so they keep every field they
116
+ // arrived with. Kimi's OpenAI-compatible surface streams preserved thinking as
117
+ // bare `summary` / `encrypted` entries keyed by a stream-only `index`; Kimi does
118
+ // not document this publicly, so the handling follows Kimi Code (Kimi's own
119
+ // client): merge summary deltas by `index`, replay without `index`, and always
120
+ // send `reasoning_content` alongside. Anything else is dropped at the boundary.
121
+ const OpenRouterDetailFields = {
122
+ id: Schema.optional(Schema.NullOr(Schema.String)),
123
+ format: Schema.optional(Schema.String),
124
+ index: Schema.optional(Schema.Number),
125
+ signature: Schema.optional(Schema.NullOr(Schema.String)),
126
+ }
127
+ const ReasoningDetail = Schema.Union([
128
+ Schema.StructWithRest(
129
+ Schema.Struct({
130
+ type: Schema.Literal("reasoning.text"),
131
+ text: Schema.optional(Schema.String),
132
+ ...OpenRouterDetailFields,
133
+ }),
134
+ [Schema.Record(Schema.String, Schema.Unknown)],
135
+ ),
136
+ Schema.StructWithRest(
137
+ Schema.Struct({
138
+ type: Schema.Literal("reasoning.summary"),
139
+ summary: Schema.optional(Schema.String),
140
+ ...OpenRouterDetailFields,
141
+ }),
142
+ [Schema.Record(Schema.String, Schema.Unknown)],
143
+ ),
144
+ Schema.StructWithRest(
145
+ Schema.Struct({ type: Schema.Literal("reasoning.encrypted"), data: Schema.String, ...OpenRouterDetailFields }),
146
+ [Schema.Record(Schema.String, Schema.Unknown)],
147
+ ),
148
+ Schema.Struct({ type: Schema.Literal("summary"), summary: Schema.String, index: Schema.optional(Schema.Number) }),
149
+ Schema.Struct({ type: Schema.Literal("encrypted"), encrypted: Schema.String, index: Schema.optional(Schema.Number) }),
150
+ ])
151
+ type ReasoningDetail = Schema.Schema.Type<typeof ReasoningDetail>
152
+ const decodeReasoningDetail = Schema.decodeUnknownOption(ReasoningDetail)
153
+ const knownReasoningDetails = (details: ReadonlyArray<unknown>) =>
154
+ details.flatMap((detail) => Option.toArray(decodeReasoningDetail(detail)))
155
+
156
+ const OpenAIChatTextContent = Schema.Struct({
157
+ type: Schema.Literal("text"),
158
+ text: Schema.String,
159
+ cache_control: Schema.optional(OpenAIChatCacheControl),
160
+ })
161
+ type OpenAIChatTextContent = Schema.Schema.Type<typeof OpenAIChatTextContent>
162
+
163
+ const OpenAIChatUserContent = Schema.Union([
164
+ OpenAIChatTextContent,
165
+ Schema.Struct({
166
+ type: Schema.Literal("image_url"),
167
+ image_url: Schema.Struct({ url: Schema.String }),
168
+ }),
169
+ Schema.Struct({
170
+ type: Schema.Literal("video_url"),
171
+ video_url: Schema.Struct({ url: Schema.String }),
172
+ }),
173
+ Schema.Struct({
174
+ type: Schema.Literal("file"),
175
+ file: Schema.Struct({ filename: Schema.String, file_data: Schema.String }),
176
+ }),
177
+ ])
178
+ type OpenAIChatUserContent = Schema.Schema.Type<typeof OpenAIChatUserContent>
179
+
180
+ export const OpenAIChatMessage = Schema.Union([
181
+ Schema.Struct({
182
+ role: Schema.Literal("system"),
183
+ content: Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContent)]),
184
+ }),
185
+ Schema.Struct({
186
+ role: Schema.Literal("user"),
187
+ content: Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContent)]),
188
+ }),
189
+ Schema.StructWithRest(
190
+ Schema.Struct({
191
+ role: Schema.Literal("assistant"),
192
+ content: Schema.NullOr(Schema.Union([Schema.String, Schema.Array(OpenAIChatTextContent)])),
193
+ tool_calls: optionalArray(Schema.Union([OpenAIChatAssistantToolCall, OpenAIChatAssistantCustomToolCall])),
194
+ reasoning_content: Schema.optional(Schema.String),
195
+ reasoning: Schema.optional(Schema.String),
196
+ reasoning_text: Schema.optional(Schema.String),
197
+ reasoning_details: Schema.optional(Schema.Unknown),
198
+ reasoning_opaque: Schema.optional(Schema.String),
199
+ }),
200
+ [Schema.Record(Schema.String, Schema.Unknown)],
201
+ ),
202
+ Schema.Struct({
203
+ role: Schema.Literal("tool"),
204
+ tool_call_id: Schema.String,
205
+ content: Schema.Union([Schema.String, Schema.Array(OpenAIChatTextContent)]),
206
+ }),
207
+ ]).pipe(Schema.toTaggedUnion("role"))
208
+ type OpenAIChatMessage = Schema.Schema.Type<typeof OpenAIChatMessage>
209
+
210
+ const OpenAIChatToolChoice = Schema.Union([
211
+ Schema.Literals(["auto", "none", "required"]),
212
+ Schema.Struct({
213
+ type: Schema.tag("function"),
214
+ function: Schema.Struct({ name: Schema.String }),
215
+ }),
216
+ Schema.Struct({
217
+ type: Schema.tag("custom"),
218
+ custom: Schema.Struct({ name: Schema.String }),
219
+ }),
220
+ ])
221
+
222
+ export const bodyFields = {
223
+ model: Schema.String,
224
+ messages: Schema.Array(OpenAIChatMessage),
225
+ tools: optionalArray(OpenAIChatTool),
226
+ tool_choice: Schema.optional(OpenAIChatToolChoice),
227
+ stream: Schema.Literal(true),
228
+ stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),
229
+ store: Schema.optional(Schema.Boolean),
230
+ prompt_cache_key: Schema.optional(Schema.String),
231
+ prompt_cache_retention: Schema.optional(Schema.String),
232
+ prompt_cache_options: Schema.optional(Schema.Struct({ ttl: Schema.optional(Schema.String) })),
233
+ reasoning_effort: Schema.optional(OpenResponsesOptions.ReasoningEffort),
234
+ verbosity: Schema.optional(OpenResponsesOptions.TextVerbositySchema),
235
+ service_tier: Schema.optional(OpenResponsesOptions.ServiceTierSchema),
236
+ parallel_tool_calls: Schema.optional(Schema.Boolean),
237
+ metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
238
+ safety_identifier: Schema.optional(Schema.String),
239
+ tool_stream: Schema.optional(Schema.Boolean),
240
+ max_completion_tokens: Schema.optional(Schema.Number),
241
+ max_tokens: Schema.optional(Schema.Number),
242
+ temperature: Schema.optional(Schema.Number),
243
+ top_p: Schema.optional(Schema.Number),
244
+ frequency_penalty: Schema.optional(Schema.Number),
245
+ presence_penalty: Schema.optional(Schema.Number),
246
+ seed: Schema.optional(Schema.Number),
247
+ stop: optionalArray(Schema.String),
248
+ }
249
+ const OpenAIChatBody = Schema.Struct(bodyFields)
250
+ export type OpenAIChatBody = Schema.Schema.Type<typeof OpenAIChatBody>
251
+
252
+ // =============================================================================
253
+ // Streaming Event Schema
254
+ // =============================================================================
255
+ // The event schema is one decoded SSE `data:` payload. `Framing.sse` splits the
256
+ // byte stream into strings, then `Protocol.jsonEvent` decodes each string into
257
+ // this provider-native event shape.
258
+ export const OpenAIChatUsage = Schema.StructWithRest(
259
+ Schema.Struct({
260
+ prompt_tokens: optionalNull(Schema.Number),
261
+ completion_tokens: optionalNull(Schema.Number),
262
+ total_tokens: optionalNull(Schema.Number),
263
+ // Provider-specific cache accounting fields.
264
+ cached_tokens: optionalNull(Schema.Number),
265
+ prompt_cache_hit_tokens: optionalNull(Schema.Number),
266
+ cache_read_input_tokens: optionalNull(Schema.Number),
267
+ cache_created_input_tokens: optionalNull(Schema.Number),
268
+ // GitHub Copilot reports reasoning at the top level instead of in `completion_tokens_details`.
269
+ reasoning_tokens: optionalNull(Schema.Number),
270
+ prompt_tokens_details: optionalNull(
271
+ Schema.StructWithRest(
272
+ Schema.Struct({
273
+ cached_tokens: optionalNull(Schema.Number),
274
+ cache_write_tokens: optionalNull(Schema.Number),
275
+ }),
276
+ [Schema.Record(Schema.String, Schema.Unknown)],
277
+ ),
278
+ ),
279
+ completion_tokens_details: optionalNull(
280
+ Schema.StructWithRest(
281
+ Schema.Struct({
282
+ reasoning_tokens: optionalNull(Schema.Number),
283
+ accepted_prediction_tokens: optionalNull(Schema.Number),
284
+ rejected_prediction_tokens: optionalNull(Schema.Number),
285
+ }),
286
+ [Schema.Record(Schema.String, Schema.Unknown)],
287
+ ),
288
+ ),
289
+ }),
290
+ [Schema.Record(Schema.String, Schema.Unknown)],
291
+ )
292
+
293
+ const OpenAIChatToolCallDeltaFunction = Schema.Struct({
294
+ name: optionalNull(Schema.String),
295
+ arguments: optionalNull(Schema.String),
296
+ })
297
+
298
+ export const OpenAIChatToolCallDelta = Schema.Struct({
299
+ index: optionalNull(Schema.Number),
300
+ id: optionalNull(Schema.String),
301
+ function: optionalNull(OpenAIChatToolCallDeltaFunction),
302
+ custom: optionalNull(Schema.Struct({ name: optionalNull(Schema.String), input: optionalNull(Schema.String) })),
303
+ extra_content: optionalNull(Schema.Unknown),
304
+ })
305
+ type OpenAIChatToolCallDelta = Schema.Schema.Type<typeof OpenAIChatToolCallDelta>
306
+
307
+ export const OpenAIChatDelta = Schema.StructWithRest(
308
+ Schema.Struct({
309
+ content: optionalNull(Schema.String),
310
+ refusal: optionalNull(Schema.String),
311
+ reasoning_content: optionalNull(Schema.String),
312
+ reasoning: optionalNull(Schema.String),
313
+ reasoning_text: optionalNull(Schema.String),
314
+ reasoning_details: optionalNull(Schema.Unknown),
315
+ // GitHub Copilot's opaque reasoning state, which must be replayed for multi-turn reasoning.
316
+ reasoning_opaque: optionalNull(Schema.String),
317
+ tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
318
+ }),
319
+ [Schema.Record(Schema.String, Schema.Unknown)],
320
+ )
321
+
322
+ export const OpenAIChatChoice = Schema.StructWithRest(
323
+ Schema.Struct({
324
+ delta: optionalNull(OpenAIChatDelta),
325
+ finish_reason: optionalNull(Schema.String),
326
+ native_finish_reason: optionalNull(Schema.String),
327
+ // Moonshot streams usage on `choice.usage` instead of top-level `usage`.
328
+ usage: optionalNull(OpenAIChatUsage),
329
+ }),
330
+ [Schema.Record(Schema.String, Schema.Unknown)],
331
+ )
332
+
333
+ const OpenAIChatError = Schema.StructWithRest(
334
+ Schema.Struct({
335
+ code: optionalNull(Schema.Union([Schema.String, Schema.Number])),
336
+ message: Schema.String,
337
+ }),
338
+ [Schema.Record(Schema.String, Schema.Unknown)],
339
+ )
340
+
341
+ export const OpenAIChatEvent = Schema.StructWithRest(
342
+ Schema.Struct({
343
+ choices: optionalNull(Schema.Array(OpenAIChatChoice)),
344
+ usage: optionalNull(OpenAIChatUsage),
345
+ error: optionalNull(OpenAIChatError),
346
+ }),
347
+ [Schema.Record(Schema.String, Schema.Unknown)],
348
+ )
349
+ export type OpenAIChatEvent = Schema.Schema.Type<typeof OpenAIChatEvent>
350
+ const DONE = "[DONE]" as const
351
+ const OpenAIChatStreamEvent = Schema.Union([Schema.Literal(DONE), Protocol.jsonEvent(OpenAIChatEvent)])
352
+
353
+ interface PendingToolDelta {
354
+ readonly id?: string
355
+ readonly name?: string
356
+ readonly input: string
357
+ readonly extraContent?: Schema.Schema.Type<typeof ExtraContent>
358
+ }
359
+
360
+ export interface ParserState {
361
+ readonly providerMetadataKey: string
362
+ readonly tools: ToolStream.State<number>
363
+ readonly custom: ReadonlyMap<string, OpenAIFreeform.Custom>
364
+ /** Stream indexes of custom tool calls, whose JSON fragment closes when the call finishes. */
365
+ readonly customCalls: ReadonlySet<number>
366
+ readonly pendingTools: Partial<Record<number, PendingToolDelta>>
367
+ readonly toolCallEvents: ReadonlyArray<LLMEvent>
368
+ readonly usage?: Usage
369
+ readonly finishReason?: FinishReasonDetails
370
+ readonly lifecycle: Lifecycle.State
371
+ readonly reasoningField?: string
372
+ /** A scalar reasoning field (`reasoning_content`, ...) has carried text in this stream. */
373
+ readonly reasoningTextObserved: boolean
374
+ readonly reasoningDetails: Array<ReasoningDetail>
375
+ readonly reasoningDetailsObserved: boolean
376
+ /** Latest `reasoning_opaque`; interleaved reasoning sends a new one before each tool call. */
377
+ readonly reasoningOpaque?: string
378
+ readonly reasoningEmitted: boolean
379
+ readonly latestToolIndex?: number
380
+ readonly nextToolIndex: number
381
+ readonly requireFinishReason: boolean
382
+ }
383
+
384
+ // =============================================================================
385
+ // Request Lowering
386
+ // =============================================================================
387
+ // Lowering is the only place that knows how common LLM messages map onto the
388
+ // OpenAI Chat wire format. Keep provider quirks here instead of leaking native
389
+ // fields into `LLMRequest`.
390
+ interface LoweringOptions {
391
+ readonly cacheControl?: (cache: CacheHint | undefined) => OpenAIChatCacheControl | undefined
392
+ readonly toolCallID?: (id: string) => string
393
+ /** Project provider-specific fields from the exact source, even when other messages are dropped during lowering. */
394
+ readonly assistant?: (source: AssistantMessage, message: OpenAIChatMessage) => OpenAIChatMessage
395
+ }
396
+
397
+ type MessageLoweringOptions = LoweringOptions & {
398
+ readonly providerMetadataKey: string
399
+ readonly custom: ReadonlyMap<string, OpenAIFreeform.Custom>
400
+ }
401
+
402
+ const lowerTool = (
403
+ tool: ToolDefinition,
404
+ options: LoweringOptions,
405
+ supportsStrictMode: boolean,
406
+ custom: OpenAIFreeform.Custom | undefined,
407
+ ): OpenAIChatTool => {
408
+ if (custom) {
409
+ const grammar = OpenAIFreeform.grammar(custom)
410
+ return {
411
+ type: "custom",
412
+ custom: {
413
+ name: tool.name,
414
+ description: OpenAIFreeform.description(tool, custom),
415
+ format: grammar ? { type: "grammar", grammar } : { type: "text" },
416
+ },
417
+ cache_control: options.cacheControl?.(tool.cache),
418
+ }
419
+ }
420
+ return {
421
+ type: "function",
422
+ function: {
423
+ name: tool.name,
424
+ description: tool.description,
425
+ parameters: tool.inputSchema,
426
+ ...(supportsStrictMode ? { strict: false } : {}),
427
+ },
428
+ cache_control: options.cacheControl?.(tool.cache),
429
+ }
430
+ }
431
+
432
+ const lowerToolChoice = (
433
+ toolChoice: NonNullable<LLMRequest["toolChoice"]>,
434
+ custom: ReadonlyMap<string, OpenAIFreeform.Custom>,
435
+ ) =>
436
+ ProviderShared.matchToolChoice("OpenAI Chat", toolChoice, {
437
+ auto: () => "auto" as const,
438
+ none: () => "none" as const,
439
+ required: () => "required" as const,
440
+ tool: (name) =>
441
+ custom.has(name)
442
+ ? { type: "custom" as const, custom: { name } }
443
+ : { type: "function" as const, function: { name } },
444
+ })
445
+
446
+ // A call replays as the type its tool is declared with in this request.
447
+ const lowerToolCall = (part: ToolCallPart, options: MessageLoweringOptions): OpenAIChatAssistantToolCall => {
448
+ const custom = options.custom.get(part.name)
449
+ if (custom)
450
+ return {
451
+ id: options.toolCallID?.(part.id) ?? part.id,
452
+ type: "custom",
453
+ custom: {
454
+ name: part.name,
455
+ input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[options.providerMetadataKey]?.header),
456
+ },
457
+ }
458
+ return {
459
+ id: options.toolCallID?.(part.id) ?? part.id,
460
+ type: "function",
461
+ function: {
462
+ name: part.name,
463
+ arguments: ProviderShared.encodeJson(part.input === undefined ? {} : part.input),
464
+ },
465
+ extra_content: decodeExtraContent(part.providerMetadata?.[options.providerMetadataKey]?.extraContent),
466
+ }
467
+ }
468
+
469
+ const lowerMedia = Effect.fnUntraced(function* (part: MediaPart) {
470
+ // Chat Completions accepts PDFs, and no other documents, as inline `file` parts; file URLs are not supported.
471
+ if (part.media.mediaType.toLowerCase() === "application/pdf")
472
+ return {
473
+ type: "file" as const,
474
+ file: {
475
+ filename: part.filename ?? "document.pdf",
476
+ file_data: (yield* ProviderShared.requireInlineMedia("OpenAI Chat", part.media)).dataUrl,
477
+ },
478
+ }
479
+ if (part.media.kind !== "image" && part.media.kind !== "video")
480
+ return yield* ProviderShared.invalidRequest(`OpenAI Chat does not support media type ${part.media.mediaType}`)
481
+ const url =
482
+ ProviderShared.mediaUrl(part.media) ?? (yield* ProviderShared.requireInlineMedia("OpenAI Chat", part.media)).dataUrl
483
+ if (part.media.kind === "video") return { type: "video_url" as const, video_url: { url } }
484
+ return { type: "image_url" as const, image_url: { url } }
485
+ })
486
+
487
+ const reasoningField = (part: ReasoningPart, providerMetadataKey: string) => {
488
+ const field = part.providerMetadata?.[providerMetadataKey]?.reasoningField
489
+ return typeof field === "string" ? field : undefined
490
+ }
491
+
492
+ const reasoningDetails = (parts: ReadonlyArray<ReasoningPart>, providerMetadataKey: string) => {
493
+ const observed = parts.flatMap((part) => {
494
+ const details = part.providerMetadata?.[providerMetadataKey]?.reasoningDetails
495
+ return Array.isArray(details) ? details : []
496
+ })
497
+ if (parts.some((part) => Array.isArray(part.providerMetadata?.[providerMetadataKey]?.reasoningDetails)))
498
+ return knownReasoningDetails(observed).map(lowerReasoningDetail)
499
+ }
500
+
501
+ // Kimi rejects its stream-only `index` on requests
502
+ // ("the reasoning_details ... must not contain streaming index").
503
+ const lowerReasoningDetail = (detail: ReasoningDetail) => {
504
+ if (detail.type === "summary") return { type: detail.type, summary: detail.summary }
505
+ if (detail.type === "encrypted") return { type: detail.type, encrypted: detail.encrypted }
506
+ return detail
507
+ }
508
+
509
+ // Interleaved reasoning yields one opaque value per segment; like the Copilot VS Code
510
+ // client, replay the latest one with the concatenated reasoning text.
511
+ const reasoningOpaque = (parts: ReadonlyArray<ReasoningPart>, providerMetadataKey: string) =>
512
+ parts
513
+ .map((part) => part.providerMetadata?.[providerMetadataKey]?.reasoningOpaque)
514
+ .findLast((value) => typeof value === "string")
515
+
516
+ const isKimiDetail = (detail: { readonly type: string }) => detail.type === "summary" || detail.type === "encrypted"
517
+
518
+ const lowerUserMessage = Effect.fnUntraced(function* (message: UserMessage, options: LoweringOptions) {
519
+ const content: OpenAIChatUserContent[] = []
520
+ for (const part of message.content) {
521
+ if (part.type === "text") {
522
+ content.push({ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) })
523
+ continue
524
+ }
525
+ if (part.type === "media") {
526
+ content.push(yield* lowerMedia(part))
527
+ continue
528
+ }
529
+ }
530
+ if (content.every((part) => part.type === "text" && part.cache_control === undefined))
531
+ return {
532
+ role: "user" as const,
533
+ content: content.map((part) => (part.type === "text" ? part.text : "")).join(""),
534
+ }
535
+ return { role: "user" as const, content }
536
+ })
537
+
538
+ const lowerAssistantMessage = Effect.fnUntraced(function* (
539
+ message: AssistantMessage,
540
+ configuredField: string | undefined,
541
+ requireReasoning: boolean,
542
+ options: MessageLoweringOptions,
543
+ ) {
544
+ const content: OpenAIChatTextContent[] = []
545
+ const reasoning: ReasoningPart[] = []
546
+ const toolCalls: OpenAIChatAssistantToolCall[] = []
547
+ for (const part of message.content) {
548
+ if (!ProviderShared.supportsContent(part, ["text", "reasoning", "tool-call"]))
549
+ return yield* ProviderShared.unsupportedContent("OpenAI Chat", "assistant", ["text", "reasoning", "tool-call"])
550
+ if (part.type === "text") {
551
+ content.push({ type: "text", text: part.text, cache_control: options.cacheControl?.(part.cache) })
552
+ continue
553
+ }
554
+ if (part.type === "reasoning") {
555
+ reasoning.push(part)
556
+ continue
557
+ }
558
+ if (part.type === "tool-call") {
559
+ toolCalls.push(lowerToolCall(part, options))
560
+ continue
561
+ }
562
+ }
563
+ const text = reasoning.map((part) => part.text).join("")
564
+ const details = reasoningDetails(reasoning, options.providerMetadataKey)
565
+ const observedField = reasoning
566
+ .map((part) => reasoningField(part, options.providerMetadataKey))
567
+ .find((value) => value !== undefined)
568
+ const fullyStructured = reasoning.every((part) =>
569
+ Array.isArray(part.providerMetadata?.[options.providerMetadataKey]?.reasoningDetails),
570
+ )
571
+ const field = (() => {
572
+ if (configuredField !== undefined && (requireReasoning || reasoning.length > 0)) return configuredField
573
+ if (reasoning.length === 0) return requireReasoning ? "reasoning_content" : undefined
574
+ if (observedField !== undefined) return observedField
575
+ if (!fullyStructured || requireReasoning) return "reasoning_content"
576
+ // Kimi always expects `reasoning_content` on replayed assistant messages,
577
+ // even when thinking arrived only through structured details.
578
+ if (details?.some(isKimiDetail)) return "reasoning_content"
579
+ })()
580
+ const opaque = reasoningOpaque(reasoning, options.providerMetadataKey)
581
+ const reasoningText =
582
+ reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text
583
+ // A model that declares a different reasoning field reads reasoning there, so structured details and opaque values
584
+ // from earlier turns (including another model served under the same provider metadata key) must not be replayed.
585
+ const replaysStructured = configuredField === undefined || configuredField === "reasoning_details"
586
+ const result = {
587
+ role: "assistant" as const,
588
+ content: (() => {
589
+ if (content.some((part) => part.cache_control !== undefined)) return content
590
+ if (content.length === 0 && toolCalls.length > 0) return null
591
+ return content.map((part) => part.text).join("")
592
+ })(),
593
+ ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
594
+ ...(details !== undefined && replaysStructured ? { reasoning_details: details } : {}),
595
+ ...(opaque !== undefined && replaysStructured ? { reasoning_opaque: opaque } : {}),
596
+ }
597
+ // `reasoning_details` is the structured list itself, so scalar text must not be written over it.
598
+ if (field === undefined || reasoningText === undefined || field === "reasoning_details") return result
599
+ return { ...result, [field]: reasoningText }
600
+ })
601
+
602
+ const lowerToolMessages = Effect.fnUntraced(function* (message: ToolMessage, options: LoweringOptions) {
603
+ const messages: OpenAIChatMessage[] = []
604
+ const attachments: OpenAIChatUserContent[] = []
605
+ for (const part of message.content) {
606
+ if (part.result.type !== "content") {
607
+ messages.push(
608
+ toolMessage(
609
+ options.toolCallID?.(part.id) ?? part.id,
610
+ ProviderShared.toolResultText(part),
611
+ options.cacheControl?.(part.cache),
612
+ ),
613
+ )
614
+ continue
615
+ }
616
+ const content: ReadonlyArray<Tool.Content> = part.result.value
617
+ const text = content.filter((item) => item.type === "text").map((item) => item.text)
618
+ messages.push(
619
+ toolMessage(options.toolCallID?.(part.id) ?? part.id, text.join("\n"), options.cacheControl?.(part.cache)),
620
+ )
621
+ const files = content.filter((item) => item.type === "file")
622
+ attachments.push(...(yield* Effect.forEach(files, (item) => lowerMedia(ProviderShared.toolFileMedia(item)))))
623
+ }
624
+ return { messages, attachments }
625
+ })
626
+
627
+ // Chat cache breakpoints belong on text content parts, not on the message itself.
628
+ const toolMessage = (toolCallID: string, text: string, cacheControl: OpenAIChatCacheControl | undefined) => ({
629
+ role: "tool" as const,
630
+ tool_call_id: toolCallID,
631
+ content: cacheControl === undefined ? text : [{ type: "text" as const, text, cache_control: cacheControl }],
632
+ })
633
+
634
+ const lowerMessage = Effect.fnUntraced(function* (
635
+ message: UserMessage | AssistantMessage,
636
+ reasoningField: string | undefined,
637
+ requireReasoning: boolean,
638
+ options: MessageLoweringOptions,
639
+ ) {
640
+ if (message.role === "user") return [yield* lowerUserMessage(message, options)]
641
+ const lowered = yield* lowerAssistantMessage(message, reasoningField, requireReasoning, options)
642
+ return [options.assistant?.(message, lowered) ?? lowered]
643
+ })
644
+
645
+ const lowerMessages = Effect.fnUntraced(function* (
646
+ request: LLMRequest,
647
+ options: Omit<MessageLoweringOptions, "providerMetadataKey">,
648
+ ) {
649
+ const system: OpenAIChatMessage[] =
650
+ request.system.length === 0
651
+ ? []
652
+ : request.system.some((part) => part.cache !== undefined) && options.cacheControl !== undefined
653
+ ? [
654
+ {
655
+ role: "system",
656
+ content: request.system.map((part) => ({
657
+ type: "text",
658
+ text: part.text,
659
+ cache_control: options.cacheControl?.(part.cache),
660
+ })),
661
+ },
662
+ ]
663
+ : [{ role: "system", content: ProviderShared.joinText(request.system) }]
664
+ const messages = [...system]
665
+ const modelID = request.model.id.toLowerCase()
666
+ const requireReasoning =
667
+ request.model.compatibility?.requireReasoning ??
668
+ (request.model.compatibility?.reasoningField !== undefined ||
669
+ request.model.provider === "deepseek" ||
670
+ request.model.route.endpoint.baseURL?.toLowerCase().includes("deepseek.com") ||
671
+ modelID.includes("deepseek"))
672
+ const reasoningField = request.model.compatibility?.reasoningField
673
+ const mistral = ["mistral", "devstral", "codestral", "pixtral", "mixtral"].some((family) => modelID.includes(family))
674
+ const lowering = {
675
+ ...options,
676
+ providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
677
+ toolCallID: (id: string) => {
678
+ if (mistral)
679
+ return id
680
+ .replace(/[^a-zA-Z0-9]/g, "")
681
+ .slice(0, 9)
682
+ .padEnd(9, "0")
683
+ if (modelID.includes("claude")) return id.replace(/[^a-zA-Z0-9_-]/g, "_")
684
+ if (request.model.provider === "openai" || request.model.provider === "azure" || modelID.startsWith("openai/"))
685
+ return id.slice(0, 40)
686
+ return id
687
+ },
688
+ }
689
+ const requireAssistantAfterTool = request.model.compatibility?.requireAssistantAfterTool ?? mistral
690
+ const bridgeTools = () => {
691
+ if (requireAssistantAfterTool && messages.at(-1)?.role === "tool")
692
+ messages.push({ role: "assistant", content: "Done." })
693
+ }
694
+ const pendingAttachments: OpenAIChatUserContent[] = []
695
+ const flushAttachments = () => {
696
+ if (pendingAttachments.length === 0) return
697
+ bridgeTools()
698
+ messages.push({ role: "user", content: pendingAttachments.splice(0) })
699
+ }
700
+ for (const message of request.messages) {
701
+ if (message.role === "user") bridgeTools()
702
+ if (message.role === "system") {
703
+ const part = yield* ProviderShared.wrappedSystemUpdate("OpenAI Chat", message)
704
+ const cacheControl = options.cacheControl?.(part.cache)
705
+ if (pendingAttachments.length > 0) {
706
+ messages.push({
707
+ role: "user",
708
+ content: [...pendingAttachments.splice(0), { type: "text", text: part.text, cache_control: cacheControl }],
709
+ })
710
+ continue
711
+ }
712
+ const previous = messages.at(-1)
713
+ if (previous?.role === "user" && typeof previous.content === "string")
714
+ messages[messages.length - 1] = cacheControl
715
+ ? {
716
+ role: "user",
717
+ content: [
718
+ { type: "text", text: previous.content },
719
+ { type: "text", text: part.text, cache_control: cacheControl },
720
+ ],
721
+ }
722
+ : { role: "user", content: `${previous.content}\n${part.text}` }
723
+ else if (previous?.role === "user" && Array.isArray(previous.content))
724
+ messages[messages.length - 1] = {
725
+ role: "user",
726
+ content: [...previous.content, { type: "text", text: part.text, cache_control: cacheControl }],
727
+ }
728
+ else
729
+ messages.push(
730
+ cacheControl
731
+ ? {
732
+ role: "user",
733
+ content: [{ type: "text", text: part.text, cache_control: cacheControl }],
734
+ }
735
+ : { role: "user", content: part.text },
736
+ )
737
+ continue
738
+ }
739
+ if (
740
+ message.role === "assistant" &&
741
+ message.content.every((part) => part.type === "text" && part.text.trim() === "")
742
+ )
743
+ continue
744
+ if (message.role === "tool") {
745
+ const lowered = yield* lowerToolMessages(message, lowering)
746
+ messages.push(...lowered.messages)
747
+ pendingAttachments.push(...lowered.attachments)
748
+ continue
749
+ }
750
+ flushAttachments()
751
+ messages.push(...(yield* lowerMessage(message, reasoningField, requireReasoning, lowering)))
752
+ }
753
+ flushAttachments()
754
+ return messages
755
+ })
756
+
757
+ // Anthropic via LiteLLM and Amazon Bedrock require `tools` to be present
758
+ // whenever the conversation history contains tool calls/results. Send an
759
+ // explicit empty array when we have history but no active tools.
760
+ const hasToolHistory = (messages: ReadonlyArray<LLMRequest["messages"][number]>) => {
761
+ for (const message of messages) {
762
+ if (message.role === "tool") return true
763
+ if (message.role === "assistant" && message.content.some((part) => part.type === "tool-call")) return true
764
+ }
765
+ return false
766
+ }
767
+
768
+ // Derive `max_tokens` vs `max_completion_tokens` from provider/baseURL when
769
+ // explicit `compatibility.maxTokensField` is not set. Aligned with
770
+ // models.dev provider naming: DeepSeek, Moonshot AI, Together AI, ZAI
771
+ // (Zhipu + Coding Plan variants), Nvidia, Cerebras, Chutes, etc. still
772
+ // require `max_tokens`.
773
+ const detectMaxTokensField = (
774
+ provider: string,
775
+ baseURL: string | undefined,
776
+ ): "max_tokens" | "max_completion_tokens" => {
777
+ const p = provider.toLowerCase()
778
+ const url = (baseURL ?? "").toLowerCase()
779
+ if (
780
+ p === "deepseek" ||
781
+ url.includes("deepseek.com") ||
782
+ p === "moonshotai" ||
783
+ url.includes("api.moonshot.ai") ||
784
+ p === "togetherai" ||
785
+ url.includes("api.together.") ||
786
+ p === "zai" ||
787
+ p === "zai-coding-plan" ||
788
+ p === "zhipuai" ||
789
+ p === "zhipuai-coding-plan" ||
790
+ url.includes("api.z.ai") ||
791
+ url.includes("open.bigmodel.cn") ||
792
+ p === "nvidia" ||
793
+ url.includes("integrate.api.nvidia.com") ||
794
+ p === "cerebras" ||
795
+ url.includes("cerebras.ai") ||
796
+ url.includes("llm.chutes.ai") ||
797
+ p === "chutes" ||
798
+ p === "cloudflare-ai-gateway" ||
799
+ url.includes("gateway.ai.cloudflare.com") ||
800
+ p === "cloudflare-workers-ai" ||
801
+ url.includes("api.cloudflare.com")
802
+ )
803
+ return "max_tokens"
804
+ return "max_completion_tokens"
805
+ }
806
+
807
+ // `store` defaults to false on OpenAI and Azure, but org-level logging can still
808
+ // store requests that omit it, so send an explicit `store: false` there. Strict
809
+ // OpenAI-style APIs reject the field with a 400, so omit it everywhere else.
810
+ const detectSupportsStore = (provider: string, baseURL: string | undefined): boolean => {
811
+ const p = provider.toLowerCase()
812
+ const url = (baseURL ?? "").toLowerCase()
813
+ return (
814
+ p === "openai" ||
815
+ p === "azure" ||
816
+ url.includes("api.openai.com") ||
817
+ url.includes(".openai.azure.com") ||
818
+ url.includes(".cognitiveservices.azure.com") ||
819
+ url.includes(".services.ai.azure.com")
820
+ )
821
+ }
822
+
823
+ const detectSupportsStrictMode = (provider: string, baseURL: string | undefined): boolean => {
824
+ const p = provider.toLowerCase()
825
+ const url = (baseURL ?? "").toLowerCase()
826
+ const isMoonshot = p === "moonshotai" || p === "moonshotai-cn" || url.includes("api.moonshot.")
827
+ const isTogether = p === "togetherai" || p === "together" || url.includes("api.together.")
828
+ const isCloudflareAiGateway = p === "cloudflare-ai-gateway" || url.includes("gateway.ai.cloudflare.com")
829
+ const isNvidia = p === "nvidia" || url.includes("integrate.api.nvidia.com")
830
+ return !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia
831
+ }
832
+
833
+ const detectZaiToolStream = (provider: string, baseURL: string | undefined, modelID: string): boolean => {
834
+ const p = provider.toLowerCase()
835
+ const url = (baseURL ?? "").toLowerCase()
836
+ const isZai =
837
+ p === "zai" ||
838
+ p === "zai-coding-plan" ||
839
+ p === "zhipuai" ||
840
+ p === "zhipuai-coding-plan" ||
841
+ url.includes("api.z.ai") ||
842
+ url.includes("open.bigmodel.cn")
843
+ if (!isZai) return false
844
+ const id = modelID.toLowerCase()
845
+ if (id === "glm-4.5" || id === "glm-4.5-air" || id === "glm-4.5-flash" || id === "glm-4.5v") return false
846
+ return true
847
+ }
848
+
849
+ const lowerOptions = (request: LLMRequest, supportsStore: boolean, hasActiveTools: boolean) => {
850
+ const options = OpenResponsesOptions.resolve(request)
851
+ // OpenAI rejects `parallel_tool_calls` unless tools are present.
852
+ const parallelToolCalls = hasActiveTools ? resolveParallelToolCalls(request, options) : undefined
853
+ // Default off: strict providers 400 on unknown body fields, so only send
854
+ // the key where compatibility explicitly allows it. Header-based affinity
855
+ // (x-session-affinity, x-grok-conv-id, ...) is unaffected.
856
+ const cacheKey =
857
+ (request.model.capabilities?.promptCacheKey ?? false) ? ProviderShared.promptCacheKey(request) : undefined
858
+ return {
859
+ ...(supportsStore ? { store: options.store ?? false } : {}),
860
+ ...(cacheKey ? { prompt_cache_key: cacheKey } : {}),
861
+ // Inline markers carry the lifetime when the policy places them.
862
+ ...(placesMarkers(request) ? {} : Cache.openAIRequestTTL(requestTTL(request))),
863
+ ...(options.reasoningEffort ? { reasoning_effort: options.reasoningEffort } : {}),
864
+ ...(options.textVerbosity ? { verbosity: options.textVerbosity } : {}),
865
+ ...(options.serviceTier ? { service_tier: options.serviceTier } : {}),
866
+ ...(parallelToolCalls !== undefined ? { parallel_tool_calls: parallelToolCalls } : {}),
867
+ ...(options.metadata ? { metadata: options.metadata } : {}),
868
+ ...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
869
+ }
870
+ }
871
+
872
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
873
+ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
874
+ request: LLMRequest,
875
+ options: LoweringOptions = {},
876
+ ) {
877
+ // `fromRequest` returns the provider body only. Endpoint, auth, framing,
878
+ // validation, and HTTP execution are composed by `Route.make`.
879
+ const reasoningField = request.model.compatibility?.reasoningField
880
+ if (reasoningField && RESERVED_REASONING_FIELDS.has(reasoningField))
881
+ return yield* ProviderShared.invalidRequest(
882
+ `OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`,
883
+ )
884
+ const definitions = ProviderShared.flattenTools(request.tools)
885
+ const provider = request.model.provider
886
+ const baseURL = request.model.route.endpoint.baseURL
887
+ const detectedMaxTokensField = detectMaxTokensField(provider, baseURL)
888
+ const maxTokensField = request.model.compatibility?.maxTokensField ?? detectedMaxTokensField
889
+ const supportsStore = request.model.capabilities?.store ?? detectSupportsStore(provider, baseURL)
890
+ const supportsStrictMode = request.model.capabilities?.tools?.strict ?? detectSupportsStrictMode(provider, baseURL)
891
+ const zaiToolStream =
892
+ request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id)
893
+ const hasHistory = hasToolHistory(request.messages)
894
+ const hasActiveTools = definitions.length > 0
895
+ const custom = OpenAIFreeform.tools(request)
896
+ const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom }
897
+ return {
898
+ model: request.model.id,
899
+ messages: yield* lowerMessages(request, lowering),
900
+ tools:
901
+ definitions.length === 0
902
+ ? hasHistory
903
+ ? []
904
+ : undefined
905
+ : definitions.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
906
+ tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined,
907
+ stream: true as const,
908
+ ...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}),
909
+ ...(zaiToolStream && hasActiveTools ? { tool_stream: true } : {}),
910
+ ...(maxTokensField === "max_completion_tokens"
911
+ ? { max_completion_tokens: request.maxTokens }
912
+ : { max_tokens: request.maxTokens }),
913
+ temperature: request.temperature,
914
+ top_p: request.topP,
915
+ frequency_penalty: request.frequencyPenalty,
916
+ presence_penalty: request.presencePenalty,
917
+ seed: request.seed,
918
+ stop: request.stop,
919
+ ...lowerOptions(request, supportsStore, hasActiveTools),
920
+ }
921
+ })
922
+
923
+ // Provider wrappers that pass their own marker writer keep it; otherwise a declared cache format adds one.
924
+ const declaredCacheControl = (request: LLMRequest) =>
925
+ request.model.compatibility?.cacheFormat === undefined ? undefined : Cache.cacheControl()
926
+
927
+ // =============================================================================
928
+ // Stream Parsing
929
+ // =============================================================================
930
+ // Streaming parsers are small state machines: every event returns a new state
931
+ // plus the common `LLMEvent`s produced by that event. Tool calls are accumulated
932
+ // because OpenAI streams JSON arguments across multiple deltas.
933
+ const mapFinishReason = Effect.fnUntraced(function* (event: OpenAIChatEvent, reason: string) {
934
+ switch (reason) {
935
+ case "error":
936
+ return yield* new AIError({
937
+ reason: new UnknownProviderError({
938
+ message: "Provider reported an error (finish_reason: error)",
939
+ body: ProviderShared.encodeJson(event),
940
+ }),
941
+ })
942
+ case "network_error":
943
+ return yield* new AIError({
944
+ reason: new ProviderInternalError({
945
+ message: "Provider reported a network error (finish_reason: network_error)",
946
+ body: ProviderShared.encodeJson(event),
947
+ }),
948
+ })
949
+ case "stop":
950
+ case "end":
951
+ return "stop" as const
952
+ case "length":
953
+ return "length" as const
954
+ case "content_filter":
955
+ return "content-filter" as const
956
+ case "function_call":
957
+ case "tool_calls":
958
+ return "tool-calls" as const
959
+ default:
960
+ return "unknown" as const
961
+ }
962
+ })
963
+
964
+ // OpenAI Chat reports `prompt_tokens` (inclusive total) with a
965
+ // cached-read and cache-write subsets, and `completion_tokens` (inclusive
966
+ // total) with a `reasoning_tokens` subset. We pass the inclusive totals
967
+ // through and derive the non-cached breakdown so the `AI.Usage` contract is
968
+ // satisfied on both sides.
969
+ // Providers differ on cache-hit location: OpenAI uses
970
+ // `prompt_tokens_details.cached_tokens`, DeepSeek uses
971
+ // `prompt_cache_hit_tokens`, Zai uses top-level `cached_tokens`, and
972
+ // DigitalOcean uses top-level `cache_read_input_tokens` / `cache_created_input_tokens`.
973
+ const mapUsage = (
974
+ usage: OpenAIChatEvent["usage"],
975
+ providerMetadataKey: string,
976
+ frame: OpenAIChatEvent,
977
+ ): Usage | undefined => {
978
+ if (!usage) return undefined
979
+ const input = usage.prompt_tokens ?? undefined
980
+ const completion = usage.completion_tokens ?? undefined
981
+ const cached =
982
+ usage.prompt_tokens_details?.cached_tokens ??
983
+ usage.prompt_cache_hit_tokens ??
984
+ usage.cached_tokens ??
985
+ usage.cache_read_input_tokens ??
986
+ undefined
987
+ const cacheWrite = usage.prompt_tokens_details?.cache_write_tokens ?? usage.cache_created_input_tokens ?? undefined
988
+ const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? usage.reasoning_tokens ?? undefined
989
+ // Copilot's Gemini counts reasoning beside `completion_tokens` rather than inside it; the total tells which.
990
+ const output =
991
+ completion !== undefined &&
992
+ reasoning !== undefined &&
993
+ usage.total_tokens === ProviderShared.sumTokens(input, completion, reasoning)
994
+ ? completion + reasoning
995
+ : completion
996
+ const nonCached = ProviderShared.subtractTokens(input, ProviderShared.sumTokens(cached, cacheWrite))
997
+ return new Usage({
998
+ inputTokens: input,
999
+ outputTokens: output,
1000
+ nonCachedInputTokens: nonCached,
1001
+ cacheReadInputTokens: cached,
1002
+ cacheWriteInputTokens: cacheWrite,
1003
+ reasoningTokens: reasoning,
1004
+ totalTokens: ProviderShared.totalTokens(input, output, usage.total_tokens ?? undefined),
1005
+ ...ProviderShared.reportedBilling(usage, frame),
1006
+ providerMetadata: { [providerMetadataKey]: usage },
1007
+ })
1008
+ }
1009
+
1010
+ const toolIndexByID = (
1011
+ tools: ParserState["tools"],
1012
+ pendingTools: ParserState["pendingTools"],
1013
+ id: string | undefined,
1014
+ ) => {
1015
+ if (!id) return undefined
1016
+ const entry = Object.entries({ ...pendingTools, ...tools }).find(([, tool]) => tool?.id === id)
1017
+ return entry ? Number(entry[0]) : undefined
1018
+ }
1019
+
1020
+ const reasoningDelta = (
1021
+ delta: Schema.Schema.Type<typeof OpenAIChatDelta> | null | undefined,
1022
+ configuredField?: string,
1023
+ ) => {
1024
+ if (!delta) return undefined
1025
+ const fields = new Set([configuredField, "reasoning_content", "reasoning", "reasoning_text"])
1026
+ for (const field of fields) {
1027
+ if (field === undefined) continue
1028
+ const text = delta[field]
1029
+ if (typeof text === "string" && text.length > 0) return { field, text }
1030
+ }
1031
+ return undefined
1032
+ }
1033
+
1034
+ const detailText = (details: ReadonlyArray<ReasoningDetail>, hideKimiSummary: boolean) => {
1035
+ const text = details.flatMap((detail) => {
1036
+ if (detail.type === "reasoning.text") return detail.text ? [detail.text] : []
1037
+ if (detail.type === "reasoning.summary") return detail.summary ? [detail.summary] : []
1038
+ // Kimi streams the full thinking through `reasoning_content` and a separate
1039
+ // summary through details; show the summary only when nothing else does.
1040
+ if (detail.type === "summary") return detail.summary && !hideKimiSummary ? [detail.summary] : []
1041
+ return []
1042
+ })
1043
+ if (text.length > 0) return text.join("")
1044
+ }
1045
+
1046
+ const appendReasoningDetails = (result: Array<ReasoningDetail>, details: ReadonlyArray<ReasoningDetail>) => {
1047
+ for (const detail of details) {
1048
+ const previous = result.at(-1)
1049
+ const merged = previous === undefined ? undefined : mergeReasoningDetails(previous, detail)
1050
+ if (merged === undefined) {
1051
+ result.push(detail)
1052
+ continue
1053
+ }
1054
+ result[result.length - 1] = merged
1055
+ }
1056
+ }
1057
+
1058
+ // Consecutive text or summary deltas of the same kind accumulate into one
1059
+ // entry; encrypted entries are opaque and never merge.
1060
+ const mergeReasoningDetails = (previous: ReasoningDetail, detail: ReasoningDetail): ReasoningDetail | undefined => {
1061
+ if (conflictingReasoningDetails(previous, detail)) return undefined
1062
+ if (previous.type === "reasoning.text" && detail.type === "reasoning.text")
1063
+ return {
1064
+ ...previous,
1065
+ ...detail,
1066
+ text: `${previous.text ?? ""}${detail.text ?? ""}`,
1067
+ ...mergeDetailIdentity(previous, detail),
1068
+ }
1069
+ if (previous.type === "reasoning.summary" && detail.type === "reasoning.summary")
1070
+ return {
1071
+ ...previous,
1072
+ ...detail,
1073
+ summary: `${previous.summary ?? ""}${detail.summary ?? ""}`,
1074
+ ...mergeDetailIdentity(previous, detail),
1075
+ }
1076
+ if (previous.type === "summary" && detail.type === "summary")
1077
+ return { ...previous, ...detail, summary: previous.summary + detail.summary }
1078
+ }
1079
+
1080
+ type DetailIdentity = {
1081
+ readonly id?: string | null
1082
+ readonly index?: number
1083
+ readonly format?: string
1084
+ readonly signature?: string | null
1085
+ }
1086
+
1087
+ // The first non-empty signature and format win; a later delta may carry the
1088
+ // signature for text that streamed earlier.
1089
+ const mergeDetailIdentity = (previous: DetailIdentity, current: DetailIdentity) => {
1090
+ const signature = mergeDetailValue(previous.signature, current.signature)
1091
+ const format = mergeDetailValue(previous.format, current.format)
1092
+ return {
1093
+ ...(signature === undefined ? {} : { signature }),
1094
+ ...(format === undefined ? {} : { format }),
1095
+ }
1096
+ }
1097
+
1098
+ const mergeDetailValue = <T>(previous: T | undefined, current: T | undefined) =>
1099
+ previous || current || (previous !== undefined ? previous : current)
1100
+
1101
+ const conflictingReasoningDetails = (previous: DetailIdentity, current: DetailIdentity) =>
1102
+ conflictingDetailValue(previous.id, current.id) ||
1103
+ conflictingDetailValue(previous.index, current.index) ||
1104
+ conflictingDetailValue(previous.format, current.format) ||
1105
+ (Boolean(previous.signature) && Boolean(current.signature) && previous.signature !== current.signature)
1106
+
1107
+ const conflictingDetailValue = (previous: unknown, current: unknown) =>
1108
+ previous !== undefined && previous !== null && current !== undefined && current !== null && previous !== current
1109
+
1110
+ const reasoningMetadata = (
1111
+ providerMetadataKey: string,
1112
+ field: ParserState["reasoningField"],
1113
+ details?: ReadonlyArray<ReasoningDetail>,
1114
+ opaque?: string,
1115
+ ) => ({
1116
+ [providerMetadataKey]: {
1117
+ ...(field ? { reasoningField: field } : {}),
1118
+ ...(details ? { reasoningDetails: details } : {}),
1119
+ ...(opaque ? { reasoningOpaque: opaque } : {}),
1120
+ },
1121
+ })
1122
+
1123
+ const step = (state: ParserState, event: OpenAIChatEvent) =>
1124
+ Effect.gen(function* () {
1125
+ if (event.error) {
1126
+ const body = ProviderShared.encodeJson(event)
1127
+ return yield* new AIError({
1128
+ reason: classifyProviderFailure({
1129
+ message: event.error.message,
1130
+ status: typeof event.error.code === "number" ? event.error.code : undefined,
1131
+ rawBody: body,
1132
+ }),
1133
+ })
1134
+ }
1135
+ const events: LLMEvent[] = []
1136
+ const choice = event.choices?.[0]
1137
+ // Moonshot (and a few other OpenAI-compatible providers) attach usage to
1138
+ // `choice.usage` instead of the top-level `usage` field.
1139
+ const usage =
1140
+ mapUsage(event.usage, state.providerMetadataKey, event) ??
1141
+ mapUsage(choice?.usage, state.providerMetadataKey, event) ??
1142
+ state.usage
1143
+ const rawFinishReason = choice?.finish_reason
1144
+ const finishReason = rawFinishReason
1145
+ ? {
1146
+ normalized: yield* mapFinishReason(event, rawFinishReason),
1147
+ raw: choice?.native_finish_reason ?? rawFinishReason,
1148
+ ...(rawFinishReason === "content_filter"
1149
+ ? {
1150
+ category: ProviderShared.contentFilterCategory(
1151
+ choice?.delta?.copilot_annotations,
1152
+ choice?.content_filter_results,
1153
+ ),
1154
+ }
1155
+ : {}),
1156
+ }
1157
+ : state.finishReason
1158
+ const delta = choice?.delta
1159
+ const toolDeltas = delta?.tool_calls ?? []
1160
+ let tools = state.tools
1161
+ let pendingTools = state.pendingTools
1162
+ let customCalls = state.customCalls
1163
+ let latestToolIndex = state.latestToolIndex
1164
+ let nextToolIndex = state.nextToolIndex
1165
+
1166
+ let lifecycle = state.lifecycle
1167
+
1168
+ const reasoning = reasoningDelta(delta, state.reasoningField)
1169
+ if (
1170
+ state.finishReason !== undefined &&
1171
+ toolDeltas.some(
1172
+ (tool) =>
1173
+ Boolean(tool.id) ||
1174
+ Boolean(tool.function?.name) ||
1175
+ Boolean(tool.function?.arguments) ||
1176
+ Boolean(tool.custom?.input),
1177
+ )
1178
+ )
1179
+ return yield* ProviderShared.eventError(
1180
+ ADAPTER,
1181
+ "OpenAI Chat received content after the finish reason",
1182
+ ProviderShared.encodeJson(event),
1183
+ )
1184
+
1185
+ const reasoningField = state.reasoningField ?? reasoning?.field
1186
+ const reasoningTextObserved = state.reasoningTextObserved || reasoning !== undefined
1187
+ const detailDelta = Array.isArray(delta?.reasoning_details)
1188
+ ? knownReasoningDetails(delta.reasoning_details)
1189
+ : undefined
1190
+ if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)
1191
+ const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined
1192
+ const reasoningOpaque = delta?.reasoning_opaque || state.reasoningOpaque
1193
+ const deltaMetadata = reasoningMetadata(state.providerMetadataKey, reasoningField)
1194
+ const text = detailDelta?.length
1195
+ ? (detailText(detailDelta, reasoningTextObserved) ?? reasoning?.text)
1196
+ : reasoning?.text
1197
+ if (text !== undefined) lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", text, deltaMetadata)
1198
+ else if (
1199
+ (reasoningDetailsObserved || reasoningOpaque !== undefined) &&
1200
+ !lifecycle.reasoning.has("reasoning-0") &&
1201
+ (Boolean(delta?.content) || Boolean(delta?.refusal) || toolDeltas.length > 0)
1202
+ )
1203
+ lifecycle = Lifecycle.reasoningStart(lifecycle, events, "reasoning-0", deltaMetadata)
1204
+ const reasoningEmitted = state.reasoningEmitted || lifecycle.reasoning.has("reasoning-0")
1205
+
1206
+ // Reasoning is one response-wide channel: it stays open alongside text and
1207
+ // refusal output so late reasoning deltas and details join the same block,
1208
+ // and `finishEvents` closes it once with the complete metadata.
1209
+ if (delta?.content) lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.content)
1210
+
1211
+ if (delta?.refusal) lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.refusal)
1212
+
1213
+ // Compatible providers may omit indexes. Prefer durable identity, then use
1214
+ // batch position for parallel deltas or the latest call for sparse chunks.
1215
+ for (const [position, tool] of toolDeltas.entries()) {
1216
+ const matched = toolIndexByID(tools, pendingTools, tool.id || undefined)
1217
+ const fallback = toolDeltas.length > 1 ? position : (latestToolIndex ?? position)
1218
+ const fallbackTool = tools[fallback] ?? pendingTools[fallback]
1219
+ const index =
1220
+ tool.index ?? matched ?? (tool.id && fallbackTool?.id && fallbackTool.id !== tool.id ? nextToolIndex : fallback)
1221
+ const current = tools[index]
1222
+ const pending = pendingTools[index]
1223
+ const id = current?.id ?? pending?.id ?? (tool.id || undefined)
1224
+ const name = current?.name ?? pending?.name ?? (tool.function?.name || tool.custom?.name || undefined)
1225
+ // Custom calls stream raw text; re-encode it as JSON arguments for the call's field.
1226
+ const opening = Boolean(tool.custom) && !customCalls.has(index)
1227
+ if (opening) customCalls = new Set([...customCalls, index])
1228
+ const raw = tool.custom?.input ?? ""
1229
+ const fragment = tool.custom
1230
+ ? opening
1231
+ ? OpenAIFreeform.streamStart(state.custom.get(name ?? ""), raw)
1232
+ : OpenAIFreeform.streamDelta(raw)
1233
+ : (tool.function?.arguments ?? "")
1234
+ const text = `${pending?.input ?? ""}${fragment}`
1235
+ const extraContent = pending?.extraContent ?? decodeExtraContent(tool.extra_content)
1236
+ latestToolIndex = index
1237
+ nextToolIndex = Math.max(nextToolIndex, index + 1)
1238
+ if (!current && (!id || !name)) {
1239
+ pendingTools = {
1240
+ ...pendingTools,
1241
+ [index]: { id: id || undefined, name: name || undefined, input: text, extraContent },
1242
+ }
1243
+ continue
1244
+ }
1245
+ if (pending) {
1246
+ pendingTools = { ...pendingTools }
1247
+ delete pendingTools[index]
1248
+ }
1249
+ const result = ToolStream.appendOrStart(
1250
+ ADAPTER,
1251
+ tools,
1252
+ index,
1253
+ {
1254
+ id: id || undefined,
1255
+ name: name || undefined,
1256
+ text,
1257
+ providerMetadata: extraContent && { [state.providerMetadataKey]: { extraContent } },
1258
+ },
1259
+ "OpenAI Chat tool call delta is missing id or name",
1260
+ )
1261
+ if (ToolStream.isError(result))
1262
+ return yield* new AIError({
1263
+ reason: AIErrorReason.make({
1264
+ ...result.reason,
1265
+ message: result.message,
1266
+ cause: result.reason.cause,
1267
+ body: ProviderShared.encodeJson(event),
1268
+ }),
1269
+ })
1270
+ tools = result.tools
1271
+ if (result.events.length) lifecycle = Lifecycle.stepStart(lifecycle, events)
1272
+ events.push(...result.events)
1273
+ }
1274
+
1275
+ const incompleteTools = finishReason?.normalized === "content-filter" || finishReason?.normalized === "length"
1276
+ if (
1277
+ finishReason !== undefined &&
1278
+ !incompleteTools &&
1279
+ state.finishReason === undefined &&
1280
+ Object.keys(pendingTools).length
1281
+ )
1282
+ return yield* ProviderShared.eventError(
1283
+ ADAPTER,
1284
+ "OpenAI Chat tool call delta is missing id or name",
1285
+ ProviderShared.encodeJson(event),
1286
+ )
1287
+
1288
+ // Filtering or truncation terminates the response without confirming pending tool calls.
1289
+ const finished =
1290
+ finishReason !== undefined &&
1291
+ !incompleteTools &&
1292
+ state.finishReason === undefined &&
1293
+ Object.keys(tools).length > 0
1294
+ ? yield* finishTools(state, tools, customCalls)
1295
+ : undefined
1296
+
1297
+ return [
1298
+ {
1299
+ providerMetadataKey: state.providerMetadataKey,
1300
+ tools: finished?.tools ?? tools,
1301
+ custom: state.custom,
1302
+ customCalls,
1303
+ pendingTools,
1304
+ toolCallEvents: finished?.events ?? state.toolCallEvents,
1305
+ usage,
1306
+ finishReason: state.finishReason ?? finishReason,
1307
+ lifecycle,
1308
+ reasoningField,
1309
+ reasoningTextObserved,
1310
+ reasoningDetails: state.reasoningDetails,
1311
+ reasoningDetailsObserved,
1312
+ reasoningOpaque,
1313
+ reasoningEmitted,
1314
+ latestToolIndex,
1315
+ nextToolIndex,
1316
+ requireFinishReason: state.requireFinishReason,
1317
+ },
1318
+ events,
1319
+ ] as const
1320
+ })
1321
+
1322
+ // Custom calls close their JSON fragment before every pending call finishes.
1323
+ const finishTools = Effect.fnUntraced(function* (
1324
+ state: ParserState,
1325
+ tools: ParserState["tools"],
1326
+ customCalls: ReadonlySet<number>,
1327
+ ) {
1328
+ const closed = OpenAIFreeform.close(tools, customCalls, state.custom, state.providerMetadataKey)
1329
+ const finished = yield* ToolStream.finishAll(ADAPTER, closed.tools)
1330
+ return { tools: finished.tools, events: [...closed.events, ...finished.events] }
1331
+ })
1332
+
1333
+ export const finishEvents = Effect.fnUntraced(function* (state: ParserState) {
1334
+ if (state.finishReason === undefined && state.requireFinishReason)
1335
+ return yield* new AIError({
1336
+ reason: new InvalidProviderOutputError({
1337
+ message: "OpenAI Chat stream ended without finish_reason",
1338
+ classification: "incomplete-stream",
1339
+ route: ADAPTER,
1340
+ }),
1341
+ })
1342
+ const events: LLMEvent[] = []
1343
+ const toolCallEvents =
1344
+ state.finishReason === undefined && Object.keys(state.tools).length > 0
1345
+ ? (yield* finishTools(state, state.tools, state.customCalls)).events
1346
+ : state.toolCallEvents
1347
+ const hasToolCalls = toolCallEvents.length > 0
1348
+ const reason = state.finishReason
1349
+ ? {
1350
+ ...state.finishReason,
1351
+ normalized:
1352
+ state.finishReason.normalized === "stop" && hasToolCalls ? "tool-calls" : state.finishReason.normalized,
1353
+ }
1354
+ : { normalized: hasToolCalls ? ("tool-calls" as const) : ("stop" as const) }
1355
+ // Snapshot details at publish time so the emitted event never observes later
1356
+ // mutation of the accumulated `reasoningDetails` array.
1357
+ const metadata = reasoningMetadata(
1358
+ state.providerMetadataKey,
1359
+ state.reasoningField,
1360
+ state.reasoningDetailsObserved ? [...state.reasoningDetails] : undefined,
1361
+ state.reasoningOpaque,
1362
+ )
1363
+ const started =
1364
+ (state.reasoningDetailsObserved || state.reasoningOpaque !== undefined) && !state.reasoningEmitted
1365
+ ? Lifecycle.reasoningStart(
1366
+ state.lifecycle,
1367
+ events,
1368
+ "reasoning-0",
1369
+ reasoningMetadata(state.providerMetadataKey, state.reasoningField),
1370
+ )
1371
+ : state.lifecycle
1372
+ const ended = Lifecycle.reasoningEnd(started, events, "reasoning-0", metadata)
1373
+ const lifecycle = toolCallEvents.length ? Lifecycle.stepStart(ended, events) : ended
1374
+ events.push(...toolCallEvents)
1375
+ Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })
1376
+ return events
1377
+ })
1378
+
1379
+ // =============================================================================
1380
+ // Protocol And OpenAI Route
1381
+ // =============================================================================
1382
+ /**
1383
+ * The OpenAI Chat protocol — request body construction, body schema, and the
1384
+ * streaming-event state machine. Reused by every route that speaks OpenAI Chat
1385
+ * over HTTP+SSE: native OpenAI, DeepSeek, TogetherAI, Cerebras, Baseten,
1386
+ * Fireworks, DeepInfra, and (once added) Azure OpenAI Chat.
1387
+ */
1388
+ export const protocol = Protocol.make({
1389
+ id: ADAPTER,
1390
+ body: {
1391
+ schema: OpenAIChatBody,
1392
+ from: fromRequest,
1393
+ },
1394
+ stream: {
1395
+ event: OpenAIChatStreamEvent,
1396
+ initial: (request) => ({
1397
+ providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
1398
+ tools: ToolStream.empty<number>(),
1399
+ custom: OpenAIFreeform.tools(request),
1400
+ customCalls: new Set<number>(),
1401
+ pendingTools: {},
1402
+ toolCallEvents: [],
1403
+ lifecycle: Lifecycle.initial(),
1404
+ reasoningField: request.model.compatibility?.reasoningField,
1405
+ reasoningTextObserved: false,
1406
+ reasoningDetails: [],
1407
+ reasoningDetailsObserved: false,
1408
+ reasoningEmitted: false,
1409
+ nextToolIndex: 0,
1410
+ requireFinishReason: request.model.compatibility?.requireFinishReason ?? true,
1411
+ }),
1412
+ step: (state: ParserState, event) => (event === DONE ? Effect.succeed([state, []] as const) : step(state, event)),
1413
+ terminal: (event) => event === DONE,
1414
+ onHalt: finishEvents,
1415
+ },
1416
+ })
1417
+
1418
+ export const framing = Framing.sseWithDone
1419
+ export const httpTransport = HttpTransport.sseJson.with<OpenAIChatBody>().with({ framing })
1420
+
1421
+ export const route = Route.make({
1422
+ id: ADAPTER,
1423
+ provider: "openai",
1424
+ providerMetadataKey: "openai",
1425
+ protocol,
1426
+ endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),
1427
+ auth: Auth.none,
1428
+ transport: httpTransport,
1429
+ })
1430
+
1431
+ export * as OpenAIChat from "./openai-chat.js"