@radheim/ai 0.0.0-stage → 2.4.3

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 (560) hide show
  1. package/README.md +1890 -3
  2. package/dist/ai.d.ts +36 -0
  3. package/dist/ai.js +46 -0
  4. package/dist/cache-policy.d.ts +6 -0
  5. package/dist/cache-policy.js +205 -0
  6. package/dist/decision-client.d.ts +10 -0
  7. package/dist/decision-client.js +42 -0
  8. package/dist/decision.d.ts +378 -0
  9. package/dist/decision.js +171 -0
  10. package/dist/effect.d.ts +59 -0
  11. package/dist/effect.js +33 -0
  12. package/dist/effort-updates.d.ts +12 -0
  13. package/dist/effort-updates.js +23 -0
  14. package/dist/embedding-client.d.ts +10 -0
  15. package/dist/embedding-client.js +17 -0
  16. package/dist/embedding.d.ts +113 -0
  17. package/dist/embedding.js +76 -0
  18. package/dist/experimental/cloudflare-run-extraction.d.ts +17 -0
  19. package/dist/experimental/cloudflare-run-extraction.js +85 -0
  20. package/dist/experimental/extraction.d.ts +153 -0
  21. package/dist/experimental/extraction.js +103 -0
  22. package/dist/experimental/realtime.d.ts +80 -0
  23. package/dist/experimental/realtime.js +96 -0
  24. package/dist/experimental.d.ts +10 -0
  25. package/dist/experimental.js +6 -0
  26. package/dist/fetch-middleware.d.ts +7 -0
  27. package/dist/fetch-middleware.js +41 -0
  28. package/dist/generation.d.ts +77 -0
  29. package/dist/generation.js +109 -0
  30. package/dist/image-client.d.ts +14 -0
  31. package/dist/image-client.js +39 -0
  32. package/dist/image.d.ts +323 -0
  33. package/dist/image.js +103 -0
  34. package/dist/index.d.ts +300 -0
  35. package/dist/index.js +179 -0
  36. package/dist/llm.d.ts +109 -0
  37. package/dist/llm.js +177 -0
  38. package/dist/loop.d.ts +38 -0
  39. package/dist/loop.js +139 -0
  40. package/dist/media-client.d.ts +30 -0
  41. package/dist/media-client.js +44 -0
  42. package/dist/media-model.d.ts +49 -0
  43. package/dist/media-model.js +55 -0
  44. package/dist/media.d.ts +237 -0
  45. package/dist/media.js +285 -0
  46. package/dist/promise-media.d.ts +20 -0
  47. package/dist/promise-media.js +16 -0
  48. package/dist/protocols/alibaba-chat.d.ts +315 -0
  49. package/dist/protocols/alibaba-chat.js +78 -0
  50. package/dist/protocols/alibaba-images.d.ts +22 -0
  51. package/dist/protocols/alibaba-images.js +77 -0
  52. package/dist/protocols/alibaba-messages.d.ts +413 -0
  53. package/dist/protocols/alibaba-messages.js +44 -0
  54. package/dist/protocols/alibaba-responses.d.ts +298 -0
  55. package/dist/protocols/alibaba-responses.js +67 -0
  56. package/dist/protocols/anthropic-messages.d.ts +1213 -0
  57. package/dist/protocols/anthropic-messages.js +1412 -0
  58. package/dist/protocols/assemblyai-transcription.d.ts +41 -0
  59. package/dist/protocols/assemblyai-transcription.js +137 -0
  60. package/dist/protocols/bedrock-converse.d.ts +548 -0
  61. package/dist/protocols/bedrock-converse.js +801 -0
  62. package/dist/protocols/bedrock-event-stream.d.ts +14 -0
  63. package/dist/protocols/bedrock-event-stream.js +100 -0
  64. package/dist/protocols/cartesia-speech.d.ts +117 -0
  65. package/dist/protocols/cartesia-speech.js +120 -0
  66. package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
  67. package/dist/protocols/cloudflare-run-decisions.js +36 -0
  68. package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
  69. package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
  70. package/dist/protocols/cohere-chat.d.ts +184 -0
  71. package/dist/protocols/cohere-chat.js +317 -0
  72. package/dist/protocols/deepgram-speech.d.ts +109 -0
  73. package/dist/protocols/deepgram-speech.js +93 -0
  74. package/dist/protocols/deepgram-transcription.d.ts +26 -0
  75. package/dist/protocols/deepgram-transcription.js +119 -0
  76. package/dist/protocols/elevenlabs-speech.d.ts +112 -0
  77. package/dist/protocols/elevenlabs-speech.js +111 -0
  78. package/dist/protocols/elevenlabs-transcription.d.ts +28 -0
  79. package/dist/protocols/elevenlabs-transcription.js +137 -0
  80. package/dist/protocols/gemini.d.ts +388 -0
  81. package/dist/protocols/gemini.js +741 -0
  82. package/dist/protocols/google-decisions.d.ts +13 -0
  83. package/dist/protocols/google-decisions.js +133 -0
  84. package/dist/protocols/google-embed-content.d.ts +34 -0
  85. package/dist/protocols/google-embed-content.js +110 -0
  86. package/dist/protocols/google-images.d.ts +18 -0
  87. package/dist/protocols/google-images.js +169 -0
  88. package/dist/protocols/google-interactions-video.d.ts +38 -0
  89. package/dist/protocols/google-interactions-video.js +185 -0
  90. package/dist/protocols/google-interactions.d.ts +554 -0
  91. package/dist/protocols/google-interactions.js +756 -0
  92. package/dist/protocols/google-speech.d.ts +120 -0
  93. package/dist/protocols/google-speech.js +94 -0
  94. package/dist/protocols/google-transcription.d.ts +148 -0
  95. package/dist/protocols/google-transcription.js +129 -0
  96. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  97. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  98. package/dist/protocols/index.d.ts +21 -0
  99. package/dist/protocols/index.js +21 -0
  100. package/dist/protocols/meta-images.d.ts +26 -0
  101. package/dist/protocols/meta-images.js +101 -0
  102. package/dist/protocols/meta-messages.d.ts +423 -0
  103. package/dist/protocols/meta-messages.js +63 -0
  104. package/dist/protocols/meta-responses.d.ts +533 -0
  105. package/dist/protocols/meta-responses.js +189 -0
  106. package/dist/protocols/minimax-images.d.ts +25 -0
  107. package/dist/protocols/minimax-images.js +150 -0
  108. package/dist/protocols/minimax-video.d.ts +45 -0
  109. package/dist/protocols/minimax-video.js +296 -0
  110. package/dist/protocols/mistral-chat.d.ts +565 -0
  111. package/dist/protocols/mistral-chat.js +606 -0
  112. package/dist/protocols/open-responses-channel.d.ts +25 -0
  113. package/dist/protocols/open-responses-channel.js +137 -0
  114. package/dist/protocols/open-responses-continuation.d.ts +18 -0
  115. package/dist/protocols/open-responses-continuation.js +172 -0
  116. package/dist/protocols/open-responses.d.ts +2509 -0
  117. package/dist/protocols/open-responses.js +1335 -0
  118. package/dist/protocols/openai-chat.d.ts +2571 -0
  119. package/dist/protocols/openai-chat.js +1140 -0
  120. package/dist/protocols/openai-compatible-chat.d.ts +184 -0
  121. package/dist/protocols/openai-compatible-chat.js +19 -0
  122. package/dist/protocols/openai-compatible-responses.d.ts +231 -0
  123. package/dist/protocols/openai-compatible-responses.js +18 -0
  124. package/dist/protocols/openai-decisions.d.ts +22 -0
  125. package/dist/protocols/openai-decisions.js +141 -0
  126. package/dist/protocols/openai-embeddings.d.ts +16 -0
  127. package/dist/protocols/openai-embeddings.js +76 -0
  128. package/dist/protocols/openai-freeform.d.ts +78 -0
  129. package/dist/protocols/openai-freeform.js +222 -0
  130. package/dist/protocols/openai-images.d.ts +148 -0
  131. package/dist/protocols/openai-images.js +303 -0
  132. package/dist/protocols/openai-responses.d.ts +1600 -0
  133. package/dist/protocols/openai-responses.js +360 -0
  134. package/dist/protocols/openai-speech.d.ts +110 -0
  135. package/dist/protocols/openai-speech.js +112 -0
  136. package/dist/protocols/openai-transcription.d.ts +185 -0
  137. package/dist/protocols/openai-transcription.js +206 -0
  138. package/dist/protocols/openrouter-video.d.ts +36 -0
  139. package/dist/protocols/openrouter-video.js +139 -0
  140. package/dist/protocols/seedance-video.d.ts +45 -0
  141. package/dist/protocols/seedance-video.js +217 -0
  142. package/dist/protocols/shared.d.ts +249 -0
  143. package/dist/protocols/shared.js +446 -0
  144. package/dist/protocols/system-one.d.ts +145 -0
  145. package/dist/protocols/system-one.js +272 -0
  146. package/dist/protocols/utils/bedrock-auth.d.ts +60 -0
  147. package/dist/protocols/utils/bedrock-auth.js +86 -0
  148. package/dist/protocols/utils/bedrock-cache.d.ts +19 -0
  149. package/dist/protocols/utils/bedrock-cache.js +49 -0
  150. package/dist/protocols/utils/bedrock-media.d.ts +53 -0
  151. package/dist/protocols/utils/bedrock-media.js +98 -0
  152. package/dist/protocols/utils/cache.d.ts +25 -0
  153. package/dist/protocols/utils/cache.js +33 -0
  154. package/dist/protocols/utils/claude-model.d.ts +8 -0
  155. package/dist/protocols/utils/claude-model.js +15 -0
  156. package/dist/protocols/utils/gateway-protocol.d.ts +17 -0
  157. package/dist/protocols/utils/gateway-protocol.js +59 -0
  158. package/dist/protocols/utils/gemini-generate-content.d.ts +75 -0
  159. package/dist/protocols/utils/gemini-generate-content.js +96 -0
  160. package/dist/protocols/utils/gemini-json-schema.d.ts +8 -0
  161. package/dist/protocols/utils/gemini-json-schema.js +76 -0
  162. package/dist/protocols/utils/image-sizing.d.ts +31 -0
  163. package/dist/protocols/utils/image-sizing.js +73 -0
  164. package/dist/protocols/utils/lifecycle.d.ts +24 -0
  165. package/dist/protocols/utils/lifecycle.js +62 -0
  166. package/dist/protocols/utils/media-input.d.ts +32 -0
  167. package/dist/protocols/utils/media-input.js +62 -0
  168. package/dist/protocols/utils/mistral-tool-id.d.ts +5 -0
  169. package/dist/protocols/utils/mistral-tool-id.js +31 -0
  170. package/dist/protocols/utils/open-responses-options.d.ts +54 -0
  171. package/dist/protocols/utils/open-responses-options.js +59 -0
  172. package/dist/protocols/utils/partial-json-options.d.ts +61 -0
  173. package/dist/protocols/utils/partial-json-options.js +51 -0
  174. package/dist/protocols/utils/partial-json.d.ts +8 -0
  175. package/dist/protocols/utils/partial-json.js +280 -0
  176. package/dist/protocols/utils/responses-checkpoint.d.ts +4 -0
  177. package/dist/protocols/utils/responses-checkpoint.js +103 -0
  178. package/dist/protocols/utils/responses-compaction.d.ts +6 -0
  179. package/dist/protocols/utils/responses-compaction.js +162 -0
  180. package/dist/protocols/utils/responses-hosted-tools.d.ts +122 -0
  181. package/dist/protocols/utils/responses-hosted-tools.js +63 -0
  182. package/dist/protocols/utils/speaker-turns.d.ts +3 -0
  183. package/dist/protocols/utils/speaker-turns.js +9 -0
  184. package/dist/protocols/utils/speech-stream.d.ts +49 -0
  185. package/dist/protocols/utils/speech-stream.js +64 -0
  186. package/dist/protocols/utils/tool-schema.d.ts +10 -0
  187. package/dist/protocols/utils/tool-schema.js +109 -0
  188. package/dist/protocols/utils/tool-stream.d.ts +478 -0
  189. package/dist/protocols/utils/tool-stream.js +153 -0
  190. package/dist/protocols/venice-chat.d.ts +340 -0
  191. package/dist/protocols/venice-chat.js +283 -0
  192. package/dist/protocols/xai-images.d.ts +25 -0
  193. package/dist/protocols/xai-images.js +87 -0
  194. package/dist/protocols/xai-responses.d.ts +294 -0
  195. package/dist/protocols/xai-responses.js +86 -0
  196. package/dist/protocols/xai-video.d.ts +35 -0
  197. package/dist/protocols/xai-video.js +159 -0
  198. package/dist/protocols/zai-chat.d.ts +296 -0
  199. package/dist/protocols/zai-chat.js +56 -0
  200. package/dist/protocols/zai-images.d.ts +20 -0
  201. package/dist/protocols/zai-images.js +79 -0
  202. package/dist/protocols/zai-messages.d.ts +409 -0
  203. package/dist/protocols/zai-messages.js +30 -0
  204. package/dist/protocols.d.ts +1 -0
  205. package/dist/protocols.js +1 -0
  206. package/dist/provider-error.d.ts +22 -0
  207. package/dist/provider-error.js +228 -0
  208. package/dist/provider-package.d.ts +17 -0
  209. package/dist/provider-package.js +1 -0
  210. package/dist/providers/alibaba/chat.d.ts +1 -0
  211. package/dist/providers/alibaba/chat.js +1 -0
  212. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  213. package/dist/providers/alibaba/embeddings.js +1 -0
  214. package/dist/providers/alibaba/images.d.ts +2 -0
  215. package/dist/providers/alibaba/images.js +1 -0
  216. package/dist/providers/alibaba/messages.d.ts +3 -0
  217. package/dist/providers/alibaba/messages.js +1 -0
  218. package/dist/providers/alibaba/responses.d.ts +3 -0
  219. package/dist/providers/alibaba/responses.js +1 -0
  220. package/dist/providers/alibaba.d.ts +905 -0
  221. package/dist/providers/alibaba.js +119 -0
  222. package/dist/providers/amazon-bedrock/mantle/chat.d.ts +2 -0
  223. package/dist/providers/amazon-bedrock/mantle/chat.js +1 -0
  224. package/dist/providers/amazon-bedrock/mantle/messages.d.ts +2 -0
  225. package/dist/providers/amazon-bedrock/mantle/messages.js +1 -0
  226. package/dist/providers/amazon-bedrock/mantle/responses.d.ts +2 -0
  227. package/dist/providers/amazon-bedrock/mantle/responses.js +1 -0
  228. package/dist/providers/amazon-bedrock/mantle.d.ts +2 -0
  229. package/dist/providers/amazon-bedrock/mantle.js +1 -0
  230. package/dist/providers/amazon-bedrock-mantle.d.ts +789 -0
  231. package/dist/providers/amazon-bedrock-mantle.js +107 -0
  232. package/dist/providers/amazon-bedrock.d.ts +190 -0
  233. package/dist/providers/amazon-bedrock.js +44 -0
  234. package/dist/providers/anthropic-compatible.d.ts +364 -0
  235. package/dist/providers/anthropic-compatible.js +47 -0
  236. package/dist/providers/anthropic.d.ts +362 -0
  237. package/dist/providers/anthropic.js +36 -0
  238. package/dist/providers/assemblyai.d.ts +19 -0
  239. package/dist/providers/assemblyai.js +19 -0
  240. package/dist/providers/azure/chat.d.ts +2 -0
  241. package/dist/providers/azure/chat.js +1 -0
  242. package/dist/providers/azure/embeddings.d.ts +2 -0
  243. package/dist/providers/azure/embeddings.js +1 -0
  244. package/dist/providers/azure/images.d.ts +2 -0
  245. package/dist/providers/azure/images.js +1 -0
  246. package/dist/providers/azure/messages.d.ts +2 -0
  247. package/dist/providers/azure/messages.js +1 -0
  248. package/dist/providers/azure/responses.d.ts +2 -0
  249. package/dist/providers/azure/responses.js +1 -0
  250. package/dist/providers/azure.d.ts +1074 -0
  251. package/dist/providers/azure.js +150 -0
  252. package/dist/providers/baseten/decisions.d.ts +2 -0
  253. package/dist/providers/baseten/decisions.js +1 -0
  254. package/dist/providers/baseten.d.ts +384 -0
  255. package/dist/providers/baseten.js +56 -0
  256. package/dist/providers/byteplus/videos.d.ts +2 -0
  257. package/dist/providers/byteplus/videos.js +1 -0
  258. package/dist/providers/byteplus.d.ts +24 -0
  259. package/dist/providers/byteplus.js +21 -0
  260. package/dist/providers/cartesia.d.ts +18 -0
  261. package/dist/providers/cartesia.js +17 -0
  262. package/dist/providers/cerebras.d.ts +375 -0
  263. package/dist/providers/cerebras.js +33 -0
  264. package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
  265. package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
  266. package/dist/providers/cloudflare-ai-gateway.d.ts +1581 -0
  267. package/dist/providers/cloudflare-ai-gateway.js +120 -0
  268. package/dist/providers/cloudflare-shared.d.ts +9 -0
  269. package/dist/providers/cloudflare-shared.js +25 -0
  270. package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
  271. package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
  272. package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
  273. package/dist/providers/cloudflare-workers-ai/images.js +1 -0
  274. package/dist/providers/cloudflare-workers-ai.d.ts +391 -0
  275. package/dist/providers/cloudflare-workers-ai.js +69 -0
  276. package/dist/providers/cohere/chat.d.ts +4 -0
  277. package/dist/providers/cohere/chat.js +3 -0
  278. package/dist/providers/cohere/embeddings.d.ts +2 -0
  279. package/dist/providers/cohere/embeddings.js +1 -0
  280. package/dist/providers/cohere.d.ts +502 -0
  281. package/dist/providers/cohere.js +55 -0
  282. package/dist/providers/deepgram.d.ts +22 -0
  283. package/dist/providers/deepgram.js +20 -0
  284. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  285. package/dist/providers/deepinfra/embeddings.js +1 -0
  286. package/dist/providers/deepinfra.d.ts +378 -0
  287. package/dist/providers/deepinfra.js +52 -0
  288. package/dist/providers/deepseek.d.ts +376 -0
  289. package/dist/providers/deepseek.js +30 -0
  290. package/dist/providers/digitalocean/decisions.d.ts +2 -0
  291. package/dist/providers/digitalocean/decisions.js +1 -0
  292. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  293. package/dist/providers/digitalocean/embeddings.js +1 -0
  294. package/dist/providers/digitalocean/images.d.ts +2 -0
  295. package/dist/providers/digitalocean/images.js +1 -0
  296. package/dist/providers/digitalocean/responses.d.ts +4 -0
  297. package/dist/providers/digitalocean/responses.js +1 -0
  298. package/dist/providers/digitalocean.d.ts +874 -0
  299. package/dist/providers/digitalocean.js +106 -0
  300. package/dist/providers/elevenlabs.d.ts +22 -0
  301. package/dist/providers/elevenlabs.js +22 -0
  302. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  303. package/dist/providers/fireworks/embeddings.js +1 -0
  304. package/dist/providers/fireworks.d.ts +379 -0
  305. package/dist/providers/fireworks.js +40 -0
  306. package/dist/providers/google/decisions.d.ts +2 -0
  307. package/dist/providers/google/decisions.js +1 -0
  308. package/dist/providers/google/embeddings.d.ts +2 -0
  309. package/dist/providers/google/embeddings.js +1 -0
  310. package/dist/providers/google/images.d.ts +2 -0
  311. package/dist/providers/google/images.js +1 -0
  312. package/dist/providers/google/interactions.d.ts +7 -0
  313. package/dist/providers/google/interactions.js +3 -0
  314. package/dist/providers/google/videos.d.ts +2 -0
  315. package/dist/providers/google/videos.js +1 -0
  316. package/dist/providers/google-vertex/chat.d.ts +2 -0
  317. package/dist/providers/google-vertex/chat.js +1 -0
  318. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  319. package/dist/providers/google-vertex/embeddings.js +1 -0
  320. package/dist/providers/google-vertex/gemini.d.ts +2 -0
  321. package/dist/providers/google-vertex/gemini.js +1 -0
  322. package/dist/providers/google-vertex/images.d.ts +2 -0
  323. package/dist/providers/google-vertex/images.js +1 -0
  324. package/dist/providers/google-vertex/interactions.d.ts +2 -0
  325. package/dist/providers/google-vertex/interactions.js +1 -0
  326. package/dist/providers/google-vertex/messages.d.ts +2 -0
  327. package/dist/providers/google-vertex/messages.js +1 -0
  328. package/dist/providers/google-vertex/mistral.d.ts +2 -0
  329. package/dist/providers/google-vertex/mistral.js +1 -0
  330. package/dist/providers/google-vertex/responses.d.ts +2 -0
  331. package/dist/providers/google-vertex/responses.js +1 -0
  332. package/dist/providers/google-vertex-chat.d.ts +204 -0
  333. package/dist/providers/google-vertex-chat.js +29 -0
  334. package/dist/providers/google-vertex-interactions.d.ts +111 -0
  335. package/dist/providers/google-vertex-interactions.js +62 -0
  336. package/dist/providers/google-vertex-messages.d.ts +362 -0
  337. package/dist/providers/google-vertex-messages.js +51 -0
  338. package/dist/providers/google-vertex-mistral.d.ts +120 -0
  339. package/dist/providers/google-vertex-mistral.js +43 -0
  340. package/dist/providers/google-vertex-responses.d.ts +253 -0
  341. package/dist/providers/google-vertex-responses.js +30 -0
  342. package/dist/providers/google-vertex-shared.d.ts +58 -0
  343. package/dist/providers/google-vertex-shared.js +128 -0
  344. package/dist/providers/google-vertex.d.ts +132 -0
  345. package/dist/providers/google-vertex.js +161 -0
  346. package/dist/providers/google.d.ts +246 -0
  347. package/dist/providers/google.js +80 -0
  348. package/dist/providers/groq.d.ts +470 -0
  349. package/dist/providers/groq.js +63 -0
  350. package/dist/providers/index.d.ts +45 -0
  351. package/dist/providers/index.js +45 -0
  352. package/dist/providers/meta/chat.d.ts +2 -0
  353. package/dist/providers/meta/chat.js +1 -0
  354. package/dist/providers/meta/images.d.ts +2 -0
  355. package/dist/providers/meta/images.js +1 -0
  356. package/dist/providers/meta/messages.d.ts +2 -0
  357. package/dist/providers/meta/messages.js +1 -0
  358. package/dist/providers/meta/responses.d.ts +2 -0
  359. package/dist/providers/meta/responses.js +1 -0
  360. package/dist/providers/meta.d.ts +804 -0
  361. package/dist/providers/meta.js +96 -0
  362. package/dist/providers/minimax/chat.d.ts +4 -0
  363. package/dist/providers/minimax/chat.js +3 -0
  364. package/dist/providers/minimax/images.d.ts +3 -0
  365. package/dist/providers/minimax/images.js +1 -0
  366. package/dist/providers/minimax/messages.d.ts +1 -0
  367. package/dist/providers/minimax/messages.js +1 -0
  368. package/dist/providers/minimax/responses.d.ts +4 -0
  369. package/dist/providers/minimax/responses.js +3 -0
  370. package/dist/providers/minimax/videos.d.ts +3 -0
  371. package/dist/providers/minimax/videos.js +1 -0
  372. package/dist/providers/minimax.d.ts +798 -0
  373. package/dist/providers/minimax.js +99 -0
  374. package/dist/providers/mistral.d.ts +208 -0
  375. package/dist/providers/mistral.js +17 -0
  376. package/dist/providers/moonshot/chat.d.ts +1 -0
  377. package/dist/providers/moonshot/chat.js +1 -0
  378. package/dist/providers/moonshot/messages.d.ts +4 -0
  379. package/dist/providers/moonshot/messages.js +3 -0
  380. package/dist/providers/moonshot/responses.d.ts +4 -0
  381. package/dist/providers/moonshot/responses.js +3 -0
  382. package/dist/providers/moonshot.d.ts +785 -0
  383. package/dist/providers/moonshot.js +78 -0
  384. package/dist/providers/open-responses-options.d.ts +5 -0
  385. package/dist/providers/open-responses-options.js +1 -0
  386. package/dist/providers/openai/chat.d.ts +2 -0
  387. package/dist/providers/openai/chat.js +1 -0
  388. package/dist/providers/openai/embeddings.d.ts +2 -0
  389. package/dist/providers/openai/embeddings.js +1 -0
  390. package/dist/providers/openai/images.d.ts +2 -0
  391. package/dist/providers/openai/images.js +1 -0
  392. package/dist/providers/openai/responses.d.ts +2 -0
  393. package/dist/providers/openai/responses.js +1 -0
  394. package/dist/providers/openai-compatible/decisions.d.ts +2 -0
  395. package/dist/providers/openai-compatible/decisions.js +1 -0
  396. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  397. package/dist/providers/openai-compatible/embeddings.js +1 -0
  398. package/dist/providers/openai-compatible/images.d.ts +2 -0
  399. package/dist/providers/openai-compatible/images.js +1 -0
  400. package/dist/providers/openai-compatible/responses.d.ts +1 -0
  401. package/dist/providers/openai-compatible/responses.js +1 -0
  402. package/dist/providers/openai-compatible-responses.d.ts +250 -0
  403. package/dist/providers/openai-compatible-responses.js +26 -0
  404. package/dist/providers/openai-compatible.d.ts +208 -0
  405. package/dist/providers/openai-compatible.js +71 -0
  406. package/dist/providers/openai-options.d.ts +21 -0
  407. package/dist/providers/openai-options.js +37 -0
  408. package/dist/providers/openai.d.ts +522 -0
  409. package/dist/providers/openai.js +118 -0
  410. package/dist/providers/opencode/decisions.d.ts +2 -0
  411. package/dist/providers/opencode/decisions.js +1 -0
  412. package/dist/providers/opencode.d.ts +23 -0
  413. package/dist/providers/opencode.js +25 -0
  414. package/dist/providers/openrouter/decisions.d.ts +2 -0
  415. package/dist/providers/openrouter/decisions.js +1 -0
  416. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  417. package/dist/providers/openrouter/embeddings.js +1 -0
  418. package/dist/providers/openrouter/images.d.ts +2 -0
  419. package/dist/providers/openrouter/images.js +1 -0
  420. package/dist/providers/openrouter/responses.d.ts +3 -0
  421. package/dist/providers/openrouter/responses.js +1 -0
  422. package/dist/providers/openrouter/videos.d.ts +2 -0
  423. package/dist/providers/openrouter/videos.js +1 -0
  424. package/dist/providers/openrouter.d.ts +1204 -0
  425. package/dist/providers/openrouter.js +210 -0
  426. package/dist/providers/settings.d.ts +40 -0
  427. package/dist/providers/settings.js +18 -0
  428. package/dist/providers/togetherai.d.ts +375 -0
  429. package/dist/providers/togetherai.js +30 -0
  430. package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
  431. package/dist/providers/typesafe-ai/decisions.js +1 -0
  432. package/dist/providers/typesafe-ai.d.ts +23 -0
  433. package/dist/providers/typesafe-ai.js +25 -0
  434. package/dist/providers/venice/responses.d.ts +4 -0
  435. package/dist/providers/venice/responses.js +1 -0
  436. package/dist/providers/venice.d.ts +632 -0
  437. package/dist/providers/venice.js +57 -0
  438. package/dist/providers/vercel-ai-gateway/chat.d.ts +2 -0
  439. package/dist/providers/vercel-ai-gateway/chat.js +1 -0
  440. package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
  441. package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
  442. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  443. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  444. package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
  445. package/dist/providers/vercel-ai-gateway/images.js +1 -0
  446. package/dist/providers/vercel-ai-gateway/messages.d.ts +2 -0
  447. package/dist/providers/vercel-ai-gateway/messages.js +1 -0
  448. package/dist/providers/vercel-ai-gateway/responses.d.ts +2 -0
  449. package/dist/providers/vercel-ai-gateway/responses.js +1 -0
  450. package/dist/providers/vercel-ai-gateway.d.ts +111 -0
  451. package/dist/providers/vercel-ai-gateway.js +181 -0
  452. package/dist/providers/volcengine/videos.d.ts +2 -0
  453. package/dist/providers/volcengine/videos.js +1 -0
  454. package/dist/providers/volcengine.d.ts +24 -0
  455. package/dist/providers/volcengine.js +21 -0
  456. package/dist/providers/xai/images.d.ts +2 -0
  457. package/dist/providers/xai/images.js +1 -0
  458. package/dist/providers/xai/videos.d.ts +2 -0
  459. package/dist/providers/xai/videos.js +1 -0
  460. package/dist/providers/xai.d.ts +235 -0
  461. package/dist/providers/xai.js +89 -0
  462. package/dist/providers/zai/chat.d.ts +1 -0
  463. package/dist/providers/zai/chat.js +1 -0
  464. package/dist/providers/zai/images.d.ts +2 -0
  465. package/dist/providers/zai/images.js +1 -0
  466. package/dist/providers/zai-coding-plan/chat.d.ts +1 -0
  467. package/dist/providers/zai-coding-plan/chat.js +1 -0
  468. package/dist/providers/zai-coding-plan/messages.d.ts +4 -0
  469. package/dist/providers/zai-coding-plan/messages.js +3 -0
  470. package/dist/providers/zai-coding-plan/responses.d.ts +4 -0
  471. package/dist/providers/zai-coding-plan/responses.js +3 -0
  472. package/dist/providers/zai-coding-plan.d.ts +846 -0
  473. package/dist/providers/zai-coding-plan.js +56 -0
  474. package/dist/providers/zai.d.ts +285 -0
  475. package/dist/providers/zai.js +44 -0
  476. package/dist/providers.d.ts +1 -0
  477. package/dist/providers.js +1 -0
  478. package/dist/public.d.ts +18 -0
  479. package/dist/public.js +7 -0
  480. package/dist/route/auth-options.d.ts +35 -0
  481. package/dist/route/auth-options.js +17 -0
  482. package/dist/route/auth.d.ts +52 -0
  483. package/dist/route/auth.js +92 -0
  484. package/dist/route/client.d.ts +229 -0
  485. package/dist/route/client.js +293 -0
  486. package/dist/route/decision.d.ts +55 -0
  487. package/dist/route/decision.js +73 -0
  488. package/dist/route/embedding.d.ts +58 -0
  489. package/dist/route/embedding.js +85 -0
  490. package/dist/route/endpoint.d.ts +29 -0
  491. package/dist/route/endpoint.js +21 -0
  492. package/dist/route/executor-service.d.ts +54 -0
  493. package/dist/route/executor-service.js +115 -0
  494. package/dist/route/executor.d.ts +37 -0
  495. package/dist/route/executor.js +225 -0
  496. package/dist/route/framing.d.ts +44 -0
  497. package/dist/route/framing.js +63 -0
  498. package/dist/route/index.d.ts +21 -0
  499. package/dist/route/index.js +18 -0
  500. package/dist/route/media-protocol.d.ts +187 -0
  501. package/dist/route/media-protocol.js +117 -0
  502. package/dist/route/media.d.ts +91 -0
  503. package/dist/route/media.js +251 -0
  504. package/dist/route/protocol.d.ts +85 -0
  505. package/dist/route/protocol.js +19 -0
  506. package/dist/route/transport/http.d.ts +34 -0
  507. package/dist/route/transport/http.js +67 -0
  508. package/dist/route/transport/index.d.ts +42 -0
  509. package/dist/route/transport/index.js +4 -0
  510. package/dist/route/transport/websocket-channel.d.ts +56 -0
  511. package/dist/route/transport/websocket-channel.js +1 -0
  512. package/dist/route/transport/websocket.d.ts +32 -0
  513. package/dist/route/transport/websocket.js +315 -0
  514. package/dist/route.d.ts +1 -0
  515. package/dist/route.js +1 -0
  516. package/dist/schema/errors.d.ts +194 -0
  517. package/dist/schema/errors.js +217 -0
  518. package/dist/schema/events.d.ts +11001 -0
  519. package/dist/schema/events.js +542 -0
  520. package/dist/schema/ids.d.ts +17 -0
  521. package/dist/schema/ids.js +10 -0
  522. package/dist/schema/index.d.ts +5 -0
  523. package/dist/schema/index.js +5 -0
  524. package/dist/schema/messages.d.ts +2706 -0
  525. package/dist/schema/messages.js +344 -0
  526. package/dist/schema/options.d.ts +270 -0
  527. package/dist/schema/options.js +198 -0
  528. package/dist/speech.d.ts +266 -0
  529. package/dist/speech.js +114 -0
  530. package/dist/test-ai.d.ts +15 -0
  531. package/dist/test-ai.js +49 -0
  532. package/dist/testing.d.ts +1585 -0
  533. package/dist/testing.js +108 -0
  534. package/dist/tool-history.d.ts +2 -0
  535. package/dist/tool-history.js +91 -0
  536. package/dist/tool-runtime.d.ts +22 -0
  537. package/dist/tool-runtime.js +55 -0
  538. package/dist/tool-updates.d.ts +34 -0
  539. package/dist/tool-updates.js +93 -0
  540. package/dist/tool.d.ts +150 -0
  541. package/dist/tool.js +159 -0
  542. package/dist/transcription.d.ts +254 -0
  543. package/dist/transcription.js +119 -0
  544. package/dist/utils/bytes.d.ts +1 -0
  545. package/dist/utils/bytes.js +10 -0
  546. package/dist/utils/json.d.ts +4 -0
  547. package/dist/utils/json.js +4 -0
  548. package/dist/utils/media-type.d.ts +8 -0
  549. package/dist/utils/media-type.js +93 -0
  550. package/dist/utils/provider-codes.d.ts +3 -0
  551. package/dist/utils/provider-codes.js +41 -0
  552. package/dist/utils/record.d.ts +2 -0
  553. package/dist/utils/record.js +2 -0
  554. package/dist/utils/sanitize.d.ts +5 -0
  555. package/dist/utils/sanitize.js +31 -0
  556. package/dist/video-client.d.ts +12 -0
  557. package/dist/video-client.js +24 -0
  558. package/dist/video.d.ts +178 -0
  559. package/dist/video.js +79 -0
  560. package/package.json +648 -4
