@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,2609 @@
1
+ import { describe, expect } from "bun:test"
2
+ import { Effect } from "effect"
3
+ import { HttpClientRequest } from "effect/http"
4
+ import {
5
+ ai,
6
+ AIError,
7
+ CacheHint,
8
+ type LLMRequest,
9
+ Media,
10
+ Message,
11
+ ToolCallPart,
12
+ ToolDefinition,
13
+ Usage,
14
+ } from "../../src/effect.js"
15
+ import { Auth, Endpoint, LLMClient, Route } from "../../src/route.js"
16
+ import { compileRequest } from "../../src/route/client.js"
17
+ import { AnthropicMessages } from "../../src/protocols/anthropic-messages.js"
18
+ import { GoogleVertexMessages, Meta } from "../../src/providers.js"
19
+ import { continuationRequest, nativeAnthropicMessagesContinuation } from "../continuation-scenarios.js"
20
+ import { it } from "../lib/effect.js"
21
+ import { dynamicResponse, fixedResponse } from "../lib/http.js"
22
+ import { sseEvents, sseNamedEvent, sseRaw } from "../lib/sse.js"
23
+
24
+ const model = AnthropicMessages.route
25
+ .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
26
+ .model({ id: "claude-sonnet-4-5" })
27
+
28
+ const opus48 = AnthropicMessages.route
29
+ .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
30
+ .model({ id: "claude-opus-4-8" })
31
+
32
+ const compileUnsignedReasoning = (model: LLMRequest["model"]) =>
33
+ compileRequest(
34
+ ai.request({
35
+ model,
36
+ messages: [Message.assistant([{ type: "reasoning", text: "unsigned reasoning" }])],
37
+ cache: "none",
38
+ }),
39
+ )
40
+
41
+ const vertexOpus48 = GoogleVertexMessages.configure({
42
+ accessToken: "test",
43
+ location: "global",
44
+ project: "test",
45
+ }).model("claude-opus-4-8")
46
+
47
+ const request = ai.request({
48
+ id: "req_1",
49
+ model,
50
+ system: { type: "text", text: "You are concise.", cache: new CacheHint({ type: "ephemeral" }) },
51
+ prompt: "Say hello.",
52
+ // This fixture predates the `cache: "auto"` default; pin the policy off so
53
+ // existing wire-shape assertions only see the manual hint on the system part.
54
+ cache: "none",
55
+ maxTokens: 20,
56
+ temperature: 0,
57
+ })
58
+
59
+ type AnthropicToolResult = Extract<
60
+ AnthropicMessages.AnthropicMessagesBody["messages"][number]["content"][number],
61
+ { readonly type: "tool_result" }
62
+ >
63
+
64
+ const expectToolResult = (body: AnthropicMessages.AnthropicMessagesBody): AnthropicToolResult => {
65
+ const result = body.messages
66
+ .flatMap((message) => (message.role === "user" ? message.content : []))
67
+ .find((block): block is AnthropicToolResult => block.type === "tool_result")
68
+ expect(result).toBeDefined()
69
+ return result!
70
+ }
71
+
72
+ describe("Anthropic Messages route", () => {
73
+ it.effect("prepares Anthropic Messages target", () =>
74
+ Effect.gen(function* () {
75
+ const prepared = yield* compileRequest(request)
76
+
77
+ expect(prepared.body).toEqual({
78
+ model: "claude-sonnet-4-5",
79
+ system: [{ type: "text", text: "You are concise.", cache_control: { type: "ephemeral" } }],
80
+ messages: [{ role: "user", content: [{ type: "text", text: "Say hello." }] }],
81
+ stream: true,
82
+ max_tokens: 20,
83
+ temperature: 0,
84
+ })
85
+ }),
86
+ )
87
+
88
+ it.effect("omits empty system text while preserving whitespace", () =>
89
+ Effect.gen(function* () {
90
+ const empty = yield* compileRequest({ ...request, system: [{ type: "text", text: "" }] })
91
+ const whitespace = yield* compileRequest({ ...request, system: [{ type: "text", text: " " }] })
92
+
93
+ expect(empty.body.system).toBeUndefined()
94
+ expect(whitespace.body.system).toEqual([{ type: "text", text: " " }])
95
+ }),
96
+ )
97
+
98
+ it.effect("filters whitespace-only text and removes empty messages", () =>
99
+ Effect.gen(function* () {
100
+ const prepared = yield* compileRequest(
101
+ ai.request({
102
+ model,
103
+ messages: [
104
+ Message.user(" \n\t"),
105
+ Message.user([]),
106
+ Message.user([
107
+ { type: "text", text: "" },
108
+ { type: "text", text: " Keep this spacing. " },
109
+ { type: "text", text: " \n\t" },
110
+ ]),
111
+ Message.assistant(" \n\t"),
112
+ Message.assistant([]),
113
+ Message.assistant([{ type: "reasoning", text: "" }]),
114
+ Message.assistant([
115
+ { type: "text", text: "" },
116
+ { type: "reasoning", text: "", providerMetadata: { anthropic: { signature: "sig_1" } } },
117
+ ]),
118
+ ],
119
+ cache: "none",
120
+ }),
121
+ )
122
+
123
+ expect(prepared.body.messages).toEqual([
124
+ { role: "user", content: [{ type: "text", text: " Keep this spacing. " }] },
125
+ { role: "assistant", content: [{ type: "thinking", thinking: "", signature: "sig_1" }] },
126
+ ])
127
+ }),
128
+ )
129
+
130
+ it.effect("lowers adaptive thinking settings with effort", () =>
131
+ Effect.gen(function* () {
132
+ const prepared = yield* compileRequest({
133
+ ...request,
134
+ providerOptions: {
135
+ thinking: { type: "adaptive", display: "summarized" },
136
+ effort: "low",
137
+ },
138
+ })
139
+
140
+ expect(prepared.body).toMatchObject({
141
+ thinking: { type: "adaptive", display: "summarized" },
142
+ output_config: { effort: "low" },
143
+ })
144
+ }),
145
+ )
146
+
147
+ it.effect("normalizes enabled and disabled thinking settings", () =>
148
+ Effect.gen(function* () {
149
+ const enabled = yield* compileRequest({
150
+ ...request,
151
+ maxTokens: 4_096,
152
+ providerOptions: { thinking: { type: "enabled", budgetTokens: 1_024 } },
153
+ })
154
+ const legacy = yield* compileRequest({
155
+ ...request,
156
+ maxTokens: 4_096,
157
+ providerOptions: { thinking: { type: "enabled", budget_tokens: 2_048 } },
158
+ })
159
+ const disabled = yield* compileRequest({ ...request, providerOptions: { thinking: { type: "disabled" } } })
160
+
161
+ expect(enabled.body.thinking).toEqual({ type: "enabled", budget_tokens: 1_024 })
162
+ expect(legacy.body.thinking).toEqual({ type: "enabled", budget_tokens: 2_048 })
163
+ expect(disabled.body.thinking).toEqual({ type: "disabled" })
164
+ }),
165
+ )
166
+
167
+ it.effect("fits the thinking budget to half the output limit", () =>
168
+ Effect.gen(function* () {
169
+ const thinking = (maxTokens: number) =>
170
+ compileRequest({
171
+ ...request,
172
+ maxTokens,
173
+ providerOptions: { thinking: { type: "enabled", budgetTokens: 31_999 } },
174
+ }).pipe(Effect.map((prepared) => prepared.body.thinking))
175
+
176
+ expect(yield* thinking(64_000)).toEqual({ type: "enabled", budget_tokens: 31_999 })
177
+ expect(yield* thinking(20_000)).toEqual({ type: "enabled", budget_tokens: 10_000 })
178
+ expect(yield* thinking(1_500)).toEqual({ type: "enabled", budget_tokens: 1_024 })
179
+ }),
180
+ )
181
+
182
+ it.effect("rejects enabled thinking without a budget", () =>
183
+ Effect.gen(function* () {
184
+ const error = yield* compileRequest({ ...request, providerOptions: { thinking: { type: "enabled" } } }).pipe(
185
+ Effect.flip,
186
+ )
187
+
188
+ expect(error.reason._tag).toBe("InvalidRequest")
189
+ expect(error.message).toContain("budgetTokens")
190
+ }),
191
+ )
192
+
193
+ it.effect("lowers passthrough provider options and accepts either key spelling", () =>
194
+ Effect.gen(function* () {
195
+ const snake = yield* compileRequest({
196
+ ...request,
197
+ providerOptions: {
198
+ service_tier: "auto",
199
+ metadata: { user_id: "user_1" },
200
+ container: { id: "container_1" },
201
+ inference_geo: "us",
202
+ cache_control: { type: "ephemeral", ttl: "1h" },
203
+ output_config: { format: { type: "json_schema", schema: { type: "object" } } },
204
+ },
205
+ })
206
+ const camel = yield* compileRequest({
207
+ ...request,
208
+ providerOptions: {
209
+ serviceTier: "standard_only",
210
+ container: "container_2",
211
+ inferenceGeo: "eu",
212
+ cacheControl: { type: "ephemeral" },
213
+ outputConfig: { effort: "low" },
214
+ },
215
+ })
216
+
217
+ expect(snake.body).toMatchObject({
218
+ service_tier: "auto",
219
+ metadata: { user_id: "user_1" },
220
+ container: { id: "container_1" },
221
+ inference_geo: "us",
222
+ cache_control: { type: "ephemeral", ttl: "1h" },
223
+ output_config: { format: { type: "json_schema", schema: { type: "object" } } },
224
+ })
225
+ expect(camel.body).toMatchObject({
226
+ service_tier: "standard_only",
227
+ container: "container_2",
228
+ inference_geo: "eu",
229
+ cache_control: { type: "ephemeral" },
230
+ output_config: { effort: "low" },
231
+ })
232
+ }),
233
+ )
234
+
235
+ it.effect("sends fast mode speed with its beta header", () =>
236
+ Effect.gen(function* () {
237
+ const fast = { ...request, providerOptions: { speed: "fast" } }
238
+ const compiled = yield* compileRequest(fast)
239
+ const prepared = yield* AnthropicMessages.route.prepareTransport(compiled.body, fast)
240
+
241
+ expect(compiled.body.speed).toBe("fast")
242
+ expect(prepared.request.headers["anthropic-beta"]).toBe("interleaved-thinking-2025-05-14,fast-mode-2026-02-01")
243
+ }),
244
+ )
245
+
246
+ it.effect("forwards unknown values for pass-through string enums", () =>
247
+ Effect.gen(function* () {
248
+ const prepared = yield* compileRequest({
249
+ ...request,
250
+ providerOptions: {
251
+ service_tier: "future-tier",
252
+ thinking: { type: "adaptive", display: "future-display" },
253
+ },
254
+ })
255
+
256
+ expect(prepared.body).toMatchObject({
257
+ service_tier: "future-tier",
258
+ thinking: { type: "adaptive", display: "future-display" },
259
+ })
260
+ }),
261
+ )
262
+
263
+ it.effect("ignores unknown provider options and rejects malformed known ones", () =>
264
+ Effect.gen(function* () {
265
+ const prepared = yield* compileRequest({ ...request, providerOptions: { unknownOption: true } })
266
+ const malformed = [
267
+ { service_tier: 1 },
268
+ { metadata: { user_id: 42 } },
269
+ { cache_control: { type: "ephemeral", ttl: "future-ttl" } },
270
+ { output_config: { format: { type: "text" } } },
271
+ { thinking: { type: "automatic" } },
272
+ ]
273
+ const errors = yield* Effect.forEach(malformed, (providerOptions) =>
274
+ compileRequest({ ...request, providerOptions }).pipe(Effect.flip),
275
+ )
276
+
277
+ expect(prepared.body).not.toHaveProperty("unknownOption")
278
+ expect(errors.map((error) => error.reason._tag)).toEqual(malformed.map(() => "InvalidRequest"))
279
+ }),
280
+ )
281
+
282
+ it.effect("lowers chronological system updates natively for Claude Opus 4.8 with cache hints", () =>
283
+ Effect.gen(function* () {
284
+ const prepared = yield* compileRequest(
285
+ ai.request({
286
+ model: opus48,
287
+ messages: [
288
+ Message.user("Before."),
289
+ Message.system([{ type: "text", text: "Operator update.", cache: new CacheHint({ type: "ephemeral" }) }]),
290
+ Message.assistant("After."),
291
+ ],
292
+ cache: "none",
293
+ }),
294
+ )
295
+
296
+ expect(prepared.body.messages).toEqual([
297
+ { role: "user", content: [{ type: "text", text: "Before." }] },
298
+ {
299
+ role: "system",
300
+ content: [{ type: "text", text: "Operator update.", cache_control: { type: "ephemeral" } }],
301
+ },
302
+ { role: "assistant", content: [{ type: "text", text: "After." }] },
303
+ ])
304
+ }),
305
+ )
306
+
307
+ it.effect("supports native chronological system updates on documented and later Claude family versions", () =>
308
+ Effect.gen(function* () {
309
+ const ids = [
310
+ "claude-opus-4-8",
311
+ "claude-opus-5-1",
312
+ "claude-sonnet-5",
313
+ "claude-haiku-5-1",
314
+ "claude-fable-6",
315
+ "anthropic/claude-mythos-7.2",
316
+ "claude-sonnet-5-5",
317
+ "claude-opus-4-8@20260101",
318
+ "claude-nova-6",
319
+ ]
320
+
321
+ const prepared = yield* Effect.forEach(ids, (id) =>
322
+ compileRequest(
323
+ ai.request({
324
+ model: AnthropicMessages.route
325
+ .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
326
+ .model({ id }),
327
+ messages: [Message.user("Before."), Message.system("Update."), Message.assistant("After.")],
328
+ cache: "none",
329
+ }),
330
+ ),
331
+ )
332
+
333
+ expect(prepared.map((item) => item.body.messages[1]?.role)).toEqual(ids.map(() => "system"))
334
+ }),
335
+ )
336
+
337
+ it.effect("lowers chronological system updates to wrapped user text for unsupported Anthropic models", () =>
338
+ Effect.gen(function* () {
339
+ const prepared = yield* compileRequest(
340
+ ai.request({
341
+ model,
342
+ messages: [
343
+ Message.user("Before."),
344
+ Message.system("Treat </system-update> literally."),
345
+ Message.assistant("After."),
346
+ ],
347
+ cache: "none",
348
+ }),
349
+ )
350
+
351
+ expect(prepared.body.messages).toEqual([
352
+ {
353
+ role: "user",
354
+ content: [
355
+ { type: "text", text: "Before." },
356
+ { type: "text", text: "<system-update>\nTreat &lt;/system-update&gt; literally.\n</system-update>" },
357
+ ],
358
+ },
359
+ { role: "assistant", content: [{ type: "text", text: "After." }] },
360
+ ])
361
+ }),
362
+ )
363
+
364
+ it.effect("does not infer native system update support for older or undocumented Claude families", () =>
365
+ Effect.gen(function* () {
366
+ const ids = [
367
+ "claude-opus-4-7",
368
+ "claude-opus-4-20250514",
369
+ "claude-sonnet-4-9",
370
+ "claude-haiku-4-9",
371
+ "custom-model-7",
372
+ ]
373
+
374
+ const prepared = yield* Effect.forEach(ids, (id) =>
375
+ compileRequest(
376
+ ai.request({
377
+ model: AnthropicMessages.route
378
+ .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
379
+ .model({ id }),
380
+ messages: [Message.user("Before."), Message.system("Update."), Message.assistant("After.")],
381
+ cache: "none",
382
+ }),
383
+ ),
384
+ )
385
+
386
+ expect(prepared.map((item) => item.body.messages.some((message) => message.role === "system"))).toEqual(
387
+ ids.map(() => false),
388
+ )
389
+ }),
390
+ )
391
+
392
+ it.effect("falls back for unsupported native chronological system update placement", () =>
393
+ Effect.gen(function* () {
394
+ expect(
395
+ (yield* compileRequest(
396
+ ai.request({
397
+ model: opus48,
398
+ messages: [Message.assistant("Plain."), Message.system("After plain assistant.")],
399
+ cache: "none",
400
+ }),
401
+ )).body.messages,
402
+ ).toEqual([
403
+ { role: "assistant", content: [{ type: "text", text: "Plain." }] },
404
+ {
405
+ role: "user",
406
+ content: [{ type: "text", text: "<system-update>\nAfter plain assistant.\n</system-update>" }],
407
+ },
408
+ ])
409
+ expect(
410
+ (yield* compileRequest(ai.request({ model: opus48, messages: [Message.system("First.")], cache: "none" }))).body
411
+ .messages,
412
+ ).toEqual([{ role: "user", content: [{ type: "text", text: "<system-update>\nFirst.\n</system-update>" }] }])
413
+ expect(
414
+ (yield* compileRequest(
415
+ ai.request({
416
+ model: opus48,
417
+ messages: [
418
+ Message.user("Start."),
419
+ Message.assistant("One."),
420
+ Message.system("Update."),
421
+ Message.assistant("Two."),
422
+ ],
423
+ cache: "none",
424
+ }),
425
+ )).body.messages,
426
+ ).toEqual([
427
+ { role: "user", content: [{ type: "text", text: "Start." }] },
428
+ { role: "assistant", content: [{ type: "text", text: "One." }] },
429
+ { role: "user", content: [{ type: "text", text: "<system-update>\nUpdate.\n</system-update>" }] },
430
+ { role: "assistant", content: [{ type: "text", text: "Two." }] },
431
+ ])
432
+ }),
433
+ )
434
+
435
+ it.effect("moves system updates to the next assistant turn and sends consecutive updates together", () =>
436
+ Effect.gen(function* () {
437
+ const lower = (messages: ReadonlyArray<Message>) =>
438
+ compileRequest(ai.request({ model: opus48, messages: [...messages], cache: "none" })).pipe(
439
+ Effect.map((prepared) => prepared.body.messages),
440
+ )
441
+ const system = (text: string) => ({ role: "system", content: [{ type: "text", text, cache_control: undefined }] })
442
+ const user = (text: string) => ({ role: "user", content: [{ type: "text", text }] })
443
+ const assistant = (text: string) => ({ role: "assistant", content: [{ type: "text", text }] })
444
+
445
+ expect(
446
+ yield* lower([
447
+ Message.user("Fix it."),
448
+ Message.assistant("Done."),
449
+ Message.system("Update."),
450
+ Message.user("Next."),
451
+ ]),
452
+ ).toEqual([user("Fix it."), assistant("Done."), user("Next."), system("Update.")])
453
+ expect(yield* lower([Message.user("Before."), Message.system("One."), Message.system("Two.")])).toEqual([
454
+ user("Before."),
455
+ system("One."),
456
+ system("Two."),
457
+ ])
458
+ expect(
459
+ yield* lower([
460
+ Message.user("Fix it."),
461
+ Message.assistant("Done."),
462
+ Message.system("One."),
463
+ Message.user("Next."),
464
+ Message.system("Two."),
465
+ Message.assistant("After."),
466
+ ]),
467
+ ).toEqual([
468
+ user("Fix it."),
469
+ assistant("Done."),
470
+ user("Next."),
471
+ system("One."),
472
+ system("Two."),
473
+ assistant("After."),
474
+ ])
475
+ expect(
476
+ yield* lower([
477
+ Message.user("Use the tool."),
478
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
479
+ Message.tool({ id: "call_1", name: "lookup", result: "Done." }),
480
+ Message.system("Update."),
481
+ Message.user("Also check tests."),
482
+ ]),
483
+ ).toEqual([
484
+ user("Use the tool."),
485
+ { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "lookup", input: {} }] },
486
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: '"Done."' }] },
487
+ user("Also check tests."),
488
+ system("Update."),
489
+ ])
490
+ }),
491
+ )
492
+
493
+ it.effect("keeps wrapped system updates in place for models without native system updates", () =>
494
+ Effect.gen(function* () {
495
+ const prepared = yield* compileRequest(
496
+ ai.request({
497
+ model,
498
+ messages: [
499
+ Message.user("Fix it."),
500
+ Message.assistant("Done."),
501
+ Message.system("Update."),
502
+ Message.user("Next."),
503
+ ],
504
+ cache: "none",
505
+ }),
506
+ )
507
+
508
+ expect(prepared.body.messages).toEqual([
509
+ { role: "user", content: [{ type: "text", text: "Fix it." }] },
510
+ { role: "assistant", content: [{ type: "text", text: "Done." }] },
511
+ { role: "user", content: [{ type: "text", text: "<system-update>\nUpdate.\n</system-update>" }] },
512
+ { role: "user", content: [{ type: "text", text: "Next." }] },
513
+ ])
514
+ }),
515
+ )
516
+
517
+ it.effect("sends Vertex system updates after local tool results as native system messages", () =>
518
+ Effect.gen(function* () {
519
+ const toolTurn = [
520
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
521
+ Message.tool({ id: "call_1", name: "lookup", result: "Done." }),
522
+ Message.system("Operator update."),
523
+ ]
524
+ const lowered = [
525
+ { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "lookup", input: {} }] },
526
+ {
527
+ role: "user",
528
+ content: [
529
+ {
530
+ type: "tool_result",
531
+ tool_use_id: "call_1",
532
+ content: '"Done."',
533
+ is_error: undefined,
534
+ cache_control: undefined,
535
+ },
536
+ ],
537
+ },
538
+ { role: "system", content: [{ type: "text", text: "Operator update.", cache_control: undefined }] },
539
+ ]
540
+
541
+ const terminal = yield* compileRequest(ai.request({ model: vertexOpus48, messages: toolTurn, cache: "none" }))
542
+ const history = yield* compileRequest(
543
+ ai.request({
544
+ model: vertexOpus48,
545
+ messages: [...toolTurn, Message.assistant("Acknowledged."), Message.user("Next step.")],
546
+ cache: "none",
547
+ }),
548
+ )
549
+
550
+ expect(terminal.body.messages).toEqual(lowered)
551
+ expect(history.body.messages).toEqual([
552
+ ...lowered,
553
+ { role: "assistant", content: [{ type: "text", text: "Acknowledged." }] },
554
+ { role: "user", content: [{ type: "text", text: "Next step." }] },
555
+ ])
556
+ }),
557
+ )
558
+
559
+ it.effect("keeps a terminal direct Anthropic system update native", () =>
560
+ Effect.gen(function* () {
561
+ const prepared = yield* compileRequest(
562
+ ai.request({
563
+ model: opus48,
564
+ messages: [
565
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
566
+ Message.tool({ id: "call_1", name: "lookup", result: "Done." }),
567
+ Message.system("Operator update."),
568
+ ],
569
+ cache: "none",
570
+ }),
571
+ )
572
+
573
+ expect(prepared.body.messages).toEqual([
574
+ {
575
+ role: "assistant",
576
+ content: [{ type: "tool_use", id: "call_1", name: "lookup", input: {} }],
577
+ },
578
+ {
579
+ role: "user",
580
+ content: [
581
+ {
582
+ type: "tool_result",
583
+ tool_use_id: "call_1",
584
+ content: '"Done."',
585
+ is_error: undefined,
586
+ cache_control: undefined,
587
+ },
588
+ ],
589
+ },
590
+ {
591
+ role: "system",
592
+ content: [{ type: "text", text: "Operator update.", cache_control: undefined }],
593
+ },
594
+ ])
595
+ }),
596
+ )
597
+
598
+ it.effect("keeps an ordinary terminal Vertex system update native", () =>
599
+ Effect.gen(function* () {
600
+ const prepared = yield* compileRequest(
601
+ ai.request({
602
+ model: vertexOpus48,
603
+ messages: [Message.user("Before."), Message.system("Operator update.")],
604
+ cache: "none",
605
+ }),
606
+ )
607
+
608
+ expect(prepared.body.messages).toEqual([
609
+ { role: "user", content: [{ type: "text", text: "Before." }] },
610
+ {
611
+ role: "system",
612
+ content: [{ type: "text", text: "Operator update.", cache_control: undefined }],
613
+ },
614
+ ])
615
+ }),
616
+ )
617
+
618
+ it.effect("moves a system update between a local tool call and its result after the result", () =>
619
+ Effect.gen(function* () {
620
+ const prepared = yield* compileRequest(
621
+ ai.request({
622
+ model: opus48,
623
+ messages: [
624
+ Message.user("Use the tool."),
625
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
626
+ Message.system("Too early."),
627
+ Message.tool({ id: "call_1", name: "lookup", result: "Done." }),
628
+ ],
629
+ cache: "none",
630
+ }),
631
+ )
632
+
633
+ expect(prepared.body.messages.slice(1)).toEqual([
634
+ { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "lookup", input: {} }] },
635
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: '"Done."' }] },
636
+ { role: "system", content: [{ type: "text", text: "Too early.", cache_control: undefined }] },
637
+ ])
638
+ }),
639
+ )
640
+
641
+ it.effect("prepares tool call and tool result messages", () =>
642
+ Effect.gen(function* () {
643
+ const prepared = yield* compileRequest(
644
+ ai.request({
645
+ id: "req_tool_result",
646
+ model,
647
+ messages: [
648
+ Message.user("What is the weather?"),
649
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
650
+ Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
651
+ ],
652
+ cache: "none",
653
+ }),
654
+ )
655
+
656
+ expect(prepared.body).toEqual({
657
+ model: "claude-sonnet-4-5",
658
+ messages: [
659
+ { role: "user", content: [{ type: "text", text: "What is the weather?" }] },
660
+ {
661
+ role: "assistant",
662
+ content: [{ type: "tool_use", id: "call_1", name: "lookup", input: { query: "weather" } }],
663
+ },
664
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: '{"forecast":"sunny"}' }] },
665
+ ],
666
+ stream: true,
667
+ max_tokens: 32_000,
668
+ })
669
+ }),
670
+ )
671
+
672
+ it.effect("scrubs outbound tool call IDs without truncating them", () =>
673
+ Effect.gen(function* () {
674
+ const id = `functions.lookup:1|${"x".repeat(64)}`
675
+ const scrubbed = `functions_lookup_1_${"x".repeat(64)}`
676
+ const prepared = yield* compileRequest(
677
+ ai.request({
678
+ model,
679
+ messages: [
680
+ Message.assistant([ToolCallPart.make({ id, name: "lookup", input: {} })]),
681
+ Message.tool({ id, name: "lookup", result: "done" }),
682
+ ],
683
+ cache: "none",
684
+ }),
685
+ )
686
+
687
+ expect(prepared.body.messages).toMatchObject([
688
+ { role: "assistant", content: [{ type: "tool_use", id: scrubbed, name: "lookup", input: {} }] },
689
+ { role: "user", content: [{ type: "tool_result", tool_use_id: scrubbed }] },
690
+ ])
691
+ expect(scrubbed.length).toBeGreaterThan(64)
692
+ }),
693
+ )
694
+
695
+ it.effect("batches parallel tool results into one Anthropic user message", () =>
696
+ Effect.gen(function* () {
697
+ const prepared = yield* compileRequest(
698
+ ai.request({
699
+ model,
700
+ messages: [
701
+ Message.user("Check both cities."),
702
+ Message.assistant([
703
+ { type: "text", text: "I'll check both." },
704
+ ToolCallPart.make({ id: "call_paris", name: "weather", input: { city: "Paris" } }),
705
+ ToolCallPart.make({ id: "call_london", name: "weather", input: { city: "London" } }),
706
+ ]),
707
+ Message.tool({ id: "call_paris", name: "weather", result: { temperature: 22 } }),
708
+ Message.tool({ id: "call_london", name: "weather", result: { temperature: 18 } }),
709
+ ],
710
+ cache: "none",
711
+ }),
712
+ )
713
+
714
+ expect(prepared.body.messages).toMatchObject([
715
+ { role: "user", content: [{ type: "text", text: "Check both cities." }] },
716
+ {
717
+ role: "assistant",
718
+ content: [
719
+ { type: "text", text: "I'll check both." },
720
+ { type: "tool_use", id: "call_paris", name: "weather", input: { city: "Paris" } },
721
+ { type: "tool_use", id: "call_london", name: "weather", input: { city: "London" } },
722
+ ],
723
+ },
724
+ {
725
+ role: "user",
726
+ content: [
727
+ { type: "tool_result", tool_use_id: "call_paris", content: '{"temperature":22}' },
728
+ { type: "tool_result", tool_use_id: "call_london", content: '{"temperature":18}' },
729
+ ],
730
+ },
731
+ ])
732
+ expect(prepared.body.messages).toHaveLength(3)
733
+ }),
734
+ )
735
+
736
+ it.effect("keeps tools and sends tool_choice none", () =>
737
+ Effect.gen(function* () {
738
+ const prepared = yield* compileRequest(
739
+ ai.request({
740
+ id: "req_tool_choice_none",
741
+ model,
742
+ tools: [{ name: "lookup", description: "Look things up", inputSchema: { type: "object", properties: {} } }],
743
+ messages: [
744
+ Message.user("What is the weather?"),
745
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
746
+ Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
747
+ ],
748
+ toolChoice: "none",
749
+ cache: "none",
750
+ }),
751
+ )
752
+
753
+ expect(prepared.body.tools).toEqual([
754
+ {
755
+ name: "lookup",
756
+ description: "Look things up",
757
+ input_schema: { type: "object", properties: {} },
758
+ },
759
+ ])
760
+ expect(prepared.body.tool_choice).toEqual({ type: "none" })
761
+ }),
762
+ )
763
+
764
+ // Regression: read tool results must stay structured so base64 media data is
765
+ // not JSON-stringified into `tool_result.content`.
766
+ it.effect("lowers media tool-result content as structured blocks", () =>
767
+ Effect.gen(function* () {
768
+ const prepared = yield* compileRequest(
769
+ ai.request({
770
+ id: "req_tool_result_image",
771
+ model,
772
+ messages: [
773
+ Message.user("Show me the screenshot."),
774
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "read", input: { filePath: "shot.png" } })]),
775
+ Message.tool({
776
+ id: "call_1",
777
+ name: "read",
778
+ resultType: "content",
779
+ result: [
780
+ { type: "text", text: "Image read successfully" },
781
+ { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png" },
782
+ { type: "file", uri: "data:application/pdf;base64,JVBERi0xLjQ=", mime: "application/pdf" },
783
+ ],
784
+ }),
785
+ ],
786
+ cache: "none",
787
+ }),
788
+ )
789
+
790
+ expect(expectToolResult(prepared.body).content).toEqual([
791
+ { type: "text", text: "Image read successfully" },
792
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
793
+ { type: "document", source: { type: "base64", media_type: "application/pdf", data: "JVBERi0xLjQ=" } },
794
+ ])
795
+ }),
796
+ )
797
+
798
+ it.effect("lowers single-image tool-result content as a structured image block", () =>
799
+ Effect.gen(function* () {
800
+ const prepared = yield* compileRequest(
801
+ ai.request({
802
+ id: "req_tool_result_image_only",
803
+ model,
804
+ messages: [
805
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "screenshot", input: {} })]),
806
+ Message.tool({
807
+ id: "call_1",
808
+ name: "screenshot",
809
+ resultType: "content",
810
+ result: [{ type: "file", uri: "data:image/jpeg;base64,/9j/AA==", mime: "image/jpeg" }],
811
+ }),
812
+ ],
813
+ cache: "none",
814
+ }),
815
+ )
816
+
817
+ expect(expectToolResult(prepared.body).content).toEqual([
818
+ { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "/9j/AA==" } },
819
+ ])
820
+ }),
821
+ )
822
+
823
+ it.effect("rejects tool-result media that cannot be lowered", () =>
824
+ Effect.gen(function* () {
825
+ const error = yield* compileRequest(
826
+ ai.request({
827
+ id: "req_tool_result_unsupported_media",
828
+ model,
829
+ messages: [
830
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "fetch", input: {} })]),
831
+ Message.tool({
832
+ id: "call_1",
833
+ name: "fetch",
834
+ resultType: "content",
835
+ result: [{ type: "file", uri: "data:audio/mpeg;base64,AAECAw==", mime: "audio/mpeg" }],
836
+ }),
837
+ ],
838
+ cache: "none",
839
+ }),
840
+ ).pipe(Effect.flip)
841
+
842
+ expect(error.message).toContain("Anthropic Messages does not support media type audio/mpeg")
843
+ }),
844
+ )
845
+
846
+ it.effect("lowers per-part Anthropic media options from provider metadata", () =>
847
+ Effect.gen(function* () {
848
+ const prepared = yield* compileRequest(
849
+ ai.request({
850
+ model,
851
+ prompt: [
852
+ Message.media(Media.base64("AQID", "image/png"), {
853
+ providerMetadata: {
854
+ anthropic: { file_id: "file_img", transformations: { oversized_image: "downsize" } },
855
+ },
856
+ }),
857
+ Message.media(Media.url("https://example.com/report.pdf", { mediaType: "application/pdf" }), {
858
+ filename: "report.pdf",
859
+ providerMetadata: { anthropic: { context: "Q3", citations: { enabled: true } } },
860
+ }),
861
+ Message.media(Media.base64("aGk=", "text/plain"), {
862
+ filename: "notes.txt",
863
+ providerMetadata: { anthropic: { title: "Notes" } },
864
+ }),
865
+ ],
866
+ cache: "none",
867
+ }),
868
+ )
869
+
870
+ expect(prepared.body.messages[0]?.content).toEqual([
871
+ {
872
+ type: "image",
873
+ source: { type: "file", file_id: "file_img" },
874
+ transformations: { oversized_image: "downsize" },
875
+ },
876
+ {
877
+ type: "document",
878
+ source: { type: "url", url: "https://example.com/report.pdf" },
879
+ title: "report.pdf",
880
+ context: "Q3",
881
+ citations: { enabled: true },
882
+ },
883
+ { type: "document", source: { type: "text", media_type: "text/plain", data: "hi" }, title: "Notes" },
884
+ ])
885
+ }),
886
+ )
887
+
888
+ it.effect("rejects invalid per-part Anthropic media options", () =>
889
+ Effect.gen(function* () {
890
+ const error = yield* compileRequest(
891
+ ai.request({
892
+ model,
893
+ prompt: [
894
+ Message.media(Media.base64("AQID", "image/png"), {
895
+ providerMetadata: { anthropic: { transformations: { oversized_image: "shrink" } } },
896
+ }),
897
+ ],
898
+ }),
899
+ ).pipe(Effect.flip)
900
+
901
+ expect(error.message).toContain("oversized_image")
902
+ }),
903
+ )
904
+
905
+ const video = { type: "video", source: { type: "base64", media_type: "video/mp4", data: "AAECAw==" } }
906
+ const videoFile = { type: "file" as const, uri: "data:video/mp4;base64,AAECAw==", mime: "video/mp4" }
907
+ const customModel = AnthropicMessages.route.with({ provider: "custom" }).model({ id: "video-model" })
908
+
909
+ it.effect("serializes Messages video inputs", () =>
910
+ Effect.gen(function* () {
911
+ const user = ai.request({
912
+ model: customModel,
913
+ prompt: [
914
+ Message.media(Media.base64("AAECAw==", "video/mp4"), { cache: new CacheHint({ type: "ephemeral" }) }),
915
+ Message.media(Media.ref("custom", "file_clip", "video/mp4")),
916
+ ],
917
+ cache: "none",
918
+ })
919
+ const prompt = yield* compileRequest(user)
920
+ expect(prompt.body.messages).toEqual([
921
+ {
922
+ role: "user",
923
+ content: [
924
+ { ...video, cache_control: { type: "ephemeral" } },
925
+ { type: "video", source: { type: "file", file_id: "file_clip" } },
926
+ ],
927
+ },
928
+ ])
929
+
930
+ const nested = yield* compileRequest({
931
+ ...user,
932
+ messages: [
933
+ Message.assistant([ToolCallPart.make({ id: "clip", name: "read", input: {} })]),
934
+ Message.tool({
935
+ id: "clip",
936
+ name: "read",
937
+ resultType: "content",
938
+ result: [videoFile, { type: "file", uri: "storage://clip", mime: "video/mp4" }],
939
+ }),
940
+ ],
941
+ })
942
+ expect(expectToolResult(nested.body).content).toEqual([
943
+ video,
944
+ { type: "video", source: { type: "url", url: "storage://clip" } },
945
+ ])
946
+
947
+ const foreign = yield* compileRequest({ ...user, model }).pipe(Effect.flip)
948
+ expect(foreign.message).toContain("got custom:file_clip")
949
+
950
+ const native = yield* compileRequest(
951
+ ai.request({
952
+ model: AnthropicMessages.route.model({ id: "video-model" }),
953
+ prompt: Message.media(Media.base64("AAECAw==", "video/mp4")),
954
+ cache: "none",
955
+ }),
956
+ )
957
+ expect(native.body.messages).toEqual([{ role: "user", content: [video] }])
958
+ }),
959
+ )
960
+
961
+ it.effect("moves Meta tool result videos after consecutive results", () =>
962
+ Effect.gen(function* () {
963
+ const meta = ai.request({
964
+ model: Meta.configure({ apiKey: "test" }).messages("video-model"),
965
+ messages: [
966
+ Message.assistant([
967
+ ToolCallPart.make({ id: "first", name: "read", input: {} }),
968
+ ToolCallPart.make({ id: "second", name: "read", input: {} }),
969
+ ]),
970
+ Message.tool({ id: "first", name: "read", resultType: "content", result: [videoFile] }),
971
+ Message.tool({ id: "second", name: "read", resultType: "content", result: [videoFile] }),
972
+ Message.assistant("Observed."),
973
+ ],
974
+ cache: "none",
975
+ })
976
+ const hoisted = yield* compileRequest(meta)
977
+ expect(hoisted.body.messages).toMatchObject([
978
+ {
979
+ role: "assistant",
980
+ content: [
981
+ { type: "tool_use", id: "first" },
982
+ { type: "tool_use", id: "second" },
983
+ ],
984
+ },
985
+ {
986
+ role: "user",
987
+ content: [
988
+ { type: "tool_result", tool_use_id: "first", content: [] },
989
+ { type: "tool_result", tool_use_id: "second", content: [] },
990
+ video,
991
+ video,
992
+ ],
993
+ },
994
+ { role: "assistant", content: [{ type: "text", text: "Observed." }] },
995
+ ])
996
+
997
+ const generic = yield* compileRequest({ ...meta, model: customModel })
998
+ expect(generic.body.messages[1]?.content).toEqual([
999
+ { type: "tool_result", tool_use_id: "first", content: [video] },
1000
+ { type: "tool_result", tool_use_id: "second", content: [video] },
1001
+ ])
1002
+ }),
1003
+ )
1004
+
1005
+ it.effect("prepares the composed native continuation request", () =>
1006
+ Effect.gen(function* () {
1007
+ const prepared = yield* compileRequest(
1008
+ continuationRequest({
1009
+ id: "req_native_continuation_anthropic",
1010
+ model,
1011
+ features: nativeAnthropicMessagesContinuation,
1012
+ }),
1013
+ )
1014
+
1015
+ expect(prepared.body).toMatchObject({
1016
+ system: [{ type: "text", text: "You are concise. Continue from the provided history." }],
1017
+ messages: [
1018
+ {
1019
+ role: "user",
1020
+ content: [
1021
+ { type: "text", text: "What is shown here?" },
1022
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
1023
+ ],
1024
+ },
1025
+ {
1026
+ role: "assistant",
1027
+ content: [
1028
+ { type: "thinking", thinking: "I inspected the previous turn.", signature: "sig_continuation_1" },
1029
+ { type: "text", text: "It shows a small test image." },
1030
+ ],
1031
+ },
1032
+ { role: "user", content: [{ type: "text", text: "Check the weather in Paris before continuing." }] },
1033
+ {
1034
+ role: "assistant",
1035
+ content: [{ type: "tool_use", id: "call_weather_1", name: "get_weather", input: { city: "Paris" } }],
1036
+ },
1037
+ {
1038
+ role: "user",
1039
+ content: [{ type: "tool_result", tool_use_id: "call_weather_1", content: '{"temperature":22}' }],
1040
+ },
1041
+ { role: "assistant", content: [{ type: "text", text: "Paris is 22 degrees." }] },
1042
+ { role: "user", content: [{ type: "text", text: "Continue from this conversation in one short sentence." }] },
1043
+ ],
1044
+ })
1045
+ expect(prepared.body.tools).toEqual([expect.objectContaining({ name: "get_weather" })])
1046
+ }),
1047
+ )
1048
+
1049
+ it.effect("lowers preserved Anthropic reasoning signature metadata", () =>
1050
+ Effect.gen(function* () {
1051
+ const prepared = yield* compileRequest(
1052
+ ai.request({
1053
+ model,
1054
+ messages: [
1055
+ Message.assistant([
1056
+ { type: "reasoning", text: "thinking", providerMetadata: { anthropic: { signature: "sig_1" } } },
1057
+ ]),
1058
+ ],
1059
+ }),
1060
+ )
1061
+
1062
+ expect(prepared.body).toMatchObject({
1063
+ messages: [{ role: "assistant", content: [{ type: "thinking", thinking: "thinking", signature: "sig_1" }] }],
1064
+ })
1065
+ }),
1066
+ )
1067
+
1068
+ it.effect("drops unsigned reasoning when signatures are required", () =>
1069
+ Effect.gen(function* () {
1070
+ const prepared = yield* compileUnsignedReasoning(model)
1071
+
1072
+ expect(prepared.body.messages).toEqual([])
1073
+ }),
1074
+ )
1075
+
1076
+ it.effect("infers empty-signature compatibility across Kimi providers", () =>
1077
+ Effect.gen(function* () {
1078
+ const coding = AnthropicMessages.route.with({
1079
+ provider: "kimi-for-coding",
1080
+ endpoint: { baseURL: "https://compatible.test/v1/" },
1081
+ auth: Auth.header("x-api-key", "test"),
1082
+ })
1083
+ const moonshot = AnthropicMessages.route
1084
+ .with({
1085
+ provider: "moonshotai",
1086
+ endpoint: { baseURL: "https://api.moonshot.ai/anthropic" },
1087
+ auth: Auth.bearer("test"),
1088
+ })
1089
+ .model({ id: "kimi-k2.6" })
1090
+ const codingPrepared = yield* compileUnsignedReasoning(coding.model({ id: "k3" }))
1091
+ const moonshotPrepared = yield* compileUnsignedReasoning(moonshot)
1092
+ const qwenPrepared = yield* compileUnsignedReasoning(
1093
+ coding.with({ provider: "opencode" }).model({ id: "qwen3.8-flash" }),
1094
+ )
1095
+ const minimaxPrepared = yield* compileUnsignedReasoning(
1096
+ coding.with({ provider: "opencode-go" }).model({ id: "minimax-m3" }),
1097
+ )
1098
+
1099
+ for (const prepared of [codingPrepared, moonshotPrepared, qwenPrepared, minimaxPrepared]) {
1100
+ expect(prepared.body.messages).toEqual([
1101
+ {
1102
+ role: "assistant",
1103
+ content: [{ type: "thinking", thinking: "unsigned reasoning", signature: "" }],
1104
+ },
1105
+ ])
1106
+ }
1107
+ }),
1108
+ )
1109
+
1110
+ it.effect("lets an explicit signature requirement override inference", () =>
1111
+ Effect.gen(function* () {
1112
+ const compatible = AnthropicMessages.route
1113
+ .with({
1114
+ provider: "kimi-for-coding",
1115
+ endpoint: { baseURL: "https://api.kimi.com/coding/v1/" },
1116
+ auth: Auth.header("x-api-key", "test"),
1117
+ })
1118
+ .model({ id: "k3", compatibility: { requireSignature: true } })
1119
+ const prepared = yield* compileUnsignedReasoning(compatible)
1120
+
1121
+ expect(prepared.body.messages).toEqual([])
1122
+ }),
1123
+ )
1124
+
1125
+ it.effect("round-trips redacted thinking as redacted_thinking blocks", () =>
1126
+ Effect.gen(function* () {
1127
+ const prepared = yield* compileRequest(
1128
+ ai.request({
1129
+ model,
1130
+ messages: [
1131
+ Message.assistant([
1132
+ { type: "reasoning", text: "", providerMetadata: { anthropic: { redactedData: "opaque_1" } } },
1133
+ { type: "reasoning", text: "visible", providerMetadata: { anthropic: { signature: "sig_1" } } },
1134
+ ]),
1135
+ ],
1136
+ }),
1137
+ )
1138
+
1139
+ expect(prepared.body).toMatchObject({
1140
+ messages: [
1141
+ {
1142
+ role: "assistant",
1143
+ content: [
1144
+ { type: "redacted_thinking", data: "opaque_1" },
1145
+ { type: "thinking", thinking: "visible", signature: "sig_1" },
1146
+ ],
1147
+ },
1148
+ ],
1149
+ })
1150
+ }),
1151
+ )
1152
+
1153
+ it.effect("round-trips compatible provider metadata in its own namespace", () =>
1154
+ Effect.gen(function* () {
1155
+ const compatible = Route.make({
1156
+ id: "custom-anthropic-messages",
1157
+ provider: "custom-anthropic",
1158
+ protocol: AnthropicMessages.protocol,
1159
+ endpoint: Endpoint.path("/messages", { baseURL: "https://compatible.test/v1" }),
1160
+ auth: Auth.header("x-api-key", "test"),
1161
+ framing: AnthropicMessages.framing,
1162
+ }).model({ id: "custom-model" })
1163
+ const result = [
1164
+ {
1165
+ type: "web_search_result",
1166
+ url: "https://example.com",
1167
+ citations: [{ type: "web_search_result_location", cited_text: "Example" }],
1168
+ },
1169
+ ]
1170
+ const response = yield* LLMClient.generate(ai.request({ model: compatible, prompt: "Search." })).pipe(
1171
+ Effect.provide(
1172
+ fixedResponse(
1173
+ sseEvents(
1174
+ { type: "message_start", message: { usage: { input_tokens: 5, custom_start: true } } },
1175
+ { type: "content_block_start", index: 0, content_block: { type: "thinking", thinking: "Thinking." } },
1176
+ { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "custom_sig" } },
1177
+ { type: "content_block_stop", index: 0 },
1178
+ {
1179
+ type: "content_block_start",
1180
+ index: 1,
1181
+ content_block: { type: "redacted_thinking", data: "custom_redacted" },
1182
+ },
1183
+ { type: "content_block_stop", index: 1 },
1184
+ {
1185
+ type: "content_block_start",
1186
+ index: 2,
1187
+ content_block: {
1188
+ type: "server_tool_use",
1189
+ id: "custom_tool",
1190
+ name: "web_search",
1191
+ input: { query: "example" },
1192
+ },
1193
+ },
1194
+ { type: "content_block_stop", index: 2 },
1195
+ {
1196
+ type: "content_block_start",
1197
+ index: 3,
1198
+ content_block: { type: "web_search_tool_result", tool_use_id: "custom_tool", content: result },
1199
+ },
1200
+ { type: "content_block_stop", index: 3 },
1201
+ {
1202
+ type: "message_delta",
1203
+ delta: { stop_reason: "end_turn", stop_sequence: "custom_stop" },
1204
+ usage: { output_tokens: 2, custom_terminal: true },
1205
+ },
1206
+ { type: "message_stop" },
1207
+ ),
1208
+ ),
1209
+ ),
1210
+ )
1211
+
1212
+ expect(response.message.content).toMatchObject([
1213
+ { type: "reasoning", text: "Thinking.", providerMetadata: { "custom-anthropic": { signature: "custom_sig" } } },
1214
+ { type: "reasoning", text: "", providerMetadata: { "custom-anthropic": { redactedData: "custom_redacted" } } },
1215
+ { type: "tool-call", id: "custom_tool", providerExecuted: true },
1216
+ {
1217
+ type: "tool-result",
1218
+ providerExecuted: true,
1219
+ providerMetadata: { "custom-anthropic": { blockType: "web_search_tool_result", result } },
1220
+ },
1221
+ ])
1222
+ expect(response.usage?.providerMetadata).toEqual({
1223
+ "custom-anthropic": { input_tokens: 5, custom_start: true, output_tokens: 2, custom_terminal: true },
1224
+ })
1225
+ expect(response.events.at(-1)).toMatchObject({
1226
+ providerMetadata: { "custom-anthropic": { stopSequence: "custom_stop" } },
1227
+ })
1228
+
1229
+ const prepared = yield* compileRequest(
1230
+ ai.request({ model: compatible, messages: [response.message], cache: "none" }),
1231
+ )
1232
+ expect(prepared.body.messages).toEqual([
1233
+ {
1234
+ role: "assistant",
1235
+ content: [
1236
+ { type: "thinking", thinking: "Thinking.", signature: "custom_sig" },
1237
+ { type: "redacted_thinking", data: "custom_redacted" },
1238
+ { type: "server_tool_use", id: "custom_tool", name: "web_search", input: { query: "example" } },
1239
+ { type: "web_search_tool_result", tool_use_id: "custom_tool", content: result },
1240
+ ],
1241
+ },
1242
+ ])
1243
+ }),
1244
+ )
1245
+
1246
+ it.effect("preserves a reasoning signature when message_stop closes the block", () =>
1247
+ Effect.gen(function* () {
1248
+ const compatible = Route.make({
1249
+ id: "custom-anthropic-messages",
1250
+ provider: "custom-anthropic",
1251
+ protocol: AnthropicMessages.protocol,
1252
+ endpoint: Endpoint.path("/messages", { baseURL: "https://compatible.test/v1" }),
1253
+ auth: Auth.header("x-api-key", "test"),
1254
+ framing: AnthropicMessages.framing,
1255
+ }).model({ id: "custom-model" })
1256
+ const body = sseEvents(
1257
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1258
+ {
1259
+ type: "content_block_start",
1260
+ index: 0,
1261
+ content_block: { type: "thinking", thinking: "", signature: "" },
1262
+ },
1263
+ { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "Reasoning." } },
1264
+ { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "sig_1" } },
1265
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } },
1266
+ { type: "message_stop" },
1267
+ )
1268
+ const response = yield* LLMClient.generate(ai.request({ model: compatible, prompt: "Think." })).pipe(
1269
+ Effect.provide(fixedResponse(body)),
1270
+ )
1271
+
1272
+ const reasoningEnds = response.events.filter((event) => event.type === "reasoning-end")
1273
+ expect(reasoningEnds).toHaveLength(1)
1274
+ expect(reasoningEnds[0]).toMatchObject({
1275
+ providerMetadata: { "custom-anthropic": { signature: "sig_1" } },
1276
+ })
1277
+ expect(response.message.content).toEqual([
1278
+ {
1279
+ type: "reasoning",
1280
+ text: "Reasoning.",
1281
+ providerMetadata: { "custom-anthropic": { signature: "sig_1" } },
1282
+ },
1283
+ ])
1284
+
1285
+ const prepared = yield* compileRequest(
1286
+ ai.request({ model: compatible, messages: [response.message], cache: "none" }),
1287
+ )
1288
+ expect(prepared.body.messages).toEqual([
1289
+ { role: "assistant", content: [{ type: "thinking", thinking: "Reasoning.", signature: "sig_1" }] },
1290
+ ])
1291
+ }),
1292
+ )
1293
+
1294
+ it.effect("parses text, reasoning, and usage stream fixtures", () =>
1295
+ Effect.gen(function* () {
1296
+ const body = sseEvents(
1297
+ { type: "message_start", message: { usage: { input_tokens: 5, cache_read_input_tokens: 1 } } },
1298
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
1299
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } },
1300
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "!" } },
1301
+ { type: "content_block_stop", index: 0 },
1302
+ { type: "content_block_start", index: 1, content_block: { type: "thinking", thinking: "" } },
1303
+ { type: "content_block_delta", index: 1, delta: { type: "thinking_delta", thinking: "thinking" } },
1304
+ { type: "content_block_delta", index: 1, delta: { type: "signature_delta", signature: "sig_1" } },
1305
+ { type: "content_block_stop", index: 1 },
1306
+ {
1307
+ type: "message_delta",
1308
+ delta: { stop_reason: "end_turn", stop_sequence: "\n\nHuman:" },
1309
+ usage: { output_tokens: 2 },
1310
+ },
1311
+ { type: "message_stop" },
1312
+ )
1313
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
1314
+
1315
+ expect(response.text).toBe("Hello!")
1316
+ expect(response.reasoning).toBe("thinking")
1317
+ expect(response.usage).toMatchObject({
1318
+ inputTokens: 6,
1319
+ outputTokens: 2,
1320
+ nonCachedInputTokens: 5,
1321
+ cacheReadInputTokens: 1,
1322
+ totalTokens: 8,
1323
+ })
1324
+ expect(response.events.find((event) => event.type === "reasoning-end")).toMatchObject({
1325
+ providerMetadata: { anthropic: { signature: "sig_1" } },
1326
+ })
1327
+ expect(response.events.filter((event) => event.type === "reasoning-end")).toHaveLength(1)
1328
+ expect(response.events.find((event) => event.type === "reasoning-delta" && event.text === "")).toBeUndefined()
1329
+ expect(response.message.content).toEqual([
1330
+ { type: "text", text: "Hello!" },
1331
+ { type: "reasoning", text: "thinking", providerMetadata: { anthropic: { signature: "sig_1" } } },
1332
+ ])
1333
+ expect(response.events.at(-1)).toMatchObject({
1334
+ type: "finish",
1335
+ reason: { normalized: "stop", raw: "end_turn" },
1336
+ providerMetadata: { anthropic: { stopSequence: "\n\nHuman:" } },
1337
+ })
1338
+ }),
1339
+ )
1340
+
1341
+ it.effect("reports the cost the endpoint billed", () =>
1342
+ Effect.gen(function* () {
1343
+ const response = yield* LLMClient.generate(request).pipe(
1344
+ Effect.provide(
1345
+ fixedResponse(
1346
+ sseEvents(
1347
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1348
+ {
1349
+ type: "message_delta",
1350
+ delta: { stop_reason: "end_turn" },
1351
+ usage: { output_tokens: 2, cost: 0, opencode: { allowance: 0.0042 } },
1352
+ },
1353
+ { type: "message_stop" },
1354
+ ),
1355
+ ),
1356
+ ),
1357
+ )
1358
+
1359
+ expect(response.usage).toMatchObject({ inputTokens: 5, outputTokens: 2, cost: 0 })
1360
+ }),
1361
+ )
1362
+
1363
+ it.effect("converts the GitHub Copilot billing on the message delta to USD", () =>
1364
+ Effect.gen(function* () {
1365
+ const response = yield* LLMClient.generate(request).pipe(
1366
+ Effect.provide(
1367
+ fixedResponse(
1368
+ sseEvents(
1369
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1370
+ {
1371
+ type: "message_delta",
1372
+ delta: { stop_reason: "end_turn" },
1373
+ usage: { output_tokens: 2 },
1374
+ copilot_usage: { total_nano_aiu: 4_473_525_000 },
1375
+ },
1376
+ { type: "message_stop" },
1377
+ ),
1378
+ ),
1379
+ ),
1380
+ )
1381
+
1382
+ expect(response.usage).toMatchObject({ inputTokens: 5, outputTokens: 2, cost: 0.04473525 })
1383
+ }),
1384
+ )
1385
+
1386
+ it.effect("preserves terminal state across usage-only message deltas", () =>
1387
+ Effect.gen(function* () {
1388
+ const response = yield* LLMClient.generate(request).pipe(
1389
+ Effect.provide(
1390
+ fixedResponse(
1391
+ sseEvents(
1392
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1393
+ {
1394
+ type: "message_delta",
1395
+ delta: { stop_reason: "end_turn", stop_sequence: "X" },
1396
+ usage: { output_tokens: 8 },
1397
+ },
1398
+ { type: "message_delta", delta: {}, usage: { output_tokens: 10 } },
1399
+ { type: "message_stop" },
1400
+ ),
1401
+ ),
1402
+ ),
1403
+ )
1404
+
1405
+ expect(response.usage).toMatchObject({ inputTokens: 5, outputTokens: 10, totalTokens: 15 })
1406
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "end_turn" })
1407
+ expect(response.events.find((event) => event.type === "step-finish")).toMatchObject({
1408
+ reason: { normalized: "stop", raw: "end_turn" },
1409
+ usage: { inputTokens: 5, outputTokens: 10, totalTokens: 15 },
1410
+ providerMetadata: { anthropic: { stopSequence: "X" } },
1411
+ })
1412
+ expect(response.events.at(-1)).toMatchObject({
1413
+ type: "finish",
1414
+ reason: { normalized: "stop", raw: "end_turn" },
1415
+ usage: { inputTokens: 5, outputTokens: 10, totalTokens: 15 },
1416
+ providerMetadata: { anthropic: { stopSequence: "X" } },
1417
+ })
1418
+ }),
1419
+ )
1420
+
1421
+ it.effect("requires message_stop before completing a streamed message", () =>
1422
+ Effect.gen(function* () {
1423
+ const error = yield* LLMClient.generate(request).pipe(
1424
+ Effect.provide(
1425
+ fixedResponse(
1426
+ sseEvents(
1427
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1428
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
1429
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } },
1430
+ { type: "content_block_stop", index: 0 },
1431
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
1432
+ ),
1433
+ ),
1434
+ ),
1435
+ Effect.flip,
1436
+ )
1437
+
1438
+ expect(error).toMatchObject({
1439
+ reason: { _tag: "InvalidProviderOutput", classification: "incomplete-stream" },
1440
+ message: "The provider response ended unexpectedly.",
1441
+ })
1442
+ }),
1443
+ )
1444
+
1445
+ it.effect("ignores unknown named SSE events", () =>
1446
+ Effect.gen(function* () {
1447
+ const response = yield* LLMClient.generate(request).pipe(
1448
+ Effect.provide(
1449
+ fixedResponse(
1450
+ sseRaw(
1451
+ sseNamedEvent("message_start", {
1452
+ type: "message_start",
1453
+ message: { usage: { input_tokens: 5 } },
1454
+ }),
1455
+ sseNamedEvent("proxy.stats", "not json"),
1456
+ sseNamedEvent("content_block_start", {
1457
+ type: "content_block_start",
1458
+ index: 0,
1459
+ content_block: { type: "text", text: "" },
1460
+ }),
1461
+ sseNamedEvent("content_block_delta", {
1462
+ type: "content_block_delta",
1463
+ index: 0,
1464
+ delta: { type: "text_delta", text: "Hello" },
1465
+ }),
1466
+ sseNamedEvent("content_block_stop", { type: "content_block_stop", index: 0 }),
1467
+ sseNamedEvent("message_delta", {
1468
+ type: "message_delta",
1469
+ delta: { stop_reason: "end_turn" },
1470
+ usage: { output_tokens: 1 },
1471
+ }),
1472
+ sseNamedEvent("message_stop", { type: "message_stop" }),
1473
+ sseNamedEvent("proxy.done", "still not json"),
1474
+ ),
1475
+ ),
1476
+ ),
1477
+ )
1478
+
1479
+ expect(response.message.content).toEqual([{ type: "text", text: "Hello" }])
1480
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "end_turn" })
1481
+ }),
1482
+ )
1483
+
1484
+ it.effect("ignores unknown content block and delta variants", () =>
1485
+ Effect.gen(function* () {
1486
+ const response = yield* LLMClient.generate(request).pipe(
1487
+ Effect.provide(
1488
+ fixedResponse(
1489
+ sseEvents(
1490
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1491
+ { type: "future_event", content_block: 42, delta: 42 },
1492
+ { type: "content_block_start", index: 0, content_block: { type: "future_block", text: 42 } },
1493
+ { type: "content_block_delta", index: 0, delta: { text: "ignored" } },
1494
+ { type: "content_block_delta", index: 0, delta: { type: "future_delta", text: 42 } },
1495
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "hidden" } },
1496
+ { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "hidden" } },
1497
+ { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "hidden" } },
1498
+ { type: "content_block_stop", index: 0 },
1499
+ { type: "content_block_start", index: 1, content_block: { type: "text", text: "" } },
1500
+ { type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "Hello" } },
1501
+ { type: "content_block_stop", index: 1 },
1502
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
1503
+ { type: "message_stop" },
1504
+ ),
1505
+ ),
1506
+ ),
1507
+ )
1508
+
1509
+ expect(response.message.content).toEqual([{ type: "text", text: "Hello" }])
1510
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "end_turn" })
1511
+ }),
1512
+ )
1513
+
1514
+ it.effect("rejects malformed recognized content block variants", () =>
1515
+ Effect.gen(function* () {
1516
+ const error = yield* LLMClient.generate(request).pipe(
1517
+ Effect.provide(
1518
+ fixedResponse(
1519
+ sseEvents(
1520
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1521
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: 42 } },
1522
+ ),
1523
+ ),
1524
+ ),
1525
+ Effect.flip,
1526
+ )
1527
+
1528
+ expect(error).toMatchObject({
1529
+ reason: { _tag: "InvalidProviderOutput" },
1530
+ message: "Invalid anthropic/anthropic-messages stream event",
1531
+ })
1532
+ }),
1533
+ )
1534
+
1535
+ it.effect("rejects malformed recognized content delta variants", () =>
1536
+ Effect.gen(function* () {
1537
+ const error = yield* LLMClient.generate(request).pipe(
1538
+ Effect.provide(
1539
+ fixedResponse(
1540
+ sseEvents(
1541
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1542
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
1543
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: 42 } },
1544
+ ),
1545
+ ),
1546
+ ),
1547
+ Effect.flip,
1548
+ )
1549
+
1550
+ expect(error).toMatchObject({
1551
+ reason: { _tag: "InvalidProviderOutput" },
1552
+ message: "Invalid anthropic/anthropic-messages stream event",
1553
+ })
1554
+ }),
1555
+ )
1556
+
1557
+ it.effect("rejects malformed payloads on unrelated stream events", () =>
1558
+ Effect.gen(function* () {
1559
+ const events = [
1560
+ { type: "message_start", message: { usage: { input_tokens: 1 } }, delta: 42 },
1561
+ { type: "content_block_start", index: 0 },
1562
+ { type: "content_block_delta", index: 0 },
1563
+ { type: "content_block_stop", index: 0, content_block: { type: "text", text: 42 } },
1564
+ { type: "message_delta" },
1565
+ { type: "message_delta", delta: { stop_reason: 42 } },
1566
+ { type: "message_stop", delta: { text: 42 } },
1567
+ { type: "error", error: { type: "overloaded_error", message: "busy" }, content_block: 42 },
1568
+ ]
1569
+
1570
+ yield* Effect.forEach(events, (event) =>
1571
+ Effect.gen(function* () {
1572
+ const error = yield* LLMClient.generate(request).pipe(
1573
+ Effect.provide(fixedResponse(sseEvents(event))),
1574
+ Effect.flip,
1575
+ )
1576
+
1577
+ expect(error).toMatchObject({
1578
+ reason: { _tag: "InvalidProviderOutput" },
1579
+ message: "Invalid anthropic/anthropic-messages stream event",
1580
+ })
1581
+ }),
1582
+ )
1583
+ }),
1584
+ )
1585
+
1586
+ it.effect("rejects malformed recognized SSE events", () =>
1587
+ Effect.gen(function* () {
1588
+ const error = yield* LLMClient.generate(request).pipe(
1589
+ Effect.provide(fixedResponse(sseRaw(sseNamedEvent("message_start", "[DONE]")))),
1590
+ Effect.flip,
1591
+ )
1592
+
1593
+ expect(error).toMatchObject({
1594
+ reason: { _tag: "InvalidProviderOutput" },
1595
+ message: "Invalid anthropic/anthropic-messages stream event",
1596
+ })
1597
+ }),
1598
+ )
1599
+
1600
+ it.effect("maps nullable input tokens and preserves unknown Anthropic usage fields", () =>
1601
+ Effect.gen(function* () {
1602
+ const response = yield* LLMClient.generate(request).pipe(
1603
+ Effect.provide(
1604
+ fixedResponse(
1605
+ sseEvents(
1606
+ {
1607
+ type: "message_start",
1608
+ message: {
1609
+ usage: {
1610
+ input_tokens: 5,
1611
+ cache_read_input_tokens: 2,
1612
+ service_tier: "standard",
1613
+ cache_creation: { ephemeral_5m_input_tokens: 1 },
1614
+ server_tool_use: { web_search_requests: 1, start_counter: 2 },
1615
+ output_tokens_details: { thinking_tokens: 3, start_detail: "preserved" },
1616
+ },
1617
+ },
1618
+ },
1619
+ {
1620
+ type: "message_delta",
1621
+ delta: { stop_reason: "end_turn" },
1622
+ usage: {
1623
+ input_tokens: null,
1624
+ output_tokens: 8,
1625
+ server_tool_use: { web_search_requests: 2, terminal_counter: 3 },
1626
+ output_tokens_details: { terminal_detail: "preserved" },
1627
+ future_terminal: { requests: 4 },
1628
+ },
1629
+ },
1630
+ { type: "message_stop" },
1631
+ ),
1632
+ ),
1633
+ ),
1634
+ )
1635
+
1636
+ expect(response.usage).toMatchObject({
1637
+ inputTokens: 7,
1638
+ outputTokens: 8,
1639
+ reasoningTokens: 3,
1640
+ totalTokens: 15,
1641
+ providerMetadata: {
1642
+ anthropic: {
1643
+ input_tokens: null,
1644
+ cache_read_input_tokens: 2,
1645
+ service_tier: "standard",
1646
+ cache_creation: { ephemeral_5m_input_tokens: 1 },
1647
+ server_tool_use: { web_search_requests: 2, start_counter: 2, terminal_counter: 3 },
1648
+ output_tokens: 8,
1649
+ output_tokens_details: {
1650
+ thinking_tokens: 3,
1651
+ start_detail: "preserved",
1652
+ terminal_detail: "preserved",
1653
+ },
1654
+ future_terminal: { requests: 4 },
1655
+ },
1656
+ },
1657
+ })
1658
+ }),
1659
+ )
1660
+
1661
+ it.effect("round-trips omitted thinking carried only by a signature delta", () =>
1662
+ Effect.gen(function* () {
1663
+ const response = yield* LLMClient.generate(request).pipe(
1664
+ Effect.provide(
1665
+ fixedResponse(
1666
+ sseEvents(
1667
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1668
+ {
1669
+ type: "content_block_start",
1670
+ index: 0,
1671
+ content_block: { type: "thinking", thinking: "", signature: "" },
1672
+ },
1673
+ { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "sig_1" } },
1674
+ { type: "content_block_stop", index: 0 },
1675
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
1676
+ { type: "message_stop" },
1677
+ ),
1678
+ ),
1679
+ ),
1680
+ )
1681
+
1682
+ expect(response.message.content).toEqual([
1683
+ { type: "reasoning", text: "", providerMetadata: { anthropic: { signature: "sig_1" } } },
1684
+ ])
1685
+
1686
+ const prepared = yield* compileRequest(ai.request({ model, messages: [response.message], cache: "none" }))
1687
+ expect(prepared.body.messages).toEqual([
1688
+ { role: "assistant", content: [{ type: "thinking", thinking: "", signature: "sig_1" }] },
1689
+ ])
1690
+ }),
1691
+ )
1692
+
1693
+ it.effect("retains a thinking signature supplied in content_block_start", () =>
1694
+ Effect.gen(function* () {
1695
+ const response = yield* LLMClient.generate(request).pipe(
1696
+ Effect.provide(
1697
+ fixedResponse(
1698
+ sseEvents(
1699
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1700
+ {
1701
+ type: "content_block_start",
1702
+ index: 0,
1703
+ content_block: { type: "thinking", thinking: "", signature: "sig_1" },
1704
+ },
1705
+ { type: "content_block_stop", index: 0 },
1706
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
1707
+ { type: "message_stop" },
1708
+ ),
1709
+ ),
1710
+ ),
1711
+ )
1712
+
1713
+ expect(response.message.content).toEqual([
1714
+ { type: "reasoning", text: "", providerMetadata: { anthropic: { signature: "sig_1" } } },
1715
+ ])
1716
+ expect(response.events.find((event) => event.type === "reasoning-end")).toMatchObject({
1717
+ providerMetadata: { anthropic: { signature: "sig_1" } },
1718
+ })
1719
+ }),
1720
+ )
1721
+
1722
+ it.effect("retains complete tool input from content_block_start", () =>
1723
+ Effect.gen(function* () {
1724
+ const response = yield* LLMClient.generate(request).pipe(
1725
+ Effect.provide(
1726
+ fixedResponse(
1727
+ sseEvents(
1728
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1729
+ {
1730
+ type: "content_block_start",
1731
+ index: 0,
1732
+ content_block: { type: "tool_use", id: "call_1", name: "lookup", input: { query: "weather" } },
1733
+ },
1734
+ { type: "content_block_stop", index: 0 },
1735
+ { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
1736
+ { type: "message_stop" },
1737
+ ),
1738
+ ),
1739
+ ),
1740
+ )
1741
+
1742
+ expect(response.toolCalls).toMatchObject([{ id: "call_1", name: "lookup", input: { query: "weather" } }])
1743
+ }),
1744
+ )
1745
+
1746
+ it.effect("retains empty text blocks", () =>
1747
+ Effect.gen(function* () {
1748
+ const response = yield* LLMClient.generate(request).pipe(
1749
+ Effect.provide(
1750
+ fixedResponse(
1751
+ sseEvents(
1752
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1753
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
1754
+ { type: "content_block_stop", index: 0 },
1755
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
1756
+ { type: "message_stop" },
1757
+ ),
1758
+ ),
1759
+ ),
1760
+ )
1761
+
1762
+ expect(response.message.content).toEqual([{ type: "text", text: "" }])
1763
+ }),
1764
+ )
1765
+
1766
+ it.effect("parses redacted thinking into empty reasoning with redactedData metadata", () =>
1767
+ Effect.gen(function* () {
1768
+ const body = sseEvents(
1769
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1770
+ { type: "content_block_start", index: 0, content_block: { type: "redacted_thinking", data: "opaque_1" } },
1771
+ { type: "content_block_stop", index: 0 },
1772
+ { type: "content_block_start", index: 1, content_block: { type: "text", text: "" } },
1773
+ { type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "Hello" } },
1774
+ { type: "content_block_stop", index: 1 },
1775
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } },
1776
+ { type: "message_stop" },
1777
+ )
1778
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
1779
+
1780
+ expect(response.events.find((event) => event.type === "reasoning-start")).toMatchObject({
1781
+ providerMetadata: { anthropic: { redactedData: "opaque_1" } },
1782
+ })
1783
+ expect(response.message.content).toEqual([
1784
+ { type: "reasoning", text: "", providerMetadata: { anthropic: { redactedData: "opaque_1" } } },
1785
+ { type: "text", text: "Hello" },
1786
+ ])
1787
+ }),
1788
+ )
1789
+
1790
+ it.effect("round-trips streamed redacted thinking with tool use into a continuation request", () =>
1791
+ Effect.gen(function* () {
1792
+ // Anthropic types `redacted_thinking.data` as an opaque string. Its
1793
+ // contents are provider-owned and must be replayed without inspection.
1794
+ const redactedData = "cmVkYWN0ZWQtdGhpbmtpbmc="
1795
+ const response = yield* LLMClient.generate({
1796
+ ...request,
1797
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1798
+ }).pipe(
1799
+ Effect.provide(
1800
+ fixedResponse(
1801
+ sseEvents(
1802
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1803
+ {
1804
+ type: "content_block_start",
1805
+ index: 0,
1806
+ content_block: { type: "redacted_thinking", data: redactedData },
1807
+ },
1808
+ { type: "content_block_stop", index: 0 },
1809
+ {
1810
+ type: "content_block_start",
1811
+ index: 1,
1812
+ content_block: { type: "tool_use", id: "call_1", name: "lookup" },
1813
+ },
1814
+ {
1815
+ type: "content_block_delta",
1816
+ index: 1,
1817
+ delta: { type: "input_json_delta", partial_json: '{"query":"weather"}' },
1818
+ },
1819
+ { type: "content_block_stop", index: 1 },
1820
+ { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
1821
+ { type: "message_stop" },
1822
+ ),
1823
+ ),
1824
+ ),
1825
+ )
1826
+ const prepared = yield* compileRequest(
1827
+ ai.request({
1828
+ model,
1829
+ messages: [
1830
+ Message.user("Say hello."),
1831
+ response.message,
1832
+ Message.tool({ id: "call_1", name: "lookup", result: "sunny", resultType: "text" }),
1833
+ ],
1834
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1835
+ cache: "none",
1836
+ }),
1837
+ )
1838
+
1839
+ expect(prepared.body.messages).toEqual([
1840
+ { role: "user", content: [{ type: "text", text: "Say hello." }] },
1841
+ {
1842
+ role: "assistant",
1843
+ content: [
1844
+ { type: "redacted_thinking", data: redactedData },
1845
+ { type: "tool_use", id: "call_1", name: "lookup", input: { query: "weather" } },
1846
+ ],
1847
+ },
1848
+ {
1849
+ role: "user",
1850
+ content: [
1851
+ {
1852
+ type: "tool_result",
1853
+ tool_use_id: "call_1",
1854
+ content: "sunny",
1855
+ is_error: undefined,
1856
+ cache_control: undefined,
1857
+ },
1858
+ ],
1859
+ },
1860
+ ])
1861
+ }),
1862
+ )
1863
+
1864
+ it.effect("maps context-window truncation to length", () =>
1865
+ Effect.gen(function* () {
1866
+ const response = yield* LLMClient.generate(request).pipe(
1867
+ Effect.provide(
1868
+ fixedResponse(
1869
+ sseEvents(
1870
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1871
+ {
1872
+ type: "message_delta",
1873
+ delta: { stop_reason: "model_context_window_exceeded" },
1874
+ usage: { output_tokens: 1 },
1875
+ },
1876
+ { type: "message_stop" },
1877
+ ),
1878
+ ),
1879
+ ),
1880
+ )
1881
+
1882
+ expect(response.finishReason).toEqual({ normalized: "length", raw: "model_context_window_exceeded" })
1883
+ }),
1884
+ )
1885
+
1886
+ it.effect("preserves pause_turn while normalizing it to stop", () =>
1887
+ Effect.gen(function* () {
1888
+ const response = yield* LLMClient.generate(request).pipe(
1889
+ Effect.provide(
1890
+ fixedResponse(
1891
+ sseEvents(
1892
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1893
+ { type: "message_delta", delta: { stop_reason: "pause_turn" }, usage: { output_tokens: 1 } },
1894
+ { type: "message_stop" },
1895
+ ),
1896
+ ),
1897
+ ),
1898
+ )
1899
+
1900
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "pause_turn" })
1901
+ }),
1902
+ )
1903
+
1904
+ it.effect("carries a refusal's category and explanation on the content-filter finish", () =>
1905
+ Effect.gen(function* () {
1906
+ const refusal = (stop_details: unknown) =>
1907
+ LLMClient.generate(request).pipe(
1908
+ Effect.provide(
1909
+ fixedResponse(
1910
+ sseEvents(
1911
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1912
+ { type: "message_delta", delta: { stop_reason: "refusal", stop_details }, usage: { output_tokens: 0 } },
1913
+ { type: "message_stop" },
1914
+ ),
1915
+ ),
1916
+ ),
1917
+ )
1918
+
1919
+ expect(
1920
+ (yield* refusal({
1921
+ type: "refusal",
1922
+ category: "cyber",
1923
+ explanation: "This request was declined because it could enable cyber harm.",
1924
+ })).finishReason,
1925
+ ).toEqual({
1926
+ normalized: "content-filter",
1927
+ raw: "refusal",
1928
+ category: "cyber",
1929
+ explanation: "This request was declined because it could enable cyber harm.",
1930
+ })
1931
+ expect((yield* refusal({ type: "refusal", category: null, explanation: null })).finishReason).toEqual({
1932
+ normalized: "content-filter",
1933
+ raw: "refusal",
1934
+ })
1935
+ }),
1936
+ )
1937
+
1938
+ it.effect("assembles streamed tool call input", () =>
1939
+ Effect.gen(function* () {
1940
+ const body = sseEvents(
1941
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
1942
+ { type: "content_block_start", index: 0, content_block: { type: "tool_use", id: "call_1", name: "lookup" } },
1943
+ { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query"' } },
1944
+ { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: ':"weather"}' } },
1945
+ { type: "content_block_stop", index: 0 },
1946
+ { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
1947
+ { type: "message_stop" },
1948
+ )
1949
+ const response = yield* LLMClient.generate({
1950
+ ...request,
1951
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1952
+ }).pipe(Effect.provide(fixedResponse(body)))
1953
+ const usage = new Usage({
1954
+ inputTokens: 5,
1955
+ outputTokens: 1,
1956
+ nonCachedInputTokens: 5,
1957
+ cacheReadInputTokens: undefined,
1958
+ cacheWriteInputTokens: undefined,
1959
+ totalTokens: 6,
1960
+ providerMetadata: { anthropic: { input_tokens: 5, output_tokens: 1 } },
1961
+ })
1962
+
1963
+ expect(response.toolCalls).toEqual([
1964
+ {
1965
+ type: "tool-call",
1966
+ id: "call_1",
1967
+ name: "lookup",
1968
+ input: { query: "weather" },
1969
+ providerExecuted: undefined,
1970
+ providerMetadata: undefined,
1971
+ },
1972
+ ])
1973
+ expect(response.events).toEqual([
1974
+ { type: "step-start", index: 0 },
1975
+ { type: "tool-input-start", id: "call_1", name: "lookup" },
1976
+ { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"', input: {} },
1977
+ {
1978
+ type: "tool-input-delta",
1979
+ id: "call_1",
1980
+ name: "lookup",
1981
+ text: ':"weather"}',
1982
+ input: { query: "weather" },
1983
+ },
1984
+ { type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
1985
+ {
1986
+ type: "tool-call",
1987
+ id: "call_1",
1988
+ name: "lookup",
1989
+ input: { query: "weather" },
1990
+ providerExecuted: undefined,
1991
+ providerMetadata: undefined,
1992
+ },
1993
+ {
1994
+ type: "step-finish",
1995
+ index: 0,
1996
+ reason: { normalized: "tool-calls", raw: "tool_use" },
1997
+ usage,
1998
+ providerMetadata: undefined,
1999
+ },
2000
+ {
2001
+ type: "finish",
2002
+ reason: { normalized: "tool-calls", raw: "tool_use" },
2003
+ providerMetadata: undefined,
2004
+ usage,
2005
+ },
2006
+ ])
2007
+ }),
2008
+ )
2009
+
2010
+ it.effect("ignores tool input deltas without a matching tool start", () =>
2011
+ Effect.gen(function* () {
2012
+ const response = yield* LLMClient.generate(request).pipe(
2013
+ Effect.provide(
2014
+ fixedResponse(
2015
+ sseEvents(
2016
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
2017
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
2018
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } },
2019
+ {
2020
+ type: "content_block_delta",
2021
+ index: 1,
2022
+ delta: { type: "input_json_delta", partial_json: '{"query":"orphaned"}' },
2023
+ },
2024
+ { type: "content_block_stop", index: 0 },
2025
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
2026
+ { type: "message_stop" },
2027
+ ),
2028
+ ),
2029
+ ),
2030
+ )
2031
+
2032
+ expect(response.text).toBe("Hello")
2033
+ expect(response.toolCalls).toEqual([])
2034
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "end_turn" })
2035
+ }),
2036
+ )
2037
+
2038
+ it.effect("settles pending tool calls at message_stop", () =>
2039
+ Effect.gen(function* () {
2040
+ const response = yield* LLMClient.generate(request).pipe(
2041
+ Effect.provide(
2042
+ fixedResponse(
2043
+ sseEvents(
2044
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
2045
+ {
2046
+ type: "content_block_start",
2047
+ index: 0,
2048
+ content_block: { type: "tool_use", id: "call_1", name: "lookup" },
2049
+ },
2050
+ {
2051
+ type: "content_block_delta",
2052
+ index: 0,
2053
+ delta: { type: "input_json_delta", partial_json: '{"query":"weather"}' },
2054
+ },
2055
+ { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
2056
+ { type: "message_stop" },
2057
+ ),
2058
+ ),
2059
+ ),
2060
+ )
2061
+
2062
+ expect(response.toolCalls).toMatchObject([{ id: "call_1", name: "lookup", input: { query: "weather" } }])
2063
+ expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: "tool_use" })
2064
+ }),
2065
+ )
2066
+
2067
+ it.effect("assembles and persists multiple tool calls from one Anthropic response", () =>
2068
+ Effect.gen(function* () {
2069
+ const response = yield* LLMClient.generate(request).pipe(
2070
+ Effect.provide(
2071
+ fixedResponse(
2072
+ sseEvents(
2073
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
2074
+ {
2075
+ type: "content_block_start",
2076
+ index: 0,
2077
+ content_block: { type: "tool_use", id: "call_paris", name: "weather", input: {} },
2078
+ },
2079
+ {
2080
+ type: "content_block_delta",
2081
+ index: 0,
2082
+ delta: { type: "input_json_delta", partial_json: '{"city":"Paris"}' },
2083
+ },
2084
+ { type: "content_block_stop", index: 0 },
2085
+ {
2086
+ type: "content_block_start",
2087
+ index: 1,
2088
+ content_block: { type: "tool_use", id: "call_london", name: "weather", input: {} },
2089
+ },
2090
+ {
2091
+ type: "content_block_delta",
2092
+ index: 1,
2093
+ delta: { type: "input_json_delta", partial_json: '{"city":"London"}' },
2094
+ },
2095
+ { type: "content_block_stop", index: 1 },
2096
+ { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 2 } },
2097
+ { type: "message_stop" },
2098
+ ),
2099
+ ),
2100
+ ),
2101
+ )
2102
+
2103
+ expect(response.toolCalls).toMatchObject([
2104
+ { id: "call_paris", name: "weather", input: { city: "Paris" } },
2105
+ { id: "call_london", name: "weather", input: { city: "London" } },
2106
+ ])
2107
+ expect(response.message.content).toMatchObject([
2108
+ { type: "tool-call", id: "call_paris", name: "weather", input: { city: "Paris" } },
2109
+ { type: "tool-call", id: "call_london", name: "weather", input: { city: "London" } },
2110
+ ])
2111
+ expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: "tool_use" })
2112
+ }),
2113
+ )
2114
+
2115
+ it.effect("keeps malformed server tool input terminal", () =>
2116
+ Effect.gen(function* () {
2117
+ const body = sseEvents(
2118
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
2119
+ {
2120
+ type: "content_block_start",
2121
+ index: 0,
2122
+ content_block: { type: "server_tool_use", id: "call_1", name: "web_search" },
2123
+ },
2124
+ {
2125
+ type: "content_block_delta",
2126
+ index: 0,
2127
+ delta: { type: "input_json_delta", partial_json: '{"query":"partial' },
2128
+ },
2129
+ { type: "content_block_stop", index: 0 },
2130
+ )
2131
+
2132
+ const error = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
2133
+
2134
+ expect(error).toBeInstanceOf(AIError)
2135
+ expect(error.message).toContain("Invalid JSON input for anthropic-messages tool call web_search")
2136
+ }),
2137
+ )
2138
+
2139
+ it.effect("fails with a typed provider error for stream error frames", () =>
2140
+ Effect.gen(function* () {
2141
+ const error = yield* LLMClient.generate(request).pipe(
2142
+ Effect.provide(
2143
+ fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "Overloaded" } })),
2144
+ ),
2145
+ Effect.flip,
2146
+ )
2147
+
2148
+ expect(error).toMatchObject({ reason: { _tag: "ProviderInternal" }, message: "overloaded_error: Overloaded" })
2149
+ }),
2150
+ )
2151
+
2152
+ it.effect("ignores untyped stream frames but reads untyped error envelopes as errors", () =>
2153
+ Effect.gen(function* () {
2154
+ const response = yield* LLMClient.generate(request).pipe(
2155
+ Effect.provide(
2156
+ fixedResponse(
2157
+ sseEvents(
2158
+ {},
2159
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
2160
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
2161
+ { gateway: "keep-alive" },
2162
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "OK" } },
2163
+ { type: "content_block_stop", index: 0 },
2164
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
2165
+ { type: "message_stop" },
2166
+ ),
2167
+ ),
2168
+ ),
2169
+ )
2170
+ expect(response.text).toBe("OK")
2171
+
2172
+ const error = yield* LLMClient.generate(request).pipe(
2173
+ Effect.provide(fixedResponse(sseEvents({ error: { type: "overloaded_error", message: "Overloaded" } }))),
2174
+ Effect.flip,
2175
+ )
2176
+ expect(error).toMatchObject({ reason: { _tag: "ProviderInternal" }, message: "overloaded_error: Overloaded" })
2177
+ }),
2178
+ )
2179
+
2180
+ it.effect("classifies prompt-too-long provider errors", () =>
2181
+ Effect.gen(function* () {
2182
+ const error = yield* LLMClient.generate(request).pipe(
2183
+ Effect.provide(
2184
+ fixedResponse(
2185
+ sseEvents({
2186
+ type: "error",
2187
+ error: { type: "invalid_request_error", message: "prompt is too long: 210000 tokens" },
2188
+ }),
2189
+ ),
2190
+ ),
2191
+ Effect.flip,
2192
+ )
2193
+
2194
+ expect(error).toMatchObject({
2195
+ reason: { _tag: "InvalidRequest", classification: "context-overflow" },
2196
+ message: "invalid_request_error: prompt is too long: 210000 tokens",
2197
+ })
2198
+ }),
2199
+ )
2200
+
2201
+ it.effect("falls back to error type when no message is present", () =>
2202
+ Effect.gen(function* () {
2203
+ const error = yield* LLMClient.generate(request).pipe(
2204
+ Effect.provide(fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "" } }))),
2205
+ Effect.flip,
2206
+ )
2207
+
2208
+ expect(error).toMatchObject({ reason: { _tag: "ProviderInternal" }, message: "overloaded_error" })
2209
+ }),
2210
+ )
2211
+
2212
+ it.effect("falls back to a stable default when error payload is absent", () =>
2213
+ Effect.gen(function* () {
2214
+ const error = yield* LLMClient.generate(request).pipe(
2215
+ Effect.provide(fixedResponse(sseEvents({ type: "error" }))),
2216
+ Effect.flip,
2217
+ )
2218
+
2219
+ expect(error).toMatchObject({ reason: { _tag: "UnknownProvider" }, message: "Anthropic Messages stream error" })
2220
+ }),
2221
+ )
2222
+
2223
+ it.effect("fails HTTP provider errors before stream parsing", () =>
2224
+ Effect.gen(function* () {
2225
+ const error = yield* LLMClient.generate(request).pipe(
2226
+ Effect.provide(
2227
+ fixedResponse('{"type":"error","error":{"type":"invalid_request_error","message":"Bad request"}}', {
2228
+ status: 400,
2229
+ headers: { "content-type": "application/json" },
2230
+ }),
2231
+ ),
2232
+ Effect.flip,
2233
+ )
2234
+
2235
+ expect(error).toBeInstanceOf(AIError)
2236
+ expect(error).toMatchObject({ reason: { _tag: "InvalidRequest" }, message: "Bad request" })
2237
+ }),
2238
+ )
2239
+
2240
+ it.effect("decodes server_tool_use + web_search_tool_result as provider-executed events", () =>
2241
+ Effect.gen(function* () {
2242
+ const body = sseEvents(
2243
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
2244
+ {
2245
+ type: "content_block_start",
2246
+ index: 0,
2247
+ content_block: { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search" },
2248
+ },
2249
+ {
2250
+ type: "content_block_delta",
2251
+ index: 0,
2252
+ delta: { type: "input_json_delta", partial_json: '{"query":"effect 4"}' },
2253
+ },
2254
+ { type: "content_block_stop", index: 0 },
2255
+ {
2256
+ type: "content_block_start",
2257
+ index: 1,
2258
+ content_block: {
2259
+ type: "web_search_tool_result",
2260
+ tool_use_id: "srvtoolu_abc",
2261
+ content: [{ type: "web_search_result", url: "https://example.com", title: "Example" }],
2262
+ },
2263
+ },
2264
+ { type: "content_block_stop", index: 1 },
2265
+ { type: "content_block_start", index: 2, content_block: { type: "text", text: "" } },
2266
+ { type: "content_block_delta", index: 2, delta: { type: "text_delta", text: "Found it." } },
2267
+ { type: "content_block_stop", index: 2 },
2268
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 8 } },
2269
+ { type: "message_stop" },
2270
+ )
2271
+ const response = yield* LLMClient.generate({
2272
+ ...request,
2273
+ tools: [
2274
+ ToolDefinition.make({ name: "web_search", description: "Web search", inputSchema: { type: "object" } }),
2275
+ ],
2276
+ }).pipe(Effect.provide(fixedResponse(body)))
2277
+
2278
+ const toolCall = response.events.find((event) => event.type === "tool-call")
2279
+ expect(toolCall).toEqual({
2280
+ type: "tool-call",
2281
+ id: "srvtoolu_abc",
2282
+ name: "web_search",
2283
+ input: { query: "effect 4" },
2284
+ providerExecuted: true,
2285
+ })
2286
+ const toolResult = response.events.find((event) => event.type === "tool-result")
2287
+ expect(toolResult).toEqual({
2288
+ type: "tool-result",
2289
+ id: "srvtoolu_abc",
2290
+ name: "web_search",
2291
+ result: { type: "json", value: [{ type: "web_search_result", url: "https://example.com", title: "Example" }] },
2292
+ providerExecuted: true,
2293
+ // The complete payload rides in provider metadata as irreducible replay
2294
+ // state for later stateless requests.
2295
+ providerMetadata: {
2296
+ anthropic: {
2297
+ blockType: "web_search_tool_result",
2298
+ result: [{ type: "web_search_result", url: "https://example.com", title: "Example" }],
2299
+ },
2300
+ },
2301
+ })
2302
+ expect(response.text).toBe("Found it.")
2303
+ expect(response.events.at(-1)).toMatchObject({
2304
+ type: "finish",
2305
+ reason: { normalized: "stop", raw: "end_turn" },
2306
+ })
2307
+ }),
2308
+ )
2309
+
2310
+ it.effect("decodes web_search_tool_result_error as provider-executed error result", () =>
2311
+ Effect.gen(function* () {
2312
+ const body = sseEvents(
2313
+ { type: "message_start", message: { usage: { input_tokens: 5 } } },
2314
+ {
2315
+ type: "content_block_start",
2316
+ index: 0,
2317
+ content_block: { type: "server_tool_use", id: "srvtoolu_x", name: "web_search" },
2318
+ },
2319
+ { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query":"q"}' } },
2320
+ { type: "content_block_stop", index: 0 },
2321
+ {
2322
+ type: "content_block_start",
2323
+ index: 1,
2324
+ content_block: {
2325
+ type: "web_search_tool_result",
2326
+ tool_use_id: "srvtoolu_x",
2327
+ content: { type: "web_search_tool_result_error", error_code: "max_uses_exceeded" },
2328
+ },
2329
+ },
2330
+ { type: "content_block_stop", index: 1 },
2331
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
2332
+ { type: "message_stop" },
2333
+ )
2334
+ const response = yield* LLMClient.generate({
2335
+ ...request,
2336
+ tools: [
2337
+ ToolDefinition.make({ name: "web_search", description: "Web search", inputSchema: { type: "object" } }),
2338
+ ],
2339
+ }).pipe(Effect.provide(fixedResponse(body)))
2340
+
2341
+ const toolResult = response.events.find((event) => event.type === "tool-result")
2342
+ expect(toolResult).toMatchObject({
2343
+ type: "tool-result",
2344
+ id: "srvtoolu_x",
2345
+ name: "web_search",
2346
+ result: { type: "error" },
2347
+ providerExecuted: true,
2348
+ })
2349
+ }),
2350
+ )
2351
+
2352
+ it.effect("round-trips provider-executed assistant content into server tool blocks", () =>
2353
+ Effect.gen(function* () {
2354
+ const prepared = yield* compileRequest(
2355
+ ai.request({
2356
+ id: "req_round_trip",
2357
+ model,
2358
+ messages: [
2359
+ Message.user("Search for something."),
2360
+ Message.assistant([
2361
+ {
2362
+ type: "tool-call",
2363
+ id: "srvtoolu.abc",
2364
+ name: "web_search",
2365
+ input: { query: "effect 4" },
2366
+ providerExecuted: true,
2367
+ },
2368
+ {
2369
+ type: "tool-result",
2370
+ id: "srvtoolu.abc",
2371
+ name: "web_search",
2372
+ result: { type: "json", value: [{ url: "https://example.com" }] },
2373
+ providerExecuted: true,
2374
+ },
2375
+ { type: "text", text: "Found it." },
2376
+ ]),
2377
+ Message.user("Thanks."),
2378
+ ],
2379
+ }),
2380
+ )
2381
+
2382
+ expect(prepared.body).toMatchObject({
2383
+ messages: [
2384
+ { role: "user", content: [{ type: "text", text: "Search for something." }] },
2385
+ {
2386
+ role: "assistant",
2387
+ content: [
2388
+ { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search", input: { query: "effect 4" } },
2389
+ {
2390
+ type: "web_search_tool_result",
2391
+ tool_use_id: "srvtoolu_abc",
2392
+ content: [{ url: "https://example.com" }],
2393
+ },
2394
+ { type: "text", text: "Found it." },
2395
+ ],
2396
+ },
2397
+ { role: "user", content: [{ type: "text", text: "Thanks." }] },
2398
+ ],
2399
+ })
2400
+ }),
2401
+ )
2402
+
2403
+ it.effect("rejects round-trip for unknown server tool names", () =>
2404
+ Effect.gen(function* () {
2405
+ const error = yield* compileRequest(
2406
+ ai.request({
2407
+ id: "req_unknown_server_tool",
2408
+ model,
2409
+ messages: [
2410
+ Message.assistant([
2411
+ {
2412
+ type: "tool-result",
2413
+ id: "srvtoolu_abc",
2414
+ name: "future_server_tool",
2415
+ result: { type: "json", value: {} },
2416
+ providerExecuted: true,
2417
+ },
2418
+ ]),
2419
+ ],
2420
+ }),
2421
+ ).pipe(Effect.flip)
2422
+
2423
+ expect(error.message).toContain("future_server_tool")
2424
+ }),
2425
+ )
2426
+
2427
+ it.effect("continues a conversation with user media content", () =>
2428
+ Effect.gen(function* () {
2429
+ const response = yield* LLMClient.generate(
2430
+ ai.request({
2431
+ id: "req_media",
2432
+ model,
2433
+ messages: [
2434
+ Message.user([
2435
+ { type: "text", text: "What is in this image?" },
2436
+ { type: "media", media: Media.base64("AAECAw==", "image/png") },
2437
+ { type: "media", media: Media.base64("JVBERi0xLjQ=", "application/pdf"), filename: "report.pdf" },
2438
+ ]),
2439
+ ],
2440
+ }),
2441
+ ).pipe(
2442
+ Effect.provide(
2443
+ dynamicResponse((input) =>
2444
+ Effect.gen(function* () {
2445
+ const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
2446
+ expect(yield* Effect.promise(() => web.json())).toMatchObject({
2447
+ messages: [
2448
+ {
2449
+ role: "user",
2450
+ content: [
2451
+ { type: "text", text: "What is in this image?" },
2452
+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
2453
+ {
2454
+ type: "document",
2455
+ source: { type: "base64", media_type: "application/pdf", data: "JVBERi0xLjQ=" },
2456
+ },
2457
+ ],
2458
+ },
2459
+ ],
2460
+ })
2461
+ return input.respond(
2462
+ sseEvents(
2463
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
2464
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "An image." } },
2465
+ { type: "content_block_stop", index: 0 },
2466
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 3 } },
2467
+ { type: "message_stop" },
2468
+ ),
2469
+ { headers: { "content-type": "text/event-stream" } },
2470
+ )
2471
+ }),
2472
+ ),
2473
+ ),
2474
+ )
2475
+
2476
+ expect(response.text).toBe("An image.")
2477
+ }),
2478
+ )
2479
+
2480
+ it.effect("sends the hint ttl on cache_control", () =>
2481
+ Effect.gen(function* () {
2482
+ const prepared = yield* compileRequest(
2483
+ ai.request({
2484
+ model,
2485
+ system: { type: "text", text: "system", cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) },
2486
+ prompt: "hi",
2487
+ }),
2488
+ )
2489
+
2490
+ expect(prepared.body).toMatchObject({
2491
+ system: [{ type: "text", text: "system", cache_control: { type: "ephemeral", ttl: "1h" } }],
2492
+ })
2493
+ }),
2494
+ )
2495
+
2496
+ it.effect("emits cache_control on tool definitions and tool-result blocks", () =>
2497
+ Effect.gen(function* () {
2498
+ const prepared = yield* compileRequest(
2499
+ ai.request({
2500
+ model,
2501
+ tools: [
2502
+ {
2503
+ name: "lookup",
2504
+ description: "lookup tool",
2505
+ inputSchema: { type: "object", properties: {} },
2506
+ cache: new CacheHint({ type: "ephemeral" }),
2507
+ },
2508
+ ],
2509
+ messages: [
2510
+ Message.user("What's the weather?"),
2511
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
2512
+ Message.tool({
2513
+ id: "call_1",
2514
+ name: "lookup",
2515
+ result: { temp: 72 },
2516
+ cache: new CacheHint({ type: "ephemeral" }),
2517
+ }),
2518
+ ],
2519
+ }),
2520
+ )
2521
+
2522
+ expect(prepared.body).toMatchObject({
2523
+ tools: [{ name: "lookup", cache_control: { type: "ephemeral" } }],
2524
+ messages: [
2525
+ { role: "user", content: [{ type: "text", text: "What's the weather?" }] },
2526
+ { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "lookup" }] },
2527
+ {
2528
+ role: "user",
2529
+ content: [{ type: "tool_result", tool_use_id: "call_1", cache_control: { type: "ephemeral" } }],
2530
+ },
2531
+ ],
2532
+ })
2533
+ }),
2534
+ )
2535
+
2536
+ it.effect("drops cache_control breakpoints past the 4-per-request cap", () =>
2537
+ Effect.gen(function* () {
2538
+ const hint = new CacheHint({ type: "ephemeral" })
2539
+ const prepared = yield* compileRequest(
2540
+ ai.request({
2541
+ model,
2542
+ system: [
2543
+ { type: "text", text: "a", cache: hint },
2544
+ { type: "text", text: "b", cache: hint },
2545
+ { type: "text", text: "c", cache: hint },
2546
+ { type: "text", text: "d", cache: hint },
2547
+ { type: "text", text: "e", cache: hint },
2548
+ { type: "text", text: "f", cache: hint },
2549
+ ],
2550
+ prompt: "hi",
2551
+ }),
2552
+ )
2553
+
2554
+ const system = (prepared.body as { system: Array<{ cache_control?: unknown }> }).system
2555
+ const marked = system.filter((part) => part.cache_control !== undefined)
2556
+ expect(marked).toHaveLength(4)
2557
+ expect(system[4]?.cache_control).toBeUndefined()
2558
+ expect(system[5]?.cache_control).toBeUndefined()
2559
+ }),
2560
+ )
2561
+
2562
+ it.effect("spends breakpoint budget on tools before system before messages", () =>
2563
+ Effect.gen(function* () {
2564
+ const hint = new CacheHint({ type: "ephemeral" })
2565
+ const prepared = yield* compileRequest(
2566
+ ai.request({
2567
+ model,
2568
+ tools: [
2569
+ {
2570
+ name: "t1",
2571
+ description: "t1",
2572
+ inputSchema: { type: "object", properties: {} },
2573
+ cache: hint,
2574
+ },
2575
+ {
2576
+ name: "t2",
2577
+ description: "t2",
2578
+ inputSchema: { type: "object", properties: {} },
2579
+ cache: hint,
2580
+ },
2581
+ {
2582
+ name: "t3",
2583
+ description: "t3",
2584
+ inputSchema: { type: "object", properties: {} },
2585
+ cache: hint,
2586
+ },
2587
+ {
2588
+ name: "t4",
2589
+ description: "t4",
2590
+ inputSchema: { type: "object", properties: {} },
2591
+ cache: hint,
2592
+ },
2593
+ ],
2594
+ system: [{ type: "text", text: "system-tail", cache: hint }],
2595
+ messages: [Message.user([{ type: "text", text: "message-tail", cache: hint }])],
2596
+ }),
2597
+ )
2598
+
2599
+ const body = prepared.body as {
2600
+ tools: Array<{ cache_control?: unknown }>
2601
+ system: Array<{ cache_control?: unknown }>
2602
+ messages: Array<{ content: Array<{ cache_control?: unknown }> }>
2603
+ }
2604
+ expect(body.tools.every((t) => t.cache_control !== undefined)).toBe(true)
2605
+ expect(body.system[0]?.cache_control).toBeUndefined()
2606
+ expect(body.messages[0]?.content[0]?.cache_control).toBeUndefined()
2607
+ }),
2608
+ )
2609
+ })