@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,446 @@
1
+ import { Tool } from "@radheim/schema/tool";
2
+ import { Effect, Option, Predicate, Schema, SchemaGetter, SchemaTransformation } from "effect";
3
+ import { Headers, HttpClientRequest } from "effect/http";
4
+ import { Media } from "../media.js";
5
+ import { InvalidProviderOutputError, InvalidRequestError, UnsupportedOperationError, AIError, AssistantMessage, SystemMessage, ToolDefinition, ToolMessage, MediaPart, } from "../schema/index.js";
6
+ import { Json, decodeJson, encodeJson } from "../utils/json.js";
7
+ import { isRecord } from "../utils/record.js";
8
+ import { foldTools, toolsUpdate, withdrawnTools } from "../tool-updates.js";
9
+ export { Json, decodeJson, encodeJson, isRecord };
10
+ const isJson = Schema.is(Schema.Json);
11
+ export const JsonObject = Schema.Record(Schema.String, Schema.Unknown);
12
+ export const optionalArray = (schema) => Schema.optional(Schema.Array(schema));
13
+ export const optionalNull = (schema) => Schema.optional(Schema.NullOr(schema));
14
+ /** Optional provider field where an explicit `null` means absent, so decoding never yields `null`. */
15
+ export const optionalNullish = (schema) => Schema.optional(Schema.NullOr(schema)).pipe(Schema.decodeTo(Schema.optional(Schema.toType(schema)), SchemaTransformation.transformOptional({
16
+ decode: Option.filter(Predicate.isNotNullish),
17
+ encode: (value) => value,
18
+ })));
19
+ /** Optional field whose malformed value decodes to `undefined` instead of failing the enclosing struct. */
20
+ export const lenient = (schema) => Schema.optionalKey(Schema.UndefinedOr(schema).pipe(Schema.catchDecoding(() => Effect.succeed(Option.some(undefined)))));
21
+ /** A billed amount in USD; a malformed or negative one decodes as absent. */
22
+ const billedAmount = lenient(Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)));
23
+ /** Billing an endpoint reports beside its token usage: `cost` is the USD it charged (OpenRouter, LiteLLM, OpenCode Zen). */
24
+ export const ReportedBilling = Schema.Struct({
25
+ cost: billedAmount,
26
+ });
27
+ /**
28
+ * GitHub Copilot reports its charge beside usage on the frame that carries it, as `copilot_usage.total_nano_aiu`:
29
+ * billionths of an AI credit, which costs $0.01.
30
+ */
31
+ const CopilotBilling = Schema.Struct({
32
+ copilot_usage: Schema.Struct({ total_nano_aiu: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)) }),
33
+ });
34
+ const decodeCopilotBilling = Schema.decodeUnknownOption(CopilotBilling);
35
+ /**
36
+ * Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it, or
37
+ * Copilot's billing from the frames that carry the usage.
38
+ */
39
+ export const reportedBilling = (usage, ...frames) => {
40
+ const reported = Option.getOrUndefined(Schema.decodeUnknownOption(ReportedBilling)(usage))?.cost;
41
+ if (reported !== undefined)
42
+ return { cost: reported };
43
+ const nanoAiu = frames
44
+ .map((frame) => Option.getOrUndefined(decodeCopilotBilling(frame))?.copilot_usage.total_nano_aiu)
45
+ .find((value) => value !== undefined);
46
+ return nanoAiu === undefined ? {} : { cost: nanoAiu / 100_000_000_000 };
47
+ };
48
+ /**
49
+ * The filter that blocked a response, from maps keyed by filter name: Azure's `content_filter_results`
50
+ * (`{ hate: { filtered: true } }`) or GitHub Copilot's `copilot_annotations` (`{ TextCopyright: [...] }`).
51
+ */
52
+ export const contentFilterCategory = (...sources) => sources
53
+ .flatMap((source) => (isRecord(source) ? Object.entries(source) : []))
54
+ .find(([, value]) => (isRecord(value) && "filtered" in value ? value.filtered === true : Boolean(value)))?.[0];
55
+ /**
56
+ * Accepts stream frames that carry no `type`, alongside the typed event schema. Gateways inject such frames as
57
+ * keep-alives, so they decode as an ignored event; one with an `error` still decodes as an error event.
58
+ */
59
+ export const withUntypedFrames = (event) => Schema.Union([
60
+ event,
61
+ JsonObject.check(Schema.makeFilter((frame) => !("type" in frame))).pipe(Schema.decodeTo(event, {
62
+ decode: SchemaGetter.transform((frame) => ({ ...frame, type: frame.error != null ? "error" : "ignored" })),
63
+ encode: SchemaGetter.forbidden(() => "Untyped stream frames are decode-only"),
64
+ })),
65
+ ]);
66
+ /** Provider-defined string enum: known values for autocomplete, any string accepted at runtime. */
67
+ export const knownString = () => Schema.declare((value) => typeof value === "string", {
68
+ expected: "string",
69
+ });
70
+ export const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
71
+ // Whether the model accepts request affinity in the body; undefined leaves it to the protocol's default.
72
+ export const acceptsAffinity = (model) => {
73
+ const cache = model.capabilities?.cache;
74
+ return cache === false ? undefined : cache?.affinity;
75
+ };
76
+ // Body-level `prompt_cache_key` is off when caching is disabled or the model
77
+ // explicitly rejects the field. Header-based affinity is unaffected.
78
+ export const sendsPromptCacheKey = (request) => request.cache !== "none" && acceptsAffinity(request.model) !== false;
79
+ // OpenAI limits `prompt_cache_key` to 64 chars; DeepSeek and Zai inherit the same
80
+ // limit via their OpenAI-compatible APIs. Clamp with unicode-aware slicing.
81
+ export const promptCacheKey = (request) => {
82
+ if (!sendsPromptCacheKey(request) || request.affinity === undefined)
83
+ return undefined;
84
+ const chars = Array.from(request.affinity);
85
+ if (chars.length <= OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH)
86
+ return request.affinity;
87
+ return chars.slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH).join("");
88
+ };
89
+ /**
90
+ * `Usage.totalTokens` policy shared by every route. Honors a provider-
91
+ * supplied total; otherwise falls back to `inputTokens + outputTokens` only
92
+ * when at least one is defined. Returns `undefined` when neither input nor
93
+ * output is known so routes don't publish a misleading `0`.
94
+ *
95
+ * Under the inclusive `AI.Usage` contract, `inputTokens` includes cached input
96
+ * and `outputTokens` includes reasoning. Protocol mappers normalize those
97
+ * inclusive values before calling this helper. The provider-supplied total is
98
+ * the source of truth when present; otherwise their sum is the canonical total.
99
+ */
100
+ export const totalTokens = (inputTokens, outputTokens, total) => {
101
+ if (total !== undefined)
102
+ return total;
103
+ if (inputTokens === undefined && outputTokens === undefined)
104
+ return undefined;
105
+ return (inputTokens ?? 0) + (outputTokens ?? 0);
106
+ };
107
+ /**
108
+ * Subtract `subtrahend` from `total`, clamping to zero if the provider
109
+ * reports a non-sensical breakdown (e.g. `cached_tokens > prompt_tokens`).
110
+ * Used by protocol mappers when deriving a non-overlapping breakdown field
111
+ * from a provider's inclusive total — `nonCachedInputTokens` from
112
+ * `inputTokens - cacheReadInputTokens - cacheWriteInputTokens`.
113
+ *
114
+ * If `total` is `undefined`, returns `undefined` (we don't fabricate
115
+ * counts). If `subtrahend` is `undefined`, returns `total` unchanged. The
116
+ * provider-native breakdown stays available on `Usage.providerMetadata` for debugging.
117
+ */
118
+ export const subtractTokens = (total, subtrahend) => {
119
+ if (total === undefined)
120
+ return undefined;
121
+ if (subtrahend === undefined)
122
+ return total;
123
+ return Math.max(0, total - subtrahend);
124
+ };
125
+ /**
126
+ * Sum a list of optional token counts, returning `undefined` only when
127
+ * every value is `undefined` (so we don't fabricate a `0`). Used by
128
+ * protocol mappers to derive the inclusive `inputTokens` total from a
129
+ * provider that natively reports a non-overlapping breakdown
130
+ * (e.g. Anthropic, whose `input_tokens` is already non-cached only).
131
+ */
132
+ export const sumTokens = (...values) => {
133
+ if (values.every((value) => value === undefined))
134
+ return undefined;
135
+ return values.reduce((acc, value) => acc + (value ?? 0), 0);
136
+ };
137
+ /**
138
+ * Caps an explicit thinking budget at half the output limit. Thinking counts against the output limit, so a budget
139
+ * near it leaves the answer, a tool call, or a summary without room. Smaller budgets, special values such as `-1` and
140
+ * `0`, and requests without an output limit pass through unchanged.
141
+ */
142
+ export const fitThinkingBudget = (budget, maxTokens, minimum = 1) => maxTokens === undefined || budget <= maxTokens / 2 ? budget : Math.max(minimum, Math.floor(maxTokens / 2));
143
+ export const eventError = (route, message, body, cause) => new AIError({
144
+ reason: new InvalidProviderOutputError({ route, message, body, cause }),
145
+ });
146
+ export const parseJson = (route, input, message) => Effect.try({
147
+ try: () => decodeJson(input),
148
+ catch: (cause) => eventError(route, message, input, cause),
149
+ });
150
+ /**
151
+ * Join the `text` field of a list of parts with newlines. Used by routes
152
+ * that flatten system / message content arrays into a single provider string
153
+ * (OpenAI Chat `system` content, OpenAI Responses `system` content, Gemini
154
+ * `systemInstruction.parts[].text`).
155
+ */
156
+ export const joinText = (parts) => parts.map((part) => part.text).join("\n");
157
+ const escapeSystemUpdateText = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
158
+ /**
159
+ * Stable fallback representation for chronological `Message.system(...)`
160
+ * updates on routes that do not support that privileged role natively. The
161
+ * wrapper remains visibly lower-authority user text, preserves the original
162
+ * temporal position, and XML-escapes content so it cannot close the wrapper.
163
+ */
164
+ export const wrapSystemUpdate = (parts) => `<system-update>\n${escapeSystemUpdateText(joinText(parts))}\n</system-update>`;
165
+ /**
166
+ * Chronological system updates deliberately accept text only. Do not insert
167
+ * raw retrieved, tool, or web content into privileged updates: keep untrusted
168
+ * data in ordinary user/tool messages instead.
169
+ */
170
+ export const systemUpdateText = Effect.fnUntraced(function* (route, message) {
171
+ const content = [];
172
+ for (const part of message.content) {
173
+ if (!supportsContent(part, ["text"]))
174
+ return yield* unsupportedContent(route, "system", ["text"]);
175
+ content.push(part);
176
+ }
177
+ return content;
178
+ });
179
+ /** Lower an unsupported privileged update into visible, in-order user text. */
180
+ export const wrappedSystemUpdate = Effect.fnUntraced(function* (route, message) {
181
+ const content = yield* systemUpdateText(route, message);
182
+ return { type: "text", text: wrapSystemUpdate(content), cache: content.at(-1)?.cache };
183
+ });
184
+ /**
185
+ * Parse the streamed JSON input of a tool call. Treats an empty string as
186
+ * `"{}"` — providers occasionally finish a tool call without ever emitting
187
+ * input deltas (e.g. zero-arg tools). The error message is uniform across
188
+ * routes: `Invalid JSON input for <route> tool call <name>`.
189
+ */
190
+ export const parseToolInput = (route, name, raw) => parseJson(route, raw || "{}", `Invalid JSON input for ${route} tool call ${name}`);
191
+ /** Inline view or a typed `InvalidRequest` for routes that cannot fetch URLs or dereference provider refs. */
192
+ export const requireInlineMedia = (route, asset) => {
193
+ const inline = asset.inline();
194
+ return inline ? Effect.succeed(inline) : Effect.fail(inlineRequired(route, asset));
195
+ };
196
+ export const inlineRequired = (route, asset) => invalidRequest(`${route} requires inline media (bytes or base64); ${asset.source.type} sources must be materialized first`);
197
+ /** The remote URL of a `url` asset, for protocols that accept `http(s)` references natively. */
198
+ export const mediaUrl = (asset) => (asset.source.type === "url" ? asset.source.url : undefined);
199
+ /**
200
+ * The one string a provider can address an asset by: inline payloads as a data URL, `url` sources as their URL, and
201
+ * this provider's own `ref` as its id. Other providers' refs are never forwarded and fail typed; omit `provider` for
202
+ * APIs with no file handles at all.
203
+ */
204
+ export const mediaReference = (asset, provider, label) => {
205
+ const inline = asset.inline();
206
+ if (inline)
207
+ return Effect.succeed({ type: "dataUrl", value: inline.dataUrl });
208
+ const url = mediaUrl(asset);
209
+ if (url)
210
+ return Effect.succeed({ type: "url", value: url });
211
+ if (provider !== undefined && asset.source.type === "ref" && asset.source.provider === provider)
212
+ return Effect.succeed({ type: "ref", value: asset.source.id });
213
+ const accepted = provider === undefined ? "" : `, and ${provider} references`;
214
+ const got = asset.source.type === "ref" ? `; got ${asset.source.provider}:${asset.source.id}` : "";
215
+ return Effect.fail(invalidRequest(`${label} accepts inline bytes, data URLs, http(s) URLs${accepted}${got}`));
216
+ };
217
+ /**
218
+ * Lift a tool-result file into a `MediaPart`. Tool files carry either a data URL, a URI, or raw base64 in
219
+ * `uri`; the declared `mime` wins over any data-URL prefix so tool authors control the type the model sees.
220
+ */
221
+ export const toolFileMedia = (item) => {
222
+ const parsed = Media.parseDataUrl(item.uri);
223
+ const asset = parsed
224
+ ? Media.from({ ...parsed.source, mediaType: item.mime })
225
+ : item.uri.includes("://")
226
+ ? Media.url(item.uri, { mediaType: item.mime })
227
+ : Media.base64(item.uri, item.mime);
228
+ return MediaPart.make(asset, { filename: item.name });
229
+ };
230
+ export const toolResultText = (part) => {
231
+ if (part.result.type === "text")
232
+ return String(part.result.value);
233
+ if (part.result.type === "error") {
234
+ const value = part.result.value;
235
+ const prototype = typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value);
236
+ const structured = Array.isArray(value) || prototype === Object.prototype || prototype === null;
237
+ return structured && isJson(value) ? encodeJson(value) : String(value);
238
+ }
239
+ return encodeJson(part.result.value);
240
+ };
241
+ export const errorText = (error) => {
242
+ if (error instanceof Error)
243
+ return error.message;
244
+ if (typeof error === "string")
245
+ return error;
246
+ if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint")
247
+ return String(error);
248
+ if (error === null)
249
+ return "null";
250
+ if (error === undefined)
251
+ return "undefined";
252
+ return "Unknown stream error";
253
+ };
254
+ /**
255
+ * Canonical invalid-request constructor shared by protocol lowering.
256
+ */
257
+ export const invalidRequest = (message, cause) => new AIError({
258
+ reason: new InvalidRequestError({ message, cause }),
259
+ });
260
+ /**
261
+ * Canonical constructor for operations the selected route does not implement.
262
+ * Prefer this over `invalidRequest` when the failure is a missing route
263
+ * capability rather than a malformed caller input, so consumers can branch on
264
+ * `reason._tag` plus `reason.operation` instead of matching message text.
265
+ */
266
+ export const unsupportedOperation = (input) => new AIError({
267
+ reason: new UnsupportedOperationError({
268
+ operation: input.operation,
269
+ message: input.message,
270
+ provider: input.provider,
271
+ route: input.route,
272
+ cause: input.cause,
273
+ }),
274
+ });
275
+ /**
276
+ * Lower namespaces to flat definitions for protocols without a native
277
+ * namespace construct. Leaf names join their namespace path with `_` because
278
+ * `.` is not broadly accepted in provider tool names. A no-op on tools `flattenRequest` already flattened; adapters call
279
+ * it to type their tools.
280
+ */
281
+ export const flattenTools = (tools, path = []) => {
282
+ const flat = tools.flatMap((tool) => {
283
+ if (tool.type === "namespace")
284
+ return flattenTools(tool.tools, [...path, tool.name]);
285
+ if (path.length === 0)
286
+ return [tool];
287
+ return [new ToolDefinition({ ...tool, name: [...path, tool.name].join("_") })];
288
+ });
289
+ return [...new Map(flat.map((tool) => [tool.name, tool])).values()];
290
+ };
291
+ /**
292
+ * The request as a protocol without native namespaces sees it: tools, tool updates, past calls and a forced choice all
293
+ * use flattened names. `Protocol.make` applies it before `body.from` for such protocols, so adapters only see flat
294
+ * requests.
295
+ */
296
+ export const flattenRequest = (request) => {
297
+ const all = [...request.tools, ...request.messages.flatMap((message) => toolsUpdate(message)?.add ?? [])];
298
+ const declared = new Set(flattenTools(all).map((tool) => tool.name));
299
+ const flatten = (part) => flattenToolName(part, declared);
300
+ // A tool update that redefines a namespace drops the tools it leaves out, which only the namespace shows, so name
301
+ // them as explicit removals.
302
+ let tools = request.tools;
303
+ const messages = request.messages.map((message) => {
304
+ if (message.role === "system" && message.tools !== undefined) {
305
+ const next = foldTools(tools, message.tools.add, message.tools.remove);
306
+ const remove = withdrawnTools(tools, next);
307
+ tools = next;
308
+ return new SystemMessage({ ...message, tools: { add: flattenTools(message.tools.add), remove } });
309
+ }
310
+ if (message.role === "assistant") {
311
+ const content = message.content.map((part) => part.type === "tool-call" || part.type === "tool-result" ? flatten(part) : part);
312
+ return sameParts(content, message.content) ? message : new AssistantMessage({ ...message, content });
313
+ }
314
+ if (message.role !== "tool")
315
+ return message;
316
+ const content = message.content.map(flatten);
317
+ return sameParts(content, message.content) ? message : new ToolMessage({ ...message, content });
318
+ });
319
+ return {
320
+ ...request,
321
+ tools: flattenTools(request.tools),
322
+ messages,
323
+ toolChoice: flattenToolChoice(request.toolChoice, all, declared),
324
+ };
325
+ };
326
+ /**
327
+ * @deprecated Routes without native namespaces already receive flattened requests; use `flattenRequest`. Removed in
328
+ * the next minor.
329
+ */
330
+ export const flattenToolRequest = (request) => {
331
+ const flat = flattenRequest(request);
332
+ return { tools: flattenTools(flat.tools), request: flat };
333
+ };
334
+ // A forced choice names a namespaced tool by its path (`crm.lookup`); point it at the flattened definition.
335
+ const flattenToolChoice = (choice, tools, declared) => {
336
+ if (choice?.type !== "tool" || declared.has(choice.name))
337
+ return choice;
338
+ const name = new Map(namespacedPaths(tools)).get(choice.name);
339
+ return name === undefined ? choice : { ...choice, name };
340
+ };
341
+ // Each namespaced tool's path and the name flattenTools gives it.
342
+ const namespacedPaths = (tools, path = []) => tools.flatMap((tool) => {
343
+ if (tool.type === "namespace")
344
+ return namespacedPaths(tool.tools, [...path, tool.name]);
345
+ return path.length === 0 ? [] : [[[...path, tool.name].join("."), [...path, tool.name].join("_")]];
346
+ });
347
+ const flattenToolName = (part, declared) => {
348
+ const flat = part.namespace === undefined ? part.name : `${part.namespace}_${part.name}`;
349
+ // Models sometimes call names no tool declares, such as a Code Mode path like `a.b.c`. Several providers (OpenAI
350
+ // Chat Completions, Bedrock Converse) reject those characters when the call is replayed, so replace them. A
351
+ // declared name is kept as is, so a provider that accepts it sees calls under the tool's own name.
352
+ const name = declared.has(flat) ? flat : flat.replace(/[^a-zA-Z0-9_-]/g, "_") || "_";
353
+ return name === part.name && part.namespace === undefined ? part : { ...part, name, namespace: undefined };
354
+ };
355
+ const sameParts = (next, previous) => next.every((part, index) => part === previous[index]);
356
+ export const matchToolChoice = (toolChoice, cases) => {
357
+ if (toolChoice.type === "auto")
358
+ return cases.auto();
359
+ if (toolChoice.type === "none")
360
+ return cases.none();
361
+ if (toolChoice.type === "required")
362
+ return cases.required();
363
+ return cases.tool(toolChoice.name);
364
+ };
365
+ const formatContentTypes = (types) => {
366
+ if (types.length <= 1)
367
+ return types[0] ?? "";
368
+ if (types.length === 2)
369
+ return `${types[0]} and ${types[1]}`;
370
+ return `${types.slice(0, -1).join(", ")}, and ${types.at(-1)}`;
371
+ };
372
+ export const supportsContent = (part, types) => types.includes(part.type);
373
+ export const unsupportedContent = (route, role, types) => invalidRequest(`${route} ${role} messages only support ${formatContentTypes(types)} content for now`);
374
+ /**
375
+ * Build a `validate` step from a Schema decoder. Replaces the per-route
376
+ * lambda body `(payload) => decode(payload).pipe(Effect.mapError((e) =>
377
+ * invalid(e.message)))`. Any decode error is translated into
378
+ * `AIError` carrying the original parse-error message.
379
+ */
380
+ export const validateWith = (decode) => (payload) => decode(payload).pipe(Effect.mapError((error) => invalidRequest(error.message, error)));
381
+ const buildJsonPost = (input, compressed) => {
382
+ const headers = Headers.set(Headers.fromInput(input.headers), "content-type", "application/json");
383
+ if (!compressed)
384
+ return HttpClientRequest.post(input.url).pipe(HttpClientRequest.setHeaders(headers), HttpClientRequest.bodyText(input.body, "application/json"));
385
+ return HttpClientRequest.post(input.url).pipe(HttpClientRequest.setHeaders(Headers.set(headers, "content-encoding", compressed.encoding)), HttpClientRequest.bodyUint8Array(compressed.body, "application/json"));
386
+ };
387
+ /**
388
+ * Build an HTTP POST with a JSON body. Sets `content-type: application/json`
389
+ * automatically after caller-supplied headers so routes cannot accidentally
390
+ * send JSON with a stale content type. The body is passed pre-encoded so
391
+ * routes can choose between
392
+ * `Schema.encodeSync(payload)` and `ProviderShared.encodeJson(payload)`.
393
+ * A `zstd` or `gzip` encoding compresses the body and sets `content-encoding`;
394
+ * it falls back to plain JSON when the runtime has no zlib.
395
+ */
396
+ export const jsonPost = (input) => buildJsonPost(input, compressBody(input.body, input.encoding));
397
+ /**
398
+ * Effectful variant of `jsonPost` that runs gzip/zstd compression off the JS event loop via async `node:zlib`
399
+ * so large multimodal payloads do not stall concurrent sessions, PTYs, or UI streams.
400
+ */
401
+ export const jsonPostEffect = (input) => Effect.map(compressBodyAsync(input.body, input.encoding), (compressed) => buildJsonPost(input, compressed));
402
+ const fastGzipThreshold = 2 * 1024 * 1024;
403
+ const gzipOptions = (text) => (text.length > fastGzipThreshold ? { level: 1 } : {});
404
+ function compressBody(text, encoding) {
405
+ if (encoding === undefined || encoding === "none")
406
+ return undefined;
407
+ // Looked up at call time instead of imported: a runtime without node:zlib or its zstd export
408
+ // (browsers, older Node, some workerd setups) sends plain JSON rather than failing to load this module.
409
+ const zlib = globalThis.process?.getBuiltinModule?.("node:zlib");
410
+ try {
411
+ const body = encoding === "zstd" ? zlib?.zstdCompressSync?.(text) : zlib?.gzipSync(text, gzipOptions(text));
412
+ return body && { encoding, body };
413
+ }
414
+ catch {
415
+ // Compression is an optimization, so a failure sends plain JSON instead of failing the request.
416
+ return undefined;
417
+ }
418
+ }
419
+ function compressBodyAsync(text, encoding) {
420
+ if (encoding === undefined || encoding === "none")
421
+ return Effect.succeed(undefined);
422
+ const zlib = globalThis.process?.getBuiltinModule?.("node:zlib");
423
+ if (!zlib)
424
+ return Effect.succeed(undefined);
425
+ return Effect.callback((resume) => {
426
+ const onDone = (error, body) => {
427
+ // Compression is an optimization, so a failure sends plain JSON instead of failing the request.
428
+ resume(Effect.succeed(error || !body ? undefined : { encoding, body }));
429
+ };
430
+ try {
431
+ if (encoding === "zstd") {
432
+ if (typeof zlib.zstdCompress !== "function")
433
+ return resume(Effect.succeed(undefined));
434
+ zlib.zstdCompress(text, onDone);
435
+ return;
436
+ }
437
+ if (typeof zlib.gzip !== "function")
438
+ return resume(Effect.succeed(undefined));
439
+ zlib.gzip(text, gzipOptions(text), onDone);
440
+ }
441
+ catch {
442
+ resume(Effect.succeed(undefined));
443
+ }
444
+ });
445
+ }
446
+ export * as ProviderShared from "./shared.js";
@@ -0,0 +1,145 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse, type DecisionAnswer, type DecisionModelCompatibility, type DecisionQuestion, type DecisionRequest } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { AIError } from "../schema/index.js";
5
+ export declare const DEFAULT_PATH = "/systemone";
6
+ export declare const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1";
7
+ /** `state.messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
8
+ type MediaInput = NonNullable<DecisionModelCompatibility["mediaInput"]> | "state.messages";
9
+ declare const Answer: Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
10
+ readonly type: Schema.Literal<"noul">;
11
+ readonly noul: Schema.Number;
12
+ }>, Schema.Struct<{
13
+ readonly type: Schema.Literal<"choice">;
14
+ readonly choice: Schema.String;
15
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
16
+ readonly confidence: Schema.Number;
17
+ }>, Schema.Struct<{
18
+ readonly type: Schema.Literal<"score">;
19
+ readonly score: Schema.Number;
20
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
21
+ readonly confidence: Schema.Number;
22
+ }>, Schema.Struct<{
23
+ readonly type: Schema.Literal<"refusal">;
24
+ readonly message: Schema.optional<Schema.String>;
25
+ }>]>;
26
+ export declare const Response: Schema.Struct<{
27
+ readonly model: Schema.String;
28
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
29
+ readonly type: Schema.Literal<"noul">;
30
+ readonly noul: Schema.Number;
31
+ }>, Schema.Struct<{
32
+ readonly type: Schema.Literal<"choice">;
33
+ readonly choice: Schema.String;
34
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
35
+ readonly confidence: Schema.Number;
36
+ }>, Schema.Struct<{
37
+ readonly type: Schema.Literal<"score">;
38
+ readonly score: Schema.Number;
39
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
40
+ readonly confidence: Schema.Number;
41
+ }>, Schema.Struct<{
42
+ readonly type: Schema.Literal<"refusal">;
43
+ readonly message: Schema.optional<Schema.String>;
44
+ }>]>>;
45
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
46
+ readonly input_tokens: Schema.optional<Schema.Number>;
47
+ readonly output_tokens: Schema.optional<Schema.Number>;
48
+ readonly cost: Schema.optional<Schema.Number>;
49
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
50
+ readonly id: Schema.optional<Schema.String>;
51
+ readonly provider: Schema.optional<Schema.String>;
52
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
53
+ }>;
54
+ export type Response = Schema.Schema.Type<typeof Response>;
55
+ /** The System One body without `model`; media goes where the model's `mediaInput` says, else `fallback`. */
56
+ export declare const encodeBody: (request: DecisionRequest<import("../decision.js").DecisionModel<import("../decision.js").DecisionOptions>, import("../decision.js").DecisionQuestions>, fallback: MediaInput) => Effect.Effect<{
57
+ questions: any;
58
+ state: unknown;
59
+ assets?: undefined;
60
+ } | {
61
+ questions: any;
62
+ state: readonly unknown[];
63
+ assets: {
64
+ [k: string]: {
65
+ type: string;
66
+ format: string;
67
+ data_base64: string;
68
+ };
69
+ };
70
+ }, AIError, never>;
71
+ declare const encodeQuestions: (questions: ReadonlyArray<DecisionQuestion>) => Effect.Effect<any, AIError, never>;
72
+ /** Map System One's answers, keyed by question name, back to the request's question order. */
73
+ export declare const toResponse: (data: Response, request: DecisionRequest, providerMetadataKey: string, invalid: (message: string) => AIError) => Effect.Effect<never, AIError, never> | Effect.Effect<DecisionResponse, never, never>;
74
+ declare const toAnswer: (question: DecisionQuestion, answer: typeof Answer.Type) => DecisionAnswer;
75
+ export declare const protocol: DecisionRoute.Protocol;
76
+ /** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
77
+ export declare const route: DecisionRoute.Route;
78
+ export declare const SystemOne: {
79
+ readonly Answer: Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
80
+ readonly type: Schema.Literal<"noul">;
81
+ readonly noul: Schema.Number;
82
+ }>, Schema.Struct<{
83
+ readonly type: Schema.Literal<"choice">;
84
+ readonly choice: Schema.String;
85
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
86
+ readonly confidence: Schema.Number;
87
+ }>, Schema.Struct<{
88
+ readonly type: Schema.Literal<"score">;
89
+ readonly score: Schema.Number;
90
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
91
+ readonly confidence: Schema.Number;
92
+ }>, Schema.Struct<{
93
+ readonly type: Schema.Literal<"refusal">;
94
+ readonly message: Schema.optional<Schema.String>;
95
+ }>]>;
96
+ readonly Response: Schema.Struct<{
97
+ readonly model: Schema.String;
98
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
99
+ readonly type: Schema.Literal<"noul">;
100
+ readonly noul: Schema.Number;
101
+ }>, Schema.Struct<{
102
+ readonly type: Schema.Literal<"choice">;
103
+ readonly choice: Schema.String;
104
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
105
+ readonly confidence: Schema.Number;
106
+ }>, Schema.Struct<{
107
+ readonly type: Schema.Literal<"score">;
108
+ readonly score: Schema.Number;
109
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
110
+ readonly confidence: Schema.Number;
111
+ }>, Schema.Struct<{
112
+ readonly type: Schema.Literal<"refusal">;
113
+ readonly message: Schema.optional<Schema.String>;
114
+ }>]>>;
115
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
116
+ readonly input_tokens: Schema.optional<Schema.Number>;
117
+ readonly output_tokens: Schema.optional<Schema.Number>;
118
+ readonly cost: Schema.optional<Schema.Number>;
119
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
120
+ readonly id: Schema.optional<Schema.String>;
121
+ readonly provider: Schema.optional<Schema.String>;
122
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
123
+ }>;
124
+ readonly encodeBody: (request: DecisionRequest<import("../decision.js").DecisionModel<import("../decision.js").DecisionOptions>, import("../decision.js").DecisionQuestions>, fallback: MediaInput) => Effect.Effect<{
125
+ questions: any;
126
+ state: unknown;
127
+ assets?: undefined;
128
+ } | {
129
+ questions: any;
130
+ state: readonly unknown[];
131
+ assets: {
132
+ [k: string]: {
133
+ type: string;
134
+ format: string;
135
+ data_base64: string;
136
+ };
137
+ };
138
+ }, AIError, never>;
139
+ readonly encodeQuestions: typeof encodeQuestions;
140
+ readonly toAnswer: typeof toAnswer;
141
+ readonly toResponse: typeof toResponse;
142
+ readonly protocol: DecisionRoute.Protocol;
143
+ readonly route: DecisionRoute.Route;
144
+ };
145
+ export {};