@mastra/core 0.20.2 → 0.21.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (314) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +30 -121
  3. package/dist/agent/agent.d.ts +5 -10
  4. package/dist/agent/agent.d.ts.map +1 -1
  5. package/dist/agent/agent.types.d.ts +12 -14
  6. package/dist/agent/agent.types.d.ts.map +1 -1
  7. package/dist/agent/index.cjs +19 -11
  8. package/dist/agent/index.d.ts +2 -1
  9. package/dist/agent/index.d.ts.map +1 -1
  10. package/dist/agent/index.js +2 -2
  11. package/dist/agent/input-processor/index.cjs +6 -6
  12. package/dist/agent/input-processor/index.js +1 -1
  13. package/dist/agent/message-list/index.d.ts +4 -4
  14. package/dist/agent/message-list/index.d.ts.map +1 -1
  15. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +1 -1
  16. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts.map +1 -1
  17. package/dist/agent/message-list/prompt/convert-file.d.ts +2 -2
  18. package/dist/agent/message-list/prompt/convert-file.d.ts.map +1 -1
  19. package/dist/agent/message-list/types.d.ts +2 -2
  20. package/dist/agent/message-list/types.d.ts.map +1 -1
  21. package/dist/agent/message-list/utils/convert-messages.d.ts +2 -2
  22. package/dist/agent/types.d.ts +13 -5
  23. package/dist/agent/types.d.ts.map +1 -1
  24. package/dist/agent/utils.d.ts +110 -0
  25. package/dist/agent/utils.d.ts.map +1 -0
  26. package/dist/agent/workflows/prepare-stream/index.d.ts +2 -2
  27. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  28. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  29. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +2 -2
  30. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +1 -2
  31. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  32. package/dist/agent/workflows/prepare-stream/schema.d.ts +2 -2
  33. package/dist/ai-tracing/index.cjs +32 -32
  34. package/dist/ai-tracing/index.js +1 -1
  35. package/dist/ai-tracing/spans/base.d.ts +2 -0
  36. package/dist/ai-tracing/spans/base.d.ts.map +1 -1
  37. package/dist/ai-tracing/types.d.ts +24 -0
  38. package/dist/ai-tracing/types.d.ts.map +1 -1
  39. package/dist/{chunk-BWC4WQTS.js → chunk-24L3LVID.js} +21 -14
  40. package/dist/chunk-24L3LVID.js.map +1 -0
  41. package/dist/{chunk-7ZXDZXGD.cjs → chunk-2BTTHMDJ.cjs} +14 -2
  42. package/dist/chunk-2BTTHMDJ.cjs.map +1 -0
  43. package/dist/{chunk-KK5LUATU.js → chunk-2VSJYKJF.js} +4 -4
  44. package/dist/{chunk-KK5LUATU.js.map → chunk-2VSJYKJF.js.map} +1 -1
  45. package/dist/chunk-33JJWAVI.js +2077 -0
  46. package/dist/chunk-33JJWAVI.js.map +1 -0
  47. package/dist/chunk-3ZEJSGTJ.cjs +9289 -0
  48. package/dist/chunk-3ZEJSGTJ.cjs.map +1 -0
  49. package/dist/{chunk-6ZSVXXMJ.js → chunk-624FF2ZG.js} +14 -2
  50. package/dist/chunk-624FF2ZG.js.map +1 -0
  51. package/dist/{chunk-2QV245Q5.cjs → chunk-6OJROHMC.cjs} +25 -18
  52. package/dist/chunk-6OJROHMC.cjs.map +1 -0
  53. package/dist/{chunk-T5SM2HLV.cjs → chunk-74P72XBM.cjs} +4 -4
  54. package/dist/chunk-74P72XBM.cjs.map +1 -0
  55. package/dist/chunk-75CDUY5G.js +158 -0
  56. package/dist/chunk-75CDUY5G.js.map +1 -0
  57. package/dist/chunk-BLPOOPRL.js +3164 -0
  58. package/dist/chunk-BLPOOPRL.js.map +1 -0
  59. package/dist/{chunk-JZ5MQXUL.cjs → chunk-DUMAWQ7I.cjs} +4 -4
  60. package/dist/{chunk-JZ5MQXUL.cjs.map → chunk-DUMAWQ7I.cjs.map} +1 -1
  61. package/dist/chunk-EQV7XSTY.cjs +2090 -0
  62. package/dist/chunk-EQV7XSTY.cjs.map +1 -0
  63. package/dist/chunk-ILZI4MEU.js +9263 -0
  64. package/dist/chunk-ILZI4MEU.js.map +1 -0
  65. package/dist/{chunk-4PRV2Y55.cjs → chunk-LOUJSR3F.cjs} +5 -5
  66. package/dist/{chunk-4PRV2Y55.cjs.map → chunk-LOUJSR3F.cjs.map} +1 -1
  67. package/dist/{chunk-M2MHQQGJ.js → chunk-ONHTH5RH.js} +4 -4
  68. package/dist/chunk-ONHTH5RH.js.map +1 -0
  69. package/dist/{chunk-YBC4V5GE.js → chunk-PPW3SAWO.js} +5 -9
  70. package/dist/{chunk-YBC4V5GE.js.map → chunk-PPW3SAWO.js.map} +1 -1
  71. package/dist/{chunk-DBYLVMIV.js → chunk-Q4YVANA4.js} +25 -7
  72. package/dist/chunk-Q4YVANA4.js.map +1 -0
  73. package/dist/chunk-QMKBXESK.cjs +3186 -0
  74. package/dist/chunk-QMKBXESK.cjs.map +1 -0
  75. package/dist/{chunk-EB2KTBHB.js → chunk-R3W5CNKP.js} +100 -82
  76. package/dist/chunk-R3W5CNKP.js.map +1 -0
  77. package/dist/{chunk-ECMIW6W2.cjs → chunk-RXGL66T6.cjs} +134 -111
  78. package/dist/chunk-RXGL66T6.cjs.map +1 -0
  79. package/dist/{chunk-PPCSJI73.cjs → chunk-SL534RIL.cjs} +33 -14
  80. package/dist/chunk-SL534RIL.cjs.map +1 -0
  81. package/dist/{chunk-YICS4NNU.cjs → chunk-SQXKJWFX.cjs} +12 -12
  82. package/dist/{chunk-YICS4NNU.cjs.map → chunk-SQXKJWFX.cjs.map} +1 -1
  83. package/dist/{chunk-X5SB7NR3.cjs → chunk-SSDFGDFJ.cjs} +9 -10
  84. package/dist/chunk-SSDFGDFJ.cjs.map +1 -0
  85. package/dist/{chunk-OC7MSESV.cjs → chunk-TTJM3STK.cjs} +7 -11
  86. package/dist/{chunk-OC7MSESV.cjs.map → chunk-TTJM3STK.cjs.map} +1 -1
  87. package/dist/{chunk-RE7SRMBE.cjs → chunk-UPRLKS2E.cjs} +16 -16
  88. package/dist/chunk-UPRLKS2E.cjs.map +1 -0
  89. package/dist/{chunk-7H72OAZ3.js → chunk-UQCUAYWV.js} +3 -3
  90. package/dist/{chunk-7H72OAZ3.js.map → chunk-UQCUAYWV.js.map} +1 -1
  91. package/dist/{chunk-SWNIMD7I.js → chunk-XL5MZTLP.js} +3 -3
  92. package/dist/chunk-XL5MZTLP.js.map +1 -0
  93. package/dist/{chunk-HTX7EHW5.js → chunk-XQ5A3ISB.js} +3 -3
  94. package/dist/{chunk-HTX7EHW5.js.map → chunk-XQ5A3ISB.js.map} +1 -1
  95. package/dist/chunk-Y2PKC5BX.cjs +160 -0
  96. package/dist/chunk-Y2PKC5BX.cjs.map +1 -0
  97. package/dist/{chunk-VSTMNPZJ.js → chunk-YUV3LZMY.js} +7 -8
  98. package/dist/chunk-YUV3LZMY.js.map +1 -0
  99. package/dist/index.cjs +53 -49
  100. package/dist/index.js +10 -10
  101. package/dist/llm/index.cjs +9 -5
  102. package/dist/llm/index.d.ts +4 -3
  103. package/dist/llm/index.d.ts.map +1 -1
  104. package/dist/llm/index.js +1 -1
  105. package/dist/llm/model/base.types.d.ts +2 -2
  106. package/dist/llm/model/base.types.d.ts.map +1 -1
  107. package/dist/llm/model/gateways/base.d.ts +1 -1
  108. package/dist/llm/model/gateways/base.d.ts.map +1 -1
  109. package/dist/llm/model/gateways/models-dev.d.ts +1 -1
  110. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
  111. package/dist/llm/model/gateways/netlify.d.ts +1 -1
  112. package/dist/llm/model/gateways/netlify.d.ts.map +1 -1
  113. package/dist/llm/model/index.d.ts +2 -1
  114. package/dist/llm/model/index.d.ts.map +1 -1
  115. package/dist/llm/model/model.d.ts +2 -2
  116. package/dist/llm/model/model.d.ts.map +1 -1
  117. package/dist/llm/model/model.loop.d.ts +3 -3
  118. package/dist/llm/model/model.loop.d.ts.map +1 -1
  119. package/dist/llm/model/model.loop.types.d.ts +2 -3
  120. package/dist/llm/model/model.loop.types.d.ts.map +1 -1
  121. package/dist/llm/model/provider-registry.d.ts +98 -0
  122. package/dist/llm/model/provider-registry.d.ts.map +1 -0
  123. package/dist/llm/model/provider-types.generated.d.ts +679 -0
  124. package/dist/llm/model/registry-generator.d.ts +29 -0
  125. package/dist/llm/model/registry-generator.d.ts.map +1 -0
  126. package/dist/llm/model/resolve-model.d.ts +46 -0
  127. package/dist/llm/model/resolve-model.d.ts.map +1 -0
  128. package/dist/llm/model/router.d.ts +2 -2
  129. package/dist/llm/model/router.d.ts.map +1 -1
  130. package/dist/llm/model/shared.types.d.ts +10 -4
  131. package/dist/llm/model/shared.types.d.ts.map +1 -1
  132. package/dist/loop/index.cjs +2 -2
  133. package/dist/loop/index.js +1 -1
  134. package/dist/loop/loop.d.ts +1 -1
  135. package/dist/loop/loop.d.ts.map +1 -1
  136. package/dist/loop/network/index.d.ts.map +1 -1
  137. package/dist/loop/telemetry/index.d.ts +1 -1
  138. package/dist/loop/telemetry/index.d.ts.map +1 -1
  139. package/dist/loop/test-utils/options.d.ts.map +1 -1
  140. package/dist/loop/test-utils/streamObject.d.ts +1 -1
  141. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  142. package/dist/loop/test-utils/utils.d.ts +2 -2
  143. package/dist/loop/test-utils/utils.d.ts.map +1 -1
  144. package/dist/loop/types.d.ts +4 -3
  145. package/dist/loop/types.d.ts.map +1 -1
  146. package/dist/loop/workflows/agentic-execution/index.d.ts +73 -73
  147. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  148. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +50 -50
  149. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  150. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +25 -25
  151. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  152. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
  153. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  154. package/dist/loop/workflows/agentic-loop/index.d.ts +73 -73
  155. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  156. package/dist/loop/workflows/run-state.d.ts +1 -1
  157. package/dist/loop/workflows/run-state.d.ts.map +1 -1
  158. package/dist/loop/workflows/schema.d.ts +33 -33
  159. package/dist/loop/workflows/schema.d.ts.map +1 -1
  160. package/dist/loop/workflows/stream.d.ts +1 -1
  161. package/dist/loop/workflows/stream.d.ts.map +1 -1
  162. package/dist/mastra/hooks.d.ts.map +1 -1
  163. package/dist/mastra/index.cjs +2 -2
  164. package/dist/mastra/index.js +1 -1
  165. package/dist/memory/index.cjs +4 -4
  166. package/dist/memory/index.js +1 -1
  167. package/dist/memory/memory.d.ts +3 -3
  168. package/dist/memory/memory.d.ts.map +1 -1
  169. package/dist/memory/types.d.ts +3 -3
  170. package/dist/memory/types.d.ts.map +1 -1
  171. package/dist/models-dev-A334FF64.js +3 -0
  172. package/dist/models-dev-A334FF64.js.map +1 -0
  173. package/dist/models-dev-ECOIQLLK.cjs +12 -0
  174. package/dist/models-dev-ECOIQLLK.cjs.map +1 -0
  175. package/dist/netlify-CEYZ5O54.js +3 -0
  176. package/dist/netlify-CEYZ5O54.js.map +1 -0
  177. package/dist/netlify-WFAL2AA4.cjs +12 -0
  178. package/dist/netlify-WFAL2AA4.cjs.map +1 -0
  179. package/dist/processors/index.cjs +11 -11
  180. package/dist/processors/index.js +1 -1
  181. package/dist/processors/processors/language-detector.d.ts +2 -0
  182. package/dist/processors/processors/language-detector.d.ts.map +1 -1
  183. package/dist/processors/processors/moderation.d.ts +6 -3
  184. package/dist/processors/processors/moderation.d.ts.map +1 -1
  185. package/dist/processors/processors/pii-detector.d.ts +8 -4
  186. package/dist/processors/processors/pii-detector.d.ts.map +1 -1
  187. package/dist/processors/processors/prompt-injection-detector.d.ts.map +1 -1
  188. package/dist/processors/processors/structured-output.d.ts +4 -2
  189. package/dist/processors/processors/structured-output.d.ts.map +1 -1
  190. package/dist/processors/processors/system-prompt-scrubber.d.ts +2 -1
  191. package/dist/processors/processors/system-prompt-scrubber.d.ts.map +1 -1
  192. package/dist/processors/runner.d.ts +8 -2
  193. package/dist/processors/runner.d.ts.map +1 -1
  194. package/dist/provider-registry.json +1625 -0
  195. package/dist/registry-generator-7XDUEFUT.cjs +111 -0
  196. package/dist/registry-generator-7XDUEFUT.cjs.map +1 -0
  197. package/dist/registry-generator-ZKIT6I3E.js +103 -0
  198. package/dist/registry-generator-ZKIT6I3E.js.map +1 -0
  199. package/dist/relevance/index.cjs +4 -4
  200. package/dist/relevance/index.js +1 -1
  201. package/dist/relevance/mastra-agent/index.d.ts +2 -2
  202. package/dist/relevance/mastra-agent/index.d.ts.map +1 -1
  203. package/dist/scores/base.d.ts +6 -6
  204. package/dist/scores/base.d.ts.map +1 -1
  205. package/dist/scores/index.cjs +9 -9
  206. package/dist/scores/index.js +2 -2
  207. package/dist/scores/run-experiment/index.d.ts +1 -1
  208. package/dist/scores/run-experiment/index.d.ts.map +1 -1
  209. package/dist/scores/scoreTraces/index.cjs +10 -10
  210. package/dist/scores/scoreTraces/index.cjs.map +1 -1
  211. package/dist/scores/scoreTraces/index.js +5 -5
  212. package/dist/scores/scoreTraces/index.js.map +1 -1
  213. package/dist/scores/types.d.ts +1 -1
  214. package/dist/scores/types.d.ts.map +1 -1
  215. package/dist/storage/index.cjs +3 -3
  216. package/dist/storage/index.js +1 -1
  217. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  218. package/dist/stream/aisdk/v4/input.d.ts.map +1 -1
  219. package/dist/stream/aisdk/v5/compat/content.d.ts +2 -2
  220. package/dist/stream/aisdk/v5/compat/content.d.ts.map +1 -1
  221. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts +2 -2
  222. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
  223. package/dist/stream/aisdk/v5/compat/ui-message.d.ts +1 -1
  224. package/dist/stream/aisdk/v5/compat/ui-message.d.ts.map +1 -1
  225. package/dist/stream/aisdk/v5/compat/validation.d.ts +1 -1
  226. package/dist/stream/aisdk/v5/compat/validation.d.ts.map +1 -1
  227. package/dist/stream/aisdk/v5/execute.d.ts +5 -4
  228. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  229. package/dist/stream/aisdk/v5/input.d.ts +1 -1
  230. package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
  231. package/dist/stream/aisdk/v5/output-helpers.d.ts +9 -9
  232. package/dist/stream/aisdk/v5/output-helpers.d.ts.map +1 -1
  233. package/dist/stream/aisdk/v5/output.d.ts +40 -39
  234. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  235. package/dist/stream/aisdk/v5/test-utils.d.ts +1 -1
  236. package/dist/stream/aisdk/v5/test-utils.d.ts.map +1 -1
  237. package/dist/stream/aisdk/v5/transform.d.ts +2 -2
  238. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  239. package/dist/stream/base/input.d.ts +1 -1
  240. package/dist/stream/base/input.d.ts.map +1 -1
  241. package/dist/stream/base/output-format-handlers.d.ts +5 -2
  242. package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
  243. package/dist/stream/base/output.d.ts +31 -25
  244. package/dist/stream/base/output.d.ts.map +1 -1
  245. package/dist/stream/base/schema.d.ts +1 -1
  246. package/dist/stream/base/schema.d.ts.map +1 -1
  247. package/dist/stream/index.cjs +13 -9
  248. package/dist/stream/index.d.ts +1 -0
  249. package/dist/stream/index.d.ts.map +1 -1
  250. package/dist/stream/index.js +2 -2
  251. package/dist/stream/types.d.ts +19 -6
  252. package/dist/stream/types.d.ts.map +1 -1
  253. package/dist/test-utils/llm-mock.cjs +6 -6
  254. package/dist/test-utils/llm-mock.cjs.map +1 -1
  255. package/dist/test-utils/llm-mock.d.ts +1 -1
  256. package/dist/test-utils/llm-mock.d.ts.map +1 -1
  257. package/dist/test-utils/llm-mock.js +3 -3
  258. package/dist/test-utils/llm-mock.js.map +1 -1
  259. package/dist/tools/types.d.ts +2 -2
  260. package/dist/tools/types.d.ts.map +1 -1
  261. package/dist/utils.cjs +17 -17
  262. package/dist/utils.d.ts +3 -2
  263. package/dist/utils.d.ts.map +1 -1
  264. package/dist/utils.js +1 -1
  265. package/dist/vector/embed.d.ts +2 -2
  266. package/dist/vector/embed.d.ts.map +1 -1
  267. package/dist/vector/index.cjs +4 -4
  268. package/dist/vector/index.js +1 -1
  269. package/dist/vector/vector.d.ts +2 -2
  270. package/dist/vector/vector.d.ts.map +1 -1
  271. package/dist/workflows/default.d.ts +2 -2
  272. package/dist/workflows/default.d.ts.map +1 -1
  273. package/dist/workflows/evented/execution-engine.d.ts +1 -1
  274. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  275. package/dist/workflows/evented/index.cjs +10 -10
  276. package/dist/workflows/evented/index.js +1 -1
  277. package/dist/workflows/execution-engine.d.ts +1 -1
  278. package/dist/workflows/execution-engine.d.ts.map +1 -1
  279. package/dist/workflows/index.cjs +12 -12
  280. package/dist/workflows/index.js +1 -1
  281. package/dist/workflows/legacy/index.cjs +22 -22
  282. package/dist/workflows/legacy/index.js +1 -1
  283. package/dist/workflows/legacy/machine.d.ts +1 -1
  284. package/dist/workflows/legacy/workflow.d.ts +1 -1
  285. package/dist/workflows/step.d.ts +1 -1
  286. package/dist/workflows/step.d.ts.map +1 -1
  287. package/dist/workflows/types.d.ts +1 -1
  288. package/dist/workflows/types.d.ts.map +1 -1
  289. package/dist/workflows/workflow.d.ts +25 -8
  290. package/dist/workflows/workflow.d.ts.map +1 -1
  291. package/package.json +24 -19
  292. package/src/llm/model/provider-types.generated.d.ts +679 -0
  293. package/dist/chunk-2QV245Q5.cjs.map +0 -1
  294. package/dist/chunk-6ZSVXXMJ.js.map +0 -1
  295. package/dist/chunk-7ZXDZXGD.cjs.map +0 -1
  296. package/dist/chunk-BWC4WQTS.js.map +0 -1
  297. package/dist/chunk-BZ6BIHLE.js +0 -1418
  298. package/dist/chunk-BZ6BIHLE.js.map +0 -1
  299. package/dist/chunk-DBYLVMIV.js.map +0 -1
  300. package/dist/chunk-EB2KTBHB.js.map +0 -1
  301. package/dist/chunk-ECMIW6W2.cjs.map +0 -1
  302. package/dist/chunk-M2MHQQGJ.js.map +0 -1
  303. package/dist/chunk-PPCSJI73.cjs.map +0 -1
  304. package/dist/chunk-RE7SRMBE.cjs.map +0 -1
  305. package/dist/chunk-REVAU76X.cjs +0 -1423
  306. package/dist/chunk-REVAU76X.cjs.map +0 -1
  307. package/dist/chunk-SWNIMD7I.js.map +0 -1
  308. package/dist/chunk-T5SM2HLV.cjs.map +0 -1
  309. package/dist/chunk-VSTMNPZJ.js.map +0 -1
  310. package/dist/chunk-X5SB7NR3.cjs.map +0 -1
  311. package/dist/llm/model/provider-registry.generated.d.ts +0 -99
  312. package/dist/llm/model/provider-registry.generated.d.ts.map +0 -1
  313. package/dist/stream/aisdk/v5/model-supports.d.ts +0 -25
  314. package/dist/stream/aisdk/v5/model-supports.d.ts.map +0 -1
@@ -0,0 +1,3186 @@
1
+ 'use strict';
2
+
3
+ var chunk3ZEJSGTJ_cjs = require('./chunk-3ZEJSGTJ.cjs');
4
+ var provider = require('@ai-sdk/provider');
5
+ var providerUtils = require('@ai-sdk/provider-utils');
6
+ var z3 = require('zod/v4');
7
+
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule) return e;
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
18
+ });
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+
26
+ var z3__namespace = /*#__PURE__*/_interopNamespace(z3);
27
+
28
+ function convertToXaiChatMessages(prompt) {
29
+ const messages = [];
30
+ const warnings = [];
31
+ for (const { role, content } of prompt) {
32
+ switch (role) {
33
+ case "system": {
34
+ messages.push({ role: "system", content });
35
+ break;
36
+ }
37
+ case "user": {
38
+ if (content.length === 1 && content[0].type === "text") {
39
+ messages.push({ role: "user", content: content[0].text });
40
+ break;
41
+ }
42
+ messages.push({
43
+ role: "user",
44
+ content: content.map((part) => {
45
+ switch (part.type) {
46
+ case "text": {
47
+ return { type: "text", text: part.text };
48
+ }
49
+ case "file": {
50
+ if (part.mediaType.startsWith("image/")) {
51
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
52
+ return {
53
+ type: "image_url",
54
+ image_url: {
55
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${providerUtils.convertToBase64(part.data)}`
56
+ }
57
+ };
58
+ } else {
59
+ throw new provider.UnsupportedFunctionalityError({
60
+ functionality: `file part media type ${part.mediaType}`
61
+ });
62
+ }
63
+ }
64
+ }
65
+ })
66
+ });
67
+ break;
68
+ }
69
+ case "assistant": {
70
+ let text = "";
71
+ const toolCalls = [];
72
+ for (const part of content) {
73
+ switch (part.type) {
74
+ case "text": {
75
+ text += part.text;
76
+ break;
77
+ }
78
+ case "tool-call": {
79
+ toolCalls.push({
80
+ id: part.toolCallId,
81
+ type: "function",
82
+ function: {
83
+ name: part.toolName,
84
+ arguments: JSON.stringify(part.input)
85
+ }
86
+ });
87
+ break;
88
+ }
89
+ }
90
+ }
91
+ messages.push({
92
+ role: "assistant",
93
+ content: text,
94
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
95
+ });
96
+ break;
97
+ }
98
+ case "tool": {
99
+ for (const toolResponse of content) {
100
+ const output = toolResponse.output;
101
+ let contentValue;
102
+ switch (output.type) {
103
+ case "text":
104
+ case "error-text":
105
+ contentValue = output.value;
106
+ break;
107
+ case "content":
108
+ case "json":
109
+ case "error-json":
110
+ contentValue = JSON.stringify(output.value);
111
+ break;
112
+ }
113
+ messages.push({
114
+ role: "tool",
115
+ tool_call_id: toolResponse.toolCallId,
116
+ content: contentValue
117
+ });
118
+ }
119
+ break;
120
+ }
121
+ default: {
122
+ const _exhaustiveCheck = role;
123
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
124
+ }
125
+ }
126
+ }
127
+ return { messages, warnings };
128
+ }
129
+ function getResponseMetadata({
130
+ id,
131
+ model,
132
+ created
133
+ }) {
134
+ return {
135
+ id: id != null ? id : void 0,
136
+ modelId: model != null ? model : void 0,
137
+ timestamp: created != null ? new Date(created * 1e3) : void 0
138
+ };
139
+ }
140
+ function mapXaiFinishReason(finishReason) {
141
+ switch (finishReason) {
142
+ case "stop":
143
+ return "stop";
144
+ case "length":
145
+ return "length";
146
+ case "tool_calls":
147
+ case "function_call":
148
+ return "tool-calls";
149
+ case "content_filter":
150
+ return "content-filter";
151
+ default:
152
+ return "unknown";
153
+ }
154
+ }
155
+ var webSourceSchema = z3__namespace.object({
156
+ type: z3__namespace.literal("web"),
157
+ country: z3__namespace.string().length(2).optional(),
158
+ excludedWebsites: z3__namespace.array(z3__namespace.string()).max(5).optional(),
159
+ allowedWebsites: z3__namespace.array(z3__namespace.string()).max(5).optional(),
160
+ safeSearch: z3__namespace.boolean().optional()
161
+ });
162
+ var xSourceSchema = z3__namespace.object({
163
+ type: z3__namespace.literal("x"),
164
+ excludedXHandles: z3__namespace.array(z3__namespace.string()).optional(),
165
+ includedXHandles: z3__namespace.array(z3__namespace.string()).optional(),
166
+ postFavoriteCount: z3__namespace.number().int().optional(),
167
+ postViewCount: z3__namespace.number().int().optional(),
168
+ /**
169
+ * @deprecated use `includedXHandles` instead
170
+ */
171
+ xHandles: z3__namespace.array(z3__namespace.string()).optional()
172
+ });
173
+ var newsSourceSchema = z3__namespace.object({
174
+ type: z3__namespace.literal("news"),
175
+ country: z3__namespace.string().length(2).optional(),
176
+ excludedWebsites: z3__namespace.array(z3__namespace.string()).max(5).optional(),
177
+ safeSearch: z3__namespace.boolean().optional()
178
+ });
179
+ var rssSourceSchema = z3__namespace.object({
180
+ type: z3__namespace.literal("rss"),
181
+ links: z3__namespace.array(z3__namespace.string().url()).max(1)
182
+ // currently only supports one RSS link
183
+ });
184
+ var searchSourceSchema = z3__namespace.discriminatedUnion("type", [
185
+ webSourceSchema,
186
+ xSourceSchema,
187
+ newsSourceSchema,
188
+ rssSourceSchema
189
+ ]);
190
+ var xaiProviderOptions = z3__namespace.object({
191
+ reasoningEffort: z3__namespace.enum(["low", "high"]).optional(),
192
+ searchParameters: z3__namespace.object({
193
+ /**
194
+ * search mode preference
195
+ * - "off": disables search completely
196
+ * - "auto": model decides whether to search (default)
197
+ * - "on": always enables search
198
+ */
199
+ mode: z3__namespace.enum(["off", "auto", "on"]),
200
+ /**
201
+ * whether to return citations in the response
202
+ * defaults to true
203
+ */
204
+ returnCitations: z3__namespace.boolean().optional(),
205
+ /**
206
+ * start date for search data (ISO8601 format: YYYY-MM-DD)
207
+ */
208
+ fromDate: z3__namespace.string().optional(),
209
+ /**
210
+ * end date for search data (ISO8601 format: YYYY-MM-DD)
211
+ */
212
+ toDate: z3__namespace.string().optional(),
213
+ /**
214
+ * maximum number of search results to consider
215
+ * defaults to 20
216
+ */
217
+ maxSearchResults: z3__namespace.number().min(1).max(50).optional(),
218
+ /**
219
+ * data sources to search from
220
+ * defaults to ["web", "x"] if not specified
221
+ */
222
+ sources: z3__namespace.array(searchSourceSchema).optional()
223
+ }).optional()
224
+ });
225
+ var xaiErrorDataSchema = z3__namespace.object({
226
+ error: z3__namespace.object({
227
+ message: z3__namespace.string(),
228
+ type: z3__namespace.string().nullish(),
229
+ param: z3__namespace.any().nullish(),
230
+ code: z3__namespace.union([z3__namespace.string(), z3__namespace.number()]).nullish()
231
+ })
232
+ });
233
+ var xaiFailedResponseHandler = providerUtils.createJsonErrorResponseHandler({
234
+ errorSchema: xaiErrorDataSchema,
235
+ errorToMessage: (data) => data.error.message
236
+ });
237
+ function prepareTools({
238
+ tools,
239
+ toolChoice
240
+ }) {
241
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
242
+ const toolWarnings = [];
243
+ if (tools == null) {
244
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
245
+ }
246
+ const xaiTools = [];
247
+ for (const tool of tools) {
248
+ if (tool.type === "provider-defined") {
249
+ toolWarnings.push({ type: "unsupported-tool", tool });
250
+ } else {
251
+ xaiTools.push({
252
+ type: "function",
253
+ function: {
254
+ name: tool.name,
255
+ description: tool.description,
256
+ parameters: tool.inputSchema
257
+ }
258
+ });
259
+ }
260
+ }
261
+ if (toolChoice == null) {
262
+ return { tools: xaiTools, toolChoice: void 0, toolWarnings };
263
+ }
264
+ const type = toolChoice.type;
265
+ switch (type) {
266
+ case "auto":
267
+ case "none":
268
+ return { tools: xaiTools, toolChoice: type, toolWarnings };
269
+ case "required":
270
+ return { tools: xaiTools, toolChoice: "required", toolWarnings };
271
+ case "tool":
272
+ return {
273
+ tools: xaiTools,
274
+ toolChoice: {
275
+ type: "function",
276
+ function: { name: toolChoice.toolName }
277
+ },
278
+ toolWarnings
279
+ };
280
+ default: {
281
+ const _exhaustiveCheck = type;
282
+ throw new provider.UnsupportedFunctionalityError({
283
+ functionality: `tool choice type: ${_exhaustiveCheck}`
284
+ });
285
+ }
286
+ }
287
+ }
288
+ var XaiChatLanguageModel = class {
289
+ constructor(modelId, config) {
290
+ this.specificationVersion = "v2";
291
+ this.supportedUrls = {
292
+ "image/*": [/^https?:\/\/.*$/]
293
+ };
294
+ this.modelId = modelId;
295
+ this.config = config;
296
+ }
297
+ get provider() {
298
+ return this.config.provider;
299
+ }
300
+ async getArgs({
301
+ prompt,
302
+ maxOutputTokens,
303
+ temperature,
304
+ topP,
305
+ topK,
306
+ frequencyPenalty,
307
+ presencePenalty,
308
+ stopSequences,
309
+ seed,
310
+ responseFormat,
311
+ providerOptions,
312
+ tools,
313
+ toolChoice
314
+ }) {
315
+ var _a15, _b, _c;
316
+ const warnings = [];
317
+ const options = (_a15 = await providerUtils.parseProviderOptions({
318
+ provider: "xai",
319
+ providerOptions,
320
+ schema: xaiProviderOptions
321
+ })) != null ? _a15 : {};
322
+ if (topK != null) {
323
+ warnings.push({
324
+ type: "unsupported-setting",
325
+ setting: "topK"
326
+ });
327
+ }
328
+ if (frequencyPenalty != null) {
329
+ warnings.push({
330
+ type: "unsupported-setting",
331
+ setting: "frequencyPenalty"
332
+ });
333
+ }
334
+ if (presencePenalty != null) {
335
+ warnings.push({
336
+ type: "unsupported-setting",
337
+ setting: "presencePenalty"
338
+ });
339
+ }
340
+ if (stopSequences != null) {
341
+ warnings.push({
342
+ type: "unsupported-setting",
343
+ setting: "stopSequences"
344
+ });
345
+ }
346
+ if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) {
347
+ warnings.push({
348
+ type: "unsupported-setting",
349
+ setting: "responseFormat",
350
+ details: "JSON response format schema is not supported"
351
+ });
352
+ }
353
+ const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
354
+ warnings.push(...messageWarnings);
355
+ const {
356
+ tools: xaiTools,
357
+ toolChoice: xaiToolChoice,
358
+ toolWarnings
359
+ } = prepareTools({
360
+ tools,
361
+ toolChoice
362
+ });
363
+ warnings.push(...toolWarnings);
364
+ const baseArgs = {
365
+ // model id
366
+ model: this.modelId,
367
+ // standard generation settings
368
+ max_tokens: maxOutputTokens,
369
+ temperature,
370
+ top_p: topP,
371
+ seed,
372
+ reasoning_effort: options.reasoningEffort,
373
+ // response format
374
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
375
+ type: "json_schema",
376
+ json_schema: {
377
+ name: (_b = responseFormat.name) != null ? _b : "response",
378
+ schema: responseFormat.schema,
379
+ strict: true
380
+ }
381
+ } : { type: "json_object" } : void 0,
382
+ // search parameters
383
+ search_parameters: options.searchParameters ? {
384
+ mode: options.searchParameters.mode,
385
+ return_citations: options.searchParameters.returnCitations,
386
+ from_date: options.searchParameters.fromDate,
387
+ to_date: options.searchParameters.toDate,
388
+ max_search_results: options.searchParameters.maxSearchResults,
389
+ sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
390
+ var _a22;
391
+ return {
392
+ type: source.type,
393
+ ...source.type === "web" && {
394
+ country: source.country,
395
+ excluded_websites: source.excludedWebsites,
396
+ allowed_websites: source.allowedWebsites,
397
+ safe_search: source.safeSearch
398
+ },
399
+ ...source.type === "x" && {
400
+ excluded_x_handles: source.excludedXHandles,
401
+ included_x_handles: (_a22 = source.includedXHandles) != null ? _a22 : source.xHandles,
402
+ post_favorite_count: source.postFavoriteCount,
403
+ post_view_count: source.postViewCount
404
+ },
405
+ ...source.type === "news" && {
406
+ country: source.country,
407
+ excluded_websites: source.excludedWebsites,
408
+ safe_search: source.safeSearch
409
+ },
410
+ ...source.type === "rss" && {
411
+ links: source.links
412
+ }
413
+ };
414
+ })
415
+ } : void 0,
416
+ // messages in xai format
417
+ messages,
418
+ // tools in xai format
419
+ tools: xaiTools,
420
+ tool_choice: xaiToolChoice
421
+ };
422
+ return {
423
+ args: baseArgs,
424
+ warnings
425
+ };
426
+ }
427
+ async doGenerate(options) {
428
+ var _a15, _b, _c;
429
+ const { args: body, warnings } = await this.getArgs(options);
430
+ const {
431
+ responseHeaders,
432
+ value: response,
433
+ rawValue: rawResponse
434
+ } = await providerUtils.postJsonToApi({
435
+ url: `${(_a15 = this.config.baseURL) != null ? _a15 : "https://api.x.ai/v1"}/chat/completions`,
436
+ headers: providerUtils.combineHeaders(this.config.headers(), options.headers),
437
+ body,
438
+ failedResponseHandler: xaiFailedResponseHandler,
439
+ successfulResponseHandler: providerUtils.createJsonResponseHandler(
440
+ xaiChatResponseSchema
441
+ ),
442
+ abortSignal: options.abortSignal,
443
+ fetch: this.config.fetch
444
+ });
445
+ const choice = response.choices[0];
446
+ const content = [];
447
+ if (choice.message.content != null && choice.message.content.length > 0) {
448
+ let text = choice.message.content;
449
+ const lastMessage = body.messages[body.messages.length - 1];
450
+ if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
451
+ text = "";
452
+ }
453
+ if (text.length > 0) {
454
+ content.push({ type: "text", text });
455
+ }
456
+ }
457
+ if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
458
+ content.push({
459
+ type: "reasoning",
460
+ text: choice.message.reasoning_content
461
+ });
462
+ }
463
+ if (choice.message.tool_calls != null) {
464
+ for (const toolCall of choice.message.tool_calls) {
465
+ content.push({
466
+ type: "tool-call",
467
+ toolCallId: toolCall.id,
468
+ toolName: toolCall.function.name,
469
+ input: toolCall.function.arguments
470
+ });
471
+ }
472
+ }
473
+ if (response.citations != null) {
474
+ for (const url of response.citations) {
475
+ content.push({
476
+ type: "source",
477
+ sourceType: "url",
478
+ id: this.config.generateId(),
479
+ url
480
+ });
481
+ }
482
+ }
483
+ return {
484
+ content,
485
+ finishReason: mapXaiFinishReason(choice.finish_reason),
486
+ usage: {
487
+ inputTokens: response.usage.prompt_tokens,
488
+ outputTokens: response.usage.completion_tokens,
489
+ totalTokens: response.usage.total_tokens,
490
+ reasoningTokens: (_c = (_b = response.usage.completion_tokens_details) == null ? void 0 : _b.reasoning_tokens) != null ? _c : void 0
491
+ },
492
+ request: { body },
493
+ response: {
494
+ ...getResponseMetadata(response),
495
+ headers: responseHeaders,
496
+ body: rawResponse
497
+ },
498
+ warnings
499
+ };
500
+ }
501
+ async doStream(options) {
502
+ var _a15;
503
+ const { args, warnings } = await this.getArgs(options);
504
+ const body = {
505
+ ...args,
506
+ stream: true,
507
+ stream_options: {
508
+ include_usage: true
509
+ }
510
+ };
511
+ const { responseHeaders, value: response } = await providerUtils.postJsonToApi({
512
+ url: `${(_a15 = this.config.baseURL) != null ? _a15 : "https://api.x.ai/v1"}/chat/completions`,
513
+ headers: providerUtils.combineHeaders(this.config.headers(), options.headers),
514
+ body,
515
+ failedResponseHandler: xaiFailedResponseHandler,
516
+ successfulResponseHandler: providerUtils.createEventSourceResponseHandler(xaiChatChunkSchema),
517
+ abortSignal: options.abortSignal,
518
+ fetch: this.config.fetch
519
+ });
520
+ let finishReason = "unknown";
521
+ const usage = {
522
+ inputTokens: void 0,
523
+ outputTokens: void 0,
524
+ totalTokens: void 0
525
+ };
526
+ let isFirstChunk = true;
527
+ const contentBlocks = {};
528
+ const lastReasoningDeltas = {};
529
+ const self = this;
530
+ return {
531
+ stream: response.pipeThrough(
532
+ new TransformStream({
533
+ start(controller) {
534
+ controller.enqueue({ type: "stream-start", warnings });
535
+ },
536
+ transform(chunk, controller) {
537
+ var _a22, _b;
538
+ if (options.includeRawChunks) {
539
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
540
+ }
541
+ if (!chunk.success) {
542
+ controller.enqueue({ type: "error", error: chunk.error });
543
+ return;
544
+ }
545
+ const value = chunk.value;
546
+ if (isFirstChunk) {
547
+ controller.enqueue({
548
+ type: "response-metadata",
549
+ ...getResponseMetadata(value)
550
+ });
551
+ isFirstChunk = false;
552
+ }
553
+ if (value.citations != null) {
554
+ for (const url of value.citations) {
555
+ controller.enqueue({
556
+ type: "source",
557
+ sourceType: "url",
558
+ id: self.config.generateId(),
559
+ url
560
+ });
561
+ }
562
+ }
563
+ if (value.usage != null) {
564
+ usage.inputTokens = value.usage.prompt_tokens;
565
+ usage.outputTokens = value.usage.completion_tokens;
566
+ usage.totalTokens = value.usage.total_tokens;
567
+ usage.reasoningTokens = (_b = (_a22 = value.usage.completion_tokens_details) == null ? void 0 : _a22.reasoning_tokens) != null ? _b : void 0;
568
+ }
569
+ const choice = value.choices[0];
570
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
571
+ finishReason = mapXaiFinishReason(choice.finish_reason);
572
+ }
573
+ if ((choice == null ? void 0 : choice.delta) == null) {
574
+ return;
575
+ }
576
+ const delta = choice.delta;
577
+ const choiceIndex = choice.index;
578
+ if (delta.content != null && delta.content.length > 0) {
579
+ const textContent = delta.content;
580
+ const lastMessage = body.messages[body.messages.length - 1];
581
+ if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
582
+ return;
583
+ }
584
+ const blockId = `text-${value.id || choiceIndex}`;
585
+ if (contentBlocks[blockId] == null) {
586
+ contentBlocks[blockId] = { type: "text" };
587
+ controller.enqueue({
588
+ type: "text-start",
589
+ id: blockId
590
+ });
591
+ }
592
+ controller.enqueue({
593
+ type: "text-delta",
594
+ id: blockId,
595
+ delta: textContent
596
+ });
597
+ }
598
+ if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
599
+ const blockId = `reasoning-${value.id || choiceIndex}`;
600
+ if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
601
+ return;
602
+ }
603
+ lastReasoningDeltas[blockId] = delta.reasoning_content;
604
+ if (contentBlocks[blockId] == null) {
605
+ contentBlocks[blockId] = { type: "reasoning" };
606
+ controller.enqueue({
607
+ type: "reasoning-start",
608
+ id: blockId
609
+ });
610
+ }
611
+ controller.enqueue({
612
+ type: "reasoning-delta",
613
+ id: blockId,
614
+ delta: delta.reasoning_content
615
+ });
616
+ }
617
+ if (delta.tool_calls != null) {
618
+ for (const toolCall of delta.tool_calls) {
619
+ const toolCallId = toolCall.id;
620
+ controller.enqueue({
621
+ type: "tool-input-start",
622
+ id: toolCallId,
623
+ toolName: toolCall.function.name
624
+ });
625
+ controller.enqueue({
626
+ type: "tool-input-delta",
627
+ id: toolCallId,
628
+ delta: toolCall.function.arguments
629
+ });
630
+ controller.enqueue({
631
+ type: "tool-input-end",
632
+ id: toolCallId
633
+ });
634
+ controller.enqueue({
635
+ type: "tool-call",
636
+ toolCallId,
637
+ toolName: toolCall.function.name,
638
+ input: toolCall.function.arguments
639
+ });
640
+ }
641
+ }
642
+ },
643
+ flush(controller) {
644
+ for (const [blockId, block] of Object.entries(contentBlocks)) {
645
+ controller.enqueue({
646
+ type: block.type === "text" ? "text-end" : "reasoning-end",
647
+ id: blockId
648
+ });
649
+ }
650
+ controller.enqueue({ type: "finish", finishReason, usage });
651
+ }
652
+ })
653
+ ),
654
+ request: { body },
655
+ response: { headers: responseHeaders }
656
+ };
657
+ }
658
+ };
659
+ var xaiUsageSchema = z3__namespace.object({
660
+ prompt_tokens: z3__namespace.number(),
661
+ completion_tokens: z3__namespace.number(),
662
+ total_tokens: z3__namespace.number(),
663
+ completion_tokens_details: z3__namespace.object({
664
+ reasoning_tokens: z3__namespace.number().nullish()
665
+ }).nullish()
666
+ });
667
+ var xaiChatResponseSchema = z3__namespace.object({
668
+ id: z3__namespace.string().nullish(),
669
+ created: z3__namespace.number().nullish(),
670
+ model: z3__namespace.string().nullish(),
671
+ choices: z3__namespace.array(
672
+ z3__namespace.object({
673
+ message: z3__namespace.object({
674
+ role: z3__namespace.literal("assistant"),
675
+ content: z3__namespace.string().nullish(),
676
+ reasoning_content: z3__namespace.string().nullish(),
677
+ tool_calls: z3__namespace.array(
678
+ z3__namespace.object({
679
+ id: z3__namespace.string(),
680
+ type: z3__namespace.literal("function"),
681
+ function: z3__namespace.object({
682
+ name: z3__namespace.string(),
683
+ arguments: z3__namespace.string()
684
+ })
685
+ })
686
+ ).nullish()
687
+ }),
688
+ index: z3__namespace.number(),
689
+ finish_reason: z3__namespace.string().nullish()
690
+ })
691
+ ),
692
+ object: z3__namespace.literal("chat.completion"),
693
+ usage: xaiUsageSchema,
694
+ citations: z3__namespace.array(z3__namespace.string().url()).nullish()
695
+ });
696
+ var xaiChatChunkSchema = z3__namespace.object({
697
+ id: z3__namespace.string().nullish(),
698
+ created: z3__namespace.number().nullish(),
699
+ model: z3__namespace.string().nullish(),
700
+ choices: z3__namespace.array(
701
+ z3__namespace.object({
702
+ delta: z3__namespace.object({
703
+ role: z3__namespace.enum(["assistant"]).optional(),
704
+ content: z3__namespace.string().nullish(),
705
+ reasoning_content: z3__namespace.string().nullish(),
706
+ tool_calls: z3__namespace.array(
707
+ z3__namespace.object({
708
+ id: z3__namespace.string(),
709
+ type: z3__namespace.literal("function"),
710
+ function: z3__namespace.object({
711
+ name: z3__namespace.string(),
712
+ arguments: z3__namespace.string()
713
+ })
714
+ })
715
+ ).nullish()
716
+ }),
717
+ finish_reason: z3__namespace.string().nullish(),
718
+ index: z3__namespace.number()
719
+ })
720
+ ),
721
+ usage: xaiUsageSchema.nullish(),
722
+ citations: z3__namespace.array(z3__namespace.string().url()).nullish()
723
+ });
724
+ var VERSION = "2.0.24" ;
725
+ var xaiErrorStructure = {
726
+ errorSchema: xaiErrorDataSchema,
727
+ errorToMessage: (data) => data.error.message
728
+ };
729
+ function createXai(options = {}) {
730
+ var _a15;
731
+ const baseURL = providerUtils.withoutTrailingSlash(
732
+ (_a15 = options.baseURL) != null ? _a15 : "https://api.x.ai/v1"
733
+ );
734
+ const getHeaders = () => providerUtils.withUserAgentSuffix(
735
+ {
736
+ Authorization: `Bearer ${providerUtils.loadApiKey({
737
+ apiKey: options.apiKey,
738
+ environmentVariableName: "XAI_API_KEY",
739
+ description: "xAI API key"
740
+ })}`,
741
+ ...options.headers
742
+ },
743
+ `ai-sdk/xai/${VERSION}`
744
+ );
745
+ const createLanguageModel = (modelId) => {
746
+ return new XaiChatLanguageModel(modelId, {
747
+ provider: "xai.chat",
748
+ baseURL,
749
+ headers: getHeaders,
750
+ generateId: providerUtils.generateId,
751
+ fetch: options.fetch
752
+ });
753
+ };
754
+ const createImageModel = (modelId) => {
755
+ return new chunk3ZEJSGTJ_cjs.OpenAICompatibleImageModel(modelId, {
756
+ provider: "xai.image",
757
+ url: ({ path }) => `${baseURL}${path}`,
758
+ headers: getHeaders,
759
+ fetch: options.fetch,
760
+ errorStructure: xaiErrorStructure
761
+ });
762
+ };
763
+ const provider$1 = (modelId) => createLanguageModel(modelId);
764
+ provider$1.languageModel = createLanguageModel;
765
+ provider$1.chat = createLanguageModel;
766
+ provider$1.textEmbeddingModel = (modelId) => {
767
+ throw new provider.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
768
+ };
769
+ provider$1.imageModel = createImageModel;
770
+ provider$1.image = createImageModel;
771
+ return provider$1;
772
+ }
773
+ createXai();
774
+ var __defProp = Object.defineProperty;
775
+ var __defProps = Object.defineProperties;
776
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
777
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
778
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
779
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
780
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
781
+ var __spreadValues = (a, b) => {
782
+ for (var prop in b || (b = {}))
783
+ if (__hasOwnProp.call(b, prop))
784
+ __defNormalProp(a, prop, b[prop]);
785
+ if (__getOwnPropSymbols)
786
+ for (var prop of __getOwnPropSymbols(b)) {
787
+ if (__propIsEnum.call(b, prop))
788
+ __defNormalProp(a, prop, b[prop]);
789
+ }
790
+ return a;
791
+ };
792
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
793
+ var marker = "vercel.ai.error";
794
+ var symbol = Symbol.for(marker);
795
+ var _a;
796
+ var _AISDKError = class _AISDKError2 extends Error {
797
+ /**
798
+ * Creates an AI SDK Error.
799
+ *
800
+ * @param {Object} params - The parameters for creating the error.
801
+ * @param {string} params.name - The name of the error.
802
+ * @param {string} params.message - The error message.
803
+ * @param {unknown} [params.cause] - The underlying cause of the error.
804
+ */
805
+ constructor({
806
+ name: name14,
807
+ message,
808
+ cause
809
+ }) {
810
+ super(message);
811
+ this[_a] = true;
812
+ this.name = name14;
813
+ this.cause = cause;
814
+ }
815
+ /**
816
+ * Checks if the given error is an AI SDK Error.
817
+ * @param {unknown} error - The error to check.
818
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
819
+ */
820
+ static isInstance(error) {
821
+ return _AISDKError2.hasMarker(error, marker);
822
+ }
823
+ static hasMarker(error, marker15) {
824
+ const markerSymbol = Symbol.for(marker15);
825
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
826
+ }
827
+ };
828
+ _a = symbol;
829
+ var AISDKError = _AISDKError;
830
+ var name = "AI_APICallError";
831
+ var marker2 = `vercel.ai.error.${name}`;
832
+ var symbol2 = Symbol.for(marker2);
833
+ var _a2;
834
+ var APICallError = class extends AISDKError {
835
+ constructor({
836
+ message,
837
+ url,
838
+ requestBodyValues,
839
+ statusCode,
840
+ responseHeaders,
841
+ responseBody,
842
+ cause,
843
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
844
+ statusCode === 409 || // conflict
845
+ statusCode === 429 || // too many requests
846
+ statusCode >= 500),
847
+ // server error
848
+ data
849
+ }) {
850
+ super({ name, message, cause });
851
+ this[_a2] = true;
852
+ this.url = url;
853
+ this.requestBodyValues = requestBodyValues;
854
+ this.statusCode = statusCode;
855
+ this.responseHeaders = responseHeaders;
856
+ this.responseBody = responseBody;
857
+ this.isRetryable = isRetryable;
858
+ this.data = data;
859
+ }
860
+ static isInstance(error) {
861
+ return AISDKError.hasMarker(error, marker2);
862
+ }
863
+ };
864
+ _a2 = symbol2;
865
+ var name2 = "AI_EmptyResponseBodyError";
866
+ var marker3 = `vercel.ai.error.${name2}`;
867
+ var symbol3 = Symbol.for(marker3);
868
+ var _a3;
869
+ var EmptyResponseBodyError = class extends AISDKError {
870
+ // used in isInstance
871
+ constructor({ message = "Empty response body" } = {}) {
872
+ super({ name: name2, message });
873
+ this[_a3] = true;
874
+ }
875
+ static isInstance(error) {
876
+ return AISDKError.hasMarker(error, marker3);
877
+ }
878
+ };
879
+ _a3 = symbol3;
880
+ function getErrorMessage(error) {
881
+ if (error == null) {
882
+ return "unknown error";
883
+ }
884
+ if (typeof error === "string") {
885
+ return error;
886
+ }
887
+ if (error instanceof Error) {
888
+ return error.message;
889
+ }
890
+ return JSON.stringify(error);
891
+ }
892
+ var name3 = "AI_InvalidArgumentError";
893
+ var marker4 = `vercel.ai.error.${name3}`;
894
+ var symbol4 = Symbol.for(marker4);
895
+ var _a4;
896
+ var InvalidArgumentError = class extends AISDKError {
897
+ constructor({
898
+ message,
899
+ cause,
900
+ argument
901
+ }) {
902
+ super({ name: name3, message, cause });
903
+ this[_a4] = true;
904
+ this.argument = argument;
905
+ }
906
+ static isInstance(error) {
907
+ return AISDKError.hasMarker(error, marker4);
908
+ }
909
+ };
910
+ _a4 = symbol4;
911
+ var name4 = "AI_InvalidPromptError";
912
+ var marker5 = `vercel.ai.error.${name4}`;
913
+ var symbol5 = Symbol.for(marker5);
914
+ var _a5;
915
+ var InvalidPromptError = class extends AISDKError {
916
+ constructor({
917
+ prompt,
918
+ message,
919
+ cause
920
+ }) {
921
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
922
+ this[_a5] = true;
923
+ this.prompt = prompt;
924
+ }
925
+ static isInstance(error) {
926
+ return AISDKError.hasMarker(error, marker5);
927
+ }
928
+ };
929
+ _a5 = symbol5;
930
+ var name5 = "AI_InvalidResponseDataError";
931
+ var marker6 = `vercel.ai.error.${name5}`;
932
+ var symbol6 = Symbol.for(marker6);
933
+ var _a6;
934
+ var InvalidResponseDataError = class extends AISDKError {
935
+ constructor({
936
+ data,
937
+ message = `Invalid response data: ${JSON.stringify(data)}.`
938
+ }) {
939
+ super({ name: name5, message });
940
+ this[_a6] = true;
941
+ this.data = data;
942
+ }
943
+ static isInstance(error) {
944
+ return AISDKError.hasMarker(error, marker6);
945
+ }
946
+ };
947
+ _a6 = symbol6;
948
+ var name6 = "AI_JSONParseError";
949
+ var marker7 = `vercel.ai.error.${name6}`;
950
+ var symbol7 = Symbol.for(marker7);
951
+ var _a7;
952
+ var JSONParseError = class extends AISDKError {
953
+ constructor({ text, cause }) {
954
+ super({
955
+ name: name6,
956
+ message: `JSON parsing failed: Text: ${text}.
957
+ Error message: ${getErrorMessage(cause)}`,
958
+ cause
959
+ });
960
+ this[_a7] = true;
961
+ this.text = text;
962
+ }
963
+ static isInstance(error) {
964
+ return AISDKError.hasMarker(error, marker7);
965
+ }
966
+ };
967
+ _a7 = symbol7;
968
+ var name7 = "AI_LoadAPIKeyError";
969
+ var marker8 = `vercel.ai.error.${name7}`;
970
+ var symbol8 = Symbol.for(marker8);
971
+ var _a8;
972
+ var LoadAPIKeyError = class extends AISDKError {
973
+ // used in isInstance
974
+ constructor({ message }) {
975
+ super({ name: name7, message });
976
+ this[_a8] = true;
977
+ }
978
+ static isInstance(error) {
979
+ return AISDKError.hasMarker(error, marker8);
980
+ }
981
+ };
982
+ _a8 = symbol8;
983
+ var name12 = "AI_TypeValidationError";
984
+ var marker13 = `vercel.ai.error.${name12}`;
985
+ var symbol13 = Symbol.for(marker13);
986
+ var _a13;
987
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
988
+ constructor({ value, cause }) {
989
+ super({
990
+ name: name12,
991
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
992
+ Error message: ${getErrorMessage(cause)}`,
993
+ cause
994
+ });
995
+ this[_a13] = true;
996
+ this.value = value;
997
+ }
998
+ static isInstance(error) {
999
+ return AISDKError.hasMarker(error, marker13);
1000
+ }
1001
+ /**
1002
+ * Wraps an error into a TypeValidationError.
1003
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
1004
+ * Otherwise, it creates a new TypeValidationError.
1005
+ *
1006
+ * @param {Object} params - The parameters for wrapping the error.
1007
+ * @param {unknown} params.value - The value that failed validation.
1008
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
1009
+ * @returns {TypeValidationError} A TypeValidationError instance.
1010
+ */
1011
+ static wrap({
1012
+ value,
1013
+ cause
1014
+ }) {
1015
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
1016
+ }
1017
+ };
1018
+ _a13 = symbol13;
1019
+ var TypeValidationError = _TypeValidationError;
1020
+ var name13 = "AI_UnsupportedFunctionalityError";
1021
+ var marker14 = `vercel.ai.error.${name13}`;
1022
+ var symbol14 = Symbol.for(marker14);
1023
+ var _a14;
1024
+ var UnsupportedFunctionalityError3 = class extends AISDKError {
1025
+ constructor({
1026
+ functionality,
1027
+ message = `'${functionality}' functionality not supported.`
1028
+ }) {
1029
+ super({ name: name13, message });
1030
+ this[_a14] = true;
1031
+ this.functionality = functionality;
1032
+ }
1033
+ static isInstance(error) {
1034
+ return AISDKError.hasMarker(error, marker14);
1035
+ }
1036
+ };
1037
+ _a14 = symbol14;
1038
+ var ParseError = class extends Error {
1039
+ constructor(message, options) {
1040
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
1041
+ }
1042
+ };
1043
+ function noop(_arg) {
1044
+ }
1045
+ function createParser(callbacks) {
1046
+ if (typeof callbacks == "function")
1047
+ throw new TypeError(
1048
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
1049
+ );
1050
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
1051
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
1052
+ function feed(newChunk) {
1053
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
1054
+ for (const line of complete)
1055
+ parseLine(line);
1056
+ incompleteLine = incomplete, isFirstChunk = false;
1057
+ }
1058
+ function parseLine(line) {
1059
+ if (line === "") {
1060
+ dispatchEvent();
1061
+ return;
1062
+ }
1063
+ if (line.startsWith(":")) {
1064
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
1065
+ return;
1066
+ }
1067
+ const fieldSeparatorIndex = line.indexOf(":");
1068
+ if (fieldSeparatorIndex !== -1) {
1069
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
1070
+ processField(field, value, line);
1071
+ return;
1072
+ }
1073
+ processField(line, "", line);
1074
+ }
1075
+ function processField(field, value, line) {
1076
+ switch (field) {
1077
+ case "event":
1078
+ eventType = value;
1079
+ break;
1080
+ case "data":
1081
+ data = `${data}${value}
1082
+ `;
1083
+ break;
1084
+ case "id":
1085
+ id = value.includes("\0") ? void 0 : value;
1086
+ break;
1087
+ case "retry":
1088
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
1089
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
1090
+ type: "invalid-retry",
1091
+ value,
1092
+ line
1093
+ })
1094
+ );
1095
+ break;
1096
+ default:
1097
+ onError(
1098
+ new ParseError(
1099
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
1100
+ { type: "unknown-field", field, value, line }
1101
+ )
1102
+ );
1103
+ break;
1104
+ }
1105
+ }
1106
+ function dispatchEvent() {
1107
+ data.length > 0 && onEvent({
1108
+ id,
1109
+ event: eventType || void 0,
1110
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
1111
+ // then remove the last character from the data buffer.
1112
+ data: data.endsWith(`
1113
+ `) ? data.slice(0, -1) : data
1114
+ }), id = void 0, data = "", eventType = "";
1115
+ }
1116
+ function reset(options = {}) {
1117
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
1118
+ }
1119
+ return { feed, reset };
1120
+ }
1121
+ function splitLines(chunk) {
1122
+ const lines = [];
1123
+ let incompleteLine = "", searchIndex = 0;
1124
+ for (; searchIndex < chunk.length; ) {
1125
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
1126
+ `, searchIndex);
1127
+ let lineEnd = -1;
1128
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
1129
+ incompleteLine = chunk.slice(searchIndex);
1130
+ break;
1131
+ } else {
1132
+ const line = chunk.slice(searchIndex, lineEnd);
1133
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
1134
+ ` && searchIndex++;
1135
+ }
1136
+ }
1137
+ return [lines, incompleteLine];
1138
+ }
1139
+ var EventSourceParserStream = class extends TransformStream {
1140
+ constructor({ onError, onRetry, onComment } = {}) {
1141
+ let parser;
1142
+ super({
1143
+ start(controller) {
1144
+ parser = createParser({
1145
+ onEvent: (event) => {
1146
+ controller.enqueue(event);
1147
+ },
1148
+ onError(error) {
1149
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
1150
+ },
1151
+ onRetry,
1152
+ onComment
1153
+ });
1154
+ },
1155
+ transform(chunk) {
1156
+ parser.feed(chunk);
1157
+ }
1158
+ });
1159
+ }
1160
+ };
1161
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
1162
+ function combineHeaders2(...headers) {
1163
+ return headers.reduce(
1164
+ (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
1165
+ {}
1166
+ );
1167
+ }
1168
+ function extractResponseHeaders(response) {
1169
+ return Object.fromEntries([...response.headers]);
1170
+ }
1171
+ var createIdGenerator = ({
1172
+ prefix,
1173
+ size = 16,
1174
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
1175
+ separator = "-"
1176
+ } = {}) => {
1177
+ const generator = () => {
1178
+ const alphabetLength = alphabet.length;
1179
+ const chars = new Array(size);
1180
+ for (let i = 0; i < size; i++) {
1181
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
1182
+ }
1183
+ return chars.join("");
1184
+ };
1185
+ if (prefix == null) {
1186
+ return generator;
1187
+ }
1188
+ if (alphabet.includes(separator)) {
1189
+ throw new InvalidArgumentError({
1190
+ argument: "separator",
1191
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
1192
+ });
1193
+ }
1194
+ return () => `${prefix}${separator}${generator()}`;
1195
+ };
1196
+ var generateId2 = createIdGenerator();
1197
+ function isAbortError(error) {
1198
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
1199
+ error.name === "TimeoutError");
1200
+ }
1201
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
1202
+ function handleFetchError({
1203
+ error,
1204
+ url,
1205
+ requestBodyValues
1206
+ }) {
1207
+ if (isAbortError(error)) {
1208
+ return error;
1209
+ }
1210
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
1211
+ const cause = error.cause;
1212
+ if (cause != null) {
1213
+ return new APICallError({
1214
+ message: `Cannot connect to API: ${cause.message}`,
1215
+ cause,
1216
+ url,
1217
+ requestBodyValues,
1218
+ isRetryable: true
1219
+ // retry when network error
1220
+ });
1221
+ }
1222
+ }
1223
+ return error;
1224
+ }
1225
+ function removeUndefinedEntries(record) {
1226
+ return Object.fromEntries(
1227
+ Object.entries(record).filter(([_key, value]) => value != null)
1228
+ );
1229
+ }
1230
+ function loadApiKey2({
1231
+ apiKey,
1232
+ environmentVariableName,
1233
+ apiKeyParameterName = "apiKey",
1234
+ description
1235
+ }) {
1236
+ if (typeof apiKey === "string") {
1237
+ return apiKey;
1238
+ }
1239
+ if (apiKey != null) {
1240
+ throw new LoadAPIKeyError({
1241
+ message: `${description} API key must be a string.`
1242
+ });
1243
+ }
1244
+ if (typeof process === "undefined") {
1245
+ throw new LoadAPIKeyError({
1246
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
1247
+ });
1248
+ }
1249
+ apiKey = process.env[environmentVariableName];
1250
+ if (apiKey == null) {
1251
+ throw new LoadAPIKeyError({
1252
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
1253
+ });
1254
+ }
1255
+ if (typeof apiKey !== "string") {
1256
+ throw new LoadAPIKeyError({
1257
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
1258
+ });
1259
+ }
1260
+ return apiKey;
1261
+ }
1262
+ var suspectProtoRx = /"__proto__"\s*:/;
1263
+ var suspectConstructorRx = /"constructor"\s*:/;
1264
+ function _parse(text) {
1265
+ const obj = JSON.parse(text);
1266
+ if (obj === null || typeof obj !== "object") {
1267
+ return obj;
1268
+ }
1269
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
1270
+ return obj;
1271
+ }
1272
+ return filter(obj);
1273
+ }
1274
+ function filter(obj) {
1275
+ let next = [obj];
1276
+ while (next.length) {
1277
+ const nodes = next;
1278
+ next = [];
1279
+ for (const node of nodes) {
1280
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
1281
+ throw new SyntaxError("Object contains forbidden prototype property");
1282
+ }
1283
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
1284
+ throw new SyntaxError("Object contains forbidden prototype property");
1285
+ }
1286
+ for (const key in node) {
1287
+ const value = node[key];
1288
+ if (value && typeof value === "object") {
1289
+ next.push(value);
1290
+ }
1291
+ }
1292
+ }
1293
+ }
1294
+ return obj;
1295
+ }
1296
+ function secureJsonParse(text) {
1297
+ const { stackTraceLimit } = Error;
1298
+ Error.stackTraceLimit = 0;
1299
+ try {
1300
+ return _parse(text);
1301
+ } finally {
1302
+ Error.stackTraceLimit = stackTraceLimit;
1303
+ }
1304
+ }
1305
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
1306
+ function validator(validate) {
1307
+ return { [validatorSymbol]: true, validate };
1308
+ }
1309
+ function isValidator(value) {
1310
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
1311
+ }
1312
+ function asValidator(value) {
1313
+ return isValidator(value) ? value : standardSchemaValidator(value);
1314
+ }
1315
+ function standardSchemaValidator(standardSchema) {
1316
+ return validator(async (value) => {
1317
+ const result = await standardSchema["~standard"].validate(value);
1318
+ return result.issues == null ? { success: true, value: result.value } : {
1319
+ success: false,
1320
+ error: new TypeValidationError({
1321
+ value,
1322
+ cause: result.issues
1323
+ })
1324
+ };
1325
+ });
1326
+ }
1327
+ async function validateTypes({
1328
+ value,
1329
+ schema
1330
+ }) {
1331
+ const result = await safeValidateTypes({ value, schema });
1332
+ if (!result.success) {
1333
+ throw TypeValidationError.wrap({ value, cause: result.error });
1334
+ }
1335
+ return result.value;
1336
+ }
1337
+ async function safeValidateTypes({
1338
+ value,
1339
+ schema
1340
+ }) {
1341
+ const validator2 = asValidator(schema);
1342
+ try {
1343
+ if (validator2.validate == null) {
1344
+ return { success: true, value, rawValue: value };
1345
+ }
1346
+ const result = await validator2.validate(value);
1347
+ if (result.success) {
1348
+ return { success: true, value: result.value, rawValue: value };
1349
+ }
1350
+ return {
1351
+ success: false,
1352
+ error: TypeValidationError.wrap({ value, cause: result.error }),
1353
+ rawValue: value
1354
+ };
1355
+ } catch (error) {
1356
+ return {
1357
+ success: false,
1358
+ error: TypeValidationError.wrap({ value, cause: error }),
1359
+ rawValue: value
1360
+ };
1361
+ }
1362
+ }
1363
+ async function parseJSON({
1364
+ text,
1365
+ schema
1366
+ }) {
1367
+ try {
1368
+ const value = secureJsonParse(text);
1369
+ if (schema == null) {
1370
+ return value;
1371
+ }
1372
+ return validateTypes({ value, schema });
1373
+ } catch (error) {
1374
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
1375
+ throw error;
1376
+ }
1377
+ throw new JSONParseError({ text, cause: error });
1378
+ }
1379
+ }
1380
+ async function safeParseJSON({
1381
+ text,
1382
+ schema
1383
+ }) {
1384
+ try {
1385
+ const value = secureJsonParse(text);
1386
+ if (schema == null) {
1387
+ return { success: true, value, rawValue: value };
1388
+ }
1389
+ return await safeValidateTypes({ value, schema });
1390
+ } catch (error) {
1391
+ return {
1392
+ success: false,
1393
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
1394
+ rawValue: void 0
1395
+ };
1396
+ }
1397
+ }
1398
+ function isParsableJson(input) {
1399
+ try {
1400
+ secureJsonParse(input);
1401
+ return true;
1402
+ } catch (e) {
1403
+ return false;
1404
+ }
1405
+ }
1406
+ function parseJsonEventStream({
1407
+ stream,
1408
+ schema
1409
+ }) {
1410
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
1411
+ new TransformStream({
1412
+ async transform({ data }, controller) {
1413
+ if (data === "[DONE]") {
1414
+ return;
1415
+ }
1416
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
1417
+ }
1418
+ })
1419
+ );
1420
+ }
1421
+ var getOriginalFetch2 = () => globalThis.fetch;
1422
+ var postJsonToApi2 = async ({
1423
+ url,
1424
+ headers,
1425
+ body,
1426
+ failedResponseHandler,
1427
+ successfulResponseHandler,
1428
+ abortSignal,
1429
+ fetch: fetch2
1430
+ }) => postToApi({
1431
+ url,
1432
+ headers: __spreadValues({
1433
+ "Content-Type": "application/json"
1434
+ }, headers),
1435
+ body: {
1436
+ content: JSON.stringify(body),
1437
+ values: body
1438
+ },
1439
+ failedResponseHandler,
1440
+ successfulResponseHandler,
1441
+ abortSignal,
1442
+ fetch: fetch2
1443
+ });
1444
+ var postToApi = async ({
1445
+ url,
1446
+ headers = {},
1447
+ body,
1448
+ successfulResponseHandler,
1449
+ failedResponseHandler,
1450
+ abortSignal,
1451
+ fetch: fetch2 = getOriginalFetch2()
1452
+ }) => {
1453
+ try {
1454
+ const response = await fetch2(url, {
1455
+ method: "POST",
1456
+ headers: removeUndefinedEntries(headers),
1457
+ body: body.content,
1458
+ signal: abortSignal
1459
+ });
1460
+ const responseHeaders = extractResponseHeaders(response);
1461
+ if (!response.ok) {
1462
+ let errorInformation;
1463
+ try {
1464
+ errorInformation = await failedResponseHandler({
1465
+ response,
1466
+ url,
1467
+ requestBodyValues: body.values
1468
+ });
1469
+ } catch (error) {
1470
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1471
+ throw error;
1472
+ }
1473
+ throw new APICallError({
1474
+ message: "Failed to process error response",
1475
+ cause: error,
1476
+ statusCode: response.status,
1477
+ url,
1478
+ responseHeaders,
1479
+ requestBodyValues: body.values
1480
+ });
1481
+ }
1482
+ throw errorInformation.value;
1483
+ }
1484
+ try {
1485
+ return await successfulResponseHandler({
1486
+ response,
1487
+ url,
1488
+ requestBodyValues: body.values
1489
+ });
1490
+ } catch (error) {
1491
+ if (error instanceof Error) {
1492
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1493
+ throw error;
1494
+ }
1495
+ }
1496
+ throw new APICallError({
1497
+ message: "Failed to process successful response",
1498
+ cause: error,
1499
+ statusCode: response.status,
1500
+ url,
1501
+ responseHeaders,
1502
+ requestBodyValues: body.values
1503
+ });
1504
+ }
1505
+ } catch (error) {
1506
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
1507
+ }
1508
+ };
1509
+ var createJsonErrorResponseHandler2 = ({
1510
+ errorSchema,
1511
+ errorToMessage,
1512
+ isRetryable
1513
+ }) => async ({ response, url, requestBodyValues }) => {
1514
+ const responseBody = await response.text();
1515
+ const responseHeaders = extractResponseHeaders(response);
1516
+ if (responseBody.trim() === "") {
1517
+ return {
1518
+ responseHeaders,
1519
+ value: new APICallError({
1520
+ message: response.statusText,
1521
+ url,
1522
+ requestBodyValues,
1523
+ statusCode: response.status,
1524
+ responseHeaders,
1525
+ responseBody,
1526
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
1527
+ })
1528
+ };
1529
+ }
1530
+ try {
1531
+ const parsedError = await parseJSON({
1532
+ text: responseBody,
1533
+ schema: errorSchema
1534
+ });
1535
+ return {
1536
+ responseHeaders,
1537
+ value: new APICallError({
1538
+ message: errorToMessage(parsedError),
1539
+ url,
1540
+ requestBodyValues,
1541
+ statusCode: response.status,
1542
+ responseHeaders,
1543
+ responseBody,
1544
+ data: parsedError,
1545
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
1546
+ })
1547
+ };
1548
+ } catch (parseError) {
1549
+ return {
1550
+ responseHeaders,
1551
+ value: new APICallError({
1552
+ message: response.statusText,
1553
+ url,
1554
+ requestBodyValues,
1555
+ statusCode: response.status,
1556
+ responseHeaders,
1557
+ responseBody,
1558
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
1559
+ })
1560
+ };
1561
+ }
1562
+ };
1563
+ var createEventSourceResponseHandler2 = (chunkSchema) => async ({ response }) => {
1564
+ const responseHeaders = extractResponseHeaders(response);
1565
+ if (response.body == null) {
1566
+ throw new EmptyResponseBodyError({});
1567
+ }
1568
+ return {
1569
+ responseHeaders,
1570
+ value: parseJsonEventStream({
1571
+ stream: response.body,
1572
+ schema: chunkSchema
1573
+ })
1574
+ };
1575
+ };
1576
+ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
1577
+ const responseBody = await response.text();
1578
+ const parsedResult = await safeParseJSON({
1579
+ text: responseBody,
1580
+ schema: responseSchema
1581
+ });
1582
+ const responseHeaders = extractResponseHeaders(response);
1583
+ if (!parsedResult.success) {
1584
+ throw new APICallError({
1585
+ message: "Invalid JSON response",
1586
+ cause: parsedResult.error,
1587
+ statusCode: response.status,
1588
+ responseHeaders,
1589
+ responseBody,
1590
+ url,
1591
+ requestBodyValues
1592
+ });
1593
+ }
1594
+ return {
1595
+ responseHeaders,
1596
+ value: parsedResult.value,
1597
+ rawValue: parsedResult.rawValue
1598
+ };
1599
+ };
1600
+ var { btoa} = globalThis;
1601
+ function convertUint8ArrayToBase64(array3) {
1602
+ let latin1string = "";
1603
+ for (let i = 0; i < array3.length; i++) {
1604
+ latin1string += String.fromCodePoint(array3[i]);
1605
+ }
1606
+ return btoa(latin1string);
1607
+ }
1608
+ function withoutTrailingSlash2(url) {
1609
+ return url == null ? void 0 : url.replace(/\/$/, "");
1610
+ }
1611
+ var ReasoningDetailSummarySchema = z3.z.object({
1612
+ type: z3.z.literal(
1613
+ "reasoning.summary"
1614
+ /* Summary */
1615
+ ),
1616
+ summary: z3.z.string()
1617
+ });
1618
+ var ReasoningDetailEncryptedSchema = z3.z.object({
1619
+ type: z3.z.literal(
1620
+ "reasoning.encrypted"
1621
+ /* Encrypted */
1622
+ ),
1623
+ data: z3.z.string()
1624
+ });
1625
+ var ReasoningDetailTextSchema = z3.z.object({
1626
+ type: z3.z.literal(
1627
+ "reasoning.text"
1628
+ /* Text */
1629
+ ),
1630
+ text: z3.z.string().nullish(),
1631
+ signature: z3.z.string().nullish()
1632
+ });
1633
+ var ReasoningDetailUnionSchema = z3.z.union([
1634
+ ReasoningDetailSummarySchema,
1635
+ ReasoningDetailEncryptedSchema,
1636
+ ReasoningDetailTextSchema
1637
+ ]);
1638
+ var ReasoningDetailsWithUnknownSchema = z3.z.union([
1639
+ ReasoningDetailUnionSchema,
1640
+ z3.z.unknown().transform(() => null)
1641
+ ]);
1642
+ var ReasoningDetailArraySchema = z3.z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
1643
+ var OpenRouterErrorResponseSchema = z3.z.object({
1644
+ error: z3.z.object({
1645
+ code: z3.z.union([z3.z.string(), z3.z.number()]).nullable().optional().default(null),
1646
+ message: z3.z.string(),
1647
+ type: z3.z.string().nullable().optional().default(null),
1648
+ param: z3.z.any().nullable().optional().default(null)
1649
+ })
1650
+ });
1651
+ var openrouterFailedResponseHandler = createJsonErrorResponseHandler2({
1652
+ errorSchema: OpenRouterErrorResponseSchema,
1653
+ errorToMessage: (data) => data.error.message
1654
+ });
1655
+ function mapOpenRouterFinishReason(finishReason) {
1656
+ switch (finishReason) {
1657
+ case "stop":
1658
+ return "stop";
1659
+ case "length":
1660
+ return "length";
1661
+ case "content_filter":
1662
+ return "content-filter";
1663
+ case "function_call":
1664
+ case "tool_calls":
1665
+ return "tool-calls";
1666
+ default:
1667
+ return "unknown";
1668
+ }
1669
+ }
1670
+ function isUrl({
1671
+ url,
1672
+ protocols
1673
+ }) {
1674
+ try {
1675
+ const urlObj = new URL(url);
1676
+ return protocols.has(urlObj.protocol);
1677
+ } catch (_) {
1678
+ return false;
1679
+ }
1680
+ }
1681
+ function getFileUrl({
1682
+ part,
1683
+ defaultMediaType
1684
+ }) {
1685
+ var _a15, _b;
1686
+ if (part.data instanceof Uint8Array) {
1687
+ const base64 = convertUint8ArrayToBase64(part.data);
1688
+ return `data:${(_a15 = part.mediaType) != null ? _a15 : defaultMediaType};base64,${base64}`;
1689
+ }
1690
+ const stringUrl = part.data.toString();
1691
+ if (isUrl({
1692
+ url: stringUrl,
1693
+ protocols: /* @__PURE__ */ new Set(["http:", "https:"])
1694
+ })) {
1695
+ return stringUrl;
1696
+ }
1697
+ return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b = part.mediaType) != null ? _b : defaultMediaType};base64,${stringUrl}`;
1698
+ }
1699
+ function getMediaType(dataUrl, defaultMediaType) {
1700
+ var _a15;
1701
+ const match = dataUrl.match(/^data:([^;]+)/);
1702
+ return match ? (_a15 = match[1]) != null ? _a15 : defaultMediaType : defaultMediaType;
1703
+ }
1704
+ function getBase64FromDataUrl(dataUrl) {
1705
+ const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
1706
+ return match ? match[1] : dataUrl;
1707
+ }
1708
+ function getCacheControl(providerMetadata) {
1709
+ var _a15, _b, _c;
1710
+ const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
1711
+ const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
1712
+ return (_c = (_b = (_a15 = openrouter2 == null ? void 0 : openrouter2.cacheControl) != null ? _a15 : openrouter2 == null ? void 0 : openrouter2.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
1713
+ }
1714
+ function convertToOpenRouterChatMessages(prompt) {
1715
+ var _a15, _b, _c;
1716
+ const messages = [];
1717
+ for (const { role, content, providerOptions } of prompt) {
1718
+ switch (role) {
1719
+ case "system": {
1720
+ messages.push({
1721
+ role: "system",
1722
+ content,
1723
+ cache_control: getCacheControl(providerOptions)
1724
+ });
1725
+ break;
1726
+ }
1727
+ case "user": {
1728
+ if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
1729
+ const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
1730
+ const contentWithCacheControl = cacheControl ? [
1731
+ {
1732
+ type: "text",
1733
+ text: content[0].text,
1734
+ cache_control: cacheControl
1735
+ }
1736
+ ] : content[0].text;
1737
+ messages.push({
1738
+ role: "user",
1739
+ content: contentWithCacheControl
1740
+ });
1741
+ break;
1742
+ }
1743
+ const messageCacheControl = getCacheControl(providerOptions);
1744
+ const contentParts = content.map(
1745
+ (part) => {
1746
+ var _a16, _b2, _c2, _d, _e, _f;
1747
+ const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
1748
+ switch (part.type) {
1749
+ case "text":
1750
+ return {
1751
+ type: "text",
1752
+ text: part.text,
1753
+ // For text parts, only use part-specific cache control
1754
+ cache_control: cacheControl
1755
+ };
1756
+ case "file": {
1757
+ if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
1758
+ const url = getFileUrl({
1759
+ part,
1760
+ defaultMediaType: "image/jpeg"
1761
+ });
1762
+ return {
1763
+ type: "image_url",
1764
+ image_url: {
1765
+ url
1766
+ },
1767
+ // For image parts, use part-specific or message-level cache control
1768
+ cache_control: cacheControl
1769
+ };
1770
+ }
1771
+ const fileName = String(
1772
+ (_f = (_e = (_d = (_c2 = part.providerOptions) == null ? void 0 : _c2.openrouter) == null ? void 0 : _d.filename) != null ? _e : part.filename) != null ? _f : ""
1773
+ );
1774
+ const fileData = getFileUrl({
1775
+ part,
1776
+ defaultMediaType: "application/pdf"
1777
+ });
1778
+ if (isUrl({
1779
+ url: fileData,
1780
+ protocols: /* @__PURE__ */ new Set(["http:", "https:"])
1781
+ })) {
1782
+ return {
1783
+ type: "file",
1784
+ file: {
1785
+ filename: fileName,
1786
+ file_data: fileData
1787
+ }
1788
+ };
1789
+ }
1790
+ return {
1791
+ type: "file",
1792
+ file: {
1793
+ filename: fileName,
1794
+ file_data: fileData
1795
+ },
1796
+ cache_control: cacheControl
1797
+ };
1798
+ }
1799
+ default: {
1800
+ return {
1801
+ type: "text",
1802
+ text: "",
1803
+ cache_control: cacheControl
1804
+ };
1805
+ }
1806
+ }
1807
+ }
1808
+ );
1809
+ messages.push({
1810
+ role: "user",
1811
+ content: contentParts
1812
+ });
1813
+ break;
1814
+ }
1815
+ case "assistant": {
1816
+ let text = "";
1817
+ let reasoning = "";
1818
+ const reasoningDetails = [];
1819
+ const toolCalls = [];
1820
+ for (const part of content) {
1821
+ switch (part.type) {
1822
+ case "text": {
1823
+ text += part.text;
1824
+ break;
1825
+ }
1826
+ case "tool-call": {
1827
+ toolCalls.push({
1828
+ id: part.toolCallId,
1829
+ type: "function",
1830
+ function: {
1831
+ name: part.toolName,
1832
+ arguments: JSON.stringify(part.input)
1833
+ }
1834
+ });
1835
+ break;
1836
+ }
1837
+ case "reasoning": {
1838
+ reasoning += part.text;
1839
+ reasoningDetails.push({
1840
+ type: "reasoning.text",
1841
+ text: part.text
1842
+ });
1843
+ break;
1844
+ }
1845
+ }
1846
+ }
1847
+ messages.push({
1848
+ role: "assistant",
1849
+ content: text,
1850
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
1851
+ reasoning: reasoning || void 0,
1852
+ reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
1853
+ cache_control: getCacheControl(providerOptions)
1854
+ });
1855
+ break;
1856
+ }
1857
+ case "tool": {
1858
+ for (const toolResponse of content) {
1859
+ const content2 = getToolResultContent(toolResponse);
1860
+ messages.push({
1861
+ role: "tool",
1862
+ tool_call_id: toolResponse.toolCallId,
1863
+ content: content2,
1864
+ cache_control: (_c = getCacheControl(providerOptions)) != null ? _c : getCacheControl(toolResponse.providerOptions)
1865
+ });
1866
+ }
1867
+ break;
1868
+ }
1869
+ }
1870
+ }
1871
+ return messages;
1872
+ }
1873
+ function getToolResultContent(input) {
1874
+ return input.output.type === "text" ? input.output.value : JSON.stringify(input.output.value);
1875
+ }
1876
+ z3.z.union([
1877
+ z3.z.literal("auto"),
1878
+ z3.z.literal("none"),
1879
+ z3.z.literal("required"),
1880
+ z3.z.object({
1881
+ type: z3.z.literal("function"),
1882
+ function: z3.z.object({
1883
+ name: z3.z.string()
1884
+ })
1885
+ })
1886
+ ]);
1887
+ function getChatCompletionToolChoice(toolChoice) {
1888
+ switch (toolChoice.type) {
1889
+ case "auto":
1890
+ case "none":
1891
+ case "required":
1892
+ return toolChoice.type;
1893
+ case "tool": {
1894
+ return {
1895
+ type: "function",
1896
+ function: { name: toolChoice.toolName }
1897
+ };
1898
+ }
1899
+ default: {
1900
+ throw new Error(`Invalid tool choice type: ${toolChoice}`);
1901
+ }
1902
+ }
1903
+ }
1904
+ var ImageResponseSchema = z3.z.object({
1905
+ type: z3.z.literal("image_url"),
1906
+ image_url: z3.z.object({
1907
+ url: z3.z.string()
1908
+ })
1909
+ });
1910
+ var ImageResponseWithUnknownSchema = z3.z.union([
1911
+ ImageResponseSchema,
1912
+ z3.z.unknown().transform(() => null)
1913
+ ]);
1914
+ var ImageResponseArraySchema = z3.z.array(ImageResponseWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
1915
+ var OpenRouterChatCompletionBaseResponseSchema = z3.z.object({
1916
+ id: z3.z.string().optional(),
1917
+ model: z3.z.string().optional(),
1918
+ provider: z3.z.string().optional(),
1919
+ usage: z3.z.object({
1920
+ prompt_tokens: z3.z.number(),
1921
+ prompt_tokens_details: z3.z.object({
1922
+ cached_tokens: z3.z.number()
1923
+ }).nullish(),
1924
+ completion_tokens: z3.z.number(),
1925
+ completion_tokens_details: z3.z.object({
1926
+ reasoning_tokens: z3.z.number()
1927
+ }).nullish(),
1928
+ total_tokens: z3.z.number(),
1929
+ cost: z3.z.number().optional(),
1930
+ cost_details: z3.z.object({
1931
+ upstream_inference_cost: z3.z.number().nullish()
1932
+ }).nullish()
1933
+ }).nullish()
1934
+ });
1935
+ var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
1936
+ choices: z3.z.array(
1937
+ z3.z.object({
1938
+ message: z3.z.object({
1939
+ role: z3.z.literal("assistant"),
1940
+ content: z3.z.string().nullable().optional(),
1941
+ reasoning: z3.z.string().nullable().optional(),
1942
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
1943
+ images: ImageResponseArraySchema.nullish(),
1944
+ tool_calls: z3.z.array(
1945
+ z3.z.object({
1946
+ id: z3.z.string().optional().nullable(),
1947
+ type: z3.z.literal("function"),
1948
+ function: z3.z.object({
1949
+ name: z3.z.string(),
1950
+ arguments: z3.z.string()
1951
+ })
1952
+ })
1953
+ ).optional(),
1954
+ annotations: z3.z.array(
1955
+ z3.z.object({
1956
+ type: z3.z.enum(["url_citation"]),
1957
+ url_citation: z3.z.object({
1958
+ end_index: z3.z.number(),
1959
+ start_index: z3.z.number(),
1960
+ title: z3.z.string(),
1961
+ url: z3.z.string(),
1962
+ content: z3.z.string().optional()
1963
+ })
1964
+ })
1965
+ ).nullish()
1966
+ }),
1967
+ index: z3.z.number().nullish(),
1968
+ logprobs: z3.z.object({
1969
+ content: z3.z.array(
1970
+ z3.z.object({
1971
+ token: z3.z.string(),
1972
+ logprob: z3.z.number(),
1973
+ top_logprobs: z3.z.array(
1974
+ z3.z.object({
1975
+ token: z3.z.string(),
1976
+ logprob: z3.z.number()
1977
+ })
1978
+ )
1979
+ })
1980
+ ).nullable()
1981
+ }).nullable().optional(),
1982
+ finish_reason: z3.z.string().optional().nullable()
1983
+ })
1984
+ )
1985
+ });
1986
+ var OpenRouterStreamChatCompletionChunkSchema = z3.z.union([
1987
+ OpenRouterChatCompletionBaseResponseSchema.extend({
1988
+ choices: z3.z.array(
1989
+ z3.z.object({
1990
+ delta: z3.z.object({
1991
+ role: z3.z.enum(["assistant"]).optional(),
1992
+ content: z3.z.string().nullish(),
1993
+ reasoning: z3.z.string().nullish().optional(),
1994
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
1995
+ images: ImageResponseArraySchema.nullish(),
1996
+ tool_calls: z3.z.array(
1997
+ z3.z.object({
1998
+ index: z3.z.number().nullish(),
1999
+ id: z3.z.string().nullish(),
2000
+ type: z3.z.literal("function").optional(),
2001
+ function: z3.z.object({
2002
+ name: z3.z.string().nullish(),
2003
+ arguments: z3.z.string().nullish()
2004
+ })
2005
+ })
2006
+ ).nullish(),
2007
+ annotations: z3.z.array(
2008
+ z3.z.object({
2009
+ type: z3.z.enum(["url_citation"]),
2010
+ url_citation: z3.z.object({
2011
+ end_index: z3.z.number(),
2012
+ start_index: z3.z.number(),
2013
+ title: z3.z.string(),
2014
+ url: z3.z.string(),
2015
+ content: z3.z.string().optional()
2016
+ })
2017
+ })
2018
+ ).nullish()
2019
+ }).nullish(),
2020
+ logprobs: z3.z.object({
2021
+ content: z3.z.array(
2022
+ z3.z.object({
2023
+ token: z3.z.string(),
2024
+ logprob: z3.z.number(),
2025
+ top_logprobs: z3.z.array(
2026
+ z3.z.object({
2027
+ token: z3.z.string(),
2028
+ logprob: z3.z.number()
2029
+ })
2030
+ )
2031
+ })
2032
+ ).nullable()
2033
+ }).nullish(),
2034
+ finish_reason: z3.z.string().nullable().optional(),
2035
+ index: z3.z.number().nullish()
2036
+ })
2037
+ )
2038
+ }),
2039
+ OpenRouterErrorResponseSchema
2040
+ ]);
2041
+ var OpenRouterChatLanguageModel = class {
2042
+ constructor(modelId, settings, config) {
2043
+ this.specificationVersion = "v2";
2044
+ this.provider = "openrouter";
2045
+ this.defaultObjectGenerationMode = "tool";
2046
+ this.supportedUrls = {
2047
+ "image/*": [
2048
+ /^data:image\/[a-zA-Z]+;base64,/,
2049
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
2050
+ ],
2051
+ // 'text/*': [/^data:text\//, /^https?:\/\/.+$/],
2052
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
2053
+ };
2054
+ this.modelId = modelId;
2055
+ this.settings = settings;
2056
+ this.config = config;
2057
+ }
2058
+ getArgs({
2059
+ prompt,
2060
+ maxOutputTokens,
2061
+ temperature,
2062
+ topP,
2063
+ frequencyPenalty,
2064
+ presencePenalty,
2065
+ seed,
2066
+ stopSequences,
2067
+ responseFormat,
2068
+ topK,
2069
+ tools,
2070
+ toolChoice
2071
+ }) {
2072
+ var _a15;
2073
+ const baseArgs = __spreadValues(__spreadValues({
2074
+ // model id:
2075
+ model: this.modelId,
2076
+ models: this.settings.models,
2077
+ // model specific settings:
2078
+ logit_bias: this.settings.logitBias,
2079
+ logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
2080
+ top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
2081
+ user: this.settings.user,
2082
+ parallel_tool_calls: this.settings.parallelToolCalls,
2083
+ // standardized settings:
2084
+ max_tokens: maxOutputTokens,
2085
+ temperature,
2086
+ top_p: topP,
2087
+ frequency_penalty: frequencyPenalty,
2088
+ presence_penalty: presencePenalty,
2089
+ seed,
2090
+ stop: stopSequences,
2091
+ response_format: responseFormat,
2092
+ top_k: topK,
2093
+ // messages:
2094
+ messages: convertToOpenRouterChatMessages(prompt),
2095
+ // OpenRouter specific settings:
2096
+ include_reasoning: this.settings.includeReasoning,
2097
+ reasoning: this.settings.reasoning,
2098
+ usage: this.settings.usage,
2099
+ // Web search settings:
2100
+ plugins: this.settings.plugins,
2101
+ web_search_options: this.settings.web_search_options,
2102
+ // Provider routing settings:
2103
+ provider: this.settings.provider
2104
+ }, this.config.extraBody), this.settings.extraBody);
2105
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null) {
2106
+ return __spreadProps(__spreadValues({}, baseArgs), {
2107
+ response_format: {
2108
+ type: "json_schema",
2109
+ json_schema: __spreadValues({
2110
+ schema: responseFormat.schema,
2111
+ strict: true,
2112
+ name: (_a15 = responseFormat.name) != null ? _a15 : "response"
2113
+ }, responseFormat.description && {
2114
+ description: responseFormat.description
2115
+ })
2116
+ }
2117
+ });
2118
+ }
2119
+ if (tools && tools.length > 0) {
2120
+ const mappedTools = tools.filter((tool) => tool.type === "function").map((tool) => ({
2121
+ type: "function",
2122
+ function: {
2123
+ name: tool.name,
2124
+ description: tool.description,
2125
+ parameters: tool.inputSchema
2126
+ }
2127
+ }));
2128
+ return __spreadProps(__spreadValues({}, baseArgs), {
2129
+ tools: mappedTools,
2130
+ tool_choice: toolChoice ? getChatCompletionToolChoice(toolChoice) : void 0
2131
+ });
2132
+ }
2133
+ return baseArgs;
2134
+ }
2135
+ async doGenerate(options) {
2136
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
2137
+ const providerOptions = options.providerOptions || {};
2138
+ const openrouterOptions = providerOptions.openrouter || {};
2139
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
2140
+ const { value: response, responseHeaders } = await postJsonToApi2({
2141
+ url: this.config.url({
2142
+ path: "/chat/completions",
2143
+ modelId: this.modelId
2144
+ }),
2145
+ headers: combineHeaders2(this.config.headers(), options.headers),
2146
+ body: args,
2147
+ failedResponseHandler: openrouterFailedResponseHandler,
2148
+ successfulResponseHandler: createJsonResponseHandler2(
2149
+ OpenRouterNonStreamChatCompletionResponseSchema
2150
+ ),
2151
+ abortSignal: options.abortSignal,
2152
+ fetch: this.config.fetch
2153
+ });
2154
+ const choice = response.choices[0];
2155
+ if (!choice) {
2156
+ throw new Error("No choice in response");
2157
+ }
2158
+ const usageInfo = response.usage ? {
2159
+ inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
2160
+ outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
2161
+ totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
2162
+ reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
2163
+ cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
2164
+ } : {
2165
+ inputTokens: 0,
2166
+ outputTokens: 0,
2167
+ totalTokens: 0,
2168
+ reasoningTokens: 0,
2169
+ cachedInputTokens: 0
2170
+ };
2171
+ const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
2172
+ const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
2173
+ switch (detail.type) {
2174
+ case "reasoning.text": {
2175
+ if (detail.text) {
2176
+ return {
2177
+ type: "reasoning",
2178
+ text: detail.text
2179
+ };
2180
+ }
2181
+ break;
2182
+ }
2183
+ case "reasoning.summary": {
2184
+ if (detail.summary) {
2185
+ return {
2186
+ type: "reasoning",
2187
+ text: detail.summary
2188
+ };
2189
+ }
2190
+ break;
2191
+ }
2192
+ case "reasoning.encrypted": {
2193
+ if (detail.data) {
2194
+ return {
2195
+ type: "reasoning",
2196
+ text: "[REDACTED]"
2197
+ };
2198
+ }
2199
+ break;
2200
+ }
2201
+ }
2202
+ return null;
2203
+ }).filter((p) => p !== null) : choice.message.reasoning ? [
2204
+ {
2205
+ type: "reasoning",
2206
+ text: choice.message.reasoning
2207
+ }
2208
+ ] : [];
2209
+ const content = [];
2210
+ content.push(...reasoning);
2211
+ if (choice.message.content) {
2212
+ content.push({
2213
+ type: "text",
2214
+ text: choice.message.content
2215
+ });
2216
+ }
2217
+ if (choice.message.tool_calls) {
2218
+ for (const toolCall of choice.message.tool_calls) {
2219
+ content.push({
2220
+ type: "tool-call",
2221
+ toolCallId: (_j = toolCall.id) != null ? _j : generateId2(),
2222
+ toolName: toolCall.function.name,
2223
+ input: toolCall.function.arguments
2224
+ });
2225
+ }
2226
+ }
2227
+ if (choice.message.images) {
2228
+ for (const image of choice.message.images) {
2229
+ content.push({
2230
+ type: "file",
2231
+ mediaType: getMediaType(image.image_url.url, "image/jpeg"),
2232
+ data: getBase64FromDataUrl(image.image_url.url)
2233
+ });
2234
+ }
2235
+ }
2236
+ if (choice.message.annotations) {
2237
+ for (const annotation of choice.message.annotations) {
2238
+ if (annotation.type === "url_citation") {
2239
+ content.push({
2240
+ type: "source",
2241
+ sourceType: "url",
2242
+ id: annotation.url_citation.url,
2243
+ url: annotation.url_citation.url,
2244
+ title: annotation.url_citation.title,
2245
+ providerMetadata: {
2246
+ openrouter: {
2247
+ content: annotation.url_citation.content || ""
2248
+ }
2249
+ }
2250
+ });
2251
+ }
2252
+ }
2253
+ }
2254
+ return {
2255
+ content,
2256
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
2257
+ usage: usageInfo,
2258
+ warnings: [],
2259
+ providerMetadata: {
2260
+ openrouter: {
2261
+ provider: (_k = response.provider) != null ? _k : "",
2262
+ usage: {
2263
+ promptTokens: (_l = usageInfo.inputTokens) != null ? _l : 0,
2264
+ completionTokens: (_m = usageInfo.outputTokens) != null ? _m : 0,
2265
+ totalTokens: (_n = usageInfo.totalTokens) != null ? _n : 0,
2266
+ cost: (_o = response.usage) == null ? void 0 : _o.cost,
2267
+ promptTokensDetails: {
2268
+ cachedTokens: (_r = (_q = (_p = response.usage) == null ? void 0 : _p.prompt_tokens_details) == null ? void 0 : _q.cached_tokens) != null ? _r : 0
2269
+ },
2270
+ completionTokensDetails: {
2271
+ reasoningTokens: (_u = (_t = (_s = response.usage) == null ? void 0 : _s.completion_tokens_details) == null ? void 0 : _t.reasoning_tokens) != null ? _u : 0
2272
+ },
2273
+ costDetails: {
2274
+ upstreamInferenceCost: (_x = (_w = (_v = response.usage) == null ? void 0 : _v.cost_details) == null ? void 0 : _w.upstream_inference_cost) != null ? _x : 0
2275
+ }
2276
+ }
2277
+ }
2278
+ },
2279
+ request: { body: args },
2280
+ response: {
2281
+ id: response.id,
2282
+ modelId: response.model,
2283
+ headers: responseHeaders
2284
+ }
2285
+ };
2286
+ }
2287
+ async doStream(options) {
2288
+ var _a15;
2289
+ const providerOptions = options.providerOptions || {};
2290
+ const openrouterOptions = providerOptions.openrouter || {};
2291
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
2292
+ const { value: response, responseHeaders } = await postJsonToApi2({
2293
+ url: this.config.url({
2294
+ path: "/chat/completions",
2295
+ modelId: this.modelId
2296
+ }),
2297
+ headers: combineHeaders2(this.config.headers(), options.headers),
2298
+ body: __spreadProps(__spreadValues({}, args), {
2299
+ stream: true,
2300
+ // only include stream_options when in strict compatibility mode:
2301
+ stream_options: this.config.compatibility === "strict" ? __spreadValues({
2302
+ include_usage: true
2303
+ }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
2304
+ }),
2305
+ failedResponseHandler: openrouterFailedResponseHandler,
2306
+ successfulResponseHandler: createEventSourceResponseHandler2(
2307
+ OpenRouterStreamChatCompletionChunkSchema
2308
+ ),
2309
+ abortSignal: options.abortSignal,
2310
+ fetch: this.config.fetch
2311
+ });
2312
+ const toolCalls = [];
2313
+ let finishReason = "other";
2314
+ const usage = {
2315
+ inputTokens: Number.NaN,
2316
+ outputTokens: Number.NaN,
2317
+ totalTokens: Number.NaN,
2318
+ reasoningTokens: Number.NaN,
2319
+ cachedInputTokens: Number.NaN
2320
+ };
2321
+ const openrouterUsage = {};
2322
+ let textStarted = false;
2323
+ let reasoningStarted = false;
2324
+ let textId;
2325
+ let reasoningId;
2326
+ let openrouterResponseId;
2327
+ let provider;
2328
+ return {
2329
+ stream: response.pipeThrough(
2330
+ new TransformStream({
2331
+ transform(chunk, controller) {
2332
+ var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
2333
+ if (!chunk.success) {
2334
+ finishReason = "error";
2335
+ controller.enqueue({ type: "error", error: chunk.error });
2336
+ return;
2337
+ }
2338
+ const value = chunk.value;
2339
+ if ("error" in value) {
2340
+ finishReason = "error";
2341
+ controller.enqueue({ type: "error", error: value.error });
2342
+ return;
2343
+ }
2344
+ if (value.provider) {
2345
+ provider = value.provider;
2346
+ }
2347
+ if (value.id) {
2348
+ openrouterResponseId = value.id;
2349
+ controller.enqueue({
2350
+ type: "response-metadata",
2351
+ id: value.id
2352
+ });
2353
+ }
2354
+ if (value.model) {
2355
+ controller.enqueue({
2356
+ type: "response-metadata",
2357
+ modelId: value.model
2358
+ });
2359
+ }
2360
+ if (value.usage != null) {
2361
+ usage.inputTokens = value.usage.prompt_tokens;
2362
+ usage.outputTokens = value.usage.completion_tokens;
2363
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
2364
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
2365
+ if (value.usage.prompt_tokens_details) {
2366
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
2367
+ usage.cachedInputTokens = cachedInputTokens;
2368
+ openrouterUsage.promptTokensDetails = {
2369
+ cachedTokens: cachedInputTokens
2370
+ };
2371
+ }
2372
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
2373
+ if (value.usage.completion_tokens_details) {
2374
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
2375
+ usage.reasoningTokens = reasoningTokens;
2376
+ openrouterUsage.completionTokensDetails = {
2377
+ reasoningTokens
2378
+ };
2379
+ }
2380
+ openrouterUsage.cost = value.usage.cost;
2381
+ openrouterUsage.totalTokens = value.usage.total_tokens;
2382
+ }
2383
+ const choice = value.choices[0];
2384
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
2385
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
2386
+ }
2387
+ if ((choice == null ? void 0 : choice.delta) == null) {
2388
+ return;
2389
+ }
2390
+ const delta = choice.delta;
2391
+ const emitReasoningChunk = (chunkText) => {
2392
+ if (!reasoningStarted) {
2393
+ reasoningId = openrouterResponseId || generateId2();
2394
+ controller.enqueue({
2395
+ type: "reasoning-start",
2396
+ id: reasoningId
2397
+ });
2398
+ reasoningStarted = true;
2399
+ }
2400
+ controller.enqueue({
2401
+ type: "reasoning-delta",
2402
+ delta: chunkText,
2403
+ id: reasoningId || generateId2()
2404
+ });
2405
+ };
2406
+ if (delta.reasoning_details && delta.reasoning_details.length > 0) {
2407
+ for (const detail of delta.reasoning_details) {
2408
+ switch (detail.type) {
2409
+ case "reasoning.text": {
2410
+ if (detail.text) {
2411
+ emitReasoningChunk(detail.text);
2412
+ }
2413
+ break;
2414
+ }
2415
+ case "reasoning.encrypted": {
2416
+ if (detail.data) {
2417
+ emitReasoningChunk("[REDACTED]");
2418
+ }
2419
+ break;
2420
+ }
2421
+ case "reasoning.summary": {
2422
+ if (detail.summary) {
2423
+ emitReasoningChunk(detail.summary);
2424
+ }
2425
+ break;
2426
+ }
2427
+ }
2428
+ }
2429
+ } else if (delta.reasoning) {
2430
+ emitReasoningChunk(delta.reasoning);
2431
+ }
2432
+ if (delta.content) {
2433
+ if (reasoningStarted && !textStarted) {
2434
+ controller.enqueue({
2435
+ type: "reasoning-end",
2436
+ id: reasoningId || generateId2()
2437
+ });
2438
+ reasoningStarted = false;
2439
+ }
2440
+ if (!textStarted) {
2441
+ textId = openrouterResponseId || generateId2();
2442
+ controller.enqueue({
2443
+ type: "text-start",
2444
+ id: textId
2445
+ });
2446
+ textStarted = true;
2447
+ }
2448
+ controller.enqueue({
2449
+ type: "text-delta",
2450
+ delta: delta.content,
2451
+ id: textId || generateId2()
2452
+ });
2453
+ }
2454
+ if (delta.annotations) {
2455
+ for (const annotation of delta.annotations) {
2456
+ if (annotation.type === "url_citation") {
2457
+ controller.enqueue({
2458
+ type: "source",
2459
+ sourceType: "url",
2460
+ id: annotation.url_citation.url,
2461
+ url: annotation.url_citation.url,
2462
+ title: annotation.url_citation.title,
2463
+ providerMetadata: {
2464
+ openrouter: {
2465
+ content: annotation.url_citation.content || ""
2466
+ }
2467
+ }
2468
+ });
2469
+ }
2470
+ }
2471
+ }
2472
+ if (delta.tool_calls != null) {
2473
+ for (const toolCallDelta of delta.tool_calls) {
2474
+ const index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length - 1;
2475
+ if (toolCalls[index] == null) {
2476
+ if (toolCallDelta.type !== "function") {
2477
+ throw new InvalidResponseDataError({
2478
+ data: toolCallDelta,
2479
+ message: `Expected 'function' type.`
2480
+ });
2481
+ }
2482
+ if (toolCallDelta.id == null) {
2483
+ throw new InvalidResponseDataError({
2484
+ data: toolCallDelta,
2485
+ message: `Expected 'id' to be a string.`
2486
+ });
2487
+ }
2488
+ if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) {
2489
+ throw new InvalidResponseDataError({
2490
+ data: toolCallDelta,
2491
+ message: `Expected 'function.name' to be a string.`
2492
+ });
2493
+ }
2494
+ toolCalls[index] = {
2495
+ id: toolCallDelta.id,
2496
+ type: "function",
2497
+ function: {
2498
+ name: toolCallDelta.function.name,
2499
+ arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
2500
+ },
2501
+ inputStarted: false,
2502
+ sent: false
2503
+ };
2504
+ const toolCall2 = toolCalls[index];
2505
+ if (toolCall2 == null) {
2506
+ throw new Error("Tool call is missing");
2507
+ }
2508
+ if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
2509
+ toolCall2.inputStarted = true;
2510
+ controller.enqueue({
2511
+ type: "tool-input-start",
2512
+ id: toolCall2.id,
2513
+ toolName: toolCall2.function.name
2514
+ });
2515
+ controller.enqueue({
2516
+ type: "tool-input-delta",
2517
+ id: toolCall2.id,
2518
+ delta: toolCall2.function.arguments
2519
+ });
2520
+ controller.enqueue({
2521
+ type: "tool-input-end",
2522
+ id: toolCall2.id
2523
+ });
2524
+ controller.enqueue({
2525
+ type: "tool-call",
2526
+ toolCallId: toolCall2.id,
2527
+ toolName: toolCall2.function.name,
2528
+ input: toolCall2.function.arguments
2529
+ });
2530
+ toolCall2.sent = true;
2531
+ }
2532
+ continue;
2533
+ }
2534
+ const toolCall = toolCalls[index];
2535
+ if (toolCall == null) {
2536
+ throw new Error("Tool call is missing");
2537
+ }
2538
+ if (!toolCall.inputStarted) {
2539
+ toolCall.inputStarted = true;
2540
+ controller.enqueue({
2541
+ type: "tool-input-start",
2542
+ id: toolCall.id,
2543
+ toolName: toolCall.function.name
2544
+ });
2545
+ }
2546
+ if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
2547
+ toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
2548
+ }
2549
+ controller.enqueue({
2550
+ type: "tool-input-delta",
2551
+ id: toolCall.id,
2552
+ delta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
2553
+ });
2554
+ if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson(toolCall.function.arguments)) {
2555
+ controller.enqueue({
2556
+ type: "tool-call",
2557
+ toolCallId: (_n = toolCall.id) != null ? _n : generateId2(),
2558
+ toolName: toolCall.function.name,
2559
+ input: toolCall.function.arguments
2560
+ });
2561
+ toolCall.sent = true;
2562
+ }
2563
+ }
2564
+ }
2565
+ if (delta.images != null) {
2566
+ for (const image of delta.images) {
2567
+ controller.enqueue({
2568
+ type: "file",
2569
+ mediaType: getMediaType(image.image_url.url, "image/jpeg"),
2570
+ data: getBase64FromDataUrl(image.image_url.url)
2571
+ });
2572
+ }
2573
+ }
2574
+ },
2575
+ flush(controller) {
2576
+ var _a16;
2577
+ if (finishReason === "tool-calls") {
2578
+ for (const toolCall of toolCalls) {
2579
+ if (toolCall && !toolCall.sent) {
2580
+ controller.enqueue({
2581
+ type: "tool-call",
2582
+ toolCallId: (_a16 = toolCall.id) != null ? _a16 : generateId2(),
2583
+ toolName: toolCall.function.name,
2584
+ // Coerce invalid arguments to an empty JSON object
2585
+ input: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
2586
+ });
2587
+ toolCall.sent = true;
2588
+ }
2589
+ }
2590
+ }
2591
+ if (reasoningStarted) {
2592
+ controller.enqueue({
2593
+ type: "reasoning-end",
2594
+ id: reasoningId || generateId2()
2595
+ });
2596
+ }
2597
+ if (textStarted) {
2598
+ controller.enqueue({
2599
+ type: "text-end",
2600
+ id: textId || generateId2()
2601
+ });
2602
+ }
2603
+ const openrouterMetadata = {
2604
+ usage: openrouterUsage
2605
+ };
2606
+ if (provider !== void 0) {
2607
+ openrouterMetadata.provider = provider;
2608
+ }
2609
+ controller.enqueue({
2610
+ type: "finish",
2611
+ finishReason,
2612
+ usage,
2613
+ providerMetadata: {
2614
+ openrouter: openrouterMetadata
2615
+ }
2616
+ });
2617
+ }
2618
+ })
2619
+ ),
2620
+ warnings: [],
2621
+ request: { body: args },
2622
+ response: { headers: responseHeaders }
2623
+ };
2624
+ }
2625
+ };
2626
+ function convertToOpenRouterCompletionPrompt({
2627
+ prompt,
2628
+ inputFormat,
2629
+ user = "user",
2630
+ assistant = "assistant"
2631
+ }) {
2632
+ if (prompt.length === 1 && prompt[0] && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0] && prompt[0].content[0].type === "text") {
2633
+ return { prompt: prompt[0].content[0].text };
2634
+ }
2635
+ let text = "";
2636
+ if (prompt[0] && prompt[0].role === "system") {
2637
+ text += `${prompt[0].content}
2638
+
2639
+ `;
2640
+ prompt = prompt.slice(1);
2641
+ }
2642
+ for (const { role, content } of prompt) {
2643
+ switch (role) {
2644
+ case "system": {
2645
+ throw new InvalidPromptError({
2646
+ message: `Unexpected system message in prompt: ${content}`,
2647
+ prompt
2648
+ });
2649
+ }
2650
+ case "user": {
2651
+ const userMessage = content.map((part) => {
2652
+ switch (part.type) {
2653
+ case "text": {
2654
+ return part.text;
2655
+ }
2656
+ case "file": {
2657
+ throw new UnsupportedFunctionalityError3({
2658
+ functionality: "file attachments"
2659
+ });
2660
+ }
2661
+ default: {
2662
+ return "";
2663
+ }
2664
+ }
2665
+ }).join("");
2666
+ text += `${user}:
2667
+ ${userMessage}
2668
+
2669
+ `;
2670
+ break;
2671
+ }
2672
+ case "assistant": {
2673
+ const assistantMessage = content.map(
2674
+ (part) => {
2675
+ switch (part.type) {
2676
+ case "text": {
2677
+ return part.text;
2678
+ }
2679
+ case "tool-call": {
2680
+ throw new UnsupportedFunctionalityError3({
2681
+ functionality: "tool-call messages"
2682
+ });
2683
+ }
2684
+ case "tool-result": {
2685
+ throw new UnsupportedFunctionalityError3({
2686
+ functionality: "tool-result messages"
2687
+ });
2688
+ }
2689
+ case "reasoning": {
2690
+ throw new UnsupportedFunctionalityError3({
2691
+ functionality: "reasoning messages"
2692
+ });
2693
+ }
2694
+ case "file": {
2695
+ throw new UnsupportedFunctionalityError3({
2696
+ functionality: "file attachments"
2697
+ });
2698
+ }
2699
+ default: {
2700
+ return "";
2701
+ }
2702
+ }
2703
+ }
2704
+ ).join("");
2705
+ text += `${assistant}:
2706
+ ${assistantMessage}
2707
+
2708
+ `;
2709
+ break;
2710
+ }
2711
+ case "tool": {
2712
+ throw new UnsupportedFunctionalityError3({
2713
+ functionality: "tool messages"
2714
+ });
2715
+ }
2716
+ }
2717
+ }
2718
+ text += `${assistant}:
2719
+ `;
2720
+ return {
2721
+ prompt: text
2722
+ };
2723
+ }
2724
+ var OpenRouterCompletionChunkSchema = z3.z.union([
2725
+ z3.z.object({
2726
+ id: z3.z.string().optional(),
2727
+ model: z3.z.string().optional(),
2728
+ choices: z3.z.array(
2729
+ z3.z.object({
2730
+ text: z3.z.string(),
2731
+ reasoning: z3.z.string().nullish().optional(),
2732
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
2733
+ finish_reason: z3.z.string().nullish(),
2734
+ index: z3.z.number().nullish(),
2735
+ logprobs: z3.z.object({
2736
+ tokens: z3.z.array(z3.z.string()),
2737
+ token_logprobs: z3.z.array(z3.z.number()),
2738
+ top_logprobs: z3.z.array(z3.z.record(z3.z.string(), z3.z.number())).nullable()
2739
+ }).nullable().optional()
2740
+ })
2741
+ ),
2742
+ usage: z3.z.object({
2743
+ prompt_tokens: z3.z.number(),
2744
+ prompt_tokens_details: z3.z.object({
2745
+ cached_tokens: z3.z.number()
2746
+ }).nullish(),
2747
+ completion_tokens: z3.z.number(),
2748
+ completion_tokens_details: z3.z.object({
2749
+ reasoning_tokens: z3.z.number()
2750
+ }).nullish(),
2751
+ total_tokens: z3.z.number(),
2752
+ cost: z3.z.number().optional()
2753
+ }).nullish()
2754
+ }),
2755
+ OpenRouterErrorResponseSchema
2756
+ ]);
2757
+ var OpenRouterCompletionLanguageModel = class {
2758
+ constructor(modelId, settings, config) {
2759
+ this.specificationVersion = "v2";
2760
+ this.provider = "openrouter";
2761
+ this.supportedUrls = {
2762
+ "image/*": [
2763
+ /^data:image\/[a-zA-Z]+;base64,/,
2764
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
2765
+ ],
2766
+ "text/*": [/^data:text\//, /^https?:\/\/.+$/],
2767
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
2768
+ };
2769
+ this.defaultObjectGenerationMode = void 0;
2770
+ this.modelId = modelId;
2771
+ this.settings = settings;
2772
+ this.config = config;
2773
+ }
2774
+ getArgs({
2775
+ prompt,
2776
+ maxOutputTokens,
2777
+ temperature,
2778
+ topP,
2779
+ frequencyPenalty,
2780
+ presencePenalty,
2781
+ seed,
2782
+ responseFormat,
2783
+ topK,
2784
+ stopSequences,
2785
+ tools,
2786
+ toolChoice
2787
+ }) {
2788
+ const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
2789
+ prompt,
2790
+ inputFormat: "prompt"
2791
+ });
2792
+ if (tools == null ? void 0 : tools.length) {
2793
+ throw new UnsupportedFunctionalityError3({
2794
+ functionality: "tools"
2795
+ });
2796
+ }
2797
+ if (toolChoice) {
2798
+ throw new UnsupportedFunctionalityError3({
2799
+ functionality: "toolChoice"
2800
+ });
2801
+ }
2802
+ return __spreadValues(__spreadValues({
2803
+ // model id:
2804
+ model: this.modelId,
2805
+ models: this.settings.models,
2806
+ // model specific settings:
2807
+ logit_bias: this.settings.logitBias,
2808
+ logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
2809
+ suffix: this.settings.suffix,
2810
+ user: this.settings.user,
2811
+ // standardized settings:
2812
+ max_tokens: maxOutputTokens,
2813
+ temperature,
2814
+ top_p: topP,
2815
+ frequency_penalty: frequencyPenalty,
2816
+ presence_penalty: presencePenalty,
2817
+ seed,
2818
+ stop: stopSequences,
2819
+ response_format: responseFormat,
2820
+ top_k: topK,
2821
+ // prompt:
2822
+ prompt: completionPrompt,
2823
+ // OpenRouter specific settings:
2824
+ include_reasoning: this.settings.includeReasoning,
2825
+ reasoning: this.settings.reasoning
2826
+ }, this.config.extraBody), this.settings.extraBody);
2827
+ }
2828
+ async doGenerate(options) {
2829
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
2830
+ const providerOptions = options.providerOptions || {};
2831
+ const openrouterOptions = providerOptions.openrouter || {};
2832
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
2833
+ const { value: response, responseHeaders } = await postJsonToApi2({
2834
+ url: this.config.url({
2835
+ path: "/completions",
2836
+ modelId: this.modelId
2837
+ }),
2838
+ headers: combineHeaders2(this.config.headers(), options.headers),
2839
+ body: args,
2840
+ failedResponseHandler: openrouterFailedResponseHandler,
2841
+ successfulResponseHandler: createJsonResponseHandler2(
2842
+ OpenRouterCompletionChunkSchema
2843
+ ),
2844
+ abortSignal: options.abortSignal,
2845
+ fetch: this.config.fetch
2846
+ });
2847
+ if ("error" in response) {
2848
+ throw new Error(`${response.error.message}`);
2849
+ }
2850
+ const choice = response.choices[0];
2851
+ if (!choice) {
2852
+ throw new Error("No choice in OpenRouter completion response");
2853
+ }
2854
+ return {
2855
+ content: [
2856
+ {
2857
+ type: "text",
2858
+ text: (_a15 = choice.text) != null ? _a15 : ""
2859
+ }
2860
+ ],
2861
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
2862
+ usage: {
2863
+ inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
2864
+ outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
2865
+ totalTokens: ((_g = (_f = response.usage) == null ? void 0 : _f.prompt_tokens) != null ? _g : 0) + ((_i = (_h = response.usage) == null ? void 0 : _h.completion_tokens) != null ? _i : 0),
2866
+ reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
2867
+ cachedInputTokens: (_o = (_n = (_m = response.usage) == null ? void 0 : _m.prompt_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : 0
2868
+ },
2869
+ warnings: [],
2870
+ response: {
2871
+ headers: responseHeaders
2872
+ }
2873
+ };
2874
+ }
2875
+ async doStream(options) {
2876
+ const providerOptions = options.providerOptions || {};
2877
+ const openrouterOptions = providerOptions.openrouter || {};
2878
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
2879
+ const { value: response, responseHeaders } = await postJsonToApi2({
2880
+ url: this.config.url({
2881
+ path: "/completions",
2882
+ modelId: this.modelId
2883
+ }),
2884
+ headers: combineHeaders2(this.config.headers(), options.headers),
2885
+ body: __spreadProps(__spreadValues({}, args), {
2886
+ stream: true,
2887
+ // only include stream_options when in strict compatibility mode:
2888
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
2889
+ }),
2890
+ failedResponseHandler: openrouterFailedResponseHandler,
2891
+ successfulResponseHandler: createEventSourceResponseHandler2(
2892
+ OpenRouterCompletionChunkSchema
2893
+ ),
2894
+ abortSignal: options.abortSignal,
2895
+ fetch: this.config.fetch
2896
+ });
2897
+ let finishReason = "other";
2898
+ const usage = {
2899
+ inputTokens: Number.NaN,
2900
+ outputTokens: Number.NaN,
2901
+ totalTokens: Number.NaN,
2902
+ reasoningTokens: Number.NaN,
2903
+ cachedInputTokens: Number.NaN
2904
+ };
2905
+ const openrouterUsage = {};
2906
+ return {
2907
+ stream: response.pipeThrough(
2908
+ new TransformStream({
2909
+ transform(chunk, controller) {
2910
+ var _a15, _b;
2911
+ if (!chunk.success) {
2912
+ finishReason = "error";
2913
+ controller.enqueue({ type: "error", error: chunk.error });
2914
+ return;
2915
+ }
2916
+ const value = chunk.value;
2917
+ if ("error" in value) {
2918
+ finishReason = "error";
2919
+ controller.enqueue({ type: "error", error: value.error });
2920
+ return;
2921
+ }
2922
+ if (value.usage != null) {
2923
+ usage.inputTokens = value.usage.prompt_tokens;
2924
+ usage.outputTokens = value.usage.completion_tokens;
2925
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
2926
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
2927
+ if (value.usage.prompt_tokens_details) {
2928
+ const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
2929
+ usage.cachedInputTokens = cachedInputTokens;
2930
+ openrouterUsage.promptTokensDetails = {
2931
+ cachedTokens: cachedInputTokens
2932
+ };
2933
+ }
2934
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
2935
+ if (value.usage.completion_tokens_details) {
2936
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
2937
+ usage.reasoningTokens = reasoningTokens;
2938
+ openrouterUsage.completionTokensDetails = {
2939
+ reasoningTokens
2940
+ };
2941
+ }
2942
+ openrouterUsage.cost = value.usage.cost;
2943
+ openrouterUsage.totalTokens = value.usage.total_tokens;
2944
+ }
2945
+ const choice = value.choices[0];
2946
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
2947
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
2948
+ }
2949
+ if ((choice == null ? void 0 : choice.text) != null) {
2950
+ controller.enqueue({
2951
+ type: "text-delta",
2952
+ delta: choice.text,
2953
+ id: generateId2()
2954
+ });
2955
+ }
2956
+ },
2957
+ flush(controller) {
2958
+ controller.enqueue({
2959
+ type: "finish",
2960
+ finishReason,
2961
+ usage,
2962
+ providerMetadata: {
2963
+ openrouter: {
2964
+ usage: openrouterUsage
2965
+ }
2966
+ }
2967
+ });
2968
+ }
2969
+ })
2970
+ ),
2971
+ response: {
2972
+ headers: responseHeaders
2973
+ }
2974
+ };
2975
+ }
2976
+ };
2977
+ function createOpenRouter(options = {}) {
2978
+ var _a15, _b, _c;
2979
+ const baseURL = (_b = withoutTrailingSlash2((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
2980
+ const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
2981
+ const getHeaders = () => __spreadValues({
2982
+ Authorization: `Bearer ${loadApiKey2({
2983
+ apiKey: options.apiKey,
2984
+ environmentVariableName: "OPENROUTER_API_KEY",
2985
+ description: "OpenRouter"
2986
+ })}`
2987
+ }, options.headers);
2988
+ const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
2989
+ provider: "openrouter.chat",
2990
+ url: ({ path }) => `${baseURL}${path}`,
2991
+ headers: getHeaders,
2992
+ compatibility,
2993
+ fetch: options.fetch,
2994
+ extraBody: options.extraBody
2995
+ });
2996
+ const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
2997
+ provider: "openrouter.completion",
2998
+ url: ({ path }) => `${baseURL}${path}`,
2999
+ headers: getHeaders,
3000
+ compatibility,
3001
+ fetch: options.fetch,
3002
+ extraBody: options.extraBody
3003
+ });
3004
+ const createLanguageModel = (modelId, settings) => {
3005
+ if (new.target) {
3006
+ throw new Error(
3007
+ "The OpenRouter model function cannot be called with the new keyword."
3008
+ );
3009
+ }
3010
+ if (modelId === "openai/gpt-3.5-turbo-instruct") {
3011
+ return createCompletionModel(
3012
+ modelId,
3013
+ settings
3014
+ );
3015
+ }
3016
+ return createChatModel(modelId, settings);
3017
+ };
3018
+ const provider = (modelId, settings) => createLanguageModel(modelId, settings);
3019
+ provider.languageModel = createLanguageModel;
3020
+ provider.chat = createChatModel;
3021
+ provider.completion = createCompletionModel;
3022
+ return provider;
3023
+ }
3024
+ createOpenRouter({
3025
+ compatibility: "strict"
3026
+ // strict for OpenRouter API
3027
+ });
3028
+
3029
+ // src/llm/model/gateway-resolver.ts
3030
+ function parseModelRouterId(routerId, gatewayPrefix) {
3031
+ if (gatewayPrefix && !routerId.startsWith(`${gatewayPrefix}/`)) {
3032
+ throw new Error(`Expected ${gatewayPrefix}/ in model router ID ${routerId}`);
3033
+ }
3034
+ const idParts = routerId.split("/");
3035
+ if (gatewayPrefix && idParts.length < 3) {
3036
+ throw new Error(
3037
+ `Expected atleast 3 id parts ${gatewayPrefix}/provider/model, but only saw ${idParts.length} in ${routerId}`
3038
+ );
3039
+ }
3040
+ const providerId = idParts.at(gatewayPrefix ? 1 : 0);
3041
+ const modelId = idParts.slice(gatewayPrefix ? 2 : 1).join(`/`);
3042
+ if (!routerId.includes(`/`) || !providerId || !modelId) {
3043
+ throw new Error(
3044
+ `Attempted to parse provider/model from ${routerId} but this ID doesn't appear to contain a provider`
3045
+ );
3046
+ }
3047
+ return {
3048
+ providerId,
3049
+ modelId
3050
+ };
3051
+ }
3052
+
3053
+ // src/llm/model/gateways/constants.ts
3054
+ var PROVIDERS_WITH_INSTALLED_PACKAGES = ["anthropic", "google", "openai", "openrouter", "xai"];
3055
+ var EXCLUDED_PROVIDERS = ["github-copilot"];
3056
+
3057
+ // src/llm/model/gateways/models-dev.ts
3058
+ var OPENAI_COMPATIBLE_OVERRIDES = {
3059
+ cerebras: {
3060
+ url: "https://api.cerebras.ai/v1"
3061
+ },
3062
+ mistral: {
3063
+ url: "https://api.mistral.ai/v1"
3064
+ },
3065
+ groq: {
3066
+ url: "https://api.groq.com/openai/v1"
3067
+ },
3068
+ togetherai: {
3069
+ url: "https://api.together.xyz/v1"
3070
+ },
3071
+ deepinfra: {
3072
+ url: "https://api.deepinfra.com/v1/openai"
3073
+ },
3074
+ perplexity: {
3075
+ url: "https://api.perplexity.ai"
3076
+ },
3077
+ vercel: {
3078
+ url: "https://ai-gateway.vercel.sh/v1",
3079
+ apiKeyEnvVar: "AI_GATEWAY_API_KEY"
3080
+ }
3081
+ };
3082
+ var ModelsDevGateway = class extends chunk3ZEJSGTJ_cjs.MastraModelGateway {
3083
+ name = "models.dev";
3084
+ prefix = void 0;
3085
+ // No prefix for registry gateway
3086
+ providerConfigs = {};
3087
+ constructor(providerConfigs) {
3088
+ super();
3089
+ if (providerConfigs) this.providerConfigs = providerConfigs;
3090
+ }
3091
+ async fetchProviders() {
3092
+ const response = await fetch("https://models.dev/api.json");
3093
+ if (!response.ok) {
3094
+ throw new Error(`Failed to fetch from models.dev: ${response.statusText}`);
3095
+ }
3096
+ const data = await response.json();
3097
+ const providerConfigs = {};
3098
+ for (const [providerId, providerInfo] of Object.entries(data)) {
3099
+ if (EXCLUDED_PROVIDERS.includes(providerId)) continue;
3100
+ if (!providerInfo || typeof providerInfo !== "object" || !providerInfo.models) continue;
3101
+ const normalizedId = providerId;
3102
+ const isOpenAICompatible = providerInfo.npm === "@ai-sdk/openai-compatible" || providerInfo.npm === "@ai-sdk/gateway" || // Vercel AI Gateway is OpenAI-compatible
3103
+ normalizedId in OPENAI_COMPATIBLE_OVERRIDES;
3104
+ const hasInstalledPackage = PROVIDERS_WITH_INSTALLED_PACKAGES.includes(providerId);
3105
+ const hasApiAndEnv = providerInfo.api && providerInfo.env && providerInfo.env.length > 0;
3106
+ if (isOpenAICompatible || hasInstalledPackage || hasApiAndEnv) {
3107
+ const modelIds = Object.keys(providerInfo.models).sort();
3108
+ const url = providerInfo.api || OPENAI_COMPATIBLE_OVERRIDES[normalizedId]?.url;
3109
+ if (!hasInstalledPackage && !url) {
3110
+ continue;
3111
+ }
3112
+ const apiKeyEnvVar = providerInfo.env?.[0] || `${normalizedId.toUpperCase().replace(/-/g, "_")}_API_KEY`;
3113
+ const apiKeyHeader = !hasInstalledPackage ? OPENAI_COMPATIBLE_OVERRIDES[normalizedId]?.apiKeyHeader || "Authorization" : void 0;
3114
+ providerConfigs[normalizedId] = {
3115
+ url,
3116
+ apiKeyEnvVar,
3117
+ apiKeyHeader,
3118
+ name: providerInfo.name || providerId.charAt(0).toUpperCase() + providerId.slice(1),
3119
+ models: modelIds,
3120
+ docUrl: providerInfo.doc,
3121
+ // Include documentation URL if available
3122
+ gateway: `models.dev`
3123
+ };
3124
+ }
3125
+ }
3126
+ this.providerConfigs = providerConfigs;
3127
+ return providerConfigs;
3128
+ }
3129
+ buildUrl(routerId, envVars) {
3130
+ const { providerId } = parseModelRouterId(routerId);
3131
+ const config = this.providerConfigs[providerId];
3132
+ if (!config?.url) {
3133
+ return;
3134
+ }
3135
+ const baseUrlEnvVar = `${providerId.toUpperCase().replace(/-/g, "_")}_BASE_URL`;
3136
+ const customBaseUrl = envVars?.[baseUrlEnvVar] || process.env[baseUrlEnvVar];
3137
+ return customBaseUrl || config.url;
3138
+ }
3139
+ getApiKey(modelId) {
3140
+ const [provider, model] = modelId.split("/");
3141
+ if (!provider || !model) {
3142
+ throw new Error(`Could not identify provider from model id ${modelId}`);
3143
+ }
3144
+ const config = this.providerConfigs[provider];
3145
+ if (!config) {
3146
+ throw new Error(`Could not find config for provider ${provider} with model id ${modelId}`);
3147
+ }
3148
+ const apiKey = typeof config.apiKeyEnvVar === `string` ? process.env[config.apiKeyEnvVar] : void 0;
3149
+ if (!apiKey) {
3150
+ throw new Error(`Could not find API key process.env.${config.apiKeyEnvVar} for model id ${modelId}`);
3151
+ }
3152
+ return Promise.resolve(apiKey);
3153
+ }
3154
+ async resolveLanguageModel({
3155
+ modelId,
3156
+ providerId,
3157
+ apiKey
3158
+ }) {
3159
+ const baseURL = this.buildUrl(`${providerId}/${modelId}`);
3160
+ switch (providerId) {
3161
+ case "openai":
3162
+ return chunk3ZEJSGTJ_cjs.createOpenAI({ apiKey }).responses(modelId);
3163
+ case "gemini":
3164
+ case "google":
3165
+ return chunk3ZEJSGTJ_cjs.createGoogleGenerativeAI({
3166
+ apiKey
3167
+ }).chat(modelId);
3168
+ case "anthropic":
3169
+ return chunk3ZEJSGTJ_cjs.createAnthropic({ apiKey })(modelId);
3170
+ case "openrouter":
3171
+ return createOpenRouter({ apiKey })(modelId);
3172
+ case "xai":
3173
+ return createXai({
3174
+ apiKey
3175
+ })(modelId);
3176
+ default:
3177
+ if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
3178
+ return chunk3ZEJSGTJ_cjs.createOpenAICompatible({ name: providerId, apiKey, baseURL }).chatModel(modelId);
3179
+ }
3180
+ }
3181
+ };
3182
+
3183
+ exports.ModelsDevGateway = ModelsDevGateway;
3184
+ exports.parseModelRouterId = parseModelRouterId;
3185
+ //# sourceMappingURL=chunk-QMKBXESK.cjs.map
3186
+ //# sourceMappingURL=chunk-QMKBXESK.cjs.map