@@ -0,0 +1,1412 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { Effect, Option, Schema, SchemaGetter } from "effect";
3
+ import { Tool } from "@radheim/schema/tool";
4
+ import { Route } from "../route/client.js";
5
+ import { Auth } from "../route/auth.js";
6
+ import { Endpoint } from "../route/endpoint.js";
7
+ import { Framing } from "../route/framing.js";
8
+ import { Protocol } from "../route/protocol.js";
9
+ import { Headers } from "effect/http";
10
+ import { HttpTransport } from "../route/transport/index.js";
11
+ import { AIError, CacheTTL, StreamEvent, mergeJsonRecords, Usage, } from "../schema/index.js";
12
+ import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js";
13
+ import { classifyProviderFailure } from "../provider-error.js";
14
+ import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js";
15
+ import { addsTools, toolsUpdate } from "../tool-updates.js";
16
+ import * as Cache from "./utils/cache.js";
17
+ import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js";
18
+ import { Lifecycle } from "./utils/lifecycle.js";
19
+ import { ToolStream } from "./utils/tool-stream.js";
20
+ const ADAPTER = "anthropic-messages";
21
+ export const DEFAULT_BASE_URL = "https://api.anthropic.com/v1";
22
+ export const PATH = "/messages";
23
+ export const DEFAULT_MAX_TOKENS = 32_000;
24
+ const MIN_THINKING_BUDGET = 1_024;
25
+ const DEFAULT_EFFORT = "high";
26
+ const SSE_EVENTS = new Set([
27
+ "message",
28
+ "message_start",
29
+ "message_delta",
30
+ "message_stop",
31
+ "content_block_start",
32
+ "content_block_delta",
33
+ "content_block_stop",
34
+ "ping",
35
+ "error",
36
+ ]);
37
+ export const framing = Framing.sseEvents(SSE_EVENTS);
38
+ export const ContextManagement = Schema.Struct({
39
+ edits: Schema.Array(Schema.Struct({
40
+ type: Schema.Literal("compact_20260112"),
41
+ trigger: Schema.optional(Schema.Struct({
42
+ type: Schema.Literal("input_tokens"),
43
+ value: Schema.Int.check(Schema.isGreaterThanOrEqualTo(50000)),
44
+ })),
45
+ pauseAfterCompaction: Schema.optional(Schema.Boolean),
46
+ instructions: Schema.optional(Schema.String),
47
+ })),
48
+ });
49
+ // =============================================================================
50
+ // Request Body Schema
51
+ // =============================================================================
52
+ const AnthropicCacheControl = Schema.Struct({
53
+ type: Schema.tag("ephemeral"),
54
+ ttl: Schema.optional(CacheTTL),
55
+ });
56
+ const AnthropicServiceTier = knownString();
57
+ const AnthropicSpeed = knownString();
58
+ const AnthropicTextBlock = Schema.Struct({
59
+ type: Schema.tag("text"),
60
+ text: Schema.String,
61
+ cache_control: Schema.optional(AnthropicCacheControl),
62
+ });
63
+ // SDK: Base64ImageSource:201 {type:"base64", media_type:"image/jpeg"|... , data}, URLImageSource:3817 {type:"url", url}, FileImageSource:2350 {type:"file", file_id}
64
+ // SDK: ImageBlockParam:2356 {source: Base64|URL|File, cache_control, transformations:2381 {oversized_image?}}
65
+ const AnthropicBase64ImageSource = Schema.Struct({
66
+ type: Schema.tag("base64"),
67
+ media_type: Schema.String,
68
+ data: Schema.String,
69
+ });
70
+ const AnthropicURLImageSource = Schema.Struct({ type: Schema.tag("url"), url: Schema.String });
71
+ const AnthropicFileImageSource = Schema.Struct({ type: Schema.tag("file"), file_id: Schema.String });
72
+ const AnthropicImageSource = Schema.Union([
73
+ AnthropicBase64ImageSource,
74
+ AnthropicURLImageSource,
75
+ AnthropicFileImageSource,
76
+ ]);
77
+ const AnthropicImageTransformations = Schema.Struct({
78
+ oversized_image: Schema.optional(Schema.Literals(["downsize", "error"])),
79
+ });
80
+ const AnthropicImageBlock = Schema.Struct({
81
+ type: Schema.tag("image"),
82
+ source: AnthropicImageSource,
83
+ cache_control: Schema.optional(AnthropicCacheControl),
84
+ transformations: Schema.optional(AnthropicImageTransformations),
85
+ });
86
+ const AnthropicVideoBlock = Schema.Struct({
87
+ type: Schema.tag("video"),
88
+ source: AnthropicImageSource,
89
+ cache_control: Schema.optional(AnthropicCacheControl),
90
+ });
91
+ // SDK: Base64PDFSource:209 {type:"base64", media_type:"application/pdf", data}, PlainTextSource:2716 {type:"text", media_type:"text/plain", data},
92
+ // SDK: URLPDFSource:3823 {type:"url", url}, FileDocumentSource:2344 {type:"file", file_id}, ContentBlockSource:2266 {type:"content", content}
93
+ // SDK: DocumentBlockParam:2297 {source: 5-way union, cache_control, citations, context, title}
94
+ const AnthropicBase64PDFSource = Schema.Struct({
95
+ type: Schema.tag("base64"),
96
+ media_type: Schema.Literal("application/pdf"),
97
+ data: Schema.String,
98
+ });
99
+ const AnthropicPlainTextSource = Schema.Struct({
100
+ type: Schema.tag("text"),
101
+ media_type: Schema.Literal("text/plain"),
102
+ data: Schema.String,
103
+ });
104
+ const AnthropicURLPDFSource = Schema.Struct({ type: Schema.tag("url"), url: Schema.String });
105
+ const AnthropicFileDocumentSource = Schema.Struct({ type: Schema.tag("file"), file_id: Schema.String });
106
+ const AnthropicDocumentSource = Schema.Union([
107
+ AnthropicBase64PDFSource,
108
+ AnthropicPlainTextSource,
109
+ AnthropicURLPDFSource,
110
+ AnthropicFileDocumentSource,
111
+ ]);
112
+ const AnthropicDocumentBlock = Schema.Struct({
113
+ type: Schema.tag("document"),
114
+ source: AnthropicDocumentSource,
115
+ cache_control: Schema.optional(AnthropicCacheControl),
116
+ title: Schema.optional(Schema.String),
117
+ context: Schema.optional(Schema.String),
118
+ citations: Schema.optional(Schema.Struct({ enabled: Schema.Boolean })),
119
+ });
120
+ const AnthropicThinkingBlock = Schema.Struct({
121
+ type: Schema.tag("thinking"),
122
+ thinking: Schema.String,
123
+ signature: Schema.String,
124
+ cache_control: Schema.optional(AnthropicCacheControl),
125
+ });
126
+ // Safety-filtered thinking arrives as an opaque encrypted `data` payload with
127
+ // no visible text. It must round-trip verbatim so multi-turn thinking + tool
128
+ // use conversations keep their reasoning continuity.
129
+ const AnthropicRedactedThinkingBlock = Schema.Struct({
130
+ type: Schema.tag("redacted_thinking"),
131
+ data: Schema.String,
132
+ cache_control: Schema.optional(AnthropicCacheControl),
133
+ });
134
+ const AnthropicToolUseBlock = Schema.Struct({
135
+ type: Schema.tag("tool_use"),
136
+ id: Schema.String,
137
+ name: Schema.String,
138
+ input: Schema.Unknown,
139
+ cache_control: Schema.optional(AnthropicCacheControl),
140
+ });
141
+ const AnthropicServerToolUseBlock = Schema.Struct({
142
+ type: Schema.tag("server_tool_use"),
143
+ id: Schema.String,
144
+ name: Schema.String,
145
+ input: Schema.Unknown,
146
+ cache_control: Schema.optional(AnthropicCacheControl),
147
+ });
148
+ // Server tool result blocks: web_search_tool_result, code_execution_tool_result,
149
+ // and web_fetch_tool_result. The provider executes the tool and inlines the
150
+ // structured result into the assistant turn — there is no client tool_result
151
+ // round-trip. We round-trip the structured `content` payload as opaque JSON so
152
+ // the next request can echo it back when continuing the conversation.
153
+ const AnthropicServerToolResultType = Schema.Literals([
154
+ "web_search_tool_result",
155
+ "code_execution_tool_result",
156
+ "web_fetch_tool_result",
157
+ ]);
158
+ const AnthropicServerToolResultBlock = Schema.Struct({
159
+ type: AnthropicServerToolResultType,
160
+ tool_use_id: Schema.String,
161
+ content: Schema.Unknown,
162
+ cache_control: Schema.optional(AnthropicCacheControl),
163
+ });
164
+ // Anthropic accepts either a plain string or an ordered array of text, image, and
165
+ // document blocks inside `tool_result.content`. The array form keeps media as native
166
+ // model input instead of JSON-stringifying base64 into prompt text.
167
+ const AnthropicToolResultContent = Schema.Union([
168
+ AnthropicTextBlock,
169
+ AnthropicImageBlock,
170
+ AnthropicDocumentBlock,
171
+ AnthropicVideoBlock,
172
+ ]);
173
+ const AnthropicToolResultBlock = Schema.Struct({
174
+ type: Schema.tag("tool_result"),
175
+ tool_use_id: Schema.String,
176
+ content: Schema.Union([Schema.String, Schema.Array(AnthropicToolResultContent)]),
177
+ is_error: Schema.optional(Schema.Boolean),
178
+ cache_control: Schema.optional(AnthropicCacheControl),
179
+ });
180
+ const AnthropicUserBlock = Schema.Union([
181
+ AnthropicTextBlock,
182
+ AnthropicImageBlock,
183
+ AnthropicDocumentBlock,
184
+ AnthropicVideoBlock,
185
+ AnthropicToolResultBlock,
186
+ ]);
187
+ const AnthropicCompactionBlock = Schema.Struct({
188
+ type: Schema.Literal("compaction"),
189
+ content: Schema.NullOr(Schema.String),
190
+ });
191
+ const AnthropicAssistantBlock = Schema.Union([
192
+ AnthropicCompactionBlock,
193
+ AnthropicTextBlock,
194
+ AnthropicThinkingBlock,
195
+ AnthropicRedactedThinkingBlock,
196
+ AnthropicToolUseBlock,
197
+ AnthropicServerToolUseBlock,
198
+ AnthropicServerToolResultBlock,
199
+ ]);
200
+ const AnthropicTool = Schema.Struct({
201
+ name: Schema.String,
202
+ description: Schema.String,
203
+ input_schema: JsonObject,
204
+ cache_control: Schema.optional(AnthropicCacheControl),
205
+ });
206
+ const AnthropicToolAdditionBlock = Schema.Struct({
207
+ type: Schema.tag("tool_addition"),
208
+ tool: Schema.Struct({ type: Schema.tag("tool_definition"), definition: AnthropicTool }),
209
+ });
210
+ const AnthropicToolRemovalBlock = Schema.Struct({
211
+ type: Schema.tag("tool_removal"),
212
+ tool: Schema.Struct({ type: Schema.tag("tool_reference"), name: Schema.String }),
213
+ });
214
+ const AnthropicMessage = Schema.Union([
215
+ Schema.Struct({ role: Schema.Literal("user"), content: Schema.Array(AnthropicUserBlock) }),
216
+ Schema.Struct({ role: Schema.Literal("assistant"), content: Schema.Array(AnthropicAssistantBlock) }),
217
+ Schema.Struct({
218
+ role: Schema.Literal("system"),
219
+ content: Schema.Array(Schema.Union([AnthropicTextBlock, AnthropicToolAdditionBlock, AnthropicToolRemovalBlock])),
220
+ output_config: Schema.optional(Schema.Struct({ effort: Schema.String })),
221
+ }),
222
+ ]).pipe(Schema.toTaggedUnion("role"));
223
+ const AnthropicToolChoice = Schema.Union([
224
+ Schema.Struct({
225
+ type: Schema.Literals(["auto", "any", "none"]),
226
+ disable_parallel_tool_use: Schema.optional(Schema.Boolean),
227
+ }),
228
+ Schema.Struct({
229
+ type: Schema.tag("tool"),
230
+ name: Schema.String,
231
+ disable_parallel_tool_use: Schema.optional(Schema.Boolean),
232
+ }),
233
+ ]);
234
+ const AnthropicThinkingBlockBinding = Schema.Struct({
235
+ prefix_mismatch_behavior: Schema.optional(knownString()),
236
+ });
237
+ const AnthropicThinkingFields = {
238
+ display: Schema.optional(knownString()),
239
+ block_binding: Schema.optional(AnthropicThinkingBlockBinding),
240
+ };
241
+ const AnthropicThinkingEnabled = Schema.Struct({
242
+ type: Schema.tag("enabled"),
243
+ budget_tokens: Schema.Number,
244
+ ...AnthropicThinkingFields,
245
+ });
246
+ const AnthropicThinkingAdaptive = Schema.Struct({ type: Schema.tag("adaptive"), ...AnthropicThinkingFields });
247
+ const AnthropicThinkingDisabled = Schema.Struct({ type: Schema.Literals(["disabled", "between_tools"]) });
248
+ const AnthropicThinking = Schema.Union([AnthropicThinkingEnabled, AnthropicThinkingAdaptive, AnthropicThinkingDisabled]);
249
+ // SDK OutputConfig:2684 {effort?: "low"|"medium"|"high"|"xhigh"|"max"|null, format?: JSONOutputFormat:2399}
250
+ const AnthropicJsonOutputFormat = Schema.Struct({
251
+ type: Schema.Literal("json_schema"),
252
+ schema: JsonObject,
253
+ });
254
+ const AnthropicOutputConfig = Schema.Struct({
255
+ effort: Schema.optional(Schema.String),
256
+ format: Schema.optional(Schema.NullOr(AnthropicJsonOutputFormat)),
257
+ });
258
+ // SDK Metadata:2649 {user_id?: string|null}
259
+ const AnthropicMetadata = Schema.Struct({ user_id: optionalNull(Schema.String) });
260
+ // SDK MessageCreateParamsContainer:2596 ContainerParams|string; ContainerParams:2172 {id?, skills?}
261
+ const AnthropicContainer = Schema.Union([
262
+ Schema.String,
263
+ Schema.Struct({
264
+ id: optionalNull(Schema.String),
265
+ skills: optionalNull(Schema.Array(JsonObject)),
266
+ }),
267
+ ]);
268
+ // =============================================================================
269
+ // Provider Options
270
+ // =============================================================================
271
+ // Callers spell the budget as `budgetTokens` or the wire `budget_tokens`; the
272
+ // keys are disjoint per variant so the input type requires exactly one and the
273
+ // transform can narrow on it. Decoding straight to the wire block keeps the
274
+ // alias out of the rest of the file.
275
+ const ThinkingEnabledInput = Schema.Union([
276
+ Schema.Struct({ type: Schema.tag("enabled"), budgetTokens: Schema.Number, ...AnthropicThinkingFields }),
277
+ Schema.Struct({ type: Schema.tag("enabled"), budget_tokens: Schema.Number, ...AnthropicThinkingFields }),
278
+ ]).pipe(Schema.decodeTo(AnthropicThinkingEnabled, {
279
+ decode: SchemaGetter.transform((input) => ({
280
+ type: "enabled",
281
+ budget_tokens: "budgetTokens" in input ? input.budgetTokens : input.budget_tokens,
282
+ display: input.display,
283
+ block_binding: input.block_binding,
284
+ })),
285
+ encode: SchemaGetter.passthrough({ strict: false }),
286
+ }));
287
+ const Thinking = Schema.Union([ThinkingEnabledInput, AnthropicThinkingAdaptive, AnthropicThinkingDisabled]);
288
+ const OutputConfigInput = Schema.Struct({
289
+ effort: optionalNull(Schema.String),
290
+ format: optionalNull(AnthropicJsonOutputFormat),
291
+ });
292
+ // Both key spellings are accepted; `fromRequest` prefers the snake_case one.
293
+ const Options = Schema.Struct({
294
+ /** Advanced in-band compaction. The caller owns checkpoint persistence and recovery. */
295
+ contextManagement: Schema.optional(ContextManagement),
296
+ thinking: Schema.optional(Thinking),
297
+ effort: Schema.optional(Schema.String),
298
+ service_tier: Schema.optional(AnthropicServiceTier),
299
+ serviceTier: Schema.optional(AnthropicServiceTier),
300
+ speed: Schema.optional(AnthropicSpeed),
301
+ metadata: Schema.optional(AnthropicMetadata),
302
+ container: Schema.optional(AnthropicContainer),
303
+ inference_geo: optionalNull(Schema.String),
304
+ inferenceGeo: optionalNull(Schema.String),
305
+ cache_control: Schema.optional(AnthropicCacheControl),
306
+ cacheControl: Schema.optional(AnthropicCacheControl),
307
+ output_config: Schema.optional(OutputConfigInput),
308
+ outputConfig: Schema.optional(OutputConfigInput),
309
+ });
310
+ const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options));
311
+ const AnthropicBodyFields = {
312
+ context_management: Schema.optional(Schema.Struct({
313
+ edits: Schema.Array(Schema.Struct({
314
+ type: Schema.Literal("compact_20260112"),
315
+ trigger: ContextManagement.fields.edits.value.fields.trigger,
316
+ pause_after_compaction: Schema.optional(Schema.Boolean),
317
+ instructions: Schema.optional(Schema.String),
318
+ })),
319
+ })),
320
+ model: Schema.String,
321
+ system: optionalArray(AnthropicTextBlock),
322
+ messages: Schema.Array(AnthropicMessage),
323
+ tools: optionalArray(AnthropicTool),
324
+ tool_choice: Schema.optional(AnthropicToolChoice),
325
+ stream: Schema.Literal(true),
326
+ max_tokens: Schema.Number,
327
+ temperature: Schema.optional(Schema.Number),
328
+ top_p: Schema.optional(Schema.Number),
329
+ top_k: Schema.optional(Schema.Number),
330
+ stop_sequences: optionalArray(Schema.String),
331
+ thinking: Schema.optional(AnthropicThinking),
332
+ output_config: Schema.optional(AnthropicOutputConfig),
333
+ // SDK top-level passthrough: cache_control:4638, container:4643, inference_geo:4649, metadata:4654, service_tier:4670
334
+ cache_control: Schema.optional(AnthropicCacheControl),
335
+ container: Schema.optional(Schema.NullOr(AnthropicContainer)),
336
+ inference_geo: Schema.optional(Schema.NullOr(Schema.String)),
337
+ metadata: Schema.optional(AnthropicMetadata),
338
+ service_tier: Schema.optional(AnthropicServiceTier),
339
+ speed: Schema.optional(AnthropicSpeed),
340
+ };
341
+ export const AnthropicMessagesBody = Schema.Struct(AnthropicBodyFields);
342
+ const AnthropicIterationUsage = Schema.StructWithRest(Schema.Struct({
343
+ input_tokens: optionalNull(Schema.Number),
344
+ output_tokens: Schema.optional(Schema.Number),
345
+ cache_creation_input_tokens: optionalNull(Schema.Number),
346
+ cache_read_input_tokens: optionalNull(Schema.Number),
347
+ server_tool_use: optionalNull(Schema.StructWithRest(Schema.Struct({ web_search_requests: Schema.optional(Schema.Number) }), [
348
+ Schema.Record(Schema.String, Schema.Unknown),
349
+ ])),
350
+ output_tokens_details: optionalNull(Schema.StructWithRest(Schema.Struct({ thinking_tokens: Schema.optional(Schema.Number) }), [
351
+ Schema.Record(Schema.String, Schema.Unknown),
352
+ ])),
353
+ }), [Schema.Record(Schema.String, Schema.Unknown)]);
354
+ const AnthropicUsage = Schema.StructWithRest(Schema.Struct({
355
+ ...AnthropicIterationUsage.schema.fields,
356
+ iterations: Schema.optional(Schema.Array(AnthropicIterationUsage)),
357
+ }), [JsonObject]);
358
+ const AnthropicStreamBlock = Schema.StructWithRest(Schema.Struct({
359
+ type: Schema.String,
360
+ id: Schema.optional(Schema.String),
361
+ name: Schema.optional(Schema.String),
362
+ text: Schema.optional(Schema.String),
363
+ thinking: Schema.optional(Schema.String),
364
+ signature: Schema.optional(Schema.String),
365
+ // redacted_thinking blocks arrive whole in content_block_start with the
366
+ // encrypted payload in `data`; there is no streaming delta sequence.
367
+ data: Schema.optional(Schema.String),
368
+ input: Schema.optional(Schema.Unknown),
369
+ // *_tool_result blocks arrive whole as content_block_start (no streaming
370
+ // delta) with the structured payload in `content` and the originating
371
+ // server_tool_use id in `tool_use_id`.
372
+ tool_use_id: Schema.optional(Schema.String),
373
+ content: Schema.optional(Schema.Unknown),
374
+ }), [JsonObject]);
375
+ const decodeAnthropicStreamBlock = Schema.decodeUnknownOption(AnthropicStreamBlock);
376
+ const AnthropicStreamDelta = Schema.StructWithRest(Schema.Struct({
377
+ content: optionalNull(Schema.String),
378
+ type: Schema.optional(Schema.String),
379
+ text: Schema.optional(Schema.String),
380
+ thinking: Schema.optional(Schema.String),
381
+ partial_json: Schema.optional(Schema.String),
382
+ signature: Schema.optional(Schema.String),
383
+ stop_reason: optionalNull(Schema.String),
384
+ stop_sequence: optionalNull(Schema.String),
385
+ stop_details: optionalNull(Schema.StructWithRest(Schema.Struct({ category: optionalNull(Schema.String), explanation: optionalNull(Schema.String) }), [JsonObject])),
386
+ }), [JsonObject]);
387
+ const decodeAnthropicStreamDelta = Schema.decodeUnknownOption(AnthropicStreamDelta);
388
+ const TypedAnthropicEvent = Schema.StructWithRest(Schema.Struct({
389
+ type: Schema.String,
390
+ index: Schema.optional(Schema.Number),
391
+ message: Schema.optional(Schema.StructWithRest(Schema.Struct({ usage: Schema.optional(AnthropicUsage) }), [JsonObject])),
392
+ content_block: Schema.optional(Schema.Unknown),
393
+ delta: Schema.optional(Schema.Unknown),
394
+ usage: Schema.optional(AnthropicUsage),
395
+ // `type` and `message` are both required per Anthropic's spec, but
396
+ // OpenAI-compatible proxies and gateway translations occasionally drop one
397
+ // or the other; mark them optional so a partial payload still parses and
398
+ // the parser can fall back to whichever field is populated.
399
+ error: Schema.optional(Schema.StructWithRest(Schema.Struct({ type: Schema.optional(Schema.String), message: Schema.optional(Schema.String) }), [JsonObject])),
400
+ }), [JsonObject]);
401
+ const AnthropicEvent = withUntypedFrames(TypedAnthropicEvent);
402
+ const invalid = ProviderShared.invalidRequest;
403
+ // =============================================================================
404
+ // Request Lowering
405
+ // =============================================================================
406
+ // Anthropic accepts at most 4 explicit cache_control breakpoints per request,
407
+ // across `tools`, `system`, and `messages`. Beyond the cap the API returns a
408
+ // 400 — so the lowering layer counts emitted markers and silently drops any
409
+ // that exceed it.
410
+ const ANTHROPIC_BREAKPOINT_CAP = 4;
411
+ const cacheControl = (breakpoints, cache) => {
412
+ if (cache?.type !== "ephemeral" && cache?.type !== "persistent")
413
+ return undefined;
414
+ if (!Cache.take(breakpoints))
415
+ return undefined;
416
+ return { type: "ephemeral", ...(cache.ttl === undefined ? {} : { ttl: cache.ttl }) };
417
+ };
418
+ const providerMetadata = (key, metadata) => ({ [key]: metadata });
419
+ const signatureFromMetadata = (metadata, key) => {
420
+ const provider = metadata?.[key];
421
+ if (!provider)
422
+ return undefined;
423
+ return typeof provider.signature === "string" ? provider.signature : undefined;
424
+ };
425
+ const redactedDataFromMetadata = (metadata, key) => {
426
+ const provider = metadata?.[key];
427
+ if (!provider)
428
+ return undefined;
429
+ return typeof provider.redactedData === "string" ? provider.redactedData : undefined;
430
+ };
431
+ const lowerTool = (breakpoints, tool) => ({
432
+ name: tool.name,
433
+ description: tool.description,
434
+ input_schema: tool.inputSchema,
435
+ cache_control: cacheControl(breakpoints, tool.cache),
436
+ });
437
+ const lowerToolChoice = (toolChoice) => ProviderShared.matchToolChoice(toolChoice, {
438
+ auto: () => ({
439
+ type: "auto",
440
+ ...(toolChoice.disableParallelToolUse === undefined
441
+ ? {}
442
+ : { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
443
+ }),
444
+ none: () => ({ type: "none" }),
445
+ required: () => ({
446
+ type: "any",
447
+ ...(toolChoice.disableParallelToolUse === undefined
448
+ ? {}
449
+ : { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
450
+ }),
451
+ tool: (name) => ({
452
+ type: "tool",
453
+ name,
454
+ ...(toolChoice.disableParallelToolUse === undefined
455
+ ? {}
456
+ : { disable_parallel_tool_use: toolChoice.disableParallelToolUse }),
457
+ }),
458
+ });
459
+ const scrubToolCallID = (id) => id.replace(/[^a-zA-Z0-9_-]/g, "_");
460
+ const lowerToolCall = (part) => ({
461
+ type: "tool_use",
462
+ id: scrubToolCallID(part.id),
463
+ name: part.name,
464
+ input: part.input,
465
+ });
466
+ const lowerServerToolCall = (part) => ({
467
+ type: "server_tool_use",
468
+ id: scrubToolCallID(part.id),
469
+ name: part.name,
470
+ input: part.input,
471
+ });
472
+ // Server tool result blocks are typed by name. Anthropic ships three today;
473
+ // extend this list when new server tools land. The block content is the
474
+ // structured payload returned by the provider, which we round-trip as-is.
475
+ const serverToolResultType = (name) => {
476
+ if (name === "web_search")
477
+ return "web_search_tool_result";
478
+ if (name === "code_execution")
479
+ return "code_execution_tool_result";
480
+ if (name === "web_fetch")
481
+ return "web_fetch_tool_result";
482
+ return undefined;
483
+ };
484
+ const lowerServerToolResult = Effect.fnUntraced(function* (part, providerMetadataKey) {
485
+ const wireType = serverToolResultType(part.name);
486
+ if (!wireType)
487
+ return yield* invalid(`Anthropic Messages does not know how to round-trip server tool result for ${part.name}`);
488
+ // Prefer the provider-owned replay payload; fall back to the result value for
489
+ // histories constructed directly from provider events.
490
+ const payload = part.providerMetadata?.[providerMetadataKey]?.["result"] ?? part.result.value;
491
+ return {
492
+ type: wireType,
493
+ tool_use_id: scrubToolCallID(part.id),
494
+ content: payload,
495
+ };
496
+ });
497
+ // Per-part Anthropic block fields, read from `providerMetadata[providerMetadataKey]` with Anthropic's wire names.
498
+ const MediaOptions = Schema.Struct({
499
+ file_id: Schema.optional(Schema.String),
500
+ title: Schema.optional(Schema.String),
501
+ context: Schema.optional(Schema.String),
502
+ citations: Schema.optional(Schema.Struct({ enabled: Schema.Boolean })),
503
+ transformations: Schema.optional(AnthropicImageTransformations),
504
+ });
505
+ const decodeMediaOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(MediaOptions));
506
+ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());
507
+ const lowerMedia = Effect.fnUntraced(function* (part, request, breakpoints) {
508
+ const mime = part.media.mediaType.toLowerCase();
509
+ const cacheControlValue = breakpoints ? cacheControl(breakpoints, part.cache) : undefined;
510
+ if (mime.startsWith("video/")) {
511
+ const inline = part.media.inline();
512
+ const source = inline
513
+ ? { type: "base64", media_type: mime, data: inline.base64 }
514
+ : yield* ProviderShared.mediaReference(part.media, request.model.provider, "Messages video").pipe(Effect.map((reference) => reference.type === "ref" && !reference.value.includes("://")
515
+ ? { type: "file", file_id: reference.value }
516
+ : { type: "url", url: reference.value }));
517
+ return {
518
+ type: "video",
519
+ source,
520
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
521
+ };
522
+ }
523
+ const options = yield* decodeMediaOptions(part.providerMetadata?.[request.model.route.providerMetadataKey ?? request.model.provider] ?? {});
524
+ const image = (source) => ({
525
+ type: "image",
526
+ source,
527
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
528
+ ...(options.transformations === undefined ? {} : { transformations: options.transformations }),
529
+ });
530
+ const document = (source) => {
531
+ const title = options.title ?? (part.filename ? part.filename : undefined);
532
+ return {
533
+ type: "document",
534
+ source,
535
+ ...(cacheControlValue === undefined ? {} : { cache_control: cacheControlValue }),
536
+ ...(title === undefined ? {} : { title }),
537
+ ...(options.context === undefined ? {} : { context: options.context }),
538
+ ...(options.citations === undefined ? {} : { citations: options.citations }),
539
+ };
540
+ };
541
+ // SDK file sources: FileImageSource:2350 / FileDocumentSource:2344 {type:"file", file_id}
542
+ if (options.file_id) {
543
+ if (mime.startsWith("image/"))
544
+ return image({ type: "file", file_id: options.file_id });
545
+ return document({ type: "file", file_id: options.file_id });
546
+ }
547
+ const rawString = ProviderShared.mediaUrl(part.media)?.trim();
548
+ // SDK URL sources: URLImageSource:3817 / URLPDFSource:3823 {type:"url", url}
549
+ if (rawString && isHttpUrl(rawString)) {
550
+ if (mime.startsWith("image/"))
551
+ return image({ type: "url", url: rawString });
552
+ if (mime === "application/pdf")
553
+ return document({ type: "url", url: rawString });
554
+ }
555
+ const media = yield* ProviderShared.requireInlineMedia("Anthropic Messages", part.media);
556
+ // SDK PlainTextSource:2716 {type:"text", media_type:"text/plain", data}
557
+ if (mime === "text/plain")
558
+ return document({
559
+ type: "text",
560
+ media_type: "text/plain",
561
+ data: Buffer.from(media.base64, "base64").toString("utf8"),
562
+ });
563
+ if (media.mime === "application/pdf")
564
+ return document({ type: "base64", media_type: "application/pdf", data: media.base64 });
565
+ if (!media.mime.startsWith("image/"))
566
+ return yield* invalid(`Anthropic Messages does not support media type ${part.media.mediaType}`);
567
+ return image({ type: "base64", media_type: media.mime, data: media.base64 });
568
+ });
569
+ // Tool results may carry structured text, images, and documents. Keep media as provider-native
570
+ // content instead of JSON-stringifying base64 into a prompt string.
571
+ const lowerToolResultContentItem = Effect.fnUntraced(function* (item, request) {
572
+ if (item.type === "text")
573
+ return { type: "text", text: item.text };
574
+ return yield* lowerMedia(ProviderShared.toolFileMedia(item), request);
575
+ });
576
+ const lowerToolResultContent = Effect.fnUntraced(function* (part, request) {
577
+ // Text / json / error results stay as a string for backward compatibility
578
+ // with existing cassettes and provider expectations.
579
+ if (part.result.type !== "content")
580
+ return ProviderShared.toolResultText(part);
581
+ // Preserve the narrowed array element type when compiled through a consumer package.
582
+ const content = part.result.value;
583
+ return yield* Effect.forEach(content, (item) => lowerToolResultContentItem(item, request));
584
+ });
585
+ const requireThinkingSignature = (request) => {
586
+ if (request.model.compatibility?.requireSignature !== undefined)
587
+ return request.model.compatibility.requireSignature;
588
+ const provider = request.model.provider.toLowerCase();
589
+ const model = request.model.id.toLowerCase();
590
+ const baseURL = (request.model.route.endpoint.baseURL ?? "").toLowerCase();
591
+ if (provider === "kimi-for-coding" ||
592
+ provider === "moonshotai" ||
593
+ provider === "moonshotai-cn" ||
594
+ model.startsWith("kimi-") ||
595
+ baseURL.includes("api.kimi.com/coding") ||
596
+ baseURL.includes("api.moonshot.ai/anthropic") ||
597
+ baseURL.includes("api.moonshot.cn/anthropic"))
598
+ return false;
599
+ if (provider.includes("xiaomi") || model.includes("mimo") || baseURL.includes("xiaomimimo.com"))
600
+ return false;
601
+ if (model.startsWith("qwen") || model.startsWith("minimax-"))
602
+ return false;
603
+ return true;
604
+ };
605
+ // Opus 4.8 and every Claude 5 model accept mid-conversation system messages; later versions inherit support.
606
+ const supportsNativeSystemUpdates = (request) => {
607
+ const override = request.model.capabilities?.systemUpdates;
608
+ if (override !== undefined)
609
+ return override;
610
+ const version = claudeVersion(request.model.id);
611
+ if (version === undefined)
612
+ return false;
613
+ if (version.family === "opus" && version.major === 4)
614
+ return version.minor >= 8;
615
+ return version.major >= 5;
616
+ };
617
+ // Native system messages must follow a user turn (tool results count) or a paused server-tool turn.
618
+ const acceptsNativeSystemAfter = (message) => message?.role === "user" || (message?.role === "assistant" && message.content.at(-1)?.type === "server_tool_use");
619
+ const splitsLocalToolResults = (messages, index) => {
620
+ const pending = new Set();
621
+ for (const message of messages.slice(0, index)) {
622
+ for (const part of message.content) {
623
+ if (message.role === "assistant" && part.type === "tool-call" && part.providerExecuted !== true)
624
+ pending.add(part.id);
625
+ if (message.role === "tool" && part.type === "tool-result")
626
+ pending.delete(part.id);
627
+ }
628
+ }
629
+ return pending.size > 0;
630
+ };
631
+ const lowerNativeSystemUpdate = Effect.fnUntraced(function* (message, breakpoints) {
632
+ const content = yield* ProviderShared.systemUpdateText("Anthropic Messages", message);
633
+ return {
634
+ role: "system",
635
+ content: content.map((part) => ({
636
+ type: "text",
637
+ text: part.text,
638
+ cache_control: cacheControl(breakpoints, part.cache),
639
+ })),
640
+ };
641
+ });
642
+ const lowerWrappedSystemUpdate = Effect.fnUntraced(function* (message, breakpoints) {
643
+ const part = yield* ProviderShared.wrappedSystemUpdate("Anthropic Messages", message);
644
+ return { type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) };
645
+ });
646
+ const lowerToolsUpdate = Effect.fnUntraced(function* (message, update, breakpoints) {
647
+ const text = message.content.length === 0 ? [] : (yield* lowerNativeSystemUpdate(message, breakpoints)).content;
648
+ return {
649
+ role: "system",
650
+ content: [
651
+ ...ProviderShared.flattenTools(update.add).map((tool) => ({
652
+ type: "tool_addition",
653
+ tool: { type: "tool_definition", definition: lowerTool(breakpoints, tool) },
654
+ })),
655
+ ...update.remove.map((name) => ({
656
+ type: "tool_removal",
657
+ tool: { type: "tool_reference", name },
658
+ })),
659
+ ...text,
660
+ ],
661
+ };
662
+ });
663
+ const appendToUserTurn = (messages, block) => {
664
+ const last = messages.at(-1);
665
+ if (last?.role === "user")
666
+ messages[messages.length - 1] = { role: "user", content: [...last.content, block] };
667
+ else
668
+ messages.push({ role: "user", content: [block] });
669
+ };
670
+ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
671
+ const messages = [];
672
+ const providerMetadataKey = request.model.route.providerMetadataKey ?? request.model.provider;
673
+ // Text updates stay where they are unless a user turn follows them; then they move after the latest
674
+ // user turn, the nearest spot where Anthropic accepts a native system message.
675
+ const holdUpdates = supportsNativeSystemUpdates(request);
676
+ const held = [];
677
+ const releaseHeld = Effect.fnUntraced(function* () {
678
+ const native = acceptsNativeSystemAfter(messages.findLast((message) => message.role !== "system"));
679
+ for (const update of held.splice(0)) {
680
+ const tools = toolsUpdate(update);
681
+ if (tools !== undefined) {
682
+ if (!native)
683
+ return yield* invalid("Anthropic Messages tool updates must follow a user message or tool result");
684
+ const lowered = yield* lowerToolsUpdate(update, tools, breakpoints);
685
+ if (lowered.content.length > 0)
686
+ messages.push(lowered);
687
+ continue;
688
+ }
689
+ if (native)
690
+ messages.push(yield* lowerNativeSystemUpdate(update, breakpoints));
691
+ else
692
+ appendToUserTurn(messages, yield* lowerWrappedSystemUpdate(update, breakpoints));
693
+ }
694
+ });
695
+ for (const [index, message] of request.messages.entries()) {
696
+ if (message.role === "system") {
697
+ const update = effortUpdate(message);
698
+ if (update) {
699
+ // Accepted at any position, so the text-update placement rules do not apply.
700
+ messages.push({ role: "system", content: [], output_config: { effort: update.effort ?? DEFAULT_EFFORT } });
701
+ continue;
702
+ }
703
+ // Held like text updates, so one between a tool call and its result lands after the result. Planning keeps a
704
+ // marker in place only on models that take native system messages.
705
+ if (toolsUpdate(message) !== undefined) {
706
+ held.push(message);
707
+ continue;
708
+ }
709
+ if (splitsLocalToolResults(request.messages, index))
710
+ return yield* invalid("Anthropic Messages system updates cannot split a local tool call from its tool result");
711
+ if (holdUpdates)
712
+ held.push(message);
713
+ else
714
+ appendToUserTurn(messages, yield* lowerWrappedSystemUpdate(message, breakpoints));
715
+ continue;
716
+ }
717
+ if (message.role === "user") {
718
+ const content = [];
719
+ for (const part of message.content) {
720
+ if (part.type === "text") {
721
+ if (part.text.trim().length === 0)
722
+ continue;
723
+ content.push({ type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) });
724
+ continue;
725
+ }
726
+ if (part.type === "media") {
727
+ content.push(yield* lowerMedia(part, request, breakpoints));
728
+ continue;
729
+ }
730
+ }
731
+ if (content.length > 0)
732
+ messages.push({ role: "user", content });
733
+ continue;
734
+ }
735
+ if (message.role === "assistant") {
736
+ const content = [];
737
+ for (const part of message.content) {
738
+ if (part.type === "compaction") {
739
+ if (part.provider !== request.model.provider || part.text === undefined)
740
+ return yield* invalid("Compaction state must be replayed to its originating provider and API");
741
+ content.push({ type: "compaction", content: part.text });
742
+ continue;
743
+ }
744
+ if (part.type === "text") {
745
+ if (part.text.trim().length === 0)
746
+ continue;
747
+ content.push({ type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) });
748
+ continue;
749
+ }
750
+ if (part.type === "reasoning") {
751
+ // A signature marks visible thinking; only signature-less parts carrying
752
+ // redactedData round-trip as opaque redacted_thinking blocks.
753
+ const signature = part.encrypted ?? signatureFromMetadata(part.providerMetadata, providerMetadataKey);
754
+ const redactedData = redactedDataFromMetadata(part.providerMetadata, providerMetadataKey);
755
+ if (signature === undefined && redactedData !== undefined) {
756
+ content.push({ type: "redacted_thinking", data: redactedData });
757
+ continue;
758
+ }
759
+ if (!signature || signature.trim().length === 0) {
760
+ if (part.text.trim().length > 0 && !requireThinkingSignature(request)) {
761
+ content.push({ type: "thinking", thinking: part.text, signature: "" });
762
+ }
763
+ continue;
764
+ }
765
+ content.push({ type: "thinking", thinking: part.text, signature });
766
+ continue;
767
+ }
768
+ if (part.type === "tool-call") {
769
+ content.push(part.providerExecuted ? lowerServerToolCall(part) : lowerToolCall(part));
770
+ continue;
771
+ }
772
+ if (part.type === "tool-result" && part.providerExecuted) {
773
+ content.push(yield* lowerServerToolResult(part, providerMetadataKey));
774
+ continue;
775
+ }
776
+ return yield* invalid(`Anthropic Messages assistant messages only support text, reasoning, and tool-call content for now`);
777
+ }
778
+ if (content.length === 0)
779
+ continue;
780
+ yield* releaseHeld();
781
+ messages.push({ role: "assistant", content });
782
+ continue;
783
+ }
784
+ const content = [];
785
+ for (const part of message.content) {
786
+ content.push({
787
+ type: "tool_result",
788
+ tool_use_id: scrubToolCallID(part.id),
789
+ content: yield* lowerToolResultContent(part, request),
790
+ is_error: part.result.type === "error" ? true : undefined,
791
+ cache_control: cacheControl(breakpoints, part.cache),
792
+ });
793
+ }
794
+ const previous = messages.at(-1);
795
+ if (previous?.role === "user" && previous.content.every((block) => block.type === "tool_result"))
796
+ messages[messages.length - 1] = { role: "user", content: [...previous.content, ...content] };
797
+ else
798
+ messages.push({ role: "user", content });
799
+ }
800
+ yield* releaseHeld();
801
+ return messages;
802
+ });
803
+ // The model-ID checks below are fallbacks for models that leave `capabilities.reasoning.updates`,
804
+ // `capabilities.systemUpdates` and `compatibility.supportsThinkingBlockBinding` unset.
805
+ const isThinkingOff = Schema.is(AnthropicThinkingDisabled);
806
+ // Per-turn effort started with Claude Opus 5 and every Claude 5.1 model; later versions of any family inherit it.
807
+ const supportsEffortUpdates = (request) => {
808
+ if (isThinkingOff(request.providerOptions?.thinking))
809
+ return false;
810
+ const override = request.model.capabilities?.reasoning?.updates;
811
+ if (override !== undefined)
812
+ return override;
813
+ const version = claudeVersion(request.model.id);
814
+ if (version === undefined)
815
+ return false;
816
+ if (version.family === "opus" && version.major >= 5)
817
+ return true;
818
+ return version.major > 5 || (version.major === 5 && version.minor >= 1);
819
+ };
820
+ // `tool_addition` adds a tool, or redefines one with the same name; `tool_removal` removes one. A held marker is
821
+ // released just before the next assistant message, where Anthropic only accepts a native system message after a
822
+ // user message or tool result; a marker that would land elsewhere folds.
823
+ const toolUpdates = {
824
+ kinds: ["add", "remove", "replace"],
825
+ placeable: (request, index) => {
826
+ if (!supportsNativeSystemUpdates(request))
827
+ return false;
828
+ const end = request.messages.findIndex((next, at) => at > index && next.role === "assistant");
829
+ const role = request.messages
830
+ .slice(0, end === -1 ? undefined : end)
831
+ .findLast((next) => next.role !== "system")?.role;
832
+ return role === "user" || role === "tool";
833
+ },
834
+ };
835
+ const applyThinkingBindingDefault = (model, thinking) => {
836
+ if (isThinkingOff(thinking))
837
+ return thinking;
838
+ if (!supportsThinkingBlockBinding(model))
839
+ return thinking;
840
+ return {
841
+ ...(thinking ?? { type: "adaptive" }),
842
+ block_binding: {
843
+ prefix_mismatch_behavior: "drop_block",
844
+ ...thinking?.block_binding,
845
+ },
846
+ };
847
+ };
848
+ // Anthropic also requires an explicit thinking budget below `max_tokens` and at or above its minimum.
849
+ const fitThinking = (thinking, maxTokens) => thinking?.type === "enabled"
850
+ ? {
851
+ ...thinking,
852
+ budget_tokens: ProviderShared.fitThinkingBudget(thinking.budget_tokens, maxTokens, MIN_THINKING_BUDGET),
853
+ }
854
+ : thinking;
855
+ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (request) {
856
+ const options = yield* decodeOptions(request.providerOptions ?? {});
857
+ const management = options.contextManagement;
858
+ const outputConfig = options.output_config ?? options.outputConfig;
859
+ const format = outputConfig?.format ?? undefined;
860
+ const updates = resolveEffortUpdates(request, options.effort ?? outputConfig?.effort ?? undefined);
861
+ // Allocate the 4-breakpoint budget in invalidation order: tools → system →
862
+ // messages. Tools live highest in the cache hierarchy, so when callers
863
+ // over-mark we keep their tool hints and shed the message-tail ones first.
864
+ const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP);
865
+ const definitions = ProviderShared.flattenTools(updates.request.tools);
866
+ const tools = definitions.length === 0 ? undefined : definitions.map((tool) => lowerTool(breakpoints, tool));
867
+ // Anthropic rejects tool_choice when no tool is declared; "none" is only meaningful with tools present.
868
+ const declared = tools !== undefined || addsTools(request);
869
+ const toolChoice = !declared || !request.toolChoice ? undefined : lowerToolChoice(request.toolChoice);
870
+ const systemParts = request.system.filter((part) => part.text.length > 0);
871
+ const system = systemParts.length === 0
872
+ ? undefined
873
+ : systemParts.map((part) => ({
874
+ type: "text",
875
+ text: part.text,
876
+ cache_control: cacheControl(breakpoints, part.cache),
877
+ }));
878
+ const messages = yield* lowerMessages(updates.request, breakpoints);
879
+ yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP);
880
+ const output_config = updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format };
881
+ const maxTokens = request.maxTokens ?? DEFAULT_MAX_TOKENS;
882
+ const body = {
883
+ model: request.model.id,
884
+ system,
885
+ messages,
886
+ tools,
887
+ tool_choice: toolChoice,
888
+ stream: true,
889
+ max_tokens: maxTokens,
890
+ temperature: request.temperature,
891
+ top_p: request.topP,
892
+ top_k: request.topK,
893
+ stop_sequences: request.stop,
894
+ thinking: applyThinkingBindingDefault(request.model, fitThinking(options.thinking, maxTokens)),
895
+ output_config,
896
+ // top-level passthrough per SDK MessageCreateParamsBase:4638,4643,4649,4654,4670
897
+ cache_control: options.cache_control ?? options.cacheControl,
898
+ container: options.container,
899
+ inference_geo: options.inference_geo ?? options.inferenceGeo ?? undefined,
900
+ metadata: options.metadata,
901
+ service_tier: options.service_tier ?? options.serviceTier,
902
+ speed: options.speed,
903
+ };
904
+ if (!management)
905
+ return body;
906
+ return {
907
+ ...body,
908
+ context_management: {
909
+ edits: management.edits.map((edit) => ({
910
+ type: edit.type,
911
+ trigger: edit.trigger,
912
+ pause_after_compaction: edit.pauseAfterCompaction,
913
+ instructions: edit.instructions,
914
+ })),
915
+ },
916
+ };
917
+ });
918
+ // =============================================================================
919
+ // Stream Parsing
920
+ // =============================================================================
921
+ const mapFinishReason = (reason) => {
922
+ if (reason === "end_turn" || reason === "stop_sequence" || reason === "pause_turn")
923
+ return "stop";
924
+ if (reason === "max_tokens" || reason === "model_context_window_exceeded")
925
+ return "length";
926
+ if (reason === "tool_use")
927
+ return "tool-calls";
928
+ if (reason === "refusal")
929
+ return "content-filter";
930
+ return "unknown";
931
+ };
932
+ // Anthropic reports the non-overlapping breakdown natively — its
933
+ // `input_tokens` is the *non-cached* count per the Messages API docs, with
934
+ // cache reads and writes as separate fields. We sum them to derive the
935
+ // inclusive `inputTokens` the rest of the contract expects. Extended
936
+ // thinking tokens are included in `output_tokens`; newer responses also
937
+ // expose that subset through `output_tokens_details.thinking_tokens`.
938
+ const mapUsage = (usage, providerMetadataKey, frame) => {
939
+ if (!usage)
940
+ return undefined;
941
+ const iterations = usage.iterations?.length ? usage.iterations : [usage];
942
+ const last = usage.iterations?.at(-1);
943
+ const nonCached = ProviderShared.sumTokens(...iterations.map((item) => item.input_tokens ?? undefined));
944
+ const cacheRead = ProviderShared.sumTokens(...iterations.map((item) => item.cache_read_input_tokens ?? undefined));
945
+ const cacheWrite = ProviderShared.sumTokens(...iterations.map((item) => item.cache_creation_input_tokens ?? undefined));
946
+ const inputTokens = ProviderShared.sumTokens(nonCached, cacheRead, cacheWrite);
947
+ const outputTokens = ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens));
948
+ return new Usage({
949
+ inputTokens,
950
+ outputTokens,
951
+ contextTokens: last?.type === "message" || last?.type === "fallback_message"
952
+ ? ProviderShared.sumTokens(last.input_tokens ?? undefined, last.cache_read_input_tokens ?? undefined, last.cache_creation_input_tokens ?? undefined)
953
+ : undefined,
954
+ nonCachedInputTokens: nonCached,
955
+ cacheReadInputTokens: cacheRead,
956
+ cacheWriteInputTokens: cacheWrite,
957
+ reasoningTokens: ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens_details?.thinking_tokens)),
958
+ totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
959
+ ...ProviderShared.reportedBilling(usage, frame),
960
+ providerMetadata: { [providerMetadataKey]: usage },
961
+ });
962
+ };
963
+ // Anthropic emits usage on `message_start` and again on `message_delta` — the
964
+ // final delta carries the authoritative totals. Right-biased merge: each
965
+ // field prefers `right` when defined, falls back to `left`. `inputTokens` is
966
+ // recomputed from the merged breakdown so the inclusive total stays
967
+ // consistent with `nonCached + cacheRead + cacheWrite`.
968
+ const mergeUsage = (left, right, providerMetadataKey) => {
969
+ if (!left)
970
+ return right;
971
+ if (!right)
972
+ return left;
973
+ const nonCachedInputTokens = right.nonCachedInputTokens ?? left.nonCachedInputTokens;
974
+ const cacheReadInputTokens = right.cacheReadInputTokens ?? left.cacheReadInputTokens;
975
+ const cacheWriteInputTokens = right.cacheWriteInputTokens ?? left.cacheWriteInputTokens;
976
+ const inputTokens = ProviderShared.sumTokens(nonCachedInputTokens, cacheReadInputTokens, cacheWriteInputTokens);
977
+ const outputTokens = right.outputTokens ?? left.outputTokens;
978
+ const reasoningTokens = right.reasoningTokens ?? left.reasoningTokens;
979
+ return new Usage({
980
+ inputTokens,
981
+ outputTokens,
982
+ contextTokens: right.contextTokens ?? left.contextTokens,
983
+ nonCachedInputTokens,
984
+ cacheReadInputTokens,
985
+ cacheWriteInputTokens,
986
+ reasoningTokens,
987
+ totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
988
+ cost: right.cost ?? left.cost,
989
+ providerMetadata: {
990
+ [providerMetadataKey]: mergeJsonRecords(left.providerMetadata?.[providerMetadataKey], right.providerMetadata?.[providerMetadataKey]) ??
991
+ {},
992
+ },
993
+ });
994
+ };
995
+ // Server tool result blocks come whole in `content_block_start` (no streaming
996
+ // delta sequence). We convert the payload to a `tool-result` event with
997
+ // `providerExecuted: true`. The runtime appends it to the assistant message
998
+ // for round-trip; downstream consumers can inspect `result.value` for the
999
+ // structured payload.
1000
+ const SERVER_TOOL_RESULT_NAMES = {
1001
+ web_search_tool_result: "web_search",
1002
+ code_execution_tool_result: "code_execution",
1003
+ web_fetch_tool_result: "web_fetch",
1004
+ };
1005
+ const isServerToolResultType = (type) => type in SERVER_TOOL_RESULT_NAMES;
1006
+ const serverToolResultEvent = (block, providerMetadataKey) => {
1007
+ if (!block.type || !isServerToolResultType(block.type))
1008
+ return undefined;
1009
+ const errorPayload = ProviderShared.isRecord(block.content) && "type" in block.content ? String(block.content.type) : "";
1010
+ const isError = errorPayload.endsWith("_tool_result_error");
1011
+ return StreamEvent.toolResult({
1012
+ id: block.tool_use_id ?? "",
1013
+ name: SERVER_TOOL_RESULT_NAMES[block.type],
1014
+ result: isError ? { type: "error", value: block.content } : { type: "json", value: block.content },
1015
+ providerExecuted: true,
1016
+ // The complete payload is irreducible provider replay state: subsequent
1017
+ // stateless requests must round-trip the typed result block verbatim.
1018
+ providerMetadata: providerMetadata(providerMetadataKey, { blockType: block.type, result: block.content }),
1019
+ });
1020
+ };
1021
+ const NO_EVENTS = [];
1022
+ const onMessageStart = (state, event) => {
1023
+ const usage = mapUsage(event.message?.usage, state.providerMetadataKey);
1024
+ return [usage ? { ...state, usage: mergeUsage(state.usage, usage, state.providerMetadataKey) } : state, NO_EVENTS];
1025
+ };
1026
+ const onContentBlockStart = (state, event) => {
1027
+ const block = event.content_block;
1028
+ if (block.type === "tool_use" || block.type === "server_tool_use") {
1029
+ if (event.index === undefined || !block.id)
1030
+ return [state, NO_EVENTS];
1031
+ const events = [];
1032
+ const lifecycle = Lifecycle.start(state.lifecycle);
1033
+ return [
1034
+ {
1035
+ ...state,
1036
+ lifecycle,
1037
+ tools: ToolStream.start(state.tools, event.index, {
1038
+ id: block.id,
1039
+ name: block.name ?? "",
1040
+ input: block.input !== undefined && (!ProviderShared.isRecord(block.input) || Object.keys(block.input).length > 0)
1041
+ ? ProviderShared.encodeJson(block.input)
1042
+ : undefined,
1043
+ providerExecuted: block.type === "server_tool_use",
1044
+ }),
1045
+ },
1046
+ [
1047
+ ...events,
1048
+ StreamEvent.toolInputStart({
1049
+ id: block.id,
1050
+ name: block.name ?? "",
1051
+ providerExecuted: block.type === "server_tool_use" ? true : undefined,
1052
+ }),
1053
+ ],
1054
+ ];
1055
+ }
1056
+ if (block.type === "text" && block.text !== undefined) {
1057
+ const events = [];
1058
+ const id = `text-${event.index ?? 0}`;
1059
+ const lifecycle = Lifecycle.textStart(state.lifecycle, events, id);
1060
+ return [
1061
+ { ...state, lifecycle: block.text ? Lifecycle.textDelta(lifecycle, events, id, block.text) : lifecycle },
1062
+ events,
1063
+ ];
1064
+ }
1065
+ if (block.type === "thinking" && block.thinking !== undefined) {
1066
+ const events = [];
1067
+ const id = `reasoning-${event.index ?? 0}`;
1068
+ const metadata = block.signature === undefined
1069
+ ? undefined
1070
+ : providerMetadata(state.providerMetadataKey, { signature: block.signature });
1071
+ const lifecycle = Lifecycle.reasoningStart(state.lifecycle, events, id, metadata);
1072
+ return [
1073
+ {
1074
+ ...state,
1075
+ lifecycle: block.thinking
1076
+ ? Lifecycle.reasoningDelta(lifecycle, events, id, block.thinking, metadata)
1077
+ : lifecycle,
1078
+ reasoningSignatures: event.index === undefined || block.signature === undefined
1079
+ ? state.reasoningSignatures
1080
+ : { ...state.reasoningSignatures, [event.index]: block.signature },
1081
+ },
1082
+ events,
1083
+ ];
1084
+ }
1085
+ // Redacted thinking surfaces as an empty reasoning part carrying the opaque
1086
+ // payload as `redactedData` metadata (same model as Vercel's
1087
+ // @ai-sdk/anthropic). The existing content_block_stop closes the part.
1088
+ if (block.type === "redacted_thinking" && block.data !== undefined) {
1089
+ const events = [];
1090
+ return [
1091
+ {
1092
+ ...state,
1093
+ lifecycle: Lifecycle.reasoningStart(state.lifecycle, events, `reasoning-${event.index ?? 0}`, providerMetadata(state.providerMetadataKey, { redactedData: block.data })),
1094
+ },
1095
+ events,
1096
+ ];
1097
+ }
1098
+ const result = serverToolResultEvent(block, state.providerMetadataKey);
1099
+ if (!result)
1100
+ return [state, NO_EVENTS];
1101
+ const events = [];
1102
+ return [{ ...state, lifecycle: Lifecycle.start(state.lifecycle) }, [...events, result]];
1103
+ };
1104
+ const onContentBlockDelta = Effect.fnUntraced(function* (state, event) {
1105
+ const delta = event.delta;
1106
+ if (delta.type === "compaction_delta") {
1107
+ if (event.index === undefined || !(event.index in state.compactions) || delta.content === undefined)
1108
+ return yield* ProviderShared.eventError(ADAPTER, "Compaction delta is missing its block or content");
1109
+ return [
1110
+ { ...state, compactions: { ...state.compactions, [event.index]: delta.content } },
1111
+ NO_EVENTS,
1112
+ ];
1113
+ }
1114
+ if (delta.type === "text_delta" && delta.text) {
1115
+ if (!state.lifecycle.text.has(`text-${event.index ?? 0}`))
1116
+ return [state, NO_EVENTS];
1117
+ const events = [];
1118
+ return [
1119
+ { ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, `text-${event.index ?? 0}`, delta.text) },
1120
+ events,
1121
+ ];
1122
+ }
1123
+ if (delta.type === "thinking_delta" && delta.thinking) {
1124
+ if (!state.lifecycle.reasoning.has(`reasoning-${event.index ?? 0}`))
1125
+ return [state, NO_EVENTS];
1126
+ const events = [];
1127
+ return [
1128
+ {
1129
+ ...state,
1130
+ lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, `reasoning-${event.index ?? 0}`, delta.thinking),
1131
+ },
1132
+ events,
1133
+ ];
1134
+ }
1135
+ if (delta.type === "signature_delta" && delta.signature) {
1136
+ const index = event.index ?? 0;
1137
+ if (!state.lifecycle.reasoning.has(`reasoning-${index}`))
1138
+ return [state, NO_EVENTS];
1139
+ return [
1140
+ {
1141
+ ...state,
1142
+ reasoningSignatures: { ...state.reasoningSignatures, [index]: delta.signature },
1143
+ },
1144
+ NO_EVENTS,
1145
+ ];
1146
+ }
1147
+ if (delta.type === "input_json_delta" && event.index !== undefined) {
1148
+ if (!delta.partial_json)
1149
+ return [state, NO_EVENTS];
1150
+ if (!state.tools[event.index])
1151
+ return [state, NO_EVENTS];
1152
+ const result = ToolStream.appendExisting(ADAPTER, state.tools, event.index, delta.partial_json, "Anthropic Messages tool argument delta is missing its tool call");
1153
+ if (ToolStream.isError(result))
1154
+ return yield* result;
1155
+ const events = [];
1156
+ const lifecycle = result.events.length ? Lifecycle.start(state.lifecycle) : state.lifecycle;
1157
+ events.push(...result.events);
1158
+ return [{ ...state, lifecycle, tools: result.tools }, events];
1159
+ }
1160
+ return [state, NO_EVENTS];
1161
+ });
1162
+ const onContentBlockStop = Effect.fnUntraced(function* (state, event) {
1163
+ if (event.index === undefined)
1164
+ return [state, NO_EVENTS];
1165
+ if (event.index in state.compactions) {
1166
+ const { [event.index]: content, ...compactions } = state.compactions;
1167
+ const events = [];
1168
+ const lifecycle = Lifecycle.start(state.lifecycle);
1169
+ events.push(StreamEvent.compaction({
1170
+ provider: state.provider,
1171
+ text: content,
1172
+ }));
1173
+ return [{ ...state, compactions, lifecycle }, events];
1174
+ }
1175
+ const result = yield* ToolStream.finish(ADAPTER, state.tools, event.index);
1176
+ const events = [];
1177
+ const resultEvents = result.events ?? [];
1178
+ const signature = state.reasoningSignatures[event.index];
1179
+ const lifecycle = resultEvents.length
1180
+ ? Lifecycle.start(state.lifecycle)
1181
+ : Lifecycle.reasoningEnd(Lifecycle.textEnd(state.lifecycle, events, `text-${event.index}`), events, `reasoning-${event.index}`, signature === undefined ? undefined : providerMetadata(state.providerMetadataKey, { signature }));
1182
+ events.push(...resultEvents);
1183
+ const reasoningSignatures = { ...state.reasoningSignatures };
1184
+ delete reasoningSignatures[event.index];
1185
+ return [{ ...state, lifecycle, tools: result.tools, reasoningSignatures }, events];
1186
+ });
1187
+ const onMessageDelta = (state, event) => {
1188
+ const usage = mergeUsage(state.usage, mapUsage(event.usage, state.providerMetadataKey, event), state.providerMetadataKey);
1189
+ const pendingFinish = (() => {
1190
+ const stopReason = event.delta?.stop_reason;
1191
+ if (stopReason === null || stopReason === undefined)
1192
+ return state.pendingFinish;
1193
+ const stopSequence = event.delta?.stop_sequence;
1194
+ const finishMetadata = stopSequence === null || stopSequence === undefined
1195
+ ? state.pendingFinish?.providerMetadata
1196
+ : providerMetadata(state.providerMetadataKey, { stopSequence });
1197
+ const category = event.delta?.stop_details?.category;
1198
+ const explanation = event.delta?.stop_details?.explanation;
1199
+ const detail = explanation && category ? `${explanation} (${category})` : explanation || category;
1200
+ return {
1201
+ reason: mapFinishReason(stopReason),
1202
+ raw: stopReason,
1203
+ ...(detail ? { detail } : {}),
1204
+ providerMetadata: finishMetadata,
1205
+ };
1206
+ })();
1207
+ return [
1208
+ {
1209
+ ...state,
1210
+ usage,
1211
+ pendingFinish,
1212
+ },
1213
+ NO_EVENTS,
1214
+ ];
1215
+ };
1216
+ const onMessageStop = Effect.fnUntraced(function* (state) {
1217
+ if (Object.keys(state.compactions).length)
1218
+ return yield* ProviderShared.eventError(ADAPTER, "Response ended with an incomplete compaction block");
1219
+ const result = yield* ToolStream.finishAll(ADAPTER, state.tools);
1220
+ const events = [];
1221
+ const lifecycle = result.events.length ? Lifecycle.start(state.lifecycle) : state.lifecycle;
1222
+ events.push(...result.events);
1223
+ const closed = Object.entries(state.reasoningSignatures).reduce((current, [index, signature]) => Lifecycle.reasoningEnd(current, events, `reasoning-${index}`, providerMetadata(state.providerMetadataKey, { signature })), lifecycle);
1224
+ const finished = Lifecycle.finish(closed, events, {
1225
+ ...(state.pendingFinish ?? { reason: "unknown" }),
1226
+ usage: state.usage,
1227
+ });
1228
+ return [{ ...state, lifecycle: finished, tools: result.tools }, events];
1229
+ });
1230
+ // Prefix `error.type` so overloads, rate limits, and quota errors are visible
1231
+ // even when the provider message is generic or empty.
1232
+ const providerErrorMessage = (event) => {
1233
+ const type = event.error?.type;
1234
+ const message = event.error?.message;
1235
+ if (type && message)
1236
+ return `${type}: ${message}`;
1237
+ return message || type || "Anthropic Messages stream error";
1238
+ };
1239
+ const onError = (event) => {
1240
+ const message = providerErrorMessage(event);
1241
+ const body = ProviderShared.encodeJson(event);
1242
+ return Effect.fail(new AIError({
1243
+ reason: classifyProviderFailure({ message, rawBody: body }),
1244
+ }));
1245
+ };
1246
+ const STREAM_BLOCK_TYPES = new Set([
1247
+ "compaction",
1248
+ "text",
1249
+ "thinking",
1250
+ "redacted_thinking",
1251
+ "tool_use",
1252
+ "server_tool_use",
1253
+ ]);
1254
+ const STREAM_DELTA_TYPES = new Set([
1255
+ "compaction_delta",
1256
+ "text_delta",
1257
+ "thinking_delta",
1258
+ "signature_delta",
1259
+ "input_json_delta",
1260
+ ]);
1261
+ const invalidStreamEvent = (event) => Effect.fail(ProviderShared.eventError(ADAPTER, "Invalid anthropic/anthropic-messages stream event", ProviderShared.encodeJson(event)));
1262
+ const step = (state, event) => {
1263
+ if (!SSE_EVENTS.has(event.type))
1264
+ return Effect.succeed([state, NO_EVENTS]);
1265
+ if (event.type !== "content_block_start" &&
1266
+ event.content_block !== undefined &&
1267
+ Option.isNone(decodeAnthropicStreamBlock(event.content_block)))
1268
+ return invalidStreamEvent(event);
1269
+ if (event.type !== "content_block_delta" &&
1270
+ event.delta !== undefined &&
1271
+ Option.isNone(decodeAnthropicStreamDelta(event.delta)))
1272
+ return invalidStreamEvent(event);
1273
+ if (event.type === "message_start")
1274
+ return Effect.succeed(onMessageStart(state, event));
1275
+ if (event.type === "content_block_start") {
1276
+ if (!ProviderShared.isRecord(event.content_block) || typeof event.content_block.type !== "string")
1277
+ return invalidStreamEvent(event);
1278
+ if (event.content_block.type === "compaction") {
1279
+ const decoded = Schema.decodeUnknownOption(AnthropicCompactionBlock)(event.content_block);
1280
+ if (event.index === undefined || Option.isNone(decoded))
1281
+ return invalidStreamEvent(event);
1282
+ return Effect.succeed([
1283
+ { ...state, compactions: { ...state.compactions, [event.index]: decoded.value.content } },
1284
+ NO_EVENTS,
1285
+ ]);
1286
+ }
1287
+ if (!STREAM_BLOCK_TYPES.has(event.content_block.type) && !isServerToolResultType(event.content_block.type))
1288
+ return Effect.succeed([state, NO_EVENTS]);
1289
+ const decoded = decodeAnthropicStreamBlock(event.content_block);
1290
+ if (Option.isNone(decoded))
1291
+ return invalidStreamEvent(event);
1292
+ const block = decoded.value;
1293
+ if (block.type === "tool_use" || block.type === "server_tool_use") {
1294
+ if (event.index === undefined)
1295
+ return Effect.fail(ProviderShared.eventError(ADAPTER, `Anthropic ${block.type} missing index`));
1296
+ if (!block.id)
1297
+ return Effect.fail(ProviderShared.eventError(ADAPTER, `Anthropic tool_use missing id at index ${event.index}`));
1298
+ }
1299
+ return Effect.succeed(onContentBlockStart(state, { ...event, content_block: block }));
1300
+ }
1301
+ if (event.type === "content_block_delta") {
1302
+ if (!ProviderShared.isRecord(event.delta))
1303
+ return invalidStreamEvent(event);
1304
+ if (typeof event.delta.type === "string" && !STREAM_DELTA_TYPES.has(event.delta.type))
1305
+ return Effect.succeed([state, NO_EVENTS]);
1306
+ const decoded = decodeAnthropicStreamDelta(event.delta);
1307
+ if (Option.isNone(decoded))
1308
+ return invalidStreamEvent(event);
1309
+ return onContentBlockDelta(state, { ...event, delta: decoded.value });
1310
+ }
1311
+ if (event.type === "content_block_stop")
1312
+ return onContentBlockStop(state, event);
1313
+ if (event.type === "message_delta") {
1314
+ const decoded = decodeAnthropicStreamDelta(event.delta);
1315
+ if (Option.isNone(decoded))
1316
+ return invalidStreamEvent(event);
1317
+ return Effect.succeed(onMessageDelta(state, { ...event, delta: decoded.value }));
1318
+ }
1319
+ if (event.type === "message_stop")
1320
+ return onMessageStop(state);
1321
+ if (event.type === "error")
1322
+ return onError(event);
1323
+ return Effect.succeed([state, NO_EVENTS]);
1324
+ };
1325
+ // =============================================================================
1326
+ // Protocol And Anthropic Route
1327
+ // =============================================================================
1328
+ /**
1329
+ * The Anthropic Messages protocol — request body construction, body schema,
1330
+ * and the streaming-event state machine shared by Anthropic-compatible and
1331
+ * Vertex-hosted Messages routes.
1332
+ */
1333
+ export const protocol = Protocol.make({
1334
+ id: ADAPTER,
1335
+ body: {
1336
+ schema: AnthropicMessagesBody,
1337
+ from: fromRequest,
1338
+ },
1339
+ stream: {
1340
+ event: Protocol.jsonEvent(AnthropicEvent),
1341
+ initial: (request) => ({
1342
+ provider: request.model.provider,
1343
+ compactions: {},
1344
+ providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
1345
+ tools: ToolStream.empty(),
1346
+ reasoningSignatures: {},
1347
+ lifecycle: Lifecycle.initial(),
1348
+ }),
1349
+ step,
1350
+ },
1351
+ supportsEffortUpdates,
1352
+ toolUpdates,
1353
+ });
1354
+ export const transport = () => {
1355
+ const http = HttpTransport.httpJson({ framing });
1356
+ return {
1357
+ ...http,
1358
+ prepare: (input) => {
1359
+ const requiredBetas = requiredBetaHeaders(input.body);
1360
+ if (requiredBetas.length === 0)
1361
+ return http.prepare(input);
1362
+ const headers = Headers.fromInput(input.request.http?.headers);
1363
+ const existingBetas = (headers["anthropic-beta"] ?? "")
1364
+ .split(",")
1365
+ .map((item) => item.trim())
1366
+ .filter(Boolean);
1367
+ const betas = new Set([...existingBetas, ...requiredBetas]);
1368
+ return http.prepare({
1369
+ ...input,
1370
+ request: {
1371
+ ...input.request,
1372
+ http: { ...input.request.http, headers: { ...headers, "anthropic-beta": [...betas].join(",") } },
1373
+ },
1374
+ });
1375
+ },
1376
+ };
1377
+ };
1378
+ function requiredBetaHeaders(body) {
1379
+ // Always request interleaved thinking. The API accepts the header on any
1380
+ // model and ignores it where unsupported, while manual-thinking models need
1381
+ // it for thinking between tool calls.
1382
+ const betas = ["interleaved-thinking-2025-05-14"];
1383
+ const requestsCompaction = (body.context_management?.edits.length ?? 0) > 0;
1384
+ const replaysCompaction = body.messages.some((message) => message.content.some((block) => block.type === "compaction"));
1385
+ if (requestsCompaction || replaysCompaction)
1386
+ betas.push("compact-2026-01-12");
1387
+ if (body.messages.some((message) => message.role === "system" && message.output_config !== undefined))
1388
+ betas.push("mid-conversation-output-config-2026-07-01");
1389
+ if (body.messages.some((message) => message.role === "system" &&
1390
+ message.content.some((block) => block.type === "tool_addition" || block.type === "tool_removal")))
1391
+ betas.push("inline-tools-2026-09-15");
1392
+ // Opus 5.5 accepts `speed` without this header; earlier fast-mode models reject `speed` without it.
1393
+ if (body.speed !== undefined)
1394
+ betas.push("fast-mode-2026-02-01");
1395
+ const thinking = body.thinking;
1396
+ if (thinking && !isThinkingOff(thinking) && thinking.block_binding)
1397
+ betas.push(THINKING_BINDING_BETA);
1398
+ return betas;
1399
+ }
1400
+ export const route = Route.make({
1401
+ id: ADAPTER,
1402
+ provider: "anthropic",
1403
+ providerMetadataKey: "anthropic",
1404
+ protocol,
1405
+ endpoint: Endpoint.path((input) => (input.request.model.provider === "anthropic" ? `${PATH}?beta=true` : PATH), {
1406
+ baseURL: DEFAULT_BASE_URL,
1407
+ }),
1408
+ auth: Auth.none,
1409
+ transport: transport(),
1410
+ headers: () => ({ "anthropic-version": "2023-06-01" }),
1411
+ });
1412
+ export * as AnthropicMessages from "./anthropic-messages.js";