@zyro-sec/ai 1.0.0 → 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 (827) hide show
  1. package/AGENTS.md +23 -0
  2. package/example/tutorial.ts +284 -0
  3. package/package.json +11 -166
  4. package/script/pack.ts +5 -0
  5. package/script/recording-cost-report.ts +250 -0
  6. package/script/setup-recording-env.ts +602 -0
  7. package/src/ai-client.ts +28 -0
  8. package/src/cache-policy.ts +249 -0
  9. package/src/decision-client.ts +88 -0
  10. package/src/decision.ts +335 -0
  11. package/src/effect.ts +44 -0
  12. package/src/effort-updates.ts +25 -0
  13. package/src/embedding-client.ts +46 -0
  14. package/src/embedding.ts +167 -0
  15. package/src/experimental/cloudflare-run-extraction.ts +112 -0
  16. package/src/experimental/extraction.ts +190 -0
  17. package/src/experimental/realtime.ts +211 -0
  18. package/src/experimental.ts +51 -0
  19. package/src/generation.ts +210 -0
  20. package/src/image-client.ts +89 -0
  21. package/src/image.ts +236 -0
  22. package/src/index.ts +363 -0
  23. package/src/llm.ts +364 -0
  24. package/src/loop.ts +214 -0
  25. package/src/media-client.ts +94 -0
  26. package/src/media-model.ts +129 -0
  27. package/src/media.ts +408 -0
  28. package/src/protocols/alibaba-chat.ts +95 -0
  29. package/src/protocols/alibaba-images.ts +126 -0
  30. package/src/protocols/alibaba-messages.ts +49 -0
  31. package/src/protocols/alibaba-responses.ts +86 -0
  32. package/src/protocols/anthropic-messages.ts +1664 -0
  33. package/src/protocols/assemblyai-transcription.ts +209 -0
  34. package/src/protocols/bedrock-converse.ts +984 -0
  35. package/src/protocols/bedrock-event-stream.ts +147 -0
  36. package/src/protocols/cartesia-speech.ts +182 -0
  37. package/src/protocols/cloudflare-run-decisions.ts +55 -0
  38. package/src/protocols/cloudflare-workers-ai-images.ts +124 -0
  39. package/src/protocols/cohere-chat.ts +353 -0
  40. package/src/protocols/deepgram-speech.ts +148 -0
  41. package/src/protocols/deepgram-transcription.ts +179 -0
  42. package/src/protocols/elevenlabs-speech.ts +207 -0
  43. package/src/protocols/elevenlabs-transcription.ts +211 -0
  44. package/src/protocols/gemini.ts +908 -0
  45. package/src/protocols/google-decisions.ts +179 -0
  46. package/src/protocols/google-embed-content.ts +165 -0
  47. package/src/protocols/google-images.ts +255 -0
  48. package/src/protocols/google-interactions-video.ts +264 -0
  49. package/src/protocols/google-interactions.ts +904 -0
  50. package/src/protocols/google-speech.ts +157 -0
  51. package/src/protocols/google-transcription.ts +206 -0
  52. package/src/protocols/google-vertex-predict-embeddings.ts +104 -0
  53. package/src/protocols/index.ts +21 -0
  54. package/src/protocols/meta-images.ts +162 -0
  55. package/src/protocols/meta-messages.ts +67 -0
  56. package/src/protocols/meta-responses.ts +249 -0
  57. package/src/protocols/minimax-images.ts +215 -0
  58. package/src/protocols/minimax-video.ts +406 -0
  59. package/src/protocols/mistral-chat.ts +768 -0
  60. package/src/protocols/open-responses-channel.ts +198 -0
  61. package/src/protocols/open-responses-continuation.ts +218 -0
  62. package/src/protocols/open-responses.ts +1636 -0
  63. package/src/protocols/openai-chat.ts +1431 -0
  64. package/src/protocols/openai-compatible-chat.ts +22 -0
  65. package/src/protocols/openai-compatible-responses.ts +21 -0
  66. package/src/protocols/openai-decisions.ts +174 -0
  67. package/src/protocols/openai-embeddings.ts +105 -0
  68. package/src/protocols/openai-freeform.ts +287 -0
  69. package/src/protocols/openai-images.ts +442 -0
  70. package/src/protocols/openai-responses.ts +442 -0
  71. package/src/protocols/openai-speech.ts +164 -0
  72. package/src/protocols/openai-transcription.ts +295 -0
  73. package/src/protocols/openrouter-video.ts +215 -0
  74. package/src/protocols/seedance-video.ts +301 -0
  75. package/src/protocols/shared.ts +552 -0
  76. package/src/protocols/system-one.ts +335 -0
  77. package/src/protocols/utils/bedrock-auth.ts +147 -0
  78. package/src/protocols/utils/bedrock-cache.ts +56 -0
  79. package/src/protocols/utils/bedrock-media.ts +121 -0
  80. package/src/protocols/utils/cache.ts +44 -0
  81. package/src/protocols/utils/claude-model.ts +19 -0
  82. package/src/protocols/utils/gateway-protocol.ts +92 -0
  83. package/src/protocols/utils/gemini-generate-content.ts +172 -0
  84. package/src/protocols/utils/gemini-json-schema.ts +77 -0
  85. package/src/protocols/utils/image-sizing.ts +117 -0
  86. package/src/protocols/utils/lifecycle.ts +120 -0
  87. package/src/protocols/utils/media-input.ts +98 -0
  88. package/src/protocols/utils/mistral-tool-id.ts +34 -0
  89. package/src/protocols/utils/open-responses-options.ts +82 -0
  90. package/src/protocols/utils/partial-json-options.ts +62 -0
  91. package/src/protocols/utils/partial-json.ts +283 -0
  92. package/src/protocols/utils/responses-checkpoint.ts +115 -0
  93. package/src/protocols/utils/responses-compaction.ts +210 -0
  94. package/src/protocols/utils/responses-hosted-tools.ts +104 -0
  95. package/src/protocols/utils/speaker-turns.ts +10 -0
  96. package/src/protocols/utils/speech-stream.ts +111 -0
  97. package/src/protocols/utils/tool-schema.ts +115 -0
  98. package/src/protocols/utils/tool-stream.ts +240 -0
  99. package/src/protocols/venice-chat.ts +356 -0
  100. package/src/protocols/xai-images.ts +137 -0
  101. package/src/protocols/xai-responses.ts +106 -0
  102. package/src/protocols/xai-video.ts +232 -0
  103. package/src/protocols/zai-chat.ts +71 -0
  104. package/src/protocols/zai-images.ts +120 -0
  105. package/src/protocols/zai-messages.ts +34 -0
  106. package/src/protocols.ts +1 -0
  107. package/src/provider-error.ts +291 -0
  108. package/src/provider-package.ts +32 -0
  109. package/src/providers/alibaba/chat.ts +1 -0
  110. package/src/providers/alibaba/embeddings.ts +2 -0
  111. package/src/providers/alibaba/images.ts +2 -0
  112. package/src/providers/alibaba/messages.ts +3 -0
  113. package/src/providers/alibaba/responses.ts +3 -0
  114. package/src/providers/alibaba.ts +177 -0
  115. package/src/providers/amazon-bedrock/mantle/chat.ts +2 -0
  116. package/src/providers/amazon-bedrock/mantle/messages.ts +2 -0
  117. package/src/providers/amazon-bedrock/mantle/responses.ts +2 -0
  118. package/src/providers/amazon-bedrock/mantle.ts +2 -0
  119. package/src/providers/amazon-bedrock-mantle.ts +192 -0
  120. package/src/providers/amazon-bedrock.ts +81 -0
  121. package/src/providers/anthropic-compatible.ts +80 -0
  122. package/src/providers/anthropic.ts +66 -0
  123. package/src/providers/assemblyai.ts +32 -0
  124. package/src/providers/azure/chat.ts +2 -0
  125. package/src/providers/azure/embeddings.ts +2 -0
  126. package/src/providers/azure/images.ts +2 -0
  127. package/src/providers/azure/messages.ts +2 -0
  128. package/src/providers/azure/responses.ts +2 -0
  129. package/src/providers/azure.ts +240 -0
  130. package/src/providers/baseten/decisions.ts +2 -0
  131. package/src/providers/baseten.ts +88 -0
  132. package/src/providers/byteplus/videos.ts +2 -0
  133. package/src/providers/byteplus.ts +39 -0
  134. package/src/providers/cartesia.ts +28 -0
  135. package/src/providers/cerebras.ts +56 -0
  136. package/src/providers/cloudflare-ai-gateway/decisions.ts +2 -0
  137. package/src/providers/cloudflare-ai-gateway.ts +199 -0
  138. package/src/providers/cloudflare-shared.ts +29 -0
  139. package/src/providers/cloudflare-workers-ai/decisions.ts +2 -0
  140. package/src/providers/cloudflare-workers-ai/images.ts +2 -0
  141. package/src/providers/cloudflare-workers-ai.ts +104 -0
  142. package/src/providers/cohere/chat.ts +8 -0
  143. package/src/providers/cohere/embeddings.ts +2 -0
  144. package/src/providers/cohere.ts +72 -0
  145. package/src/providers/deepgram.ts +33 -0
  146. package/src/providers/deepinfra/embeddings.ts +2 -0
  147. package/src/providers/deepinfra.ts +76 -0
  148. package/src/providers/deepseek.ts +54 -0
  149. package/src/providers/digitalocean/decisions.ts +2 -0
  150. package/src/providers/digitalocean/embeddings.ts +2 -0
  151. package/src/providers/digitalocean/images.ts +2 -0
  152. package/src/providers/digitalocean/responses.ts +4 -0
  153. package/src/providers/digitalocean.ts +144 -0
  154. package/src/providers/elevenlabs.ts +35 -0
  155. package/src/providers/fireworks/embeddings.ts +2 -0
  156. package/src/providers/fireworks.ts +66 -0
  157. package/src/providers/google/decisions.ts +2 -0
  158. package/src/providers/google/embeddings.ts +2 -0
  159. package/src/providers/google/images.ts +2 -0
  160. package/src/providers/google/interactions.ts +13 -0
  161. package/src/providers/google/videos.ts +2 -0
  162. package/src/providers/google-vertex/chat.ts +2 -0
  163. package/src/providers/google-vertex/embeddings.ts +2 -0
  164. package/src/providers/google-vertex/gemini.ts +2 -0
  165. package/src/providers/google-vertex/images.ts +2 -0
  166. package/src/providers/google-vertex/interactions.ts +2 -0
  167. package/src/providers/google-vertex/messages.ts +2 -0
  168. package/src/providers/google-vertex/mistral.ts +2 -0
  169. package/src/providers/google-vertex/responses.ts +2 -0
  170. package/src/providers/google-vertex-chat.ts +63 -0
  171. package/src/providers/google-vertex-interactions.ts +104 -0
  172. package/src/providers/google-vertex-messages.ts +99 -0
  173. package/src/providers/google-vertex-mistral.ts +79 -0
  174. package/src/providers/google-vertex-responses.ts +64 -0
  175. package/src/providers/google-vertex-shared.ts +176 -0
  176. package/src/providers/google-vertex.ts +228 -0
  177. package/src/providers/google.ts +121 -0
  178. package/src/providers/groq.ts +98 -0
  179. package/src/providers/index.ts +45 -0
  180. package/src/providers/meta/chat.ts +2 -0
  181. package/src/providers/meta/images.ts +2 -0
  182. package/src/providers/meta/messages.ts +2 -0
  183. package/src/providers/meta/responses.ts +2 -0
  184. package/src/providers/meta.ts +161 -0
  185. package/src/providers/minimax/chat.ts +8 -0
  186. package/src/providers/minimax/images.ts +4 -0
  187. package/src/providers/minimax/messages.ts +1 -0
  188. package/src/providers/minimax/responses.ts +8 -0
  189. package/src/providers/minimax/videos.ts +4 -0
  190. package/src/providers/minimax.ts +162 -0
  191. package/src/providers/mistral.ts +40 -0
  192. package/src/providers/moonshot/chat.ts +1 -0
  193. package/src/providers/moonshot/messages.ts +8 -0
  194. package/src/providers/moonshot/responses.ts +8 -0
  195. package/src/providers/moonshot.ts +134 -0
  196. package/src/providers/open-responses-options.ts +4 -0
  197. package/src/providers/openai/chat.ts +2 -0
  198. package/src/providers/openai/embeddings.ts +2 -0
  199. package/src/providers/openai/images.ts +2 -0
  200. package/src/providers/openai/responses.ts +2 -0
  201. package/src/providers/openai-compatible/decisions.ts +2 -0
  202. package/src/providers/openai-compatible/embeddings.ts +2 -0
  203. package/src/providers/openai-compatible/images.ts +2 -0
  204. package/src/providers/openai-compatible/responses.ts +1 -0
  205. package/src/providers/openai-compatible-responses.ts +52 -0
  206. package/src/providers/openai-compatible.ts +108 -0
  207. package/src/providers/openai-options.ts +66 -0
  208. package/src/providers/openai.ts +207 -0
  209. package/src/providers/opencode/decisions.ts +2 -0
  210. package/src/providers/opencode.ts +45 -0
  211. package/src/providers/openrouter/decisions.ts +2 -0
  212. package/src/providers/openrouter/embeddings.ts +2 -0
  213. package/src/providers/openrouter/images.ts +2 -0
  214. package/src/providers/openrouter/responses.ts +3 -0
  215. package/src/providers/openrouter/videos.ts +2 -0
  216. package/src/providers/openrouter.ts +347 -0
  217. package/src/providers/settings.ts +54 -0
  218. package/src/providers/togetherai.ts +53 -0
  219. package/src/providers/typesafe-ai/decisions.ts +2 -0
  220. package/src/providers/typesafe-ai.ts +45 -0
  221. package/src/providers/venice/responses.ts +4 -0
  222. package/src/providers/venice.ts +93 -0
  223. package/src/providers/vercel-ai-gateway/chat.ts +2 -0
  224. package/src/providers/vercel-ai-gateway/decisions.ts +2 -0
  225. package/src/providers/vercel-ai-gateway/embeddings.ts +2 -0
  226. package/src/providers/vercel-ai-gateway/images.ts +2 -0
  227. package/src/providers/vercel-ai-gateway/messages.ts +2 -0
  228. package/src/providers/vercel-ai-gateway/responses.ts +2 -0
  229. package/src/providers/vercel-ai-gateway.ts +300 -0
  230. package/src/providers/volcengine/videos.ts +2 -0
  231. package/src/providers/volcengine.ts +39 -0
  232. package/src/providers/xai/images.ts +2 -0
  233. package/src/providers/xai/videos.ts +2 -0
  234. package/src/providers/xai.ts +125 -0
  235. package/src/providers/zai/chat.ts +1 -0
  236. package/src/providers/zai/images.ts +2 -0
  237. package/src/providers/zai-coding-plan/chat.ts +1 -0
  238. package/src/providers/zai-coding-plan/messages.ts +8 -0
  239. package/src/providers/zai-coding-plan/responses.ts +8 -0
  240. package/src/providers/zai-coding-plan.ts +86 -0
  241. package/src/providers/zai.ts +73 -0
  242. package/src/providers.ts +1 -0
  243. package/src/public.ts +204 -0
  244. package/src/route/auth-options.ts +62 -0
  245. package/src/route/auth.ts +164 -0
  246. package/src/route/client.ts +700 -0
  247. package/src/route/decision.ts +150 -0
  248. package/src/route/embedding.ts +175 -0
  249. package/src/route/endpoint.ts +63 -0
  250. package/src/route/executor-service.ts +191 -0
  251. package/src/route/executor.ts +361 -0
  252. package/src/route/framing.ts +112 -0
  253. package/src/route/index.ts +47 -0
  254. package/src/route/media-protocol.ts +321 -0
  255. package/src/route/media.ts +507 -0
  256. package/src/route/protocol.ts +97 -0
  257. package/src/route/transport/http.ts +103 -0
  258. package/src/route/transport/index.ts +59 -0
  259. package/src/route/transport/websocket-channel.ts +51 -0
  260. package/src/route/transport/websocket.ts +443 -0
  261. package/src/route.ts +1 -0
  262. package/src/schema/errors.ts +246 -0
  263. package/src/schema/events.ts +744 -0
  264. package/src/schema/ids.ts +24 -0
  265. package/src/schema/index.ts +5 -0
  266. package/src/schema/messages.ts +529 -0
  267. package/src/schema/options.ts +445 -0
  268. package/src/speech-client.ts +25 -0
  269. package/src/speech.ts +211 -0
  270. package/src/testing.ts +218 -0
  271. package/src/tool-history.ts +91 -0
  272. package/src/tool-runtime.ts +107 -0
  273. package/src/tool-updates.ts +139 -0
  274. package/src/tool.ts +281 -0
  275. package/src/transcription-client.ts +19 -0
  276. package/src/transcription.ts +234 -0
  277. package/src/utils/bytes.ts +9 -0
  278. package/src/utils/json.ts +5 -0
  279. package/src/utils/media-type.ts +93 -0
  280. package/src/utils/provider-codes.ts +43 -0
  281. package/src/utils/record.ts +3 -0
  282. package/src/utils/sanitize.ts +33 -0
  283. package/src/video-client.ts +66 -0
  284. package/src/video.ts +181 -0
  285. package/test/adapter.test.ts +180 -0
  286. package/test/auth-options.types.ts +283 -0
  287. package/test/auth.test.ts +112 -0
  288. package/test/cache-policy.test.ts +578 -0
  289. package/test/compaction-http.test.ts +96 -0
  290. package/test/compaction.test.ts +107 -0
  291. package/test/compile.test.ts +600 -0
  292. package/test/continuation-scenarios.ts +115 -0
  293. package/test/decision.test.ts +983 -0
  294. package/test/decision.types.ts +117 -0
  295. package/test/effort-updates.test.ts +574 -0
  296. package/test/embedding.test.ts +455 -0
  297. package/test/endpoint.test.ts +58 -0
  298. package/test/error-partial.test.ts +140 -0
  299. package/test/executor.test.ts +1095 -0
  300. package/test/exports.test.ts +222 -0
  301. package/test/extraction.test.ts +227 -0
  302. package/test/fixtures/audio/dialog.mp3 +0 -0
  303. package/test/fixtures/audio/hello.mp3 +0 -0
  304. package/test/fixtures/images/edit-source.jpg +0 -0
  305. package/test/fixtures/media/restroom.png +0 -0
  306. package/test/fixtures/recordings/alibaba-chat/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
  307. package/test/fixtures/recordings/alibaba-chat/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
  308. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-flash-reads-image-bytes.json +34 -0
  309. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
  310. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
  311. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-returns-a-json-object.json +34 -0
  312. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-default-effort.json +36 -0
  313. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-high-effort.json +36 -0
  314. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-low-effort.json +36 -0
  315. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-max-effort.json +36 -0
  316. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-medium-effort.json +36 -0
  317. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-minimal-effort.json +36 -0
  318. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-none-effort.json +36 -0
  319. package/test/fixtures/recordings/alibaba-chat/qwen-3-8-max-streams-xhigh-effort.json +36 -0
  320. package/test/fixtures/recordings/alibaba-images/edits-an-image.json +33 -0
  321. package/test/fixtures/recordings/alibaba-images/generates-qwen-image-images.json +33 -0
  322. package/test/fixtures/recordings/alibaba-images/generates-wan-images.json +33 -0
  323. package/test/fixtures/recordings/alibaba-messages/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
  324. package/test/fixtures/recordings/alibaba-messages/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
  325. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-flash-reads-image-bytes.json +34 -0
  326. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-follows-a-json-schema.json +34 -0
  327. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
  328. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
  329. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-default-effort.json +36 -0
  330. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-high-effort.json +36 -0
  331. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-low-effort.json +36 -0
  332. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-max-effort.json +36 -0
  333. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-medium-effort.json +36 -0
  334. package/test/fixtures/recordings/alibaba-messages/qwen-3-8-max-streams-xhigh-effort.json +36 -0
  335. package/test/fixtures/recordings/alibaba-responses/qwen-3-7-plus-streams-thinking-disabled.json +35 -0
  336. package/test/fixtures/recordings/alibaba-responses/qwen-3-7-plus-streams-thinking-enabled.json +35 -0
  337. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-flash-reads-image-bytes.json +34 -0
  338. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-continues-a-stored-response.json +53 -0
  339. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-obeys-named-tool-choice.json +35 -0
  340. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-replays-reasoning-through-a-tool-loop-and-follow-up.json +73 -0
  341. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-default-effort.json +36 -0
  342. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-high-effort.json +36 -0
  343. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-low-effort.json +36 -0
  344. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-max-effort.json +36 -0
  345. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-medium-effort.json +36 -0
  346. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-minimal-effort.json +36 -0
  347. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-none-effort.json +36 -0
  348. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-streams-xhigh-effort.json +36 -0
  349. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-uses-hosted-code-interpreter.json +35 -0
  350. package/test/fixtures/recordings/alibaba-responses/qwen-3-8-max-uses-hosted-web-search-and-extraction.json +36 -0
  351. package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-text.json +40 -0
  352. package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-tool-call.json +41 -0
  353. package/test/fixtures/recordings/anthropic-compatible-messages/minimax-m3-anthropic-compatible-tool-loop.json +60 -0
  354. package/test/fixtures/recordings/anthropic-messages/anthropic-opus-4-7-image-tool-result.json +43 -0
  355. package/test/fixtures/recordings/anthropic-messages-cache/keeps-a-long-tool-turn-inside-the-cache-lookback.json +48 -0
  356. package/test/fixtures/recordings/anthropic-messages-cache/writes-then-reads-cache-control-on-identical-second-call.json +48 -0
  357. package/test/fixtures/recordings/assemblyai-transcription/uploads-submits-and-polls-a-transcript.json +98 -0
  358. package/test/fixtures/recordings/azure/chat-streams-text-from-a-foundry-models-url.json +31 -0
  359. package/test/fixtures/recordings/azure/chat-streams-text.json +28 -0
  360. package/test/fixtures/recordings/azure/messages-calls-a-tool.json +31 -0
  361. package/test/fixtures/recordings/azure/messages-streams-text.json +31 -0
  362. package/test/fixtures/recordings/azure/responses-calls-a-tool.json +31 -0
  363. package/test/fixtures/recordings/azure/responses-continues-after-a-tool-result.json +31 -0
  364. package/test/fixtures/recordings/azure/responses-streams-text.json +31 -0
  365. package/test/fixtures/recordings/baseten-decision/decides-choice-score-and-predicate-questions.json +33 -0
  366. package/test/fixtures/recordings/bedrock-converse/continues-after-parallel-tool-results.json +36 -0
  367. package/test/fixtures/recordings/bedrock-converse/drives-a-tool-loop.json +55 -0
  368. package/test/fixtures/recordings/bedrock-converse/streams-a-tool-call.json +29 -0
  369. package/test/fixtures/recordings/bedrock-converse/streams-text.json +29 -0
  370. package/test/fixtures/recordings/bedrock-converse-cache/writes-then-reads-cachepoint-on-identical-second-call.json +48 -0
  371. package/test/fixtures/recordings/bedrock-converse-options/constrains-claude-output-to-a-json-schema.json +33 -0
  372. package/test/fixtures/recordings/bedrock-converse-options/sends-claude-effort-with-adaptive-thinking-service-tier-and-request-metadata.json +34 -0
  373. package/test/fixtures/recordings/bedrock-converse-options/sends-gpt-oss-reasoning-effort-with-the-priority-tier.json +34 -0
  374. package/test/fixtures/recordings/bedrock-converse-options/sends-nova-2-reasoning-effort.json +34 -0
  375. package/test/fixtures/recordings/bedrock-converse-thinking-binding/accepts-the-default-binding-with-no-thinking-configured.json +34 -0
  376. package/test/fixtures/recordings/bedrock-converse-thinking-binding/keeps-a-session-working-after-the-system-prompt-changes.json +71 -0
  377. package/test/fixtures/recordings/bedrock-mantle/streams-text.json +33 -0
  378. package/test/fixtures/recordings/bedrock-mantle-messages/applies-mid-conversation-effort-updates-and-thinking-block-binding-on-opus-5-5.json +57 -0
  379. package/test/fixtures/recordings/bedrock-mantle-messages/lowers-system-updates-to-wrapped-user-text-on-haiku-4-5-with-budget-thinking.json +37 -0
  380. package/test/fixtures/recordings/bedrock-mantle-messages/replays-signed-thinking-through-a-tool-loop-and-native-system-update.json +59 -0
  381. package/test/fixtures/recordings/bedrock-mantle-messages/strips-unsupported-mid-conversation-effort-updates-on-opus-5-0.json +37 -0
  382. package/test/fixtures/recordings/cartesia-speech/generates-speech.json +34 -0
  383. package/test/fixtures/recordings/cartesia-speech/streams-speech-with-timestamps.json +33 -0
  384. package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-text.json +32 -0
  385. package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-tool-call.json +32 -0
  386. package/test/fixtures/recordings/cerebras-chat/cerebras-gpt-oss-120b-tool-loop.json +50 -0
  387. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-claude-haiku-4-5-text.json +38 -0
  388. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-claude-haiku-4-5-tool-loop.json +58 -0
  389. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-openai-gpt-5-nano-text.json +37 -0
  390. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-openai-gpt-5-nano-tool-loop.json +56 -0
  391. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  392. package/test/fixtures/recordings/cloudflare-ai-gateway/cloudflare-ai-gateway-workers-ai-llama-3-1-8b-text.json +32 -0
  393. package/test/fixtures/recordings/cloudflare-ai-gateway-decision/decides-choice-score-and-predicate-questions.json +33 -0
  394. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-gpt-oss-20b-tools-tool-call.json +32 -0
  395. package/test/fixtures/recordings/cloudflare-workers-ai/cloudflare-workers-ai-llama-3-1-8b-text.json +32 -0
  396. package/test/fixtures/recordings/cloudflare-workers-ai-decision/decides-choice-score-and-predicate-questions.json +33 -0
  397. package/test/fixtures/recordings/cloudflare-workers-ai-extraction/extracts-invoice-fields.json +33 -0
  398. package/test/fixtures/recordings/cloudflare-workers-ai-images/generates-a-flux-2-image-from-multipart-fields.json +32 -0
  399. package/test/fixtures/recordings/cloudflare-workers-ai-images/generates-a-raw-binary-image.json +33 -0
  400. package/test/fixtures/recordings/cohere/continues-a-native-tool-call.json +49 -0
  401. package/test/fixtures/recordings/cohere/streams-compatible-chat-reasoning.json +31 -0
  402. package/test/fixtures/recordings/cohere/streams-native-text-and-usage.json +31 -0
  403. package/test/fixtures/recordings/cohere/streams-native-thinking-with-a-budget.json +31 -0
  404. package/test/fixtures/recordings/cohere-embedding/embeds-text-through-the-compatibility-api.json +33 -0
  405. package/test/fixtures/recordings/deepgram-speech/generates-speech.json +36 -0
  406. package/test/fixtures/recordings/deepgram-speech/streams-speech.json +36 -0
  407. package/test/fixtures/recordings/deepgram-transcription/splits-utterances-at-speaker-changes.json +32 -0
  408. package/test/fixtures/recordings/deepgram-transcription/transcribes-raw-audio-with-speakers-and-word-timestamps.json +50 -0
  409. package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-text.json +32 -0
  410. package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-tool-call.json +32 -0
  411. package/test/fixtures/recordings/deepinfra-chat/deepinfra-llama-3-3-70b-tool-loop.json +50 -0
  412. package/test/fixtures/recordings/digitalocean-chat/gpt-nano-continues-a-tool-call-with-cache-markers.json +54 -0
  413. package/test/fixtures/recordings/digitalocean-chat/gpt-nano-reuses-a-cached-prompt.json +53 -0
  414. package/test/fixtures/recordings/digitalocean-chat/haiku-continues-a-tool-call-with-cache-markers.json +54 -0
  415. package/test/fixtures/recordings/digitalocean-chat/haiku-reuses-a-cached-prompt.json +53 -0
  416. package/test/fixtures/recordings/digitalocean-decision/decides-choice-score-and-predicate-questions.json +33 -0
  417. package/test/fixtures/recordings/digitalocean-responses/calls-a-freeform-text-tool.json +35 -0
  418. package/test/fixtures/recordings/digitalocean-responses/continues-a-tool-call.json +53 -0
  419. package/test/fixtures/recordings/digitalocean-responses/streams-text.json +35 -0
  420. package/test/fixtures/recordings/elevenlabs-speech/generates-speech.json +35 -0
  421. package/test/fixtures/recordings/elevenlabs-speech/streams-speech-with-timestamps.json +34 -0
  422. package/test/fixtures/recordings/elevenlabs-transcription/groups-diarized-words-into-speaker-turns.json +32 -0
  423. package/test/fixtures/recordings/elevenlabs-transcription/transcribes-audio-with-word-timestamps.json +50 -0
  424. package/test/fixtures/recordings/gemini/gemini-2-5-flash-image.json +32 -0
  425. package/test/fixtures/recordings/gemini-cache/reports-cachedcontenttokencount-on-identical-second-call.json +46 -0
  426. package/test/fixtures/recordings/google-decision/decides-choice-score-and-predicate-questions.json +33 -0
  427. package/test/fixtures/recordings/google-embedding/embeds-an-image-and-text-into-one-vector-each.json +32 -0
  428. package/test/fixtures/recordings/google-embedding/embeds-text-through-batchembedcontents.json +32 -0
  429. package/test/fixtures/recordings/google-embedding/maps-inputtype-to-a-task-type-for-gemini-embedding-001.json +50 -0
  430. package/test/fixtures/recordings/google-images/edits-an-image.json +28 -0
  431. package/test/fixtures/recordings/google-images/generates-an-image.json +28 -0
  432. package/test/fixtures/recordings/google-interactions/continues-tool-results-with-previous-interaction-id.json +66 -0
  433. package/test/fixtures/recordings/google-interactions/replays-native-tool-results-and-signatures-statelessly.json +50 -0
  434. package/test/fixtures/recordings/google-interactions/streams-reasoning-and-retains-thought-signatures.json +32 -0
  435. package/test/fixtures/recordings/google-interactions/streams-text-and-reports-usage.json +32 -0
  436. package/test/fixtures/recordings/google-interactions-video/generates-a-video.json +96 -0
  437. package/test/fixtures/recordings/google-speech/generates-speech.json +32 -0
  438. package/test/fixtures/recordings/google-speech/streams-speech.json +32 -0
  439. package/test/fixtures/recordings/google-transcription/streams-speaker-turns.json +32 -0
  440. package/test/fixtures/recordings/google-transcription/transcribes-with-speakers-and-word-timestamps.json +32 -0
  441. package/test/fixtures/recordings/google-vertex/calls-a-tool.json +32 -0
  442. package/test/fixtures/recordings/google-vertex/continues-after-a-tool-result.json +32 -0
  443. package/test/fixtures/recordings/google-vertex/streams-text.json +32 -0
  444. package/test/fixtures/recordings/google-vertex-embedding/embeds-gemini-embedding-001-one-text-per-predict-request.json +50 -0
  445. package/test/fixtures/recordings/google-vertex-embedding/embeds-text-through-predict.json +32 -0
  446. package/test/fixtures/recordings/groq-chat/continues-qwen-parallel-tool-calls.json +47 -0
  447. package/test/fixtures/recordings/groq-chat/replays-gpt-oss-reasoning-through-a-tool-loop.json +47 -0
  448. package/test/fixtures/recordings/groq-chat/streams-qwen-parsed-reasoning.json +29 -0
  449. package/test/fixtures/recordings/groq-chat/streams-text-with-usage.json +29 -0
  450. package/test/fixtures/recordings/meta-chat/continues-a-generated-tool-call.json +56 -0
  451. package/test/fixtures/recordings/meta-chat/streams-text-with-default-reasoning.json +37 -0
  452. package/test/fixtures/recordings/meta-chat/streams-text-with-high-reasoning.json +29 -0
  453. package/test/fixtures/recordings/meta-chat/streams-text-with-low-reasoning.json +29 -0
  454. package/test/fixtures/recordings/meta-chat/streams-text-with-max-reasoning.json +29 -0
  455. package/test/fixtures/recordings/meta-chat/streams-text-with-medium-reasoning.json +37 -0
  456. package/test/fixtures/recordings/meta-chat/streams-text-with-minimal-reasoning.json +37 -0
  457. package/test/fixtures/recordings/meta-chat/streams-text-with-xhigh-reasoning.json +29 -0
  458. package/test/fixtures/recordings/meta-images/edits-image-bytes-and-returns-png.json +29 -0
  459. package/test/fixtures/recordings/meta-images/generates-default-webp-bytes.json +29 -0
  460. package/test/fixtures/recordings/meta-images/replays-a-signed-image-handle-for-a-responses-edit.json +55 -0
  461. package/test/fixtures/recordings/meta-messages/replays-encrypted-thinking-through-a-tool-loop.json +54 -0
  462. package/test/fixtures/recordings/meta-messages/streams-text-with-adaptive-thinking.json +36 -0
  463. package/test/fixtures/recordings/meta-messages/streams-text-with-enabled-thinking.json +36 -0
  464. package/test/fixtures/recordings/meta-responses/replays-encrypted-reasoning-through-a-tool-loop.json +56 -0
  465. package/test/fixtures/recordings/meta-responses/streams-text-with-default-reasoning.json +37 -0
  466. package/test/fixtures/recordings/meta-responses/streams-text-with-high-reasoning.json +37 -0
  467. package/test/fixtures/recordings/meta-responses/streams-text-with-low-reasoning.json +37 -0
  468. package/test/fixtures/recordings/meta-responses/streams-text-with-max-reasoning.json +37 -0
  469. package/test/fixtures/recordings/meta-responses/streams-text-with-medium-reasoning.json +37 -0
  470. package/test/fixtures/recordings/meta-responses/streams-text-with-minimal-reasoning.json +37 -0
  471. package/test/fixtures/recordings/meta-responses/streams-text-with-xhigh-reasoning.json +37 -0
  472. package/test/fixtures/recordings/meta-search/searches-and-replays-grounded-messages.json +56 -0
  473. package/test/fixtures/recordings/meta-search/searches-and-replays-grounded-responses.json +56 -0
  474. package/test/fixtures/recordings/minimax-chat/m3-continues-a-tool-loop-with-default-thinking.json +56 -0
  475. package/test/fixtures/recordings/minimax-chat/m3-streams-text-with-thinking-disabled.json +36 -0
  476. package/test/fixtures/recordings/minimax-images/generates-an-image.json +32 -0
  477. package/test/fixtures/recordings/minimax-images/generates-from-a-subject-reference.json +32 -0
  478. package/test/fixtures/recordings/minimax-messages/m2-7-streams-default-thinking.json +36 -0
  479. package/test/fixtures/recordings/minimax-messages/m3-continues-a-tool-loop-with-adaptive-thinking.json +56 -0
  480. package/test/fixtures/recordings/minimax-messages/m3-generates-a-named-tool-call-with-default-thinking-off.json +36 -0
  481. package/test/fixtures/recordings/minimax-messages/m3-streams-adaptive-thinking.json +36 -0
  482. package/test/fixtures/recordings/minimax-messages/m3-streams-text-with-thinking-disabled.json +36 -0
  483. package/test/fixtures/recordings/minimax-responses/m3-continues-a-tool-loop-with-effort-minimal.json +56 -0
  484. package/test/fixtures/recordings/minimax-responses/m3-streams-text-with-effort-none.json +36 -0
  485. package/test/fixtures/recordings/minimax-video/generates-a-hailuo-video-from-a-first-frame.json +176 -0
  486. package/test/fixtures/recordings/minimax-video/generates-an-h3-video.json +96 -0
  487. package/test/fixtures/recordings/mistral-chat/drives-a-tool-loop.json +54 -0
  488. package/test/fixtures/recordings/mistral-chat/replays-native-reasoning.json +47 -0
  489. package/test/fixtures/recordings/mistral-chat/streams-text-with-usage.json +29 -0
  490. package/test/fixtures/recordings/mistral-chat-glm/streams-an-indexed-tool-call.json +36 -0
  491. package/test/fixtures/recordings/moonshot-chat/k3-reads-image-bytes.json +29 -0
  492. package/test/fixtures/recordings/moonshot-chat/k3-respects-tool-choice-none.json +29 -0
  493. package/test/fixtures/recordings/moonshot-chat/k3-respects-tool-choice-required.json +29 -0
  494. package/test/fixtures/recordings/moonshot-chat/k3-returns-native-structured-output.json +29 -0
  495. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-default-effort.json +29 -0
  496. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-high-effort.json +29 -0
  497. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-low-effort.json +29 -0
  498. package/test/fixtures/recordings/moonshot-chat/k3-streams-text-with-max-effort.json +29 -0
  499. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  500. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-default-thinking.json +29 -0
  501. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-disabled-thinking.json +29 -0
  502. package/test/fixtures/recordings/moonshot-chat/kimi-k2-6-streams-text-with-enabled-thinking.json +29 -0
  503. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-highspeed-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  504. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-highspeed-streams-text-with-default-thinking.json +29 -0
  505. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  506. package/test/fixtures/recordings/moonshot-chat/kimi-k2-7-code-streams-text-with-default-thinking.json +29 -0
  507. package/test/fixtures/recordings/moonshot-chat/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  508. package/test/fixtures/recordings/moonshot-messages/k3-reads-image-bytes.json +36 -0
  509. package/test/fixtures/recordings/moonshot-messages/k3-respects-tool-choice-none.json +36 -0
  510. package/test/fixtures/recordings/moonshot-messages/k3-respects-tool-choice-required.json +36 -0
  511. package/test/fixtures/recordings/moonshot-messages/k3-returns-native-structured-output.json +35 -0
  512. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-default-effort.json +36 -0
  513. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-high-effort.json +36 -0
  514. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-low-effort.json +36 -0
  515. package/test/fixtures/recordings/moonshot-messages/k3-streams-text-with-max-effort.json +36 -0
  516. package/test/fixtures/recordings/moonshot-messages/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  517. package/test/fixtures/recordings/moonshot-responses/k3-reads-image-bytes.json +36 -0
  518. package/test/fixtures/recordings/moonshot-responses/k3-rejects-unsupported-tool-choice-none.json +36 -0
  519. package/test/fixtures/recordings/moonshot-responses/k3-rejects-unsupported-tool-choice-required.json +36 -0
  520. package/test/fixtures/recordings/moonshot-responses/k3-returns-native-structured-output.json +35 -0
  521. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-default-effort.json +36 -0
  522. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-high-effort.json +36 -0
  523. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-low-effort.json +36 -0
  524. package/test/fixtures/recordings/moonshot-responses/k3-streams-text-with-max-effort.json +36 -0
  525. package/test/fixtures/recordings/moonshot-responses/kimi-k3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +74 -0
  526. package/test/fixtures/recordings/openai-compatible-chat/gemini-parallel-tool-signatures.json +54 -0
  527. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-text.json +28 -0
  528. package/test/fixtures/recordings/openai-compatible-chat/togetherai-streams-tool-call.json +28 -0
  529. package/test/fixtures/recordings/openai-decision/decides-choice-score-and-predicate-questions-about-json-state.json +33 -0
  530. package/test/fixtures/recordings/openai-embedding/embeds-text-with-requested-dimensions.json +33 -0
  531. package/test/fixtures/recordings/openai-images/edits-an-image.json +28 -0
  532. package/test/fixtures/recordings/openai-images/generates-an-image.json +28 -0
  533. package/test/fixtures/recordings/openai-images/streams-a-partial-image-before-the-final-image.json +32 -0
  534. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-image-tool-result.json +42 -0
  535. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning-continuation.json +58 -0
  536. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-reasoning.json +38 -0
  537. package/test/fixtures/recordings/openai-responses/openai-responses-gpt-5-5-tool-loop.json +57 -0
  538. package/test/fixtures/recordings/openai-responses-cache/caches-the-system-prompt-on-gpt-6-2-sol.json +51 -0
  539. package/test/fixtures/recordings/openai-responses-cache/reports-cached-tokens-on-identical-second-call.json +51 -0
  540. package/test/fixtures/recordings/openai-responses-images/generates-and-edits-an-image-with-the-hosted-tool.json +50 -0
  541. package/test/fixtures/recordings/openai-responses-websocket/continues-a-tool-call-over-one-socket.json +588 -0
  542. package/test/fixtures/recordings/openai-responses-websocket/reconstructs-full-context-after-reconnect.json +167 -0
  543. package/test/fixtures/recordings/openai-responses-websocket/recovers-from-explicit-continuation-rejection.json +167 -0
  544. package/test/fixtures/recordings/openai-speech/generates-speech.json +33 -0
  545. package/test/fixtures/recordings/openai-speech/streams-speech.json +32 -0
  546. package/test/fixtures/recordings/openai-transcription/diarizes-speakers-into-segments.json +32 -0
  547. package/test/fixtures/recordings/openai-transcription/returns-whisper-word-timestamps.json +32 -0
  548. package/test/fixtures/recordings/openai-transcription/streams-text-deltas.json +32 -0
  549. package/test/fixtures/recordings/openai-transcription/transcribes-with-a-language-hint.json +32 -0
  550. package/test/fixtures/recordings/opencode-decision/decides-choice-score-and-predicate-questions.json +33 -0
  551. package/test/fixtures/recordings/openrouter-decision/decides-choice-score-and-predicate-questions.json +33 -0
  552. package/test/fixtures/recordings/openrouter-images/edits-an-image-through-input-references.json +32 -0
  553. package/test/fixtures/recordings/openrouter-images/renders-flux-3-from-an-aspect-ratio-and-tier.json +32 -0
  554. package/test/fixtures/recordings/openrouter-images/renders-gemini-at-the-requested-2k-tier.json +32 -0
  555. package/test/fixtures/recordings/openrouter-reasoning-tool-loop.json +55 -0
  556. package/test/fixtures/recordings/openrouter-reasoning.json +29 -0
  557. package/test/fixtures/recordings/openrouter-responses/calls-a-freeform-text-tool.json +35 -0
  558. package/test/fixtures/recordings/openrouter-responses/continues-a-tool-call.json +53 -0
  559. package/test/fixtures/recordings/openrouter-responses/streams-text.json +35 -0
  560. package/test/fixtures/recordings/openrouter-video/generates-a-video.json +113 -0
  561. package/test/fixtures/recordings/pdf/anthropic-tool-result.json +28 -0
  562. package/test/fixtures/recordings/pdf/anthropic-user-input.json +28 -0
  563. package/test/fixtures/recordings/pdf/bedrock-tool-result.json +29 -0
  564. package/test/fixtures/recordings/pdf/bedrock-user-input.json +29 -0
  565. package/test/fixtures/recordings/pdf/gemini-tool-result.json +53 -0
  566. package/test/fixtures/recordings/pdf/gemini-user-input.json +28 -0
  567. package/test/fixtures/recordings/pdf/openai-tool-result.json +35 -0
  568. package/test/fixtures/recordings/pdf/openai-user-input.json +34 -0
  569. package/test/fixtures/recordings/pdf/xai-tool-result.json +35 -0
  570. package/test/fixtures/recordings/pdf/xai-user-input.json +34 -0
  571. package/test/fixtures/recordings/typesafe-decision/decides-choice-score-and-predicate-questions.json +33 -0
  572. package/test/fixtures/recordings/venice-chat/claude-opus-4-8-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  573. package/test/fixtures/recordings/venice-chat/deepseek-v4-flash-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  574. package/test/fixtures/recordings/venice-chat/gemini-3-1-pro-preview-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  575. package/test/fixtures/recordings/venice-chat/gemini-preserves-per-call-signatures-through-parallel-tools.json +71 -0
  576. package/test/fixtures/recordings/venice-chat/openai-gpt-54-mini-preserves-reasoning-through-a-tool-loop-and-follow-up.json +75 -0
  577. package/test/fixtures/recordings/venice-chat/qwen-disables-reasoning.json +35 -0
  578. package/test/fixtures/recordings/venice-chat/surfaces-venice-model-errors.json +33 -0
  579. package/test/fixtures/recordings/venice-responses/calls-a-freeform-text-tool.json +35 -0
  580. package/test/fixtures/recordings/venice-responses/continues-a-tool-call.json +53 -0
  581. package/test/fixtures/recordings/venice-responses/streams-text.json +35 -0
  582. package/test/fixtures/recordings/vercel-ai-gateway-images/generates-an-image.json +32 -0
  583. package/test/fixtures/recordings/vercel-ai-gateway-images/sizes-grok-through-xai-provider-options.json +32 -0
  584. package/test/fixtures/recordings/vercel-ai-gateway-reasoning-tool-loop.json +55 -0
  585. package/test/fixtures/recordings/vercel-ai-gateway-reasoning.json +29 -0
  586. package/test/fixtures/recordings/vercel-native/automatically-caches-distinct-claude-system-blocks.json +49 -0
  587. package/test/fixtures/recordings/vercel-native/continues-chat-claude-reasoning-and-tools.json +49 -0
  588. package/test/fixtures/recordings/vercel-native/continues-chat-muse-reasoning-and-tools.json +49 -0
  589. package/test/fixtures/recordings/vercel-native/continues-messages-claude-reasoning-and-tools.json +49 -0
  590. package/test/fixtures/recordings/vercel-native/continues-messages-deepseek-reasoning-and-tools.json +49 -0
  591. package/test/fixtures/recordings/vercel-native/continues-messages-gemini-reasoning-and-tools.json +49 -0
  592. package/test/fixtures/recordings/vercel-native/continues-responses-gpt-reasoning-and-tools.json +49 -0
  593. package/test/fixtures/recordings/vercel-native/continues-responses-grok-reasoning-and-tools.json +49 -0
  594. package/test/fixtures/recordings/vercel-native/rejects-invalid-credentials-without-retryable-classification.json +31 -0
  595. package/test/fixtures/recordings/xai-images/edits-an-image.json +28 -0
  596. package/test/fixtures/recordings/xai-images/generates-an-image.json +28 -0
  597. package/test/fixtures/recordings/xai-video/generates-a-video.json +129 -0
  598. package/test/fixtures/recordings/zai-chat/glm-4-5-calls-a-tool-without-streaming-arguments.json +28 -0
  599. package/test/fixtures/recordings/zai-chat/glm-4-7-streams-thinking-disabled.json +28 -0
  600. package/test/fixtures/recordings/zai-chat/glm-4-7-streams-thinking-enabled.json +28 -0
  601. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-high-effort.json +28 -0
  602. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-low-effort.json +28 -0
  603. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-max-effort.json +28 -0
  604. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-medium-effort.json +28 -0
  605. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-minimal-effort.json +28 -0
  606. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-none-effort.json +28 -0
  607. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-thinking-disabled.json +28 -0
  608. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-thinking-enabled.json +28 -0
  609. package/test/fixtures/recordings/zai-chat/glm-5-2-streams-xhigh-effort.json +28 -0
  610. package/test/fixtures/recordings/zai-chat/glm-5-3-flash-reads-image-bytes.json +28 -0
  611. package/test/fixtures/recordings/zai-chat/glm-5-3-preserves-reasoning-through-a-tool-loop-and-follow-up.json +64 -0
  612. package/test/fixtures/recordings/zai-chat/glm-5-3-rejects-disabled-thinking.json +27 -0
  613. package/test/fixtures/recordings/zai-chat/glm-5-3-returns-a-json-object.json +28 -0
  614. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-default-effort.json +28 -0
  615. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-high-effort.json +28 -0
  616. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-low-effort.json +28 -0
  617. package/test/fixtures/recordings/zai-chat/glm-5-3-streams-max-effort.json +28 -0
  618. package/test/fixtures/recordings/zai-images/generates-an-image.json +28 -0
  619. package/test/generate-object.test.ts +281 -0
  620. package/test/generation.test.ts +191 -0
  621. package/test/google-interactions-video.test.ts +351 -0
  622. package/test/http-hooks.test.ts +137 -0
  623. package/test/http-timeout.test.ts +287 -0
  624. package/test/image-job.test.ts +199 -0
  625. package/test/image-sizing.test.ts +47 -0
  626. package/test/image.test.ts +1114 -0
  627. package/test/image.types.ts +203 -0
  628. package/test/keyless-auth.test.ts +85 -0
  629. package/test/lib/effect.ts +50 -0
  630. package/test/lib/env.ts +30 -0
  631. package/test/lib/http.ts +141 -0
  632. package/test/lib/image.ts +29 -0
  633. package/test/lib/openai-chunks.ts +27 -0
  634. package/test/lib/sse.ts +20 -0
  635. package/test/lib/tool-runtime.ts +152 -0
  636. package/test/llm-option-types.types.ts +153 -0
  637. package/test/llm.test.ts +286 -0
  638. package/test/loop-steps.test.ts +77 -0
  639. package/test/loop-tools.types.ts +79 -0
  640. package/test/loop.test.ts +425 -0
  641. package/test/media-input.test.ts +98 -0
  642. package/test/media-usage.test.ts +13 -0
  643. package/test/media.test.ts +340 -0
  644. package/test/minimax-video.test.ts +553 -0
  645. package/test/openai-freeform.test.ts +252 -0
  646. package/test/openrouter-video.test.ts +294 -0
  647. package/test/partial-json.test.ts +58 -0
  648. package/test/promise-parity.types.ts +83 -0
  649. package/test/promise.test.ts +632 -0
  650. package/test/provider/alibaba-capabilities.recorded.test.ts +253 -0
  651. package/test/provider/alibaba-images.recorded.test.ts +71 -0
  652. package/test/provider/alibaba-images.test.ts +199 -0
  653. package/test/provider/alibaba.recorded.test.ts +165 -0
  654. package/test/provider/alibaba.test.ts +419 -0
  655. package/test/provider/anthropic-compaction.test.ts +171 -0
  656. package/test/provider/anthropic-messages-cache.recorded.test.ts +111 -0
  657. package/test/provider/anthropic-messages.recorded.test.ts +45 -0
  658. package/test/provider/anthropic-messages.test.ts +2609 -0
  659. package/test/provider/anthropic-thinking-binding.test.ts +65 -0
  660. package/test/provider/assemblyai-transcription.recorded.test.ts +39 -0
  661. package/test/provider/azure.recorded.test.ts +139 -0
  662. package/test/provider/azure.test.ts +48 -0
  663. package/test/provider/bedrock-converse-cache.recorded.test.ts +61 -0
  664. package/test/provider/bedrock-converse-cache.test.ts +168 -0
  665. package/test/provider/bedrock-converse-options.recorded.test.ts +119 -0
  666. package/test/provider/bedrock-converse-options.test.ts +149 -0
  667. package/test/provider/bedrock-converse-thinking-binding.recorded.test.ts +103 -0
  668. package/test/provider/bedrock-converse-thinking-binding.test.ts +107 -0
  669. package/test/provider/bedrock-converse.test.ts +2548 -0
  670. package/test/provider/bedrock-mantle.test.ts +444 -0
  671. package/test/provider/bedrock-mistral-ids.test.ts +86 -0
  672. package/test/provider/cartesia-speech.recorded.test.ts +47 -0
  673. package/test/provider/checkpoint.test.ts +324 -0
  674. package/test/provider/cloudflare-workers-ai-images.recorded.test.ts +57 -0
  675. package/test/provider/cloudflare-workers-ai-images.test.ts +155 -0
  676. package/test/provider/cloudflare.test.ts +330 -0
  677. package/test/provider/cohere.recorded.test.ts +94 -0
  678. package/test/provider/cohere.test.ts +301 -0
  679. package/test/provider/compaction-websocket.test.ts +50 -0
  680. package/test/provider/compaction.recorded.test.ts +89 -0
  681. package/test/provider/compaction.test.ts +178 -0
  682. package/test/provider/conversation-lowering.test.ts +31 -0
  683. package/test/provider/decision.recorded.test.ts +211 -0
  684. package/test/provider/deepgram-speech.recorded.test.ts +41 -0
  685. package/test/provider/deepgram-transcription.recorded.test.ts +47 -0
  686. package/test/provider/digitalocean.recorded.test.ts +78 -0
  687. package/test/provider/digitalocean.test.ts +123 -0
  688. package/test/provider/elevenlabs-speech.recorded.test.ts +54 -0
  689. package/test/provider/elevenlabs-transcription.recorded.test.ts +50 -0
  690. package/test/provider/embedding.recorded.test.ts +109 -0
  691. package/test/provider/empty-tool-choice.test.ts +80 -0
  692. package/test/provider/error-retention.test.ts +158 -0
  693. package/test/provider/explicit-compaction.test.ts +503 -0
  694. package/test/provider/extraction.recorded.test.ts +46 -0
  695. package/test/provider/freeform-tools.test.ts +446 -0
  696. package/test/provider/gemini-cache.recorded.test.ts +49 -0
  697. package/test/provider/gemini-openai-chat.recorded.test.ts +69 -0
  698. package/test/provider/gemini.test.ts +2336 -0
  699. package/test/provider/golden.recorded.test.ts +287 -0
  700. package/test/provider/google-images.recorded.test.ts +53 -0
  701. package/test/provider/google-interactions-video.recorded.test.ts +48 -0
  702. package/test/provider/google-interactions.recorded.test.ts +169 -0
  703. package/test/provider/google-interactions.test.ts +593 -0
  704. package/test/provider/google-speech.recorded.test.ts +45 -0
  705. package/test/provider/google-transcription.recorded.test.ts +54 -0
  706. package/test/provider/google-vertex-interactions.test.ts +307 -0
  707. package/test/provider/google-vertex.recorded.test.ts +75 -0
  708. package/test/provider/google-vertex.test.ts +595 -0
  709. package/test/provider/groq.recorded.test.ts +187 -0
  710. package/test/provider/groq.test.ts +134 -0
  711. package/test/provider/image-detail.test.ts +58 -0
  712. package/test/provider/media-entrypoints.test.ts +618 -0
  713. package/test/provider/meta-capabilities.test.ts +216 -0
  714. package/test/provider/meta-images.recorded.test.ts +119 -0
  715. package/test/provider/meta-messages.recorded.test.ts +121 -0
  716. package/test/provider/meta-search.recorded.test.ts +97 -0
  717. package/test/provider/meta.recorded.test.ts +182 -0
  718. package/test/provider/meta.test.ts +140 -0
  719. package/test/provider/minimax-images.recorded.test.ts +52 -0
  720. package/test/provider/minimax-images.test.ts +236 -0
  721. package/test/provider/minimax-video.recorded.test.ts +83 -0
  722. package/test/provider/minimax.recorded.test.ts +257 -0
  723. package/test/provider/minimax.test.ts +110 -0
  724. package/test/provider/missing-tool-input.test.ts +73 -0
  725. package/test/provider/mistral-chat.test.ts +757 -0
  726. package/test/provider/mistral.recorded.test.ts +170 -0
  727. package/test/provider/moonshot-capabilities.recorded.test.ts +131 -0
  728. package/test/provider/moonshot.recorded.test.ts +191 -0
  729. package/test/provider/moonshot.test.ts +218 -0
  730. package/test/provider/native-providers.test.ts +299 -0
  731. package/test/provider/open-responses-errors.test.ts +141 -0
  732. package/test/provider/open-responses-finals.test.ts +209 -0
  733. package/test/provider/open-responses-lifecycle.test.ts +526 -0
  734. package/test/provider/open-responses-replay.test.ts +120 -0
  735. package/test/provider/openai-chat-reasoning.recorded.test.ts +154 -0
  736. package/test/provider/openai-chat.test.ts +2505 -0
  737. package/test/provider/openai-compatible-chat.test.ts +819 -0
  738. package/test/provider/openai-compatible-responses.test.ts +1139 -0
  739. package/test/provider/openai-images.recorded.test.ts +91 -0
  740. package/test/provider/openai-responses-cache.recorded.test.ts +68 -0
  741. package/test/provider/openai-responses-images.recorded.test.ts +66 -0
  742. package/test/provider/openai-responses-websocket.recorded.test.ts +221 -0
  743. package/test/provider/openai-responses.test.ts +5414 -0
  744. package/test/provider/openai-speech.recorded.test.ts +38 -0
  745. package/test/provider/openai-transcription.recorded.test.ts +91 -0
  746. package/test/provider/openrouter-images.recorded.test.ts +76 -0
  747. package/test/provider/openrouter-video.recorded.test.ts +53 -0
  748. package/test/provider/openrouter.test.ts +656 -0
  749. package/test/provider/pdf.recorded.test.ts +211 -0
  750. package/test/provider/queued-recording.ts +10 -0
  751. package/test/provider/responses-routes.recorded.test.ts +91 -0
  752. package/test/provider/seedance-video.recorded.test.ts +52 -0
  753. package/test/provider/speech-recording.ts +19 -0
  754. package/test/provider/transcription-recording.ts +41 -0
  755. package/test/provider/venice.recorded.test.ts +237 -0
  756. package/test/provider/venice.test.ts +373 -0
  757. package/test/provider/vercel-ai-gateway-images.recorded.test.ts +55 -0
  758. package/test/provider/vercel-ai-gateway.recorded.test.ts +125 -0
  759. package/test/provider/vercel-ai-gateway.test.ts +303 -0
  760. package/test/provider/xai-images.recorded.test.ts +54 -0
  761. package/test/provider/xai-images.test.ts +109 -0
  762. package/test/provider/xai-responses.test.ts +339 -0
  763. package/test/provider/xai-video.recorded.test.ts +54 -0
  764. package/test/provider/zai-capabilities.recorded.test.ts +156 -0
  765. package/test/provider/zai-images.recorded.test.ts +33 -0
  766. package/test/provider/zai-images.test.ts +163 -0
  767. package/test/provider/zai.recorded.test.ts +115 -0
  768. package/test/provider/zai.test.ts +374 -0
  769. package/test/provider-api-methods.types.ts +8 -0
  770. package/test/provider-error.test.ts +800 -0
  771. package/test/provider-model.types.ts +37 -0
  772. package/test/provider-options/alibaba.types.ts +46 -0
  773. package/test/provider-options/amazon-bedrock.types.ts +33 -0
  774. package/test/provider-options/anthropic-compatible.types.ts +13 -0
  775. package/test/provider-options/anthropic.types.ts +30 -0
  776. package/test/provider-options/azure.types.ts +13 -0
  777. package/test/provider-options/checkpoint.types.ts +150 -0
  778. package/test/provider-options/cloudflare.types.ts +13 -0
  779. package/test/provider-options/compaction.types.ts +146 -0
  780. package/test/provider-options/google-vertex-chat.types.ts +7 -0
  781. package/test/provider-options/google-vertex-interactions.types.ts +29 -0
  782. package/test/provider-options/google-vertex-messages.types.ts +13 -0
  783. package/test/provider-options/google-vertex-responses.types.ts +14 -0
  784. package/test/provider-options/google-vertex.types.ts +17 -0
  785. package/test/provider-options/google.types.ts +43 -0
  786. package/test/provider-options/minimax.types.ts +33 -0
  787. package/test/provider-options/mistral.types.ts +24 -0
  788. package/test/provider-options/moonshot.types.ts +45 -0
  789. package/test/provider-options/openai-compatible-responses.types.ts +17 -0
  790. package/test/provider-options/openai-compatible.types.ts +13 -0
  791. package/test/provider-options/openai.types.ts +27 -0
  792. package/test/provider-options/openrouter.types.ts +55 -0
  793. package/test/provider-options/venice.types.ts +39 -0
  794. package/test/provider-options/vercel-ai-gateway.types.ts +30 -0
  795. package/test/provider-options/xai.types.ts +14 -0
  796. package/test/provider-options/zai.types.ts +42 -0
  797. package/test/provider-package.test.ts +586 -0
  798. package/test/raw-events.test.ts +75 -0
  799. package/test/realtime.test.ts +172 -0
  800. package/test/recorded-golden.ts +104 -0
  801. package/test/recorded-runner.ts +101 -0
  802. package/test/recorded-scenarios.ts +468 -0
  803. package/test/recorded-test.ts +127 -0
  804. package/test/recorded-utils.ts +56 -0
  805. package/test/request-encoding.test.ts +57 -0
  806. package/test/request-transport.test.ts +74 -0
  807. package/test/response.test.ts +203 -0
  808. package/test/route.test.ts +225 -0
  809. package/test/sanitize.test.ts +80 -0
  810. package/test/schema.test.ts +412 -0
  811. package/test/seedance-video.test.ts +418 -0
  812. package/test/speech.test.ts +297 -0
  813. package/test/speech.types.ts +33 -0
  814. package/test/testing.test.ts +372 -0
  815. package/test/tool-history.test.ts +162 -0
  816. package/test/tool-runtime.test.ts +926 -0
  817. package/test/tool-schema-projection.test.ts +427 -0
  818. package/test/tool-stream.test.ts +252 -0
  819. package/test/tool-updates.test.ts +849 -0
  820. package/test/tool.types.ts +131 -0
  821. package/test/transcription.test.ts +618 -0
  822. package/test/transcription.types.ts +44 -0
  823. package/test/video.test.ts +447 -0
  824. package/test/video.types.ts +110 -0
  825. package/tsconfig.build.json +8 -0
  826. package/tsconfig.json +17 -0
  827. package/tsconfig.types.json +16 -0
@@ -0,0 +1,2336 @@
1
+ import { describe, expect } from "bun:test"
2
+ import { Deferred, Effect, Fiber } from "effect"
3
+ import * as TestClock from "effect/testing/TestClock"
4
+ import {
5
+ ai,
6
+ AIError,
7
+ isRetryable,
8
+ LLMEvent,
9
+ Media,
10
+ Message,
11
+ ToolCallPart,
12
+ ToolDefinition,
13
+ Usage,
14
+ } from "../../src/effect.js"
15
+ import { Auth, LLMClient } from "../../src/route.js"
16
+ import { compileRequest } from "../../src/route/client.js"
17
+ import * as Gemini from "../../src/protocols/gemini.js"
18
+ import { Google } from "../../src/providers.js"
19
+ import { it } from "../lib/effect.js"
20
+ import { dynamicResponse, fixedResponse } from "../lib/http.js"
21
+ import { sseEvents, sseRaw } from "../lib/sse.js"
22
+
23
+ const model = Gemini.route
24
+ .with({
25
+ endpoint: { baseURL: "https://generativelanguage.test/v1beta/" },
26
+ auth: Auth.header("x-goog-api-key", "test"),
27
+ })
28
+ .model({ id: "gemini-2.5-flash" })
29
+
30
+ const gemini3 = Gemini.route
31
+ .with({
32
+ endpoint: { baseURL: "https://generativelanguage.test/v1beta/" },
33
+ auth: Auth.header("x-goog-api-key", "test"),
34
+ })
35
+ .model({ id: "gemini-3-flash-preview" })
36
+
37
+ const request = ai.request({
38
+ id: "req_1",
39
+ model,
40
+ system: "You are concise.",
41
+ prompt: "Say hello.",
42
+ maxTokens: 20,
43
+ temperature: 0,
44
+ })
45
+
46
+ describe("Gemini route", () => {
47
+ it.effect("prepares Gemini target", () =>
48
+ Effect.gen(function* () {
49
+ const prepared = yield* compileRequest(request)
50
+
51
+ expect(prepared.body).toEqual({
52
+ contents: [{ role: "user", parts: [{ text: "Say hello." }] }],
53
+ systemInstruction: { parts: [{ text: "You are concise." }] },
54
+ generationConfig: { maxOutputTokens: 20, temperature: 0 },
55
+ })
56
+ }),
57
+ )
58
+
59
+ it.effect("normalizes Gemini thinking options", () =>
60
+ Effect.gen(function* () {
61
+ const prepared = yield* compileRequest({
62
+ ...request,
63
+ providerOptions: {
64
+ cachedContent: "cachedContents/example",
65
+ safetySettings: [{ category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_ONLY_HIGH" }],
66
+ serviceTier: "priority",
67
+ thinkingConfig: { thinkingBudget: 0, includeThoughts: false, thinkingLevel: "high" },
68
+ },
69
+ })
70
+ const filtered = yield* compileRequest({
71
+ ...request,
72
+ providerOptions: { thinkingConfig: { thinkingBudget: "invalid", includeThoughts: false } },
73
+ })
74
+ const defaulted = yield* compileRequest({
75
+ ...request,
76
+ providerOptions: { thinkingConfig: { thinkingLevel: "high" } },
77
+ })
78
+ const emptySafetySettings = yield* compileRequest({ ...request, providerOptions: { safetySettings: [] } })
79
+
80
+ expect(prepared.body.generationConfig?.thinkingConfig).toEqual({
81
+ thinkingBudget: 0,
82
+ includeThoughts: false,
83
+ thinkingLevel: "high",
84
+ })
85
+ expect(prepared.body.cachedContent).toBe("cachedContents/example")
86
+ expect(prepared.body.safetySettings).toEqual([
87
+ { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_ONLY_HIGH" },
88
+ ])
89
+ expect(prepared.body.serviceTier).toBe("priority")
90
+ expect(filtered.body.generationConfig?.thinkingConfig).toEqual({ includeThoughts: false })
91
+ expect(defaulted.body.generationConfig?.thinkingConfig).toEqual({
92
+ includeThoughts: true,
93
+ thinkingLevel: "high",
94
+ })
95
+ expect(emptySafetySettings.body.safetySettings).toEqual([])
96
+ }),
97
+ )
98
+
99
+ it.effect("fits the thinking budget to half the output limit", () =>
100
+ Effect.gen(function* () {
101
+ const thinkingBudget = (budget: number, maxTokens = 32_000) =>
102
+ compileRequest({
103
+ ...request,
104
+ maxTokens,
105
+ providerOptions: { thinkingConfig: { thinkingBudget: budget } },
106
+ }).pipe(Effect.map((prepared) => prepared.body.generationConfig?.thinkingConfig?.thinkingBudget))
107
+
108
+ expect(yield* thinkingBudget(32_768)).toBe(16_000)
109
+ expect(yield* thinkingBudget(8_000)).toBe(8_000)
110
+ expect(yield* thinkingBudget(-1)).toBe(-1)
111
+ expect(yield* thinkingBudget(8_192, 1_000)).toBe(512)
112
+ }),
113
+ )
114
+
115
+ it.effect("forwards standard Gemini generation options", () =>
116
+ Effect.gen(function* () {
117
+ const prepared = yield* compileRequest(
118
+ ai.request({
119
+ model,
120
+ prompt: "Say hello.",
121
+ maxTokens: 40,
122
+ temperature: 0.2,
123
+ topP: 0.8,
124
+ topK: 12,
125
+ frequencyPenalty: 0.3,
126
+ presencePenalty: 0.4,
127
+ seed: 42,
128
+ stop: ["done"],
129
+ }),
130
+ )
131
+
132
+ expect(prepared.body.generationConfig).toEqual({
133
+ maxOutputTokens: 40,
134
+ temperature: 0.2,
135
+ topP: 0.8,
136
+ topK: 12,
137
+ frequencyPenalty: 0.3,
138
+ presencePenalty: 0.4,
139
+ seed: 42,
140
+ stopSequences: ["done"],
141
+ thinkingConfig: undefined,
142
+ })
143
+ }),
144
+ )
145
+
146
+ it.effect("lowers chronological system updates to wrapped user text in order", () =>
147
+ Effect.gen(function* () {
148
+ const prepared = yield* compileRequest(
149
+ ai.request({
150
+ model,
151
+ messages: [Message.user("Before."), Message.system("Update."), Message.assistant("After.")],
152
+ }),
153
+ )
154
+
155
+ expect(prepared.body.contents).toEqual([
156
+ { role: "user", parts: [{ text: "Before." }, { text: "<system-update>\nUpdate.\n</system-update>" }] },
157
+ { role: "model", parts: [{ text: "After." }] },
158
+ ])
159
+ }),
160
+ )
161
+
162
+ it.effect("keeps system updates separate from function responses", () =>
163
+ Effect.gen(function* () {
164
+ const prepared = yield* compileRequest(
165
+ ai.request({
166
+ model,
167
+ messages: [
168
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
169
+ Message.tool({ id: "call_1", name: "lookup", result: "done", resultType: "text" }),
170
+ Message.system("Update."),
171
+ Message.system("Later update."),
172
+ ],
173
+ }),
174
+ )
175
+
176
+ expect(prepared.body.contents).toEqual([
177
+ {
178
+ role: "model",
179
+ parts: [
180
+ {
181
+ functionCall: { name: "lookup", args: { query: "weather" } },
182
+ thoughtSignature: "skip_thought_signature_validator",
183
+ },
184
+ ],
185
+ },
186
+ {
187
+ role: "user",
188
+ parts: [
189
+ {
190
+ functionResponse: {
191
+ name: "lookup",
192
+ response: { name: "lookup", content: "done" },
193
+ },
194
+ },
195
+ ],
196
+ },
197
+ {
198
+ role: "user",
199
+ parts: [
200
+ { text: "<system-update>\nUpdate.\n</system-update>" },
201
+ { text: "<system-update>\nLater update.\n</system-update>" },
202
+ ],
203
+ },
204
+ ])
205
+ }),
206
+ )
207
+
208
+ it.effect("merges parallel tool results into one function-response turn", () =>
209
+ Effect.gen(function* () {
210
+ const prepared = yield* compileRequest(
211
+ ai.request({
212
+ model,
213
+ messages: [
214
+ Message.assistant([
215
+ ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } }),
216
+ ToolCallPart.make({ id: "call_2", name: "lookup", input: { query: "time" } }),
217
+ ]),
218
+ Message.tool({ id: "call_1", name: "lookup", result: "sunny", resultType: "text" }),
219
+ Message.tool({ id: "call_2", name: "lookup", result: "noon", resultType: "text" }),
220
+ ],
221
+ }),
222
+ )
223
+
224
+ expect(prepared.body.contents).toEqual([
225
+ {
226
+ role: "model",
227
+ parts: [
228
+ {
229
+ functionCall: { name: "lookup", args: { query: "weather" } },
230
+ thoughtSignature: "skip_thought_signature_validator",
231
+ },
232
+ {
233
+ functionCall: { name: "lookup", args: { query: "time" } },
234
+ thoughtSignature: "skip_thought_signature_validator",
235
+ },
236
+ ],
237
+ },
238
+ {
239
+ role: "user",
240
+ parts: [
241
+ {
242
+ functionResponse: {
243
+ name: "lookup",
244
+ response: { name: "lookup", content: "sunny" },
245
+ },
246
+ },
247
+ {
248
+ functionResponse: {
249
+ name: "lookup",
250
+ response: { name: "lookup", content: "noon" },
251
+ },
252
+ },
253
+ ],
254
+ },
255
+ ])
256
+ }),
257
+ )
258
+
259
+ it.effect("lowers function call ids for gemini 3 models", () =>
260
+ Effect.gen(function* () {
261
+ const prepared = yield* compileRequest(
262
+ ai.request({
263
+ model: gemini3,
264
+ messages: [
265
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
266
+ Message.tool({ id: "call_1", name: "lookup", result: "done", resultType: "text" }),
267
+ ],
268
+ }),
269
+ )
270
+
271
+ expect(prepared.body.contents).toEqual([
272
+ {
273
+ role: "model",
274
+ parts: [
275
+ {
276
+ functionCall: { id: "call_1", name: "lookup", args: { query: "weather" } },
277
+ thoughtSignature: "skip_thought_signature_validator",
278
+ },
279
+ ],
280
+ },
281
+ {
282
+ role: "user",
283
+ parts: [
284
+ {
285
+ functionResponse: {
286
+ id: "call_1",
287
+ name: "lookup",
288
+ response: { name: "lookup", content: "done" },
289
+ },
290
+ },
291
+ ],
292
+ },
293
+ ])
294
+ }),
295
+ )
296
+
297
+ it.effect("omits function call ids entirely for pre-gemini-3 models", () =>
298
+ Effect.gen(function* () {
299
+ const messages = [
300
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
301
+ Message.tool({ id: "call_1", name: "lookup", result: "done", resultType: "text" }),
302
+ ]
303
+ const legacy = yield* compileRequest(ai.request({ model, messages }))
304
+ const older = yield* compileRequest(
305
+ ai.request({
306
+ model: Gemini.route
307
+ .with({
308
+ endpoint: { baseURL: "https://generativelanguage.test/v1beta/" },
309
+ auth: Auth.header("x-goog-api-key", "test"),
310
+ })
311
+ .model({ id: "gemini-1.5-flash" }),
312
+ messages,
313
+ }),
314
+ )
315
+
316
+ expect(legacy.body.contents).toEqual([
317
+ {
318
+ role: "model",
319
+ parts: [
320
+ {
321
+ functionCall: { name: "lookup", args: { query: "weather" } },
322
+ thoughtSignature: "skip_thought_signature_validator",
323
+ },
324
+ ],
325
+ },
326
+ {
327
+ role: "user",
328
+ parts: [{ functionResponse: { name: "lookup", response: { name: "lookup", content: "done" } } }],
329
+ },
330
+ ])
331
+ expect(JSON.stringify(legacy.body.contents)).not.toContain('"id"')
332
+ expect(JSON.stringify(older.body.contents)).not.toContain('"id"')
333
+ }),
334
+ )
335
+
336
+ it.effect("includes function call ids for non-gemini model ids", () =>
337
+ Effect.gen(function* () {
338
+ const prepared = yield* compileRequest(
339
+ ai.request({
340
+ model: Gemini.route
341
+ .with({
342
+ endpoint: { baseURL: "https://generativelanguage.test/v1beta/" },
343
+ auth: Auth.header("x-goog-api-key", "test"),
344
+ })
345
+ .model({ id: "gemma-3-27b-it" }),
346
+ messages: [
347
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
348
+ Message.tool({ id: "call_1", name: "lookup", result: "done", resultType: "text" }),
349
+ ],
350
+ }),
351
+ )
352
+
353
+ expect(prepared.body.contents).toEqual([
354
+ {
355
+ role: "model",
356
+ parts: [
357
+ {
358
+ functionCall: { id: "call_1", name: "lookup", args: { query: "weather" } },
359
+ thoughtSignature: "skip_thought_signature_validator",
360
+ },
361
+ ],
362
+ },
363
+ {
364
+ role: "user",
365
+ parts: [
366
+ { functionResponse: { id: "call_1", name: "lookup", response: { name: "lookup", content: "done" } } },
367
+ ],
368
+ },
369
+ ])
370
+ }),
371
+ )
372
+
373
+ it.effect("prepares multimodal user input and tool history", () =>
374
+ Effect.gen(function* () {
375
+ const prepared = yield* compileRequest(
376
+ ai.request({
377
+ id: "req_tool_result",
378
+ model,
379
+ tools: [
380
+ {
381
+ name: "lookup",
382
+ description: "Lookup data",
383
+ inputSchema: { type: "object", properties: { query: { type: "string" } } },
384
+ },
385
+ ],
386
+ toolChoice: { type: "tool", name: "lookup" },
387
+ messages: [
388
+ Message.user([
389
+ { type: "text", text: "What is in this image?" },
390
+ { type: "media", media: Media.base64("AAECAw==", "image/png") },
391
+ { type: "media", media: Media.base64("JVBERi0xLjQ=", "application/pdf") },
392
+ ]),
393
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
394
+ Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
395
+ ],
396
+ }),
397
+ )
398
+
399
+ expect(prepared.body).toEqual({
400
+ contents: [
401
+ {
402
+ role: "user",
403
+ parts: [
404
+ { text: "What is in this image?" },
405
+ { inlineData: { mimeType: "image/png", data: "AAECAw==" } },
406
+ { inlineData: { mimeType: "application/pdf", data: "JVBERi0xLjQ=" } },
407
+ ],
408
+ },
409
+ {
410
+ role: "model",
411
+ parts: [
412
+ {
413
+ functionCall: { name: "lookup", args: { query: "weather" } },
414
+ thoughtSignature: "skip_thought_signature_validator",
415
+ },
416
+ ],
417
+ },
418
+ {
419
+ role: "user",
420
+ parts: [
421
+ {
422
+ functionResponse: {
423
+ name: "lookup",
424
+ response: { name: "lookup", content: '{"forecast":"sunny"}' },
425
+ },
426
+ },
427
+ ],
428
+ },
429
+ ],
430
+ tools: [
431
+ {
432
+ functionDeclarations: [
433
+ {
434
+ name: "lookup",
435
+ description: "Lookup data",
436
+ parametersJsonSchema: { type: "object", properties: { query: { type: "string" } } },
437
+ },
438
+ ],
439
+ },
440
+ ],
441
+ toolConfig: { functionCallingConfig: { mode: "ANY", allowedFunctionNames: ["lookup"] } },
442
+ })
443
+ }),
444
+ )
445
+
446
+ it.effect("continues media tool results as inline model input without base64 text", () =>
447
+ Effect.gen(function* () {
448
+ const prepared = yield* compileRequest(
449
+ ai.request({
450
+ model,
451
+ messages: [
452
+ Message.assistant([ToolCallPart.make({ id: "call_image", name: "read", input: { path: "pixel.png" } })]),
453
+ Message.tool({
454
+ id: "call_image",
455
+ name: "read",
456
+ result: {
457
+ type: "content",
458
+ value: [
459
+ { type: "text", text: "Image read successfully" },
460
+ { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png", name: "pixel.png" },
461
+ { type: "file", uri: "data:application/pdf;base64,JVBERi0xLjQ=", mime: "application/pdf" },
462
+ ],
463
+ },
464
+ }),
465
+ ],
466
+ }),
467
+ )
468
+
469
+ expect(prepared.body.contents).toEqual([
470
+ {
471
+ role: "model",
472
+ parts: [
473
+ {
474
+ functionCall: { name: "read", args: { path: "pixel.png" } },
475
+ thoughtSignature: "skip_thought_signature_validator",
476
+ },
477
+ ],
478
+ },
479
+ {
480
+ role: "user",
481
+ parts: [
482
+ {
483
+ functionResponse: {
484
+ name: "read",
485
+ response: { name: "read", content: "Image read successfully" },
486
+ },
487
+ },
488
+ ],
489
+ },
490
+ {
491
+ role: "user",
492
+ parts: [
493
+ { text: "Attached media from tool result:" },
494
+ { inlineData: { mimeType: "image/png", data: "AAECAw==" } },
495
+ { inlineData: { mimeType: "application/pdf", data: "JVBERi0xLjQ=" } },
496
+ ],
497
+ },
498
+ ])
499
+ expect(JSON.stringify(prepared.body.contents)).not.toContain('"content":"AAECAw=="')
500
+ }),
501
+ )
502
+
503
+ it.effect("strips matching data URLs to raw base64 inlineData", () =>
504
+ Effect.gen(function* () {
505
+ const prepared = yield* compileRequest(
506
+ ai.request({
507
+ model,
508
+ messages: [
509
+ Message.user({ type: "media", media: Media.fromDataUrl("data:image/png;base64,AAEC") }),
510
+ Message.tool({
511
+ id: "call_image",
512
+ name: "read",
513
+ result: {
514
+ type: "content",
515
+ value: [{ type: "file", uri: "data:image/jpeg;base64,/9j/", mime: "image/jpeg" }],
516
+ },
517
+ }),
518
+ ],
519
+ }),
520
+ )
521
+ expect(prepared.body.contents).toEqual([
522
+ { role: "user", parts: [{ inlineData: { mimeType: "image/png", data: "AAEC" } }] },
523
+ {
524
+ role: "user",
525
+ parts: [
526
+ {
527
+ functionResponse: {
528
+ name: "read",
529
+ response: { name: "read", content: "" },
530
+ },
531
+ },
532
+ ],
533
+ },
534
+ {
535
+ role: "user",
536
+ parts: [
537
+ { text: "Attached media from tool result:" },
538
+ { inlineData: { mimeType: "image/jpeg", data: "/9j/" } },
539
+ ],
540
+ },
541
+ ])
542
+ }),
543
+ )
544
+
545
+ it.effect("nests media inside function responses for gemini 3", () =>
546
+ Effect.gen(function* () {
547
+ const prepared = yield* compileRequest(
548
+ ai.request({
549
+ model: gemini3,
550
+ messages: [
551
+ Message.assistant([
552
+ ToolCallPart.make({
553
+ id: "call_image",
554
+ name: "read",
555
+ input: { path: "pixel.png" },
556
+ providerMetadata: { google: { thoughtSignature: "sig_1" } },
557
+ }),
558
+ ]),
559
+ Message.tool({
560
+ id: "call_image",
561
+ name: "read",
562
+ result: {
563
+ type: "content",
564
+ value: [
565
+ { type: "text", text: "Image read successfully" },
566
+ { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png", name: "pixel.png" },
567
+ ],
568
+ },
569
+ }),
570
+ ],
571
+ }),
572
+ )
573
+
574
+ expect(prepared.body.contents).toEqual([
575
+ {
576
+ role: "model",
577
+ parts: [
578
+ {
579
+ functionCall: { id: "call_image", name: "read", args: { path: "pixel.png" } },
580
+ thoughtSignature: "sig_1",
581
+ },
582
+ ],
583
+ },
584
+ {
585
+ role: "user",
586
+ parts: [
587
+ {
588
+ functionResponse: {
589
+ id: "call_image",
590
+ name: "read",
591
+ response: { name: "read", content: "Image read successfully" },
592
+ parts: [{ inlineData: { mimeType: "image/png", data: "AAECAw==" } }],
593
+ },
594
+ },
595
+ ],
596
+ },
597
+ ])
598
+ }),
599
+ )
600
+
601
+ it.effect("forwards native video URLs in user and tool input", () =>
602
+ Effect.gen(function* () {
603
+ const uri = "https://example.test/clip.mp4"
604
+ const messages = [
605
+ Message.user(Message.media(Media.url(uri, { mediaType: "video/mp4" }))),
606
+ Message.assistant([ToolCallPart.make({ id: "call_video", name: "read", input: {} })]),
607
+ Message.tool({
608
+ id: "call_video",
609
+ name: "read",
610
+ result: { type: "content", value: [{ type: "file", uri, mime: "video/mp4" }] },
611
+ }),
612
+ ]
613
+ const gemini = yield* compileRequest(ai.request({ model: gemini3, messages }))
614
+ expect(gemini.body).toEqual({
615
+ contents: [
616
+ { role: "user", parts: [{ fileData: { mimeType: "video/mp4", fileUri: uri } }] },
617
+ {
618
+ role: "model",
619
+ parts: [
620
+ {
621
+ functionCall: { id: "call_video", name: "read", args: {} },
622
+ thoughtSignature: "skip_thought_signature_validator",
623
+ },
624
+ ],
625
+ },
626
+ {
627
+ role: "user",
628
+ parts: [{ functionResponse: { id: "call_video", name: "read", response: { name: "read", content: "" } } }],
629
+ },
630
+ {
631
+ role: "user",
632
+ parts: [
633
+ { text: "Attached media from tool result:" },
634
+ { fileData: { mimeType: "video/mp4", fileUri: uri } },
635
+ ],
636
+ },
637
+ ],
638
+ })
639
+
640
+ const interactions = yield* compileRequest(
641
+ ai.request({
642
+ model: Google.configure({ apiKey: "test" }).interactions("gemini-3-flash-preview"),
643
+ messages,
644
+ }),
645
+ )
646
+ expect(interactions.body).toEqual({
647
+ model: "gemini-3-flash-preview",
648
+ input: [
649
+ { type: "user_input", content: [{ type: "video", uri, mime_type: "video/mp4" }] },
650
+ {
651
+ type: "function_call",
652
+ id: "call_video",
653
+ name: "read",
654
+ arguments: {},
655
+ signature: "skip_thought_signature_validator",
656
+ },
657
+ {
658
+ type: "function_result",
659
+ call_id: "call_video",
660
+ name: "read",
661
+ result: [{ type: "video", uri, mime_type: "video/mp4" }],
662
+ },
663
+ ],
664
+ stream: true,
665
+ store: false,
666
+ generation_config: {},
667
+ })
668
+
669
+ const error = yield* compileRequest(
670
+ ai.request({
671
+ model: gemini3,
672
+ prompt: Message.media(Media.url("https://example.test/image.png", { mediaType: "image/png" })),
673
+ }),
674
+ ).pipe(Effect.flip)
675
+ expect(error.reason._tag).toBe("InvalidRequest")
676
+ }),
677
+ )
678
+
679
+ it.effect("flushes pending media before system update text", () =>
680
+ Effect.gen(function* () {
681
+ const prepared = yield* compileRequest(
682
+ ai.request({
683
+ model,
684
+ messages: [
685
+ Message.assistant([ToolCallPart.make({ id: "call_1", name: "shot", input: {} })]),
686
+ Message.tool({
687
+ id: "call_1",
688
+ name: "shot",
689
+ result: {
690
+ type: "content",
691
+ value: [{ type: "file", uri: "data:image/png;base64,AAEC", mime: "image/png" }],
692
+ },
693
+ }),
694
+ Message.system("Update."),
695
+ ],
696
+ }),
697
+ )
698
+
699
+ expect(prepared.body.contents).toEqual([
700
+ {
701
+ role: "model",
702
+ parts: [{ functionCall: { name: "shot", args: {} }, thoughtSignature: "skip_thought_signature_validator" }],
703
+ },
704
+ {
705
+ role: "user",
706
+ parts: [{ functionResponse: { name: "shot", response: { name: "shot", content: "" } } }],
707
+ },
708
+ {
709
+ role: "user",
710
+ parts: [
711
+ { text: "Attached media from tool result:" },
712
+ { inlineData: { mimeType: "image/png", data: "AAEC" } },
713
+ { text: "<system-update>\nUpdate.\n</system-update>" },
714
+ ],
715
+ },
716
+ ])
717
+ }),
718
+ )
719
+
720
+ it.effect("collects legacy tool media into one turn after merged responses", () =>
721
+ Effect.gen(function* () {
722
+ const prepared = yield* compileRequest(
723
+ ai.request({
724
+ model,
725
+ messages: [
726
+ Message.assistant([
727
+ ToolCallPart.make({ id: "call_1", name: "shot", input: {} }),
728
+ ToolCallPart.make({ id: "call_2", name: "shot", input: {} }),
729
+ ]),
730
+ Message.tool({
731
+ id: "call_1",
732
+ name: "shot",
733
+ result: {
734
+ type: "content",
735
+ value: [{ type: "file", uri: "data:image/png;base64,AAEC", mime: "image/png" }],
736
+ },
737
+ }),
738
+ Message.tool({
739
+ id: "call_2",
740
+ name: "shot",
741
+ result: {
742
+ type: "content",
743
+ value: [{ type: "text", text: "no image here" }],
744
+ },
745
+ }),
746
+ ],
747
+ }),
748
+ )
749
+
750
+ expect(prepared.body.contents).toEqual([
751
+ {
752
+ role: "model",
753
+ parts: [
754
+ { functionCall: { name: "shot", args: {} }, thoughtSignature: "skip_thought_signature_validator" },
755
+ { functionCall: { name: "shot", args: {} }, thoughtSignature: "skip_thought_signature_validator" },
756
+ ],
757
+ },
758
+ {
759
+ role: "user",
760
+ parts: [
761
+ { functionResponse: { name: "shot", response: { name: "shot", content: "" } } },
762
+ { functionResponse: { name: "shot", response: { name: "shot", content: "no image here" } } },
763
+ ],
764
+ },
765
+ {
766
+ role: "user",
767
+ parts: [
768
+ { text: "Attached media from tool result:" },
769
+ { inlineData: { mimeType: "image/png", data: "AAEC" } },
770
+ ],
771
+ },
772
+ ])
773
+ }),
774
+ )
775
+
776
+ it.effect("passes encoded media through without local validation", () =>
777
+ Effect.gen(function* () {
778
+ const prepared = yield* compileRequest(
779
+ ai.request({
780
+ model,
781
+ messages: [
782
+ Message.user([
783
+ { type: "media", media: Media.base64("%%%=", "image/png") },
784
+ { type: "media", media: Media.fromDataUrl("data:image/jpeg;base64,/9j/") },
785
+ { type: "media", media: Media.base64("PHN2Zz4=", "image/svg+xml") },
786
+ ]),
787
+ ],
788
+ }),
789
+ )
790
+ expect(prepared.body.contents).toEqual([
791
+ {
792
+ role: "user",
793
+ parts: [
794
+ { inlineData: { mimeType: "image/png", data: "%%%=" } },
795
+ { inlineData: { mimeType: "image/jpeg", data: "/9j/" } },
796
+ { inlineData: { mimeType: "image/svg+xml", data: "PHN2Zz4=" } },
797
+ ],
798
+ },
799
+ ])
800
+ }),
801
+ )
802
+
803
+ it.effect("keeps tools and sends function calling mode NONE", () =>
804
+ Effect.gen(function* () {
805
+ const prepared = yield* compileRequest(
806
+ ai.request({
807
+ id: "req_tool_choice_none",
808
+ model,
809
+ prompt: "Say hello.",
810
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
811
+ toolChoice: { type: "none" },
812
+ }),
813
+ )
814
+
815
+ expect(prepared.body).toMatchObject({
816
+ contents: [{ role: "user", parts: [{ text: "Say hello." }] }],
817
+ tools: [{ functionDeclarations: [{ name: "lookup", description: "Lookup data" }] }],
818
+ toolConfig: { functionCallingConfig: { mode: "NONE" } },
819
+ })
820
+ }),
821
+ )
822
+
823
+ it.effect("normalizes the JSON Schema shapes Gemini rejects", () =>
824
+ Effect.gen(function* () {
825
+ const prepared = yield* compileRequest(
826
+ ai.request({
827
+ id: "req_schema_patch",
828
+ model,
829
+ prompt: "Use the tool.",
830
+ tools: [
831
+ {
832
+ name: "lookup",
833
+ description: "Lookup data",
834
+ inputSchema: {
835
+ type: "object",
836
+ required: ["ttl", "items", "parent", "missing"],
837
+ properties: {
838
+ ttl: { type: "number", minimum: 0, exclusiveMinimum: true, maximum: 60, exclusiveMaximum: false },
839
+ pair: { type: "array", items: [{ type: "string" }, { type: "integer" }], additionalItems: false },
840
+ items: { type: "array", items: { type: "string" } },
841
+ required: { type: "boolean" },
842
+ params: { $ref: "#/$defs/Json" },
843
+ tree: { $ref: "#/$defs/Node" },
844
+ chain: { $ref: "#/$defs/Link" },
845
+ batch: { $ref: "#/$defs/Batch" },
846
+ self: { $ref: "#" },
847
+ parent: { $ref: "#" },
848
+ cart: { type: "object", default: { items: ["a"] } },
849
+ },
850
+ dependentRequired: { items: ["ttl"] },
851
+ $defs: {
852
+ Json: {
853
+ anyOf: [
854
+ { type: "string" },
855
+ { type: "array", items: { $ref: "#/$defs/Json" } },
856
+ { type: "object", additionalProperties: { $ref: "#/$defs/Json" } },
857
+ ],
858
+ },
859
+ Node: { type: "object", properties: { child: { $ref: "#/$defs/Node" } } },
860
+ Link: { type: "object", required: ["next"], properties: { next: { $ref: "#/$defs/Link" } } },
861
+ Batch: { type: "array", minItems: 1, items: { $ref: "#/$defs/Batch" } },
862
+ },
863
+ },
864
+ },
865
+ ],
866
+ }),
867
+ )
868
+
869
+ expect(prepared.body.tools?.[0]?.functionDeclarations[0]?.parametersJsonSchema).toEqual({
870
+ type: "object",
871
+ required: ["ttl", "items", "parent"],
872
+ properties: {
873
+ ttl: { type: "number", exclusiveMinimum: 0, maximum: 60 },
874
+ pair: { type: "array", prefixItems: [{ type: "string" }, { type: "integer" }], items: false },
875
+ items: { type: "array", items: { type: "string" } },
876
+ required: { type: "boolean" },
877
+ params: { $ref: "#/$defs/Json" },
878
+ tree: { $ref: "#/$defs/Node" },
879
+ chain: { $ref: "#/$defs/Link" },
880
+ batch: { $ref: "#/$defs/Batch" },
881
+ self: { $ref: "#" },
882
+ parent: {},
883
+ cart: { type: "object", default: { items: ["a"] } },
884
+ },
885
+ dependentRequired: { items: ["ttl"] },
886
+ $defs: {
887
+ Json: {
888
+ anyOf: [
889
+ { type: "string" },
890
+ { type: "array", items: { $ref: "#/$defs/Json" } },
891
+ { type: "object", additionalProperties: {} },
892
+ ],
893
+ },
894
+ Node: { type: "object", properties: { child: { $ref: "#/$defs/Node" } } },
895
+ Link: { type: "object", required: ["next"], properties: { next: {} } },
896
+ Batch: { type: "array", minItems: 1, items: {} },
897
+ },
898
+ })
899
+ }),
900
+ )
901
+
902
+ it.effect("preserves nested empty object tool schemas", () =>
903
+ Effect.gen(function* () {
904
+ const prepared = yield* compileRequest(
905
+ ai.request({
906
+ model,
907
+ prompt: "Use the tool.",
908
+ tools: [
909
+ {
910
+ name: "configure",
911
+ description: "Configure the operation",
912
+ inputSchema: {
913
+ type: "object",
914
+ required: ["options"],
915
+ properties: {
916
+ options: { type: "object", description: "Optional provider settings", properties: {} },
917
+ },
918
+ },
919
+ },
920
+ ],
921
+ }),
922
+ )
923
+
924
+ expect(prepared.body.tools).toEqual([
925
+ {
926
+ functionDeclarations: [
927
+ {
928
+ name: "configure",
929
+ description: "Configure the operation",
930
+ parametersJsonSchema: {
931
+ type: "object",
932
+ required: ["options"],
933
+ properties: {
934
+ options: { type: "object", description: "Optional provider settings", properties: {} },
935
+ },
936
+ },
937
+ },
938
+ ],
939
+ },
940
+ ])
941
+ }),
942
+ )
943
+
944
+ it.effect("sends standard JSON Schema tool parameters unchanged", () =>
945
+ Effect.gen(function* () {
946
+ const inputSchema = {
947
+ type: "object",
948
+ required: ["level"],
949
+ properties: {
950
+ level: { type: "integer", enum: [1, 2, 3] },
951
+ status: { type: ["number", "string"], description: "Status filter" },
952
+ maybe: { anyOf: [{ type: "string" }, { type: "null" }] },
953
+ kind: { const: "fixed" },
954
+ mode: { enum: ["fast", "safe"] },
955
+ tags: { type: "array" },
956
+ env: { type: "object", additionalProperties: { type: "string" } },
957
+ action: {
958
+ oneOf: [
959
+ { type: "object", properties: { type: { const: "move" }, to: { type: "string" } } },
960
+ { type: "object", properties: { type: { const: "delete" } } },
961
+ ],
962
+ },
963
+ item: { $ref: "#/$defs/Item" },
964
+ },
965
+ $defs: { Item: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } },
966
+ }
967
+ const prepared = yield* compileRequest(
968
+ ai.request({
969
+ model,
970
+ prompt: "Use the tool.",
971
+ tools: [{ name: "filter", description: "Filter values", inputSchema }],
972
+ }),
973
+ )
974
+
975
+ expect(prepared.body.tools?.[0]?.functionDeclarations[0]?.parametersJsonSchema).toEqual(inputSchema)
976
+ }),
977
+ )
978
+
979
+ it.effect("reports the cost the endpoint billed", () =>
980
+ Effect.gen(function* () {
981
+ const body = sseEvents({
982
+ candidates: [{ content: { role: "model", parts: [{ text: "Hello" }] }, finishReason: "STOP" }],
983
+ usageMetadata: {
984
+ promptTokenCount: 5,
985
+ toolUsePromptTokenCount: 3,
986
+ candidatesTokenCount: 2,
987
+ cost: 0,
988
+ opencode: { allowance: 0.0042 },
989
+ },
990
+ })
991
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
992
+
993
+ expect(response.usage).toMatchObject({ inputTokens: 8, outputTokens: 2, cost: 0 })
994
+ }),
995
+ )
996
+
997
+ it.effect("counts cumulative tool-use prompts once alongside cached input", () =>
998
+ Effect.gen(function* () {
999
+ const body = sseEvents(
1000
+ {
1001
+ candidates: [{ content: { role: "model", parts: [{ text: "Working" }] } }],
1002
+ usageMetadata: {
1003
+ promptTokenCount: 271,
1004
+ cachedContentTokenCount: 100,
1005
+ toolUsePromptTokenCount: 200,
1006
+ },
1007
+ },
1008
+ {
1009
+ candidates: [{ content: { role: "model", parts: [{ text: " done" }] }, finishReason: "STOP" }],
1010
+ usageMetadata: {
1011
+ promptTokenCount: 271,
1012
+ cachedContentTokenCount: 100,
1013
+ toolUsePromptTokenCount: 480,
1014
+ candidatesTokenCount: 130,
1015
+ thoughtsTokenCount: 158,
1016
+ },
1017
+ },
1018
+ )
1019
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
1020
+
1021
+ expect(response.usage).toMatchObject({
1022
+ inputTokens: 751,
1023
+ nonCachedInputTokens: 651,
1024
+ cacheReadInputTokens: 100,
1025
+ outputTokens: 288,
1026
+ reasoningTokens: 158,
1027
+ totalTokens: 1039,
1028
+ providerMetadata: { google: { promptTokenCount: 271, toolUsePromptTokenCount: 480 } },
1029
+ })
1030
+ }),
1031
+ )
1032
+
1033
+ it.effect("parses text, reasoning, and usage stream fixtures", () =>
1034
+ Effect.gen(function* () {
1035
+ const body = sseEvents(
1036
+ {
1037
+ candidates: [
1038
+ {
1039
+ content: { role: "model", parts: [{ text: "thinking", thought: true }] },
1040
+ },
1041
+ ],
1042
+ },
1043
+ {
1044
+ candidates: [
1045
+ {
1046
+ content: { role: "model", parts: [{ text: "Hello" }] },
1047
+ },
1048
+ ],
1049
+ },
1050
+ {
1051
+ candidates: [
1052
+ {
1053
+ content: { role: "model", parts: [{ text: "!" }] },
1054
+ finishReason: "STOP",
1055
+ },
1056
+ ],
1057
+ },
1058
+ {
1059
+ usageMetadata: {
1060
+ promptTokenCount: 5,
1061
+ candidatesTokenCount: 2,
1062
+ totalTokenCount: 7,
1063
+ thoughtsTokenCount: 1,
1064
+ cachedContentTokenCount: 1,
1065
+ },
1066
+ },
1067
+ )
1068
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
1069
+
1070
+ expect(response.text).toBe("Hello!")
1071
+ expect(response.reasoning).toBe("thinking")
1072
+ expect(response.usage).toMatchObject({
1073
+ inputTokens: 5,
1074
+ outputTokens: 3,
1075
+ nonCachedInputTokens: 4,
1076
+ cacheReadInputTokens: 1,
1077
+ reasoningTokens: 1,
1078
+ totalTokens: 7,
1079
+ })
1080
+ const usage = new Usage({
1081
+ inputTokens: 5,
1082
+ outputTokens: 3,
1083
+ nonCachedInputTokens: 4,
1084
+ cacheReadInputTokens: 1,
1085
+ reasoningTokens: 1,
1086
+ totalTokens: 7,
1087
+ providerMetadata: {
1088
+ google: {
1089
+ promptTokenCount: 5,
1090
+ candidatesTokenCount: 2,
1091
+ totalTokenCount: 7,
1092
+ thoughtsTokenCount: 1,
1093
+ cachedContentTokenCount: 1,
1094
+ },
1095
+ },
1096
+ })
1097
+ expect(response.events).toEqual([
1098
+ { type: "step-start", index: 0 },
1099
+ { type: "reasoning-start", id: "reasoning-0" },
1100
+ { type: "reasoning-delta", id: "reasoning-0", text: "thinking" },
1101
+ { type: "reasoning-end", id: "reasoning-0" },
1102
+ { type: "text-start", id: "text-0" },
1103
+ { type: "text-delta", id: "text-0", text: "Hello" },
1104
+ { type: "text-delta", id: "text-0", text: "!" },
1105
+ { type: "text-end", id: "text-0" },
1106
+ {
1107
+ type: "step-finish",
1108
+ index: 0,
1109
+ reason: { normalized: "stop", raw: "STOP" },
1110
+ usage,
1111
+ providerMetadata: undefined,
1112
+ },
1113
+ {
1114
+ type: "finish",
1115
+ reason: { normalized: "stop", raw: "STOP" },
1116
+ usage,
1117
+ },
1118
+ ])
1119
+ }),
1120
+ )
1121
+
1122
+ it.effect("assigns unique ids to separated reasoning blocks", () =>
1123
+ Effect.gen(function* () {
1124
+ const body = sseEvents(
1125
+ {
1126
+ candidates: [
1127
+ {
1128
+ content: {
1129
+ role: "model",
1130
+ parts: [{ text: "A", thought: true, thoughtSignature: "reasoning_sig_a" }],
1131
+ },
1132
+ },
1133
+ ],
1134
+ },
1135
+ {
1136
+ candidates: [
1137
+ {
1138
+ content: { role: "model", parts: [{ text: "X", thoughtSignature: "text_sig_x" }] },
1139
+ },
1140
+ ],
1141
+ },
1142
+ {
1143
+ candidates: [
1144
+ {
1145
+ content: {
1146
+ role: "model",
1147
+ parts: [{ text: "B", thought: true, thoughtSignature: "reasoning_sig_b" }],
1148
+ },
1149
+ },
1150
+ ],
1151
+ },
1152
+ {
1153
+ candidates: [
1154
+ {
1155
+ content: { role: "model", parts: [{ text: "Y", thoughtSignature: "text_sig_y" }] },
1156
+ finishReason: "STOP",
1157
+ },
1158
+ ],
1159
+ },
1160
+ )
1161
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
1162
+ const starts = response.events.filter((event) => event.type === "reasoning-start")
1163
+ const deltas = response.events.filter((event) => event.type === "reasoning-delta")
1164
+ const ends = response.events.filter((event) => event.type === "reasoning-end")
1165
+
1166
+ expect(starts.map((event) => event.id)).toEqual(["reasoning-0", "reasoning-1"])
1167
+ expect(starts[0]?.id).not.toBe(starts[1]?.id)
1168
+ expect(deltas.map((event) => ({ id: event.id, text: event.text }))).toEqual([
1169
+ { id: "reasoning-0", text: "A" },
1170
+ { id: "reasoning-1", text: "B" },
1171
+ ])
1172
+ expect(ends.map((event) => event.id)).toEqual(["reasoning-0", "reasoning-1"])
1173
+ expect(response.events.filter((event) => event.type === "text-start").map((event) => event.id)).toEqual([
1174
+ "text-0",
1175
+ "text-1",
1176
+ ])
1177
+ expect(response.events.filter((event) => event.type === "text-delta").map((event) => event.id)).toEqual([
1178
+ "text-0",
1179
+ "text-1",
1180
+ ])
1181
+ expect(response.events.filter((event) => event.type === "text-end").map((event) => event.id)).toEqual([
1182
+ "text-0",
1183
+ "text-1",
1184
+ ])
1185
+ expect(response.message.content).toEqual([
1186
+ {
1187
+ type: "reasoning",
1188
+ text: "A",
1189
+ providerMetadata: { google: { thoughtSignature: "reasoning_sig_a" } },
1190
+ },
1191
+ {
1192
+ type: "text",
1193
+ text: "X",
1194
+ providerMetadata: { google: { thoughtSignature: "text_sig_x" } },
1195
+ },
1196
+ {
1197
+ type: "reasoning",
1198
+ text: "B",
1199
+ providerMetadata: { google: { thoughtSignature: "reasoning_sig_b" } },
1200
+ },
1201
+ {
1202
+ type: "text",
1203
+ text: "Y",
1204
+ providerMetadata: { google: { thoughtSignature: "text_sig_y" } },
1205
+ },
1206
+ ])
1207
+ }),
1208
+ )
1209
+
1210
+ it.effect("ignores unknown response parts", () =>
1211
+ Effect.gen(function* () {
1212
+ const response = yield* LLMClient.generate(request).pipe(
1213
+ Effect.provide(
1214
+ fixedResponse(
1215
+ sseEvents({
1216
+ candidates: [
1217
+ {
1218
+ content: {
1219
+ role: "model",
1220
+ parts: [
1221
+ { text: "Hello " },
1222
+ { executableCode: { language: "PYTHON", code: "print('ignored')" } },
1223
+ { text: "world" },
1224
+ ],
1225
+ },
1226
+ finishReason: "STOP",
1227
+ },
1228
+ ],
1229
+ }),
1230
+ ),
1231
+ ),
1232
+ )
1233
+
1234
+ expect(response.text).toBe("Hello world")
1235
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
1236
+ }),
1237
+ )
1238
+
1239
+ it.effect("rejects malformed recognized response parts", () =>
1240
+ Effect.gen(function* () {
1241
+ const error = yield* LLMClient.generate(request).pipe(
1242
+ Effect.provide(
1243
+ fixedResponse(
1244
+ sseEvents({
1245
+ candidates: [{ content: { role: "model", parts: [{ text: 42 }] } }],
1246
+ }),
1247
+ ),
1248
+ ),
1249
+ Effect.flip,
1250
+ )
1251
+
1252
+ expect(error).toBeInstanceOf(AIError)
1253
+ expect(error.reason).toMatchObject({ _tag: "InvalidProviderOutput" })
1254
+ expect(error.message).toContain("Invalid google/gemini stream event")
1255
+ }),
1256
+ )
1257
+
1258
+ it.effect("preserves thoughtSignature for reasoning and tool-call continuation", () =>
1259
+ Effect.gen(function* () {
1260
+ const body = sseEvents({
1261
+ candidates: [
1262
+ {
1263
+ content: {
1264
+ role: "model",
1265
+ parts: [
1266
+ { text: "thinking", thought: true },
1267
+ { text: "", thought: true, thoughtSignature: "thought_sig" },
1268
+ {
1269
+ functionCall: { id: "provider_call", name: "lookup", args: { query: "weather" } },
1270
+ thoughtSignature: "tool_sig",
1271
+ },
1272
+ ],
1273
+ },
1274
+ finishReason: "STOP",
1275
+ },
1276
+ ],
1277
+ })
1278
+ const response = yield* LLMClient.generate({
1279
+ ...request,
1280
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1281
+ }).pipe(Effect.provide(fixedResponse(body)))
1282
+ const reasoning = response.events.find((event) => event.type === "reasoning-start")
1283
+ const reasoningEnd = response.events.find((event) => event.type === "reasoning-end")
1284
+ const toolCall = response.events.find((event) => event.type === "tool-call")
1285
+
1286
+ expect(reasoning).toEqual({
1287
+ type: "reasoning-start",
1288
+ id: "reasoning-0",
1289
+ providerMetadata: undefined,
1290
+ })
1291
+ expect(reasoningEnd).toEqual({
1292
+ type: "reasoning-end",
1293
+ id: "reasoning-0",
1294
+ providerMetadata: { google: { thoughtSignature: "thought_sig" } },
1295
+ })
1296
+ expect(toolCall).toMatchObject({
1297
+ id: "provider_call",
1298
+ providerMetadata: { google: { thoughtSignature: "tool_sig" } },
1299
+ })
1300
+ expect(response.events.findIndex((event) => event.type === "reasoning-end")).toBeLessThan(
1301
+ response.events.findIndex((event) => event.type === "tool-call"),
1302
+ )
1303
+
1304
+ const prepared = yield* compileRequest(
1305
+ ai.request({
1306
+ model: gemini3,
1307
+ messages: [
1308
+ Message.assistant([
1309
+ { type: "reasoning", text: "thinking", providerMetadata: reasoningEnd?.providerMetadata },
1310
+ ToolCallPart.make({
1311
+ id: "provider_call",
1312
+ name: "lookup",
1313
+ input: { query: "weather" },
1314
+ providerMetadata: toolCall?.providerMetadata,
1315
+ }),
1316
+ ]),
1317
+ Message.tool({
1318
+ id: "provider_call",
1319
+ name: "lookup",
1320
+ result: "done",
1321
+ resultType: "text",
1322
+ }),
1323
+ ],
1324
+ }),
1325
+ )
1326
+ expect(prepared.body.contents).toEqual([
1327
+ {
1328
+ role: "model",
1329
+ parts: [
1330
+ { text: "thinking", thought: true, thoughtSignature: "thought_sig" },
1331
+ {
1332
+ functionCall: { id: "provider_call", name: "lookup", args: { query: "weather" } },
1333
+ thoughtSignature: "tool_sig",
1334
+ },
1335
+ ],
1336
+ },
1337
+ {
1338
+ role: "user",
1339
+ parts: [
1340
+ {
1341
+ functionResponse: {
1342
+ id: "provider_call",
1343
+ name: "lookup",
1344
+ response: { name: "lookup", content: "done" },
1345
+ },
1346
+ },
1347
+ ],
1348
+ },
1349
+ ])
1350
+ }),
1351
+ )
1352
+
1353
+ it.effect("preserves thoughtSignature on visible text parts", () =>
1354
+ Effect.gen(function* () {
1355
+ const body = sseEvents({
1356
+ candidates: [
1357
+ {
1358
+ content: { role: "model", parts: [{ text: "All done.", thoughtSignature: "text_sig" }] },
1359
+ finishReason: "STOP",
1360
+ },
1361
+ ],
1362
+ })
1363
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
1364
+ const delta = response.events.find((event) => event.type === "text-delta")
1365
+ expect(delta).toMatchObject({
1366
+ id: "text-0",
1367
+ text: "All done.",
1368
+ providerMetadata: { google: { thoughtSignature: "text_sig" } },
1369
+ })
1370
+
1371
+ const prepared = yield* compileRequest(
1372
+ ai.request({
1373
+ model,
1374
+ messages: [
1375
+ Message.assistant([{ type: "text", text: "All done.", providerMetadata: delta?.providerMetadata }]),
1376
+ ],
1377
+ }),
1378
+ )
1379
+ expect(prepared.body.contents).toEqual([
1380
+ { role: "model", parts: [{ text: "All done.", thoughtSignature: "text_sig" }] },
1381
+ ])
1382
+ }),
1383
+ )
1384
+
1385
+ it.effect("flushes a trailing empty signed text part at block close", () =>
1386
+ Effect.gen(function* () {
1387
+ const body = sseEvents({
1388
+ candidates: [
1389
+ {
1390
+ content: {
1391
+ role: "model",
1392
+ parts: [{ text: "Working." }, { text: "", thoughtSignature: "tail_sig" }],
1393
+ },
1394
+ finishReason: "STOP",
1395
+ },
1396
+ ],
1397
+ })
1398
+ const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
1399
+ const delta = response.events.find((event) => event.type === "text-delta")
1400
+ const end = response.events.find((event) => event.type === "text-end")
1401
+
1402
+ expect(delta).toMatchObject({ id: "text-0", text: "Working.", providerMetadata: undefined })
1403
+ expect(end).toMatchObject({
1404
+ id: "text-0",
1405
+ providerMetadata: { google: { thoughtSignature: "tail_sig" } },
1406
+ })
1407
+ }),
1408
+ )
1409
+
1410
+ it.effect("replays unsigned Gemini 3 tool calls with the validator bypass sentinel", () =>
1411
+ Effect.gen(function* () {
1412
+ const prepared = yield* compileRequest(
1413
+ ai.request({
1414
+ model: gemini3,
1415
+ messages: [
1416
+ Message.assistant([ToolCallPart.make({ id: "tool_0", name: "lookup", input: { query: "weather" } })]),
1417
+ Message.tool({ id: "tool_0", name: "lookup", result: "done", resultType: "text" }),
1418
+ ],
1419
+ }),
1420
+ )
1421
+
1422
+ expect(prepared.body.contents).toEqual([
1423
+ {
1424
+ role: "model",
1425
+ parts: [
1426
+ {
1427
+ functionCall: { id: "tool_0", name: "lookup", args: { query: "weather" } },
1428
+ thoughtSignature: "skip_thought_signature_validator",
1429
+ },
1430
+ ],
1431
+ },
1432
+ {
1433
+ role: "user",
1434
+ parts: [
1435
+ {
1436
+ functionResponse: {
1437
+ id: "tool_0",
1438
+ name: "lookup",
1439
+ response: { name: "lookup", content: "done" },
1440
+ },
1441
+ },
1442
+ ],
1443
+ },
1444
+ ])
1445
+ }),
1446
+ )
1447
+
1448
+ it.effect("leaves unsigned parallel calls unchanged after a signed Gemini 3 call", () =>
1449
+ Effect.gen(function* () {
1450
+ const prepared = yield* compileRequest(
1451
+ ai.request({
1452
+ model: gemini3,
1453
+ messages: [
1454
+ Message.assistant([
1455
+ ToolCallPart.make({
1456
+ id: "tool_0",
1457
+ name: "lookup",
1458
+ input: { query: "weather" },
1459
+ providerMetadata: { google: { thoughtSignature: "parallel_signature" } },
1460
+ }),
1461
+ ToolCallPart.make({ id: "tool_1", name: "lookup", input: { query: "news" } }),
1462
+ ToolCallPart.make({ id: "tool_2", name: "lookup", input: { query: "sports" } }),
1463
+ ]),
1464
+ ],
1465
+ }),
1466
+ )
1467
+
1468
+ expect(prepared.body.contents[0]).toEqual({
1469
+ role: "model",
1470
+ parts: [
1471
+ {
1472
+ functionCall: { id: "tool_0", name: "lookup", args: { query: "weather" } },
1473
+ thoughtSignature: "parallel_signature",
1474
+ },
1475
+ {
1476
+ functionCall: { id: "tool_1", name: "lookup", args: { query: "news" } },
1477
+ thoughtSignature: undefined,
1478
+ },
1479
+ {
1480
+ functionCall: { id: "tool_2", name: "lookup", args: { query: "sports" } },
1481
+ thoughtSignature: undefined,
1482
+ },
1483
+ ],
1484
+ })
1485
+ }),
1486
+ )
1487
+
1488
+ it.effect("adds the validator bypass sentinel to every call in an unsigned Gemini 3 batch", () =>
1489
+ Effect.gen(function* () {
1490
+ const prepared = yield* compileRequest(
1491
+ ai.request({
1492
+ model: gemini3,
1493
+ messages: [
1494
+ Message.assistant([
1495
+ ToolCallPart.make({ id: "tool_0", name: "lookup", input: { query: "weather" } }),
1496
+ ToolCallPart.make({ id: "tool_1", name: "lookup", input: { query: "news" } }),
1497
+ ]),
1498
+ ],
1499
+ }),
1500
+ )
1501
+
1502
+ expect(prepared.body.contents[0]).toEqual({
1503
+ role: "model",
1504
+ parts: [
1505
+ {
1506
+ functionCall: { id: "tool_0", name: "lookup", args: { query: "weather" } },
1507
+ thoughtSignature: "skip_thought_signature_validator",
1508
+ },
1509
+ {
1510
+ functionCall: { id: "tool_1", name: "lookup", args: { query: "news" } },
1511
+ thoughtSignature: "skip_thought_signature_validator",
1512
+ },
1513
+ ],
1514
+ })
1515
+ }),
1516
+ )
1517
+
1518
+ it.effect("emits streamed tool calls and maps finish reason", () =>
1519
+ Effect.gen(function* () {
1520
+ const body = sseEvents({
1521
+ candidates: [
1522
+ {
1523
+ content: {
1524
+ role: "model",
1525
+ parts: [{ functionCall: { name: "lookup", args: { query: "weather" } } }],
1526
+ },
1527
+ finishReason: "STOP",
1528
+ },
1529
+ ],
1530
+ usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 1 },
1531
+ })
1532
+ const response = yield* LLMClient.generate({
1533
+ ...request,
1534
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1535
+ }).pipe(Effect.provide(fixedResponse(body)))
1536
+ const usage = new Usage({
1537
+ inputTokens: 5,
1538
+ outputTokens: 1,
1539
+ nonCachedInputTokens: 5,
1540
+ cacheReadInputTokens: undefined,
1541
+ reasoningTokens: undefined,
1542
+ totalTokens: 6,
1543
+ providerMetadata: { google: { promptTokenCount: 5, candidatesTokenCount: 1 } },
1544
+ })
1545
+
1546
+ expect(response.toolCalls[0].id).toMatch(/^tool_[0-9a-zA-Z]+$/)
1547
+ expect(response.toolCalls[0]).toMatchObject({
1548
+ type: "tool-call",
1549
+ name: "lookup",
1550
+ input: { query: "weather" },
1551
+ })
1552
+ expect(response.events).toEqual([
1553
+ { type: "step-start", index: 0 },
1554
+ {
1555
+ type: "tool-call",
1556
+ id: response.toolCalls[0].id,
1557
+ name: "lookup",
1558
+ input: { query: "weather" },
1559
+ providerExecuted: undefined,
1560
+ providerMetadata: undefined,
1561
+ },
1562
+ {
1563
+ type: "step-finish",
1564
+ index: 0,
1565
+ reason: { normalized: "tool-calls", raw: "STOP" },
1566
+ usage,
1567
+ providerMetadata: undefined,
1568
+ },
1569
+ {
1570
+ type: "finish",
1571
+ reason: { normalized: "tool-calls", raw: "STOP" },
1572
+ usage,
1573
+ },
1574
+ ])
1575
+ }),
1576
+ )
1577
+
1578
+ it.effect("separates text blocks around streamed tool calls", () =>
1579
+ Effect.gen(function* () {
1580
+ const body = sseEvents({
1581
+ candidates: [
1582
+ {
1583
+ content: {
1584
+ role: "model",
1585
+ parts: [
1586
+ { text: "before" },
1587
+ { functionCall: { id: "call_1", name: "lookup", args: { query: "weather" } } },
1588
+ { text: "after" },
1589
+ ],
1590
+ },
1591
+ finishReason: "STOP",
1592
+ },
1593
+ ],
1594
+ })
1595
+ const response = yield* LLMClient.generate({
1596
+ ...request,
1597
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1598
+ }).pipe(Effect.provide(fixedResponse(body)))
1599
+
1600
+ expect(response.events.slice(1, 8)).toEqual([
1601
+ { type: "text-start", id: "text-0" },
1602
+ { type: "text-delta", id: "text-0", text: "before" },
1603
+ { type: "text-end", id: "text-0" },
1604
+ {
1605
+ type: "tool-call",
1606
+ id: "call_1",
1607
+ name: "lookup",
1608
+ input: { query: "weather" },
1609
+ providerExecuted: undefined,
1610
+ providerMetadata: undefined,
1611
+ },
1612
+ { type: "text-start", id: "text-1" },
1613
+ { type: "text-delta", id: "text-1", text: "after" },
1614
+ { type: "text-end", id: "text-1" },
1615
+ ])
1616
+ const textStarts = response.events.filter((event) => event.type === "text-start")
1617
+ expect(textStarts[0]?.id).not.toBe(textStarts[1]?.id)
1618
+ expect(response.message.content).toEqual([
1619
+ { type: "text", text: "before" },
1620
+ { type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" } },
1621
+ { type: "text", text: "after" },
1622
+ ])
1623
+ expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: "STOP" })
1624
+ }),
1625
+ )
1626
+
1627
+ it.effect("defaults omitted function call args to an empty object", () =>
1628
+ Effect.gen(function* () {
1629
+ const response = yield* LLMClient.generate({
1630
+ ...request,
1631
+ tools: [ToolDefinition.make({ name: "ping", description: "Ping", inputSchema: { type: "object" } })],
1632
+ }).pipe(
1633
+ Effect.provide(
1634
+ fixedResponse(
1635
+ sseEvents({
1636
+ candidates: [
1637
+ {
1638
+ content: { role: "model", parts: [{ functionCall: { name: "ping" } }] },
1639
+ finishReason: "STOP",
1640
+ },
1641
+ ],
1642
+ }),
1643
+ ),
1644
+ ),
1645
+ )
1646
+
1647
+ expect(response.toolCalls[0].id).toMatch(/^tool_[0-9a-zA-Z]+$/)
1648
+ expect(response.toolCalls).toMatchObject([{ type: "tool-call", name: "ping", input: {} }])
1649
+ }),
1650
+ )
1651
+
1652
+ it.effect("maps tool calls without a finish reason", () =>
1653
+ Effect.gen(function* () {
1654
+ const toolRequest = {
1655
+ ...request,
1656
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1657
+ }
1658
+ for (const finishReason of [undefined, "FINISH_REASON_UNSPECIFIED"] as const) {
1659
+ const response = yield* LLMClient.generate(toolRequest).pipe(
1660
+ Effect.provide(
1661
+ fixedResponse(
1662
+ sseEvents({
1663
+ candidates: [
1664
+ {
1665
+ content: {
1666
+ role: "model",
1667
+ parts: [{ functionCall: { name: "lookup", args: { query: "weather" } } }],
1668
+ },
1669
+ ...(finishReason ? { finishReason } : {}),
1670
+ },
1671
+ ],
1672
+ usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 1 },
1673
+ }),
1674
+ ),
1675
+ ),
1676
+ )
1677
+ expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: undefined })
1678
+ }
1679
+ }),
1680
+ )
1681
+
1682
+ it.effect("assigns unique ids to multiple streamed tool calls", () =>
1683
+ Effect.gen(function* () {
1684
+ const body = sseEvents({
1685
+ candidates: [
1686
+ {
1687
+ content: {
1688
+ role: "model",
1689
+ parts: [
1690
+ { functionCall: { id: "call_0", name: "lookup", args: { query: "weather" } } },
1691
+ { functionCall: { name: "lookup", args: { query: "news" } } },
1692
+ ],
1693
+ },
1694
+ finishReason: "STOP",
1695
+ },
1696
+ ],
1697
+ })
1698
+ const response = yield* LLMClient.generate({
1699
+ ...request,
1700
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1701
+ }).pipe(Effect.provide(fixedResponse(body)))
1702
+
1703
+ expect(response.toolCalls[0]).toMatchObject({
1704
+ type: "tool-call",
1705
+ id: "call_0",
1706
+ name: "lookup",
1707
+ input: { query: "weather" },
1708
+ })
1709
+ expect(response.toolCalls[1]).toMatchObject({
1710
+ type: "tool-call",
1711
+ name: "lookup",
1712
+ input: { query: "news" },
1713
+ })
1714
+ expect(response.toolCalls[1].id).toMatch(/^tool_[0-9a-zA-Z]+$/)
1715
+ expect(response.toolCalls[0].id).not.toBe(response.toolCalls[1].id)
1716
+ expect(response.events.at(-1)).toMatchObject({
1717
+ type: "finish",
1718
+ reason: { normalized: "tool-calls", raw: "STOP" },
1719
+ })
1720
+ }),
1721
+ )
1722
+
1723
+ it.effect("replaces repeated supplier ids with fresh fallback ids", () =>
1724
+ Effect.gen(function* () {
1725
+ const body = sseEvents({
1726
+ candidates: [
1727
+ {
1728
+ content: {
1729
+ role: "model",
1730
+ parts: [
1731
+ { functionCall: { id: "dup_call", name: "lookup", args: { query: "weather" } } },
1732
+ { functionCall: { id: "dup_call", name: "lookup", args: { query: "news" } } },
1733
+ ],
1734
+ },
1735
+ finishReason: "STOP",
1736
+ },
1737
+ ],
1738
+ })
1739
+ const response = yield* LLMClient.generate({
1740
+ ...request,
1741
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1742
+ }).pipe(Effect.provide(fixedResponse(body)))
1743
+
1744
+ expect(response.toolCalls[0]).toMatchObject({
1745
+ id: "dup_call",
1746
+ providerMetadata: undefined,
1747
+ })
1748
+ expect(response.toolCalls[1].id).toMatch(/^tool_[0-9a-zA-Z]+$/)
1749
+ expect(response.toolCalls[1].id).not.toBe(response.toolCalls[0].id)
1750
+ }),
1751
+ )
1752
+
1753
+ it.effect("assigns distinct unique fallback ids across separate requests", () =>
1754
+ Effect.gen(function* () {
1755
+ const body = sseEvents({
1756
+ candidates: [
1757
+ {
1758
+ content: {
1759
+ role: "model",
1760
+ parts: [{ functionCall: { name: "lookup", args: { query: "weather" } } }],
1761
+ },
1762
+ finishReason: "STOP",
1763
+ },
1764
+ ],
1765
+ })
1766
+ const req = {
1767
+ ...request,
1768
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
1769
+ }
1770
+ const first = yield* LLMClient.generate(req).pipe(Effect.provide(fixedResponse(body)))
1771
+ const second = yield* LLMClient.generate(req).pipe(Effect.provide(fixedResponse(body)))
1772
+
1773
+ expect(first.toolCalls[0].id).toMatch(/^tool_[0-9a-zA-Z]+$/)
1774
+ expect(second.toolCalls[0].id).toMatch(/^tool_[0-9a-zA-Z]+$/)
1775
+ expect(first.toolCalls[0].id).not.toBe(second.toolCalls[0].id)
1776
+ }),
1777
+ )
1778
+
1779
+ it.effect("maps length and content-filter finish reasons", () =>
1780
+ Effect.gen(function* () {
1781
+ const length = yield* LLMClient.generate(request).pipe(
1782
+ Effect.provide(
1783
+ fixedResponse(
1784
+ sseEvents({ candidates: [{ content: { role: "model", parts: [] }, finishReason: "MAX_TOKENS" }] }),
1785
+ ),
1786
+ ),
1787
+ )
1788
+ const filtered = yield* LLMClient.generate(request).pipe(
1789
+ Effect.provide(
1790
+ fixedResponse(sseEvents({ candidates: [{ content: { role: "model", parts: [] }, finishReason: "SAFETY" }] })),
1791
+ ),
1792
+ )
1793
+
1794
+ expect(length.events.map((event) => event.type)).toEqual(["step-start", "step-finish", "finish"])
1795
+ expect(length.events.at(-1)).toMatchObject({
1796
+ type: "finish",
1797
+ reason: { normalized: "length", raw: "MAX_TOKENS" },
1798
+ })
1799
+ expect(filtered.events.map((event) => event.type)).toEqual(["step-start", "step-finish", "finish"])
1800
+ expect(filtered.events.at(-1)).toMatchObject({
1801
+ type: "finish",
1802
+ reason: { normalized: "content-filter", raw: "SAFETY" },
1803
+ })
1804
+ }),
1805
+ )
1806
+
1807
+ it.effect("preserves candidate-less prompt safety blocks as content-filter outcomes", () =>
1808
+ Effect.gen(function* () {
1809
+ const blocked = yield* LLMClient.generate(request).pipe(
1810
+ Effect.provide(
1811
+ fixedResponse(
1812
+ sseEvents({
1813
+ promptFeedback: {
1814
+ blockReason: "FUTURE_SAFETY_REASON",
1815
+ blockReasonMessage: "Prompt blocked",
1816
+ safetyRatings: [{ category: "HARM_CATEGORY_HARASSMENT", blocked: true }],
1817
+ },
1818
+ }),
1819
+ ),
1820
+ ),
1821
+ )
1822
+ const blockedWithUsage = yield* LLMClient.generate(request).pipe(
1823
+ Effect.provide(
1824
+ fixedResponse(
1825
+ sseEvents(
1826
+ { promptFeedback: { blockReason: "SAFETY" } },
1827
+ { usageMetadata: { promptTokenCount: 7, totalTokenCount: 7 } },
1828
+ ),
1829
+ ),
1830
+ ),
1831
+ )
1832
+
1833
+ expect(blocked.events.map((event) => event.type)).toEqual(["step-start", "step-finish", "finish"])
1834
+ expect(blocked.events.at(-1)).toMatchObject({
1835
+ type: "finish",
1836
+ reason: { normalized: "content-filter", raw: "FUTURE_SAFETY_REASON" },
1837
+ providerMetadata: {
1838
+ google: {
1839
+ promptFeedback: {
1840
+ blockReason: "FUTURE_SAFETY_REASON",
1841
+ blockReasonMessage: "Prompt blocked",
1842
+ safetyRatings: [{ category: "HARM_CATEGORY_HARASSMENT", blocked: true }],
1843
+ },
1844
+ },
1845
+ },
1846
+ })
1847
+ expect(blockedWithUsage.finishReason).toEqual({ normalized: "content-filter", raw: "SAFETY" })
1848
+ expect(blockedWithUsage.usage).toMatchObject({ inputTokens: 7, totalTokens: 7 })
1849
+ }),
1850
+ )
1851
+
1852
+ it.effect("preserves blocking finishes and rejects invalid-output finish reasons", () =>
1853
+ Effect.gen(function* () {
1854
+ const reasons = [
1855
+ ["MODEL_ARMOR", "content-filter"],
1856
+ ["IMAGE_PROHIBITED_CONTENT", "content-filter"],
1857
+ ["IMAGE_RECITATION", "content-filter"],
1858
+ ["LANGUAGE", "content-filter"],
1859
+ ["IMAGE_OTHER", "unknown"],
1860
+ ] as const
1861
+
1862
+ for (const [raw, normalized] of reasons) {
1863
+ const response = yield* LLMClient.generate(request).pipe(
1864
+ Effect.provide(
1865
+ fixedResponse(sseEvents({ candidates: [{ content: { role: "model", parts: [] }, finishReason: raw }] })),
1866
+ ),
1867
+ )
1868
+ expect(response.finishReason).toEqual({ normalized, raw })
1869
+ }
1870
+
1871
+ for (const raw of [
1872
+ "MALFORMED_FUNCTION_CALL",
1873
+ "UNEXPECTED_TOOL_CALL",
1874
+ "NO_IMAGE",
1875
+ "TOO_MANY_TOOL_CALLS",
1876
+ "MISSING_THOUGHT_SIGNATURE",
1877
+ "MALFORMED_RESPONSE",
1878
+ ]) {
1879
+ const event = { candidates: [{ finishReason: raw, finishMessage: "Provider detail" }], responseId: "failure" }
1880
+ const error = yield* LLMClient.generate(request).pipe(
1881
+ Effect.provide(fixedResponse(sseEvents(event))),
1882
+ Effect.flip,
1883
+ )
1884
+ expect(error).toMatchObject({
1885
+ _tag: "AI.Error",
1886
+ reason: { _tag: "InvalidProviderOutput", body: JSON.stringify(event), http: { status: 200 } },
1887
+ message: `Gemini stopped with ${raw}`,
1888
+ })
1889
+ expect(isRetryable(error)).toBe(
1890
+ raw === "MALFORMED_RESPONSE" || raw === "MALFORMED_FUNCTION_CALL" || raw === "UNEXPECTED_TOOL_CALL",
1891
+ )
1892
+ }
1893
+ }),
1894
+ )
1895
+
1896
+ it.effect("leaves total usage undefined when component counts are missing", () =>
1897
+ Effect.gen(function* () {
1898
+ const response = yield* LLMClient.generate(request).pipe(
1899
+ Effect.provide(fixedResponse(sseEvents({ usageMetadata: { thoughtsTokenCount: 1 } }))),
1900
+ )
1901
+
1902
+ expect(response.usage).toMatchObject({ reasoningTokens: 1 })
1903
+ expect(response.usage?.totalTokens).toBeUndefined()
1904
+ }),
1905
+ )
1906
+
1907
+ it.effect("survives explicit null usage counts", () =>
1908
+ Effect.gen(function* () {
1909
+ const response = yield* LLMClient.generate(request).pipe(
1910
+ Effect.provide(
1911
+ fixedResponse(
1912
+ sseEvents(
1913
+ { candidates: [{ content: { role: "model", parts: [{ text: "Hi" }] } }] },
1914
+ { usageMetadata: { promptTokenCount: null, toolUsePromptTokenCount: null, candidatesTokenCount: 5 } },
1915
+ ),
1916
+ ),
1917
+ ),
1918
+ )
1919
+
1920
+ expect(response.text).toBe("Hi")
1921
+ expect(response.usage).toMatchObject({ outputTokens: 5, totalTokens: 5 })
1922
+ expect(response.usage?.inputTokens).toBeUndefined()
1923
+ expect(response.usage?.nonCachedInputTokens).toBeUndefined()
1924
+ expect(response.usage?.cacheReadInputTokens).toBeUndefined()
1925
+ expect(response.usage?.reasoningTokens).toBeUndefined()
1926
+ }),
1927
+ )
1928
+
1929
+ it.effect("survives null candidates, content, parts, and finish reason", () =>
1930
+ Effect.gen(function* () {
1931
+ const response = yield* LLMClient.generate(request).pipe(
1932
+ Effect.provide(
1933
+ fixedResponse(
1934
+ sseEvents(
1935
+ { candidates: null },
1936
+ { candidates: [{ content: { role: "model", parts: null } }] },
1937
+ { candidates: [{ content: null, finishReason: null }] },
1938
+ {
1939
+ candidates: [{ content: { role: "model", parts: [{ text: "Hello" }] }, finishReason: "STOP" as const }],
1940
+ },
1941
+ ),
1942
+ ),
1943
+ ),
1944
+ )
1945
+
1946
+ expect(response.text).toBe("Hello")
1947
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
1948
+ }),
1949
+ )
1950
+
1951
+ it.effect("treats a null thought flag on a text part as visible output", () =>
1952
+ Effect.gen(function* () {
1953
+ const response = yield* LLMClient.generate(request).pipe(
1954
+ Effect.provide(
1955
+ fixedResponse(
1956
+ sseEvents({
1957
+ candidates: [
1958
+ { content: { role: "model", parts: [{ text: "Visible", thought: null }] }, finishReason: "STOP" },
1959
+ ],
1960
+ }),
1961
+ ),
1962
+ ),
1963
+ )
1964
+ const reasoningStart = response.events.find((event) => event.type === "reasoning-start")
1965
+
1966
+ expect(reasoningStart).toBeUndefined()
1967
+ expect(response.reasoning ?? "").toBe("")
1968
+ expect(response.text).toBe("Visible")
1969
+ }),
1970
+ )
1971
+
1972
+ it.effect("fails invalid stream events", () =>
1973
+ Effect.gen(function* () {
1974
+ const error = yield* LLMClient.generate(request).pipe(
1975
+ Effect.provide(fixedResponse(sseRaw("data: {not json}"))),
1976
+ Effect.flip,
1977
+ )
1978
+
1979
+ expect(error).toBeInstanceOf(AIError)
1980
+ expect(error.reason).toMatchObject({ _tag: "InvalidProviderOutput" })
1981
+ expect(error.message).toContain("Invalid google/gemini stream event")
1982
+ }),
1983
+ )
1984
+
1985
+ it.effect("replays generated assistant media as model inline data", () =>
1986
+ Effect.gen(function* () {
1987
+ const prepared = yield* compileRequest(
1988
+ ai.request({
1989
+ id: "req_media",
1990
+ model,
1991
+ messages: [
1992
+ Message.user("Draw a cat"),
1993
+ Message.assistant([
1994
+ { type: "text", text: "Here you go." },
1995
+ {
1996
+ type: "media",
1997
+ media: Media.base64("AAECAw==", "image/png"),
1998
+ providerMetadata: { google: { thoughtSignature: "sig_1" } },
1999
+ },
2000
+ ]),
2001
+ Message.user("Now make it orange"),
2002
+ ],
2003
+ }),
2004
+ )
2005
+
2006
+ expect(prepared.body.contents[1]).toEqual({
2007
+ role: "model",
2008
+ parts: [
2009
+ { text: "Here you go." },
2010
+ { inlineData: { mimeType: "image/png", data: "AAECAw==" }, thoughtSignature: "sig_1" },
2011
+ ],
2012
+ })
2013
+ }),
2014
+ )
2015
+ })
2016
+
2017
+ describe("Gemini response continuation", () => {
2018
+ const continuedRequest = ai.request({
2019
+ model: Gemini.route
2020
+ .with({
2021
+ endpoint: { baseURL: "https://generativelanguage.test/v1beta/" },
2022
+ auth: Auth.header("x-goog-api-key", "test"),
2023
+ })
2024
+ .model({ id: "gemini-test" }),
2025
+ prompt: "Count.",
2026
+ tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
2027
+ })
2028
+
2029
+ // Serves one scripted SSE body per request, or a body whose connection drops after it, and records every sent body.
2030
+ const scripted = (responses: ReadonlyArray<string | { readonly dropped: string } | ReadableStream<Uint8Array>>) => {
2031
+ const bodies: Array<Record<string, unknown>> = []
2032
+ const layer = dynamicResponse((input) =>
2033
+ Effect.sync(() => {
2034
+ bodies.push(JSON.parse(input.text))
2035
+ const response = responses[bodies.length - 1]
2036
+ if (typeof response === "string" || response instanceof ReadableStream)
2037
+ return input.respond(response, { headers: { "content-type": "text/event-stream" } })
2038
+ let sent = false
2039
+ return input.respond(
2040
+ new ReadableStream({
2041
+ pull(controller) {
2042
+ if (sent) return controller.error(new Error("connection reset"))
2043
+ sent = true
2044
+ controller.enqueue(new TextEncoder().encode(response.dropped))
2045
+ },
2046
+ }),
2047
+ { headers: { "content-type": "text/event-stream" } },
2048
+ )
2049
+ }),
2050
+ )
2051
+ return { bodies, layer }
2052
+ }
2053
+ const chunks = (...values: ReadonlyArray<unknown>) =>
2054
+ values.map((value) => sseRaw(`data: ${JSON.stringify(value)}`)).join("")
2055
+
2056
+ const text = (value: string, extra: Record<string, unknown> = {}) => ({
2057
+ candidates: [{ content: { role: "model", parts: [{ text: value }] }, ...extra }],
2058
+ })
2059
+ const continuation = (token?: string) => ({
2060
+ candidates: [
2061
+ { content: { role: "model", parts: [{ text: "" }] }, finishReason: "CONTINUATION", continuationToken: token },
2062
+ ],
2063
+ })
2064
+
2065
+ it.effect("stitches text split across three requests into one block", () =>
2066
+ Effect.gen(function* () {
2067
+ const server = scripted([
2068
+ sseEvents(
2069
+ {
2070
+ candidates: [
2071
+ { content: { role: "model", parts: [{ text: "plan", thought: true, thoughtSignature: "sig_1" }] } },
2072
+ ],
2073
+ },
2074
+ text("THIRTEEN THOUSAND TWO"),
2075
+ continuation("token-1"),
2076
+ ),
2077
+ sseEvents(
2078
+ text(" HUNDRED SEVEN"),
2079
+ // The finishing chunk's token supersedes an earlier checkpoint's.
2080
+ text("TY-TWO", { continuationToken: "checkpoint" }),
2081
+ continuation("token-2"),
2082
+ ),
2083
+ sseEvents(text(" DONE", { finishReason: "STOP" })),
2084
+ ])
2085
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2086
+
2087
+ expect(response.text).toBe("THIRTEEN THOUSAND TWO HUNDRED SEVENTY-TWO DONE")
2088
+ expect(response.reasoning).toBe("plan")
2089
+ expect(response.events.filter((event) => event.type !== "text-delta").map((event) => event.type)).toEqual([
2090
+ "step-start",
2091
+ "reasoning-start",
2092
+ "reasoning-delta",
2093
+ "reasoning-end",
2094
+ "text-start",
2095
+ "text-end",
2096
+ "step-finish",
2097
+ "finish",
2098
+ ])
2099
+ expect(response.events.find((event) => event.type === "reasoning-end")).toMatchObject({
2100
+ providerMetadata: { google: { thoughtSignature: "sig_1" } },
2101
+ })
2102
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
2103
+ expect(server.bodies).toHaveLength(3)
2104
+ expect(server.bodies[0]).not.toHaveProperty("continuationToken")
2105
+ expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuationToken: "token-1" })
2106
+ expect(server.bodies[2]).toEqual({ ...server.bodies[0], continuationToken: "token-2" })
2107
+ }),
2108
+ )
2109
+
2110
+ it.effect("finishes with a signed tool call from a later request", () =>
2111
+ Effect.gen(function* () {
2112
+ const server = scripted([
2113
+ sseEvents(text("Looking"), continuation("token-1")),
2114
+ sseEvents({
2115
+ candidates: [
2116
+ {
2117
+ content: {
2118
+ role: "model",
2119
+ parts: [
2120
+ { text: " it up." },
2121
+ { functionCall: { id: "call_1", name: "lookup", args: {} }, thoughtSignature: "call_sig" },
2122
+ ],
2123
+ },
2124
+ finishReason: "STOP",
2125
+ },
2126
+ ],
2127
+ }),
2128
+ ])
2129
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2130
+
2131
+ expect(response.text).toBe("Looking it up.")
2132
+ expect(response.events.filter((event) => event.type === "text-start")).toHaveLength(1)
2133
+ expect(response.events.find((event) => event.type === "tool-call")).toMatchObject({
2134
+ id: "call_1",
2135
+ providerMetadata: { google: { thoughtSignature: "call_sig" } },
2136
+ })
2137
+ expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: "STOP" })
2138
+ }),
2139
+ )
2140
+
2141
+ it.effect("forgets a block once the resumed request finishes", () =>
2142
+ Effect.gen(function* () {
2143
+ const server = scripted([
2144
+ sseEvents(text("THIRTEEN", { continuationToken: "checkpoint-1" }), {
2145
+ promptFeedback: { blockReason: "OTHER" },
2146
+ }),
2147
+ sseEvents(text(" THOUSAND", { finishReason: "STOP" })),
2148
+ ])
2149
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2150
+
2151
+ expect(response.text).toBe("THIRTEEN THOUSAND")
2152
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
2153
+ expect(response.events.filter(LLMEvent.is.finish).map((event) => event.providerMetadata)).toEqual([undefined])
2154
+ }),
2155
+ )
2156
+
2157
+ it.effect("resumes a dropped stream from its latest checkpoint", () =>
2158
+ Effect.gen(function* () {
2159
+ const server = scripted([
2160
+ { dropped: chunks(text("THIRTEEN"), text(" THOUSAND", { continuationToken: "checkpoint-1" })) },
2161
+ sseEvents(text(" TWO", { finishReason: "STOP" })),
2162
+ ])
2163
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2164
+
2165
+ expect(response.text).toBe("THIRTEEN THOUSAND TWO")
2166
+ expect(response.finishReason).toEqual({ normalized: "stop", raw: "STOP" })
2167
+ expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuationToken: "checkpoint-1" })
2168
+ }),
2169
+ )
2170
+
2171
+ it.effect("counts the usage of a dropped request once resumed", () =>
2172
+ Effect.gen(function* () {
2173
+ const server = scripted([
2174
+ {
2175
+ dropped: chunks(
2176
+ { ...text("THIRTEEN"), usageMetadata: { promptTokenCount: 120, candidatesTokenCount: 5 } },
2177
+ {
2178
+ ...text(" THOUSAND", { continuationToken: "checkpoint-1" }),
2179
+ usageMetadata: { promptTokenCount: 142, candidatesTokenCount: 32768, totalTokenCount: 32910 },
2180
+ },
2181
+ ),
2182
+ },
2183
+ sseEvents({
2184
+ ...text(" TWO", { finishReason: "STOP" }),
2185
+ usageMetadata: { promptTokenCount: 32910, candidatesTokenCount: 100, totalTokenCount: 33010 },
2186
+ }),
2187
+ ])
2188
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2189
+
2190
+ expect(response.usage).toEqual(
2191
+ new Usage({
2192
+ inputTokens: 142,
2193
+ outputTokens: 32868,
2194
+ nonCachedInputTokens: 142,
2195
+ totalTokens: 33010,
2196
+ providerMetadata: {
2197
+ google: {
2198
+ promptTokenCount: 33052,
2199
+ candidatesTokenCount: 32868,
2200
+ totalTokenCount: 65920,
2201
+ requests: 2,
2202
+ },
2203
+ },
2204
+ }),
2205
+ )
2206
+ }),
2207
+ )
2208
+
2209
+ it.effect("continues a stream that ends at a checkpoint without finishing", () =>
2210
+ Effect.gen(function* () {
2211
+ const server = scripted([
2212
+ sseEvents(text("THIRTEEN", { continuationToken: "checkpoint-1" })),
2213
+ sseEvents(text(" THOUSAND", { finishReason: "STOP" })),
2214
+ ])
2215
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2216
+
2217
+ expect(response.text).toBe("THIRTEEN THOUSAND")
2218
+ expect(server.bodies[1]).toEqual({ ...server.bodies[0], continuationToken: "checkpoint-1" })
2219
+ }),
2220
+ )
2221
+
2222
+ it.effect("fails a stream dropped before any checkpoint", () =>
2223
+ Effect.gen(function* () {
2224
+ const server = scripted([{ dropped: chunks(text("Partial")) }])
2225
+ const error = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer), Effect.flip)
2226
+
2227
+ expect(error.reason._tag).toBe("Transport")
2228
+ expect(server.bodies).toHaveLength(1)
2229
+ }),
2230
+ )
2231
+
2232
+ it.effect("does not resume a response cut off by its own timeout", () =>
2233
+ Effect.gen(function* () {
2234
+ const stalled = yield* Deferred.make<void>()
2235
+ let sent = false
2236
+ const server = scripted([
2237
+ new ReadableStream({
2238
+ pull(controller) {
2239
+ if (sent) return new Promise<void>(() => Deferred.doneUnsafe(stalled, Effect.void))
2240
+ sent = true
2241
+ controller.enqueue(
2242
+ new TextEncoder().encode(chunks(text("THIRTEEN", { continuationToken: "checkpoint-1" }))),
2243
+ )
2244
+ },
2245
+ }),
2246
+ ])
2247
+ const fiber = yield* LLMClient.generate({ ...continuedRequest, timeout: 1_000 }).pipe(
2248
+ Effect.provide(server.layer),
2249
+ Effect.flip,
2250
+ Effect.forkChild({ startImmediately: true }),
2251
+ )
2252
+ yield* Deferred.await(stalled)
2253
+ yield* TestClock.adjust("1 second")
2254
+ const error = yield* Fiber.join(fiber)
2255
+
2256
+ expect(error.reason).toMatchObject({ _tag: "Transport", code: "Timeout" })
2257
+ expect(server.bodies).toHaveLength(1)
2258
+ }),
2259
+ )
2260
+
2261
+ it.effect("fails a continuation without a token", () =>
2262
+ Effect.gen(function* () {
2263
+ const server = scripted([sseEvents(text("Partial"), continuation())])
2264
+ const error = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer), Effect.flip)
2265
+
2266
+ expect(error).toMatchObject({
2267
+ reason: { _tag: "InvalidProviderOutput", http: { status: 200 } },
2268
+ message: "Gemini continued the response without a token",
2269
+ })
2270
+ expect(server.bodies).toHaveLength(1)
2271
+ }),
2272
+ )
2273
+
2274
+ it.effect("does not continue a length finish", () =>
2275
+ Effect.gen(function* () {
2276
+ const server = scripted([
2277
+ sseEvents(text("Partial", { finishReason: "MAX_TOKENS", continuationToken: "token-1" })),
2278
+ ])
2279
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2280
+
2281
+ expect(response.finishReason).toEqual({ normalized: "length", raw: "MAX_TOKENS" })
2282
+ expect(server.bodies).toHaveLength(1)
2283
+ }),
2284
+ )
2285
+
2286
+ it.effect("reports the first request's input with all output", () =>
2287
+ Effect.gen(function* () {
2288
+ const usage = [
2289
+ { promptTokenCount: 142, toolUsePromptTokenCount: 5, candidatesTokenCount: 32768, totalTokenCount: 32915 },
2290
+ { promptTokenCount: 32910, candidatesTokenCount: 32768, totalTokenCount: 65678 },
2291
+ {
2292
+ promptTokenCount: 65678,
2293
+ cachedContentTokenCount: 32911,
2294
+ candidatesTokenCount: 32768,
2295
+ totalTokenCount: 98446,
2296
+ },
2297
+ {
2298
+ promptTokenCount: 98446,
2299
+ cachedContentTokenCount: 65679,
2300
+ toolUsePromptTokenCount: 7,
2301
+ candidatesTokenCount: 7257,
2302
+ totalTokenCount: 105710,
2303
+ },
2304
+ ]
2305
+ const server = scripted([
2306
+ sseEvents(
2307
+ { ...text("a"), usageMetadata: { promptTokenCount: 120, candidatesTokenCount: 10, totalTokenCount: 130 } },
2308
+ { ...continuation("token-1"), usageMetadata: usage[0] },
2309
+ ),
2310
+ sseEvents({ ...continuation("token-2"), usageMetadata: usage[1] }),
2311
+ sseEvents({ ...continuation("token-3"), usageMetadata: usage[2] }),
2312
+ sseEvents({ ...text("b", { finishReason: "STOP" }), usageMetadata: usage[3] }),
2313
+ ])
2314
+ const response = yield* LLMClient.generate(continuedRequest).pipe(Effect.provide(server.layer))
2315
+
2316
+ expect(response.usage).toEqual(
2317
+ new Usage({
2318
+ inputTokens: 147,
2319
+ outputTokens: 105561,
2320
+ nonCachedInputTokens: 147,
2321
+ totalTokens: 105708,
2322
+ providerMetadata: {
2323
+ google: {
2324
+ promptTokenCount: 197176,
2325
+ toolUsePromptTokenCount: 12,
2326
+ cachedContentTokenCount: 98590,
2327
+ candidatesTokenCount: 105561,
2328
+ totalTokenCount: 302749,
2329
+ requests: 4,
2330
+ },
2331
+ },
2332
+ }),
2333
+ )
2334
+ }),
2335
+ )
2336
+ })