@mastra/core 1.0.0-beta.11 → 1.0.0-beta.14

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 (447) hide show
  1. package/CHANGELOG.md +343 -0
  2. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +7549 -0
  3. package/dist/_types/@internal_ai-sdk-v4/dist/test.d.ts +65 -0
  4. package/dist/_types/@internal_ai-sdk-v5/dist/index.d.ts +8396 -0
  5. package/dist/_types/@internal_ai-sdk-v5/dist/test.d.ts +1708 -0
  6. package/dist/_types/@internal_external-types/dist/index.d.ts +858 -0
  7. package/dist/agent/agent-legacy.d.ts +1 -1
  8. package/dist/agent/agent.d.ts +3 -3
  9. package/dist/agent/agent.d.ts.map +1 -1
  10. package/dist/agent/agent.types.d.ts +11 -8
  11. package/dist/agent/agent.types.d.ts.map +1 -1
  12. package/dist/agent/index.cjs +17 -9
  13. package/dist/agent/index.d.ts +1 -1
  14. package/dist/agent/index.d.ts.map +1 -1
  15. package/dist/agent/index.js +2 -2
  16. package/dist/agent/message-list/index.cjs +3 -3
  17. package/dist/agent/message-list/index.d.ts +4 -3
  18. package/dist/agent/message-list/index.d.ts.map +1 -1
  19. package/dist/agent/message-list/index.js +1 -1
  20. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +1 -1
  21. package/dist/agent/message-list/prompt/invalid-content-error.d.ts +1 -1
  22. package/dist/agent/message-list/types.d.ts +3 -3
  23. package/dist/agent/message-list/types.d.ts.map +1 -1
  24. package/dist/agent/message-list/utils/ai-v4-v5/core-model-message.d.ts +1 -1
  25. package/dist/agent/message-list/utils/ai-v4-v5/ui-message.d.ts +1 -1
  26. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts +2 -2
  27. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts.map +1 -1
  28. package/dist/agent/message-list/utils/convert-messages.d.ts +2 -2
  29. package/dist/agent/message-list/utils/convert-messages.d.ts.map +1 -1
  30. package/dist/agent/trip-wire.d.ts +2 -2
  31. package/dist/agent/trip-wire.d.ts.map +1 -1
  32. package/dist/agent/types.d.ts +3 -3
  33. package/dist/agent/utils.d.ts +7 -4
  34. package/dist/agent/utils.d.ts.map +1 -1
  35. package/dist/agent/workflows/prepare-stream/index.d.ts +4 -3
  36. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  37. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts +3 -3
  38. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  39. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +3 -3
  40. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts.map +1 -1
  41. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +3 -3
  42. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  43. package/dist/agent/workflows/prepare-stream/stream-step.d.ts +3 -1
  44. package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
  45. package/dist/bundler/types.d.ts +15 -1
  46. package/dist/bundler/types.d.ts.map +1 -1
  47. package/dist/chunk-2AU5ZHBL.js +79 -0
  48. package/dist/chunk-2AU5ZHBL.js.map +1 -0
  49. package/dist/chunk-2SQB3WBT.js +4574 -0
  50. package/dist/chunk-2SQB3WBT.js.map +1 -0
  51. package/dist/{chunk-THZTRBFS.js → chunk-373OC54J.js} +8 -8
  52. package/dist/chunk-373OC54J.js.map +1 -0
  53. package/dist/{chunk-US2U7ECW.js → chunk-3IP3DZ7G.js} +234 -101
  54. package/dist/chunk-3IP3DZ7G.js.map +1 -0
  55. package/dist/{chunk-SXNQRJQD.js → chunk-4AT6YQKZ.js} +26 -20
  56. package/dist/chunk-4AT6YQKZ.js.map +1 -0
  57. package/dist/{chunk-C36YRTZ6.js → chunk-4CMIJQF6.js} +117 -114
  58. package/dist/chunk-4CMIJQF6.js.map +1 -0
  59. package/dist/chunk-53SZJCBX.cjs +4888 -0
  60. package/dist/chunk-53SZJCBX.cjs.map +1 -0
  61. package/dist/chunk-55VPMN3N.js +250 -0
  62. package/dist/chunk-55VPMN3N.js.map +1 -0
  63. package/dist/{chunk-QM5SRDJX.js → chunk-5PTZG26U.js} +66 -84
  64. package/dist/chunk-5PTZG26U.js.map +1 -0
  65. package/dist/{chunk-U3XOLEPX.js → chunk-5UQ5TB6J.js} +6 -32
  66. package/dist/chunk-5UQ5TB6J.js.map +1 -0
  67. package/dist/{chunk-O2BJW7YA.js → chunk-67LM2UCT.js} +9 -9
  68. package/dist/chunk-67LM2UCT.js.map +1 -0
  69. package/dist/{chunk-YC6PJEPH.cjs → chunk-6CG7IY57.cjs} +266 -133
  70. package/dist/chunk-6CG7IY57.cjs.map +1 -0
  71. package/dist/chunk-6PMMP3FR.js +7 -0
  72. package/dist/chunk-6PMMP3FR.js.map +1 -0
  73. package/dist/{chunk-DZUJEN5N.cjs → chunk-6SZKM6EC.cjs} +10 -3
  74. package/dist/{chunk-DZUJEN5N.cjs.map → chunk-6SZKM6EC.cjs.map} +1 -1
  75. package/dist/{chunk-5Q6WAYEY.cjs → chunk-72E3YF6A.cjs} +35 -49
  76. package/dist/chunk-72E3YF6A.cjs.map +1 -0
  77. package/dist/{chunk-5WRI5ZAA.js → chunk-7D4SUZUM.js} +10 -4
  78. package/dist/{chunk-5WRI5ZAA.js.map → chunk-7D4SUZUM.js.map} +1 -1
  79. package/dist/{chunk-7P6BNIJH.js → chunk-AYBJ5GAD.js} +281 -35
  80. package/dist/chunk-AYBJ5GAD.js.map +1 -0
  81. package/dist/chunk-D22XABFZ.js +79 -0
  82. package/dist/chunk-D22XABFZ.js.map +1 -0
  83. package/dist/{chunk-SCUWP4II.cjs → chunk-DBW6S25C.cjs} +47 -74
  84. package/dist/chunk-DBW6S25C.cjs.map +1 -0
  85. package/dist/{chunk-MRFUISXC.cjs → chunk-EGHGFLL3.cjs} +2631 -179
  86. package/dist/chunk-EGHGFLL3.cjs.map +1 -0
  87. package/dist/{chunk-BJXKH4LG.cjs → chunk-ETWAR2YE.cjs} +43 -78
  88. package/dist/chunk-ETWAR2YE.cjs.map +1 -0
  89. package/dist/{chunk-CZEJQSWB.cjs → chunk-F75EQ574.cjs} +65 -6
  90. package/dist/chunk-F75EQ574.cjs.map +1 -0
  91. package/dist/{chunk-BUKY6CTR.cjs → chunk-FPDJ4XN6.cjs} +282 -36
  92. package/dist/chunk-FPDJ4XN6.cjs.map +1 -0
  93. package/dist/chunk-FST2G2FQ.cjs +84 -0
  94. package/dist/chunk-FST2G2FQ.cjs.map +1 -0
  95. package/dist/chunk-FVQTJUBD.cjs +2120 -0
  96. package/dist/chunk-FVQTJUBD.cjs.map +1 -0
  97. package/dist/chunk-G6E6V2Z4.js +2070 -0
  98. package/dist/chunk-G6E6V2Z4.js.map +1 -0
  99. package/dist/{chunk-JIGDJK2O.js → chunk-GBQXIVL6.js} +4 -39
  100. package/dist/chunk-GBQXIVL6.js.map +1 -0
  101. package/dist/{chunk-F2GAJSBI.js → chunk-GELVUDUY.js} +11 -8
  102. package/dist/chunk-GELVUDUY.js.map +1 -0
  103. package/dist/chunk-GVAPYQRO.cjs +252 -0
  104. package/dist/chunk-GVAPYQRO.cjs.map +1 -0
  105. package/dist/{chunk-TWH4PTDG.cjs → chunk-HWMMIRIF.cjs} +32 -27
  106. package/dist/chunk-HWMMIRIF.cjs.map +1 -0
  107. package/dist/{chunk-52RSUALV.cjs → chunk-JAGQZZ43.cjs} +1660 -1196
  108. package/dist/chunk-JAGQZZ43.cjs.map +1 -0
  109. package/dist/{chunk-PK2A5WBG.js → chunk-K66U47VL.js} +54 -7
  110. package/dist/chunk-K66U47VL.js.map +1 -0
  111. package/dist/chunk-L3NKIMF5.cjs +10 -0
  112. package/dist/chunk-L3NKIMF5.cjs.map +1 -0
  113. package/dist/chunk-L4JCRWDY.cjs +252 -0
  114. package/dist/chunk-L4JCRWDY.cjs.map +1 -0
  115. package/dist/{chunk-IVV5TOMD.js → chunk-LDXKZYOV.js} +31 -11
  116. package/dist/chunk-LDXKZYOV.js.map +1 -0
  117. package/dist/chunk-NESKUIRE.cjs +4586 -0
  118. package/dist/chunk-NESKUIRE.cjs.map +1 -0
  119. package/dist/{chunk-SVLMF4UZ.cjs → chunk-NIOEY3N3.cjs} +66 -85
  120. package/dist/chunk-NIOEY3N3.cjs.map +1 -0
  121. package/dist/{chunk-PG5H6QIO.cjs → chunk-O3ULBGV6.cjs} +40 -20
  122. package/dist/chunk-O3ULBGV6.cjs.map +1 -0
  123. package/dist/{chunk-WTSZBHIZ.cjs → chunk-O5BQBZEF.cjs} +28 -28
  124. package/dist/chunk-O5BQBZEF.cjs.map +1 -0
  125. package/dist/{chunk-4JKEUSCC.cjs → chunk-OOUFPYSX.cjs} +25 -22
  126. package/dist/chunk-OOUFPYSX.cjs.map +1 -0
  127. package/dist/chunk-QDVYP2T7.js +4883 -0
  128. package/dist/chunk-QDVYP2T7.js.map +1 -0
  129. package/dist/{chunk-2ULLRN4Y.js → chunk-QF4MHFSU.js} +1294 -834
  130. package/dist/chunk-QF4MHFSU.js.map +1 -0
  131. package/dist/{chunk-Z57R5WS4.js → chunk-SLBWA2F3.js} +4 -4
  132. package/dist/{chunk-Z57R5WS4.js.map → chunk-SLBWA2F3.js.map} +1 -1
  133. package/dist/chunk-ST7NBF4H.cjs +84 -0
  134. package/dist/chunk-ST7NBF4H.cjs.map +1 -0
  135. package/dist/{chunk-YWMMBIOM.cjs → chunk-TDM43G4I.cjs} +15 -15
  136. package/dist/{chunk-YWMMBIOM.cjs.map → chunk-TDM43G4I.cjs.map} +1 -1
  137. package/dist/{chunk-S73Z3PBJ.cjs → chunk-TRUNX3AX.cjs} +138 -134
  138. package/dist/chunk-TRUNX3AX.cjs.map +1 -0
  139. package/dist/chunk-VE6HQ7H6.js +250 -0
  140. package/dist/chunk-VE6HQ7H6.js.map +1 -0
  141. package/dist/{chunk-OEIVMCWX.js → chunk-VZJOEGQA.js} +2536 -84
  142. package/dist/chunk-VZJOEGQA.js.map +1 -0
  143. package/dist/{chunk-JJ5O45LH.js → chunk-YPLZDWG7.js} +32 -27
  144. package/dist/chunk-YPLZDWG7.js.map +1 -0
  145. package/dist/{chunk-MGCGWPQJ.cjs → chunk-Z55SJVEC.cjs} +8 -8
  146. package/dist/chunk-Z55SJVEC.cjs.map +1 -0
  147. package/dist/error/index.cjs +6 -6
  148. package/dist/error/index.d.ts +26 -20
  149. package/dist/error/index.d.ts.map +1 -1
  150. package/dist/error/index.js +1 -1
  151. package/dist/error/utils.d.ts +19 -5
  152. package/dist/error/utils.d.ts.map +1 -1
  153. package/dist/evals/index.cjs +4 -4
  154. package/dist/evals/index.js +1 -1
  155. package/dist/evals/run/index.d.ts +1 -1
  156. package/dist/evals/run/index.d.ts.map +1 -1
  157. package/dist/evals/scoreTraces/index.cjs +8 -8
  158. package/dist/evals/scoreTraces/index.js +2 -2
  159. package/dist/evals/types.d.ts +1 -1
  160. package/dist/events/event-emitter.d.ts +6 -1
  161. package/dist/events/event-emitter.d.ts.map +1 -1
  162. package/dist/index.cjs +2 -2
  163. package/dist/index.js +1 -1
  164. package/dist/integration/index.cjs +2 -2
  165. package/dist/integration/index.js +1 -1
  166. package/dist/llm/index.cjs +15 -15
  167. package/dist/llm/index.d.ts +2 -2
  168. package/dist/llm/index.d.ts.map +1 -1
  169. package/dist/llm/index.js +5 -5
  170. package/dist/llm/model/aisdk/generate-to-stream.d.ts +20 -0
  171. package/dist/llm/model/aisdk/generate-to-stream.d.ts.map +1 -0
  172. package/dist/llm/model/aisdk/v5/model.d.ts +5 -1
  173. package/dist/llm/model/aisdk/v5/model.d.ts.map +1 -1
  174. package/dist/llm/model/aisdk/v6/model.d.ts +51 -0
  175. package/dist/llm/model/aisdk/v6/model.d.ts.map +1 -0
  176. package/dist/llm/model/base.types.d.ts +2 -2
  177. package/dist/llm/model/model.d.ts +1 -1
  178. package/dist/llm/model/model.d.ts.map +1 -1
  179. package/dist/llm/model/model.loop.d.ts +3 -3
  180. package/dist/llm/model/model.loop.d.ts.map +1 -1
  181. package/dist/llm/model/model.loop.types.d.ts +1 -1
  182. package/dist/llm/model/model.loop.types.d.ts.map +1 -1
  183. package/dist/llm/model/provider-types.generated.d.ts +135 -11
  184. package/dist/llm/model/resolve-model.d.ts +2 -2
  185. package/dist/llm/model/resolve-model.d.ts.map +1 -1
  186. package/dist/llm/model/shared.types.d.ts +19 -8
  187. package/dist/llm/model/shared.types.d.ts.map +1 -1
  188. package/dist/loop/index.cjs +2 -2
  189. package/dist/loop/index.js +1 -1
  190. package/dist/loop/loop.d.ts +2 -2
  191. package/dist/loop/loop.d.ts.map +1 -1
  192. package/dist/loop/network/index.d.ts +2 -2
  193. package/dist/loop/network/index.d.ts.map +1 -1
  194. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts +2 -2
  195. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts.map +1 -1
  196. package/dist/loop/test-utils/MastraLanguageModelV3Mock.d.ts +37 -0
  197. package/dist/loop/test-utils/MastraLanguageModelV3Mock.d.ts.map +1 -0
  198. package/dist/loop/test-utils/fullStream.d.ts +2 -1
  199. package/dist/loop/test-utils/fullStream.d.ts.map +1 -1
  200. package/dist/loop/test-utils/options.d.ts.map +1 -1
  201. package/dist/loop/test-utils/resultObject.d.ts +2 -1
  202. package/dist/loop/test-utils/resultObject.d.ts.map +1 -1
  203. package/dist/loop/test-utils/streamObject.d.ts +1 -1
  204. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  205. package/dist/loop/test-utils/tools.d.ts.map +1 -1
  206. package/dist/loop/test-utils/utils-v3.d.ts +55 -0
  207. package/dist/loop/test-utils/utils-v3.d.ts.map +1 -0
  208. package/dist/loop/types.d.ts +8 -7
  209. package/dist/loop/types.d.ts.map +1 -1
  210. package/dist/loop/workflows/agentic-execution/index.d.ts +49 -49
  211. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  212. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +34 -34
  213. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  214. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +17 -17
  215. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  216. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +22 -21
  217. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  218. package/dist/loop/workflows/agentic-loop/index.d.ts +49 -49
  219. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  220. package/dist/loop/workflows/run-state.d.ts +2 -2
  221. package/dist/loop/workflows/run-state.d.ts.map +1 -1
  222. package/dist/loop/workflows/schema.d.ts +18 -18
  223. package/dist/loop/workflows/schema.d.ts.map +1 -1
  224. package/dist/loop/workflows/stream.d.ts +2 -2
  225. package/dist/loop/workflows/stream.d.ts.map +1 -1
  226. package/dist/mastra/index.cjs +2 -2
  227. package/dist/mastra/index.js +1 -1
  228. package/dist/mcp/index.cjs +4 -4
  229. package/dist/mcp/index.js +1 -1
  230. package/dist/memory/index.cjs +6 -6
  231. package/dist/memory/index.js +1 -1
  232. package/dist/memory/memory.d.ts +1 -1
  233. package/dist/memory/types.d.ts +3 -3
  234. package/dist/memory/types.d.ts.map +1 -1
  235. package/dist/models-dev-E3WWI7VA.js +3 -0
  236. package/dist/{models-dev-23RN2WHG.js.map → models-dev-E3WWI7VA.js.map} +1 -1
  237. package/dist/models-dev-PPS7X4JM.cjs +12 -0
  238. package/dist/{models-dev-EO3SUIY2.cjs.map → models-dev-PPS7X4JM.cjs.map} +1 -1
  239. package/dist/netlify-TY656UYF.js +3 -0
  240. package/dist/{netlify-GXJ5D5DD.js.map → netlify-TY656UYF.js.map} +1 -1
  241. package/dist/netlify-VZFM5UH3.cjs +12 -0
  242. package/dist/{netlify-KJLY3GFS.cjs.map → netlify-VZFM5UH3.cjs.map} +1 -1
  243. package/dist/processors/index.cjs +37 -37
  244. package/dist/processors/index.d.ts +9 -9
  245. package/dist/processors/index.d.ts.map +1 -1
  246. package/dist/processors/index.js +1 -1
  247. package/dist/processors/runner.d.ts.map +1 -1
  248. package/dist/processors/step-schema.d.ts +1293 -1293
  249. package/dist/processors/step-schema.d.ts.map +1 -1
  250. package/dist/provider-registry-NXVD764B.js +3 -0
  251. package/dist/{provider-registry-F67Y6OF2.js.map → provider-registry-NXVD764B.js.map} +1 -1
  252. package/dist/provider-registry-ZIWSEUQE.cjs +40 -0
  253. package/dist/{provider-registry-3TG2KUD2.cjs.map → provider-registry-ZIWSEUQE.cjs.map} +1 -1
  254. package/dist/provider-registry.json +276 -30
  255. package/dist/{registry-generator-UMTNPBJX.js → registry-generator-AVQXI3GX.js} +2 -2
  256. package/dist/{registry-generator-UMTNPBJX.js.map → registry-generator-AVQXI3GX.js.map} +1 -1
  257. package/dist/{registry-generator-34SC4TAU.cjs → registry-generator-KOFNIIWJ.cjs} +2 -2
  258. package/dist/{registry-generator-34SC4TAU.cjs.map → registry-generator-KOFNIIWJ.cjs.map} +1 -1
  259. package/dist/relevance/index.cjs +3 -3
  260. package/dist/relevance/index.cjs.map +1 -1
  261. package/dist/relevance/index.js +2 -2
  262. package/dist/relevance/index.js.map +1 -1
  263. package/dist/server/index.cjs +5 -5
  264. package/dist/server/index.js +1 -1
  265. package/dist/storage/base.d.ts +2 -10
  266. package/dist/storage/base.d.ts.map +1 -1
  267. package/dist/storage/domains/workflows/base.d.ts +2 -8
  268. package/dist/storage/domains/workflows/base.d.ts.map +1 -1
  269. package/dist/storage/domains/workflows/inmemory.d.ts +2 -8
  270. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  271. package/dist/storage/index.cjs +38 -38
  272. package/dist/storage/index.js +1 -1
  273. package/dist/storage/mock.d.ts +2 -8
  274. package/dist/storage/mock.d.ts.map +1 -1
  275. package/dist/storage/types.d.ts +9 -1
  276. package/dist/storage/types.d.ts.map +1 -1
  277. package/dist/stream/RunOutput.d.ts +1 -1
  278. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  279. package/dist/stream/aisdk/v5/compat/content.d.ts +1 -1
  280. package/dist/stream/aisdk/v5/compat/content.d.ts.map +1 -1
  281. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts +1 -1
  282. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
  283. package/dist/stream/aisdk/v5/compat/ui-message.d.ts +1 -1
  284. package/dist/stream/aisdk/v5/compat/ui-message.d.ts.map +1 -1
  285. package/dist/stream/aisdk/v5/compat/validation.d.ts +1 -1
  286. package/dist/stream/aisdk/v5/compat/validation.d.ts.map +1 -1
  287. package/dist/stream/aisdk/v5/execute.d.ts +6 -6
  288. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  289. package/dist/stream/aisdk/v5/input.d.ts +1 -1
  290. package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
  291. package/dist/stream/aisdk/v5/output-helpers.d.ts +12 -27
  292. package/dist/stream/aisdk/v5/output-helpers.d.ts.map +1 -1
  293. package/dist/stream/aisdk/v5/output.d.ts +41 -91
  294. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  295. package/dist/stream/aisdk/v5/transform.d.ts +1 -1
  296. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  297. package/dist/stream/base/input.d.ts +1 -1
  298. package/dist/stream/base/output.d.ts +16 -36
  299. package/dist/stream/base/output.d.ts.map +1 -1
  300. package/dist/stream/base/schema.d.ts +2 -2
  301. package/dist/stream/base/schema.d.ts.map +1 -1
  302. package/dist/stream/index.cjs +12 -12
  303. package/dist/stream/index.js +2 -2
  304. package/dist/stream/types.d.ts +32 -23
  305. package/dist/stream/types.d.ts.map +1 -1
  306. package/dist/test-utils/llm-mock.cjs +14587 -14
  307. package/dist/test-utils/llm-mock.cjs.map +1 -1
  308. package/dist/test-utils/llm-mock.d.ts +3 -3
  309. package/dist/test-utils/llm-mock.d.ts.map +1 -1
  310. package/dist/test-utils/llm-mock.js +14577 -4
  311. package/dist/test-utils/llm-mock.js.map +1 -1
  312. package/dist/token-6GSAFR2W-LTZ7QQUP.js +61 -0
  313. package/dist/token-6GSAFR2W-LTZ7QQUP.js.map +1 -0
  314. package/dist/token-6GSAFR2W-SGVIXFCP.cjs +63 -0
  315. package/dist/token-6GSAFR2W-SGVIXFCP.cjs.map +1 -0
  316. package/dist/token-6GSAFR2W-SPYPLMBM.js +61 -0
  317. package/dist/token-6GSAFR2W-SPYPLMBM.js.map +1 -0
  318. package/dist/token-6GSAFR2W-UEEINYAN.cjs +63 -0
  319. package/dist/token-6GSAFR2W-UEEINYAN.cjs.map +1 -0
  320. package/dist/token-util-NEHG7TUY-7GMW5FXI.cjs +10 -0
  321. package/dist/token-util-NEHG7TUY-7GMW5FXI.cjs.map +1 -0
  322. package/dist/token-util-NEHG7TUY-JRJTGTAB.js +8 -0
  323. package/dist/token-util-NEHG7TUY-JRJTGTAB.js.map +1 -0
  324. package/dist/token-util-NEHG7TUY-QTFZ26EN.js +8 -0
  325. package/dist/token-util-NEHG7TUY-QTFZ26EN.js.map +1 -0
  326. package/dist/token-util-NEHG7TUY-WZL2DNCG.cjs +10 -0
  327. package/dist/token-util-NEHG7TUY-WZL2DNCG.cjs.map +1 -0
  328. package/dist/tools/index.cjs +4 -4
  329. package/dist/tools/index.js +1 -1
  330. package/dist/tools/is-vercel-tool.cjs +2 -2
  331. package/dist/tools/is-vercel-tool.js +1 -1
  332. package/dist/tools/tool-builder/builder.d.ts +2 -1
  333. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  334. package/dist/tools/tool.d.ts.map +1 -1
  335. package/dist/tools/types.d.ts +5 -5
  336. package/dist/tools/types.d.ts.map +1 -1
  337. package/dist/utils.cjs +22 -22
  338. package/dist/utils.d.ts +5 -5
  339. package/dist/utils.d.ts.map +1 -1
  340. package/dist/utils.js +1 -1
  341. package/dist/vector/embed.d.ts +3 -2
  342. package/dist/vector/embed.d.ts.map +1 -1
  343. package/dist/vector/index.cjs +5316 -16
  344. package/dist/vector/index.cjs.map +1 -1
  345. package/dist/vector/index.js +5282 -4
  346. package/dist/vector/index.js.map +1 -1
  347. package/dist/vector/vector.d.ts +15 -2
  348. package/dist/vector/vector.d.ts.map +1 -1
  349. package/dist/voice/aisdk/speech.d.ts +1 -1
  350. package/dist/voice/aisdk/speech.d.ts.map +1 -1
  351. package/dist/voice/aisdk/transcription.d.ts +1 -1
  352. package/dist/voice/aisdk/transcription.d.ts.map +1 -1
  353. package/dist/voice/composite-voice.d.ts +1 -1
  354. package/dist/voice/composite-voice.d.ts.map +1 -1
  355. package/dist/voice/index.cjs +6 -6
  356. package/dist/voice/index.js +1 -1
  357. package/dist/workflows/constants.cjs +4 -4
  358. package/dist/workflows/constants.d.ts +1 -1
  359. package/dist/workflows/constants.d.ts.map +1 -1
  360. package/dist/workflows/constants.js +1 -1
  361. package/dist/workflows/default.d.ts +9 -16
  362. package/dist/workflows/default.d.ts.map +1 -1
  363. package/dist/workflows/evented/execution-engine.d.ts +3 -2
  364. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  365. package/dist/workflows/evented/index.cjs +10 -10
  366. package/dist/workflows/evented/index.js +1 -1
  367. package/dist/workflows/evented/step-executor.d.ts +5 -1
  368. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  369. package/dist/workflows/evented/workflow-event-processor/index.d.ts +16 -1
  370. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  371. package/dist/workflows/evented/workflow.d.ts +20 -0
  372. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  373. package/dist/workflows/execution-engine.d.ts +25 -2
  374. package/dist/workflows/execution-engine.d.ts.map +1 -1
  375. package/dist/workflows/handlers/control-flow.d.ts +6 -5
  376. package/dist/workflows/handlers/control-flow.d.ts.map +1 -1
  377. package/dist/workflows/handlers/entry.d.ts +5 -3
  378. package/dist/workflows/handlers/entry.d.ts.map +1 -1
  379. package/dist/workflows/handlers/sleep.d.ts +4 -3
  380. package/dist/workflows/handlers/sleep.d.ts.map +1 -1
  381. package/dist/workflows/handlers/step.d.ts +5 -3
  382. package/dist/workflows/handlers/step.d.ts.map +1 -1
  383. package/dist/workflows/index.cjs +26 -22
  384. package/dist/workflows/index.js +1 -1
  385. package/dist/workflows/step.d.ts +5 -4
  386. package/dist/workflows/step.d.ts.map +1 -1
  387. package/dist/workflows/types.d.ts +66 -14
  388. package/dist/workflows/types.d.ts.map +1 -1
  389. package/dist/workflows/utils.d.ts +11 -0
  390. package/dist/workflows/utils.d.ts.map +1 -1
  391. package/dist/workflows/workflow.d.ts +30 -9
  392. package/dist/workflows/workflow.d.ts.map +1 -1
  393. package/package.json +13 -14
  394. package/src/llm/model/provider-types.generated.d.ts +135 -11
  395. package/dist/agent/__tests__/mock-model.d.ts +0 -8
  396. package/dist/agent/__tests__/mock-model.d.ts.map +0 -1
  397. package/dist/agent/agent-types.test-d.d.ts +0 -2
  398. package/dist/agent/agent-types.test-d.d.ts.map +0 -1
  399. package/dist/ai-sdk.types.d.ts +0 -4705
  400. package/dist/chunk-2ULLRN4Y.js.map +0 -1
  401. package/dist/chunk-3E3ILV6T.cjs +0 -518
  402. package/dist/chunk-3E3ILV6T.cjs.map +0 -1
  403. package/dist/chunk-4JKEUSCC.cjs.map +0 -1
  404. package/dist/chunk-52RSUALV.cjs.map +0 -1
  405. package/dist/chunk-5PAEYE3Q.js +0 -513
  406. package/dist/chunk-5PAEYE3Q.js.map +0 -1
  407. package/dist/chunk-5Q6WAYEY.cjs.map +0 -1
  408. package/dist/chunk-7P6BNIJH.js.map +0 -1
  409. package/dist/chunk-ABJOUEVA.cjs +0 -10
  410. package/dist/chunk-ABJOUEVA.cjs.map +0 -1
  411. package/dist/chunk-BJXKH4LG.cjs.map +0 -1
  412. package/dist/chunk-BUKY6CTR.cjs.map +0 -1
  413. package/dist/chunk-C36YRTZ6.js.map +0 -1
  414. package/dist/chunk-CZEJQSWB.cjs.map +0 -1
  415. package/dist/chunk-F2GAJSBI.js.map +0 -1
  416. package/dist/chunk-IVV5TOMD.js.map +0 -1
  417. package/dist/chunk-JIGDJK2O.js.map +0 -1
  418. package/dist/chunk-JJ5O45LH.js.map +0 -1
  419. package/dist/chunk-MGCGWPQJ.cjs.map +0 -1
  420. package/dist/chunk-MRFUISXC.cjs.map +0 -1
  421. package/dist/chunk-NLNKQD2T.js +0 -7
  422. package/dist/chunk-NLNKQD2T.js.map +0 -1
  423. package/dist/chunk-O2BJW7YA.js.map +0 -1
  424. package/dist/chunk-OEIVMCWX.js.map +0 -1
  425. package/dist/chunk-PG5H6QIO.cjs.map +0 -1
  426. package/dist/chunk-PK2A5WBG.js.map +0 -1
  427. package/dist/chunk-QM5SRDJX.js.map +0 -1
  428. package/dist/chunk-S73Z3PBJ.cjs.map +0 -1
  429. package/dist/chunk-SCUWP4II.cjs.map +0 -1
  430. package/dist/chunk-SVLMF4UZ.cjs.map +0 -1
  431. package/dist/chunk-SXNQRJQD.js.map +0 -1
  432. package/dist/chunk-THZTRBFS.js.map +0 -1
  433. package/dist/chunk-TWH4PTDG.cjs.map +0 -1
  434. package/dist/chunk-U3XOLEPX.js.map +0 -1
  435. package/dist/chunk-US2U7ECW.js.map +0 -1
  436. package/dist/chunk-WTSZBHIZ.cjs.map +0 -1
  437. package/dist/chunk-YC6PJEPH.cjs.map +0 -1
  438. package/dist/llm/model/is-v2-model.d.ts +0 -3
  439. package/dist/llm/model/is-v2-model.d.ts.map +0 -1
  440. package/dist/models-dev-23RN2WHG.js +0 -3
  441. package/dist/models-dev-EO3SUIY2.cjs +0 -12
  442. package/dist/netlify-GXJ5D5DD.js +0 -3
  443. package/dist/netlify-KJLY3GFS.cjs +0 -12
  444. package/dist/provider-registry-3TG2KUD2.cjs +0 -40
  445. package/dist/provider-registry-F67Y6OF2.js +0 -3
  446. package/dist/tools/tool-stream-types.test-d.d.ts +0 -2
  447. package/dist/tools/tool-stream-types.test-d.d.ts.map +0 -1
@@ -1,9 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkCZEJQSWB_cjs = require('./chunk-CZEJQSWB.cjs');
3
+ var chunkF75EQ574_cjs = require('./chunk-F75EQ574.cjs');
4
4
  var z4 = require('zod/v4');
5
5
  var v3 = require('zod/v3');
6
- var aiSdkProviderV5 = require('@openrouter/ai-sdk-provider-v5');
7
6
 
8
7
  function _interopNamespace(e) {
9
8
  if (e && e.__esModule) return e;
@@ -55,7 +54,7 @@ var createIdGenerator = ({
55
54
  return generator;
56
55
  }
57
56
  if (alphabet.includes(separator)) {
58
- throw new chunkCZEJQSWB_cjs.InvalidArgumentError({
57
+ throw new chunkF75EQ574_cjs.InvalidArgumentError({
59
58
  argument: "separator",
60
59
  message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
61
60
  });
@@ -79,7 +78,7 @@ function handleFetchError({
79
78
  if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
80
79
  const cause = error.cause;
81
80
  if (cause != null) {
82
- return new chunkCZEJQSWB_cjs.APICallError({
81
+ return new chunkF75EQ574_cjs.APICallError({
83
82
  message: `Cannot connect to API: ${cause.message}`,
84
83
  cause,
85
84
  url,
@@ -92,11 +91,11 @@ function handleFetchError({
92
91
  return error;
93
92
  }
94
93
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
95
- var _a, _b, _c;
94
+ var _a15, _b, _c;
96
95
  if (globalThisAny.window) {
97
96
  return `runtime/browser`;
98
97
  }
99
- if ((_a = globalThisAny.navigator) == null ? void 0 : _a.userAgent) {
98
+ if ((_a15 = globalThisAny.navigator) == null ? void 0 : _a15.userAgent) {
100
99
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
101
100
  }
102
101
  if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) {
@@ -148,23 +147,23 @@ function loadApiKey2({
148
147
  return apiKey;
149
148
  }
150
149
  if (apiKey != null) {
151
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
150
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
152
151
  message: `${description} API key must be a string.`
153
152
  });
154
153
  }
155
154
  if (typeof process === "undefined") {
156
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
155
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
157
156
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
158
157
  });
159
158
  }
160
159
  apiKey = process.env[environmentVariableName];
161
160
  if (apiKey == null) {
162
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
161
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
163
162
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
164
163
  });
165
164
  }
166
165
  if (typeof apiKey !== "string") {
167
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
166
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
168
167
  message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
169
168
  });
170
169
  }
@@ -232,7 +231,7 @@ function standardSchemaValidator(standardSchema) {
232
231
  const result = await standardSchema["~standard"].validate(value);
233
232
  return result.issues == null ? { success: true, value: result.value } : {
234
233
  success: false,
235
- error: new chunkCZEJQSWB_cjs.TypeValidationError({
234
+ error: new chunkF75EQ574_cjs.TypeValidationError({
236
235
  value,
237
236
  cause: result.issues
238
237
  })
@@ -245,7 +244,7 @@ async function validateTypes({
245
244
  }) {
246
245
  const result = await safeValidateTypes({ value, schema });
247
246
  if (!result.success) {
248
- throw chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error });
247
+ throw chunkF75EQ574_cjs.TypeValidationError.wrap({ value, cause: result.error });
249
248
  }
250
249
  return result.value;
251
250
  }
@@ -264,13 +263,13 @@ async function safeValidateTypes({
264
263
  }
265
264
  return {
266
265
  success: false,
267
- error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error }),
266
+ error: chunkF75EQ574_cjs.TypeValidationError.wrap({ value, cause: result.error }),
268
267
  rawValue: value
269
268
  };
270
269
  } catch (error) {
271
270
  return {
272
271
  success: false,
273
- error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: error }),
272
+ error: chunkF75EQ574_cjs.TypeValidationError.wrap({ value, cause: error }),
274
273
  rawValue: value
275
274
  };
276
275
  }
@@ -286,10 +285,10 @@ async function parseJSON({
286
285
  }
287
286
  return validateTypes({ value, schema });
288
287
  } catch (error) {
289
- if (chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) || chunkCZEJQSWB_cjs.TypeValidationError.isInstance(error)) {
288
+ if (chunkF75EQ574_cjs.JSONParseError.isInstance(error) || chunkF75EQ574_cjs.TypeValidationError.isInstance(error)) {
290
289
  throw error;
291
290
  }
292
- throw new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error });
291
+ throw new chunkF75EQ574_cjs.JSONParseError({ text, cause: error });
293
292
  }
294
293
  }
295
294
  async function safeParseJSON({
@@ -305,7 +304,7 @@ async function safeParseJSON({
305
304
  } catch (error) {
306
305
  return {
307
306
  success: false,
308
- error: chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) ? error : new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error }),
307
+ error: chunkF75EQ574_cjs.JSONParseError.isInstance(error) ? error : new chunkF75EQ574_cjs.JSONParseError({ text, cause: error }),
309
308
  rawValue: void 0
310
309
  };
311
310
  }
@@ -322,7 +321,7 @@ function parseJsonEventStream({
322
321
  stream,
323
322
  schema
324
323
  }) {
325
- return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new chunkCZEJQSWB_cjs.EventSourceParserStream()).pipeThrough(
324
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new chunkF75EQ574_cjs.EventSourceParserStream()).pipeThrough(
326
325
  new TransformStream({
327
326
  async transform({ data }, controller) {
328
327
  if (data === "[DONE]") {
@@ -346,7 +345,7 @@ async function parseProviderOptions2({
346
345
  schema
347
346
  });
348
347
  if (!parsedProviderOptions.success) {
349
- throw new chunkCZEJQSWB_cjs.InvalidArgumentError({
348
+ throw new chunkF75EQ574_cjs.InvalidArgumentError({
350
349
  argument: "providerOptions",
351
350
  message: `invalid ${provider} provider options`,
352
351
  cause: parsedProviderOptions.error
@@ -408,10 +407,10 @@ var postToApi = async ({
408
407
  requestBodyValues: body.values
409
408
  });
410
409
  } catch (error) {
411
- if (isAbortError(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
410
+ if (isAbortError(error) || chunkF75EQ574_cjs.APICallError.isInstance(error)) {
412
411
  throw error;
413
412
  }
414
- throw new chunkCZEJQSWB_cjs.APICallError({
413
+ throw new chunkF75EQ574_cjs.APICallError({
415
414
  message: "Failed to process error response",
416
415
  cause: error,
417
416
  statusCode: response.status,
@@ -430,11 +429,11 @@ var postToApi = async ({
430
429
  });
431
430
  } catch (error) {
432
431
  if (error instanceof Error) {
433
- if (isAbortError(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
432
+ if (isAbortError(error) || chunkF75EQ574_cjs.APICallError.isInstance(error)) {
434
433
  throw error;
435
434
  }
436
435
  }
437
- throw new chunkCZEJQSWB_cjs.APICallError({
436
+ throw new chunkF75EQ574_cjs.APICallError({
438
437
  message: "Failed to process successful response",
439
438
  cause: error,
440
439
  statusCode: response.status,
@@ -457,7 +456,7 @@ var createJsonErrorResponseHandler2 = ({
457
456
  if (responseBody.trim() === "") {
458
457
  return {
459
458
  responseHeaders,
460
- value: new chunkCZEJQSWB_cjs.APICallError({
459
+ value: new chunkF75EQ574_cjs.APICallError({
461
460
  message: response.statusText,
462
461
  url,
463
462
  requestBodyValues,
@@ -475,7 +474,7 @@ var createJsonErrorResponseHandler2 = ({
475
474
  });
476
475
  return {
477
476
  responseHeaders,
478
- value: new chunkCZEJQSWB_cjs.APICallError({
477
+ value: new chunkF75EQ574_cjs.APICallError({
479
478
  message: errorToMessage2(parsedError),
480
479
  url,
481
480
  requestBodyValues,
@@ -489,7 +488,7 @@ var createJsonErrorResponseHandler2 = ({
489
488
  } catch (parseError) {
490
489
  return {
491
490
  responseHeaders,
492
- value: new chunkCZEJQSWB_cjs.APICallError({
491
+ value: new chunkF75EQ574_cjs.APICallError({
493
492
  message: response.statusText,
494
493
  url,
495
494
  requestBodyValues,
@@ -504,7 +503,7 @@ var createJsonErrorResponseHandler2 = ({
504
503
  var createEventSourceResponseHandler2 = (chunkSchema) => async ({ response }) => {
505
504
  const responseHeaders = extractResponseHeaders(response);
506
505
  if (response.body == null) {
507
- throw new chunkCZEJQSWB_cjs.EmptyResponseBodyError({});
506
+ throw new chunkF75EQ574_cjs.EmptyResponseBodyError({});
508
507
  }
509
508
  return {
510
509
  responseHeaders,
@@ -522,7 +521,7 @@ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, req
522
521
  });
523
522
  const responseHeaders = extractResponseHeaders(response);
524
523
  if (!parsedResult.success) {
525
- throw new chunkCZEJQSWB_cjs.APICallError({
524
+ throw new chunkF75EQ574_cjs.APICallError({
526
525
  message: "Invalid JSON response",
527
526
  cause: parsedResult.error,
528
527
  statusCode: response.status,
@@ -580,11 +579,11 @@ function parseAnyDef() {
580
579
  return {};
581
580
  }
582
581
  function parseArrayDef(def, refs) {
583
- var _a, _b, _c;
582
+ var _a15, _b, _c;
584
583
  const res = {
585
584
  type: "array"
586
585
  };
587
- if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) {
586
+ if (((_a15 = def.type) == null ? void 0 : _a15._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) {
588
587
  res.items = parseDef(def.type._def, {
589
588
  ...refs,
590
589
  currentPath: [...refs.currentPath, "items"]
@@ -943,8 +942,8 @@ function escapeNonAlphaNumeric(source) {
943
942
  return result;
944
943
  }
945
944
  function addFormat(schema, value, message, refs) {
946
- var _a;
947
- if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
945
+ var _a15;
946
+ if (schema.format || ((_a15 = schema.anyOf) == null ? void 0 : _a15.some((x) => x.format))) {
948
947
  if (!schema.anyOf) {
949
948
  schema.anyOf = [];
950
949
  }
@@ -963,8 +962,8 @@ function addFormat(schema, value, message, refs) {
963
962
  }
964
963
  }
965
964
  function addPattern(schema, regex, message, refs) {
966
- var _a;
967
- if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
965
+ var _a15;
966
+ if (schema.pattern || ((_a15 = schema.allOf) == null ? void 0 : _a15.some((x) => x.pattern))) {
968
967
  if (!schema.allOf) {
969
968
  schema.allOf = [];
970
969
  }
@@ -983,7 +982,7 @@ function addPattern(schema, regex, message, refs) {
983
982
  }
984
983
  }
985
984
  function stringifyRegExpWithFlags(regex, refs) {
986
- var _a;
985
+ var _a15;
987
986
  if (!refs.applyRegexFlags || !regex.flags) {
988
987
  return regex.source;
989
988
  }
@@ -1013,7 +1012,7 @@ function stringifyRegExpWithFlags(regex, refs) {
1013
1012
  pattern += source[i];
1014
1013
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1015
1014
  inCharRange = false;
1016
- } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
1015
+ } else if (source[i + 1] === "-" && ((_a15 = source[i + 2]) == null ? void 0 : _a15.match(/[a-z]/))) {
1017
1016
  pattern += source[i];
1018
1017
  inCharRange = true;
1019
1018
  } else {
@@ -1055,13 +1054,13 @@ function stringifyRegExpWithFlags(regex, refs) {
1055
1054
  return pattern;
1056
1055
  }
1057
1056
  function parseRecordDef(def, refs) {
1058
- var _a, _b, _c, _d, _e, _f;
1057
+ var _a15, _b, _c, _d, _e, _f;
1059
1058
  const schema = {
1060
1059
  type: "object",
1061
- additionalProperties: (_a = parseDef(def.valueType._def, {
1060
+ additionalProperties: (_a15 = parseDef(def.valueType._def, {
1062
1061
  ...refs,
1063
1062
  currentPath: [...refs.currentPath, "additionalProperties"]
1064
- })) != null ? _a : refs.allowedAdditionalProperties
1063
+ })) != null ? _a15 : refs.allowedAdditionalProperties
1065
1064
  };
1066
1065
  if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1067
1066
  const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
@@ -1318,8 +1317,8 @@ function safeIsOptional(schema) {
1318
1317
  }
1319
1318
  }
1320
1319
  var parseOptionalDef = (def, refs) => {
1321
- var _a;
1322
- if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
1320
+ var _a15;
1321
+ if (refs.currentPath.toString() === ((_a15 = refs.propertyPath) == null ? void 0 : _a15.toString())) {
1323
1322
  return parseDef(def.innerType._def, refs);
1324
1323
  }
1325
1324
  const innerSchema = parseDef(def.innerType._def, {
@@ -1489,10 +1488,10 @@ var selectParser = (def, typeName, refs) => {
1489
1488
  }
1490
1489
  };
1491
1490
  function parseDef(def, refs, forceResolution = false) {
1492
- var _a;
1491
+ var _a15;
1493
1492
  const seenItem = refs.seen.get(def);
1494
1493
  if (refs.override) {
1495
- const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(
1494
+ const overrideResult = (_a15 = refs.override) == null ? void 0 : _a15.call(
1496
1495
  refs,
1497
1496
  def,
1498
1497
  refs,
@@ -1558,11 +1557,11 @@ var getRefs = (options) => {
1558
1557
  currentPath,
1559
1558
  propertyPath: void 0,
1560
1559
  seen: new Map(
1561
- Object.entries(_options.definitions).map(([name, def]) => [
1560
+ Object.entries(_options.definitions).map(([name14, def]) => [
1562
1561
  def._def,
1563
1562
  {
1564
1563
  def: def._def,
1565
- path: [..._options.basePath, _options.definitionPath, name],
1564
+ path: [..._options.basePath, _options.definitionPath, name14],
1566
1565
  // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1567
1566
  jsonSchema: void 0
1568
1567
  }
@@ -1571,50 +1570,50 @@ var getRefs = (options) => {
1571
1570
  };
1572
1571
  };
1573
1572
  var zodToJsonSchema = (schema, options) => {
1574
- var _a;
1573
+ var _a15;
1575
1574
  const refs = getRefs(options);
1576
1575
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1577
- (acc, [name2, schema2]) => {
1578
- var _a2;
1576
+ (acc, [name22, schema2]) => {
1577
+ var _a22;
1579
1578
  return {
1580
1579
  ...acc,
1581
- [name2]: (_a2 = parseDef(
1580
+ [name22]: (_a22 = parseDef(
1582
1581
  schema2._def,
1583
1582
  {
1584
1583
  ...refs,
1585
- currentPath: [...refs.basePath, refs.definitionPath, name2]
1584
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
1586
1585
  },
1587
1586
  true
1588
- )) != null ? _a2 : parseAnyDef()
1587
+ )) != null ? _a22 : parseAnyDef()
1589
1588
  };
1590
1589
  },
1591
1590
  {}
1592
1591
  ) : void 0;
1593
- const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1594
- const main = (_a = parseDef(
1592
+ const name14 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1593
+ const main = (_a15 = parseDef(
1595
1594
  schema._def,
1596
- name === void 0 ? refs : {
1595
+ name14 === void 0 ? refs : {
1597
1596
  ...refs,
1598
- currentPath: [...refs.basePath, refs.definitionPath, name]
1597
+ currentPath: [...refs.basePath, refs.definitionPath, name14]
1599
1598
  },
1600
1599
  false
1601
- )) != null ? _a : parseAnyDef();
1600
+ )) != null ? _a15 : parseAnyDef();
1602
1601
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1603
1602
  if (title !== void 0) {
1604
1603
  main.title = title;
1605
1604
  }
1606
- const combined = name === void 0 ? definitions ? {
1605
+ const combined = name14 === void 0 ? definitions ? {
1607
1606
  ...main,
1608
1607
  [refs.definitionPath]: definitions
1609
1608
  } : main : {
1610
1609
  $ref: [
1611
1610
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1612
1611
  refs.definitionPath,
1613
- name
1612
+ name14
1614
1613
  ].join("/"),
1615
1614
  [refs.definitionPath]: {
1616
1615
  ...definitions,
1617
- [name]: main
1616
+ [name14]: main
1618
1617
  }
1619
1618
  };
1620
1619
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -1622,8 +1621,8 @@ var zodToJsonSchema = (schema, options) => {
1622
1621
  };
1623
1622
  var zod_to_json_schema_default = zodToJsonSchema;
1624
1623
  function zod3Schema(zodSchema2, options) {
1625
- var _a;
1626
- const useReferences = (_a = void 0 ) != null ? _a : false;
1624
+ var _a15;
1625
+ const useReferences = (_a15 = void 0 ) != null ? _a15 : false;
1627
1626
  return jsonSchema(
1628
1627
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1629
1628
  () => zod_to_json_schema_default(zodSchema2, {
@@ -1638,8 +1637,8 @@ function zod3Schema(zodSchema2, options) {
1638
1637
  );
1639
1638
  }
1640
1639
  function zod4Schema(zodSchema2, options) {
1641
- var _a;
1642
- const useReferences = (_a = void 0 ) != null ? _a : false;
1640
+ var _a15;
1641
+ const useReferences = (_a15 = void 0 ) != null ? _a15 : false;
1643
1642
  return jsonSchema(
1644
1643
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1645
1644
  () => z4__namespace.toJSONSchema(zodSchema2, {
@@ -1954,7 +1953,7 @@ function prepareTools({
1954
1953
  };
1955
1954
  default: {
1956
1955
  const _exhaustiveCheck = type;
1957
- throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
1956
+ throw new chunkF75EQ574_cjs.UnsupportedFunctionalityError({
1958
1957
  functionality: `tool choice type: ${_exhaustiveCheck}`
1959
1958
  });
1960
1959
  }
@@ -2019,12 +2018,12 @@ var DeepSeekChatLanguageModel = class {
2019
2018
  toolChoice,
2020
2019
  seed
2021
2020
  }) {
2022
- var _a, _b;
2023
- const deepseekOptions = (_a = await parseProviderOptions2({
2021
+ var _a15, _b;
2022
+ const deepseekOptions = (_a15 = await parseProviderOptions2({
2024
2023
  provider: this.providerOptionsName,
2025
2024
  providerOptions,
2026
2025
  schema: deepseekChatOptions
2027
- })) != null ? _a : {};
2026
+ })) != null ? _a15 : {};
2028
2027
  const { messages, warnings } = convertToDeepSeekChatMessages({
2029
2028
  prompt,
2030
2029
  responseFormat
@@ -2062,7 +2061,7 @@ var DeepSeekChatLanguageModel = class {
2062
2061
  };
2063
2062
  }
2064
2063
  async doGenerate(options) {
2065
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2064
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2066
2065
  const { args, warnings } = await this.getArgs({ ...options });
2067
2066
  const {
2068
2067
  responseHeaders,
@@ -2095,7 +2094,7 @@ var DeepSeekChatLanguageModel = class {
2095
2094
  for (const toolCall of choice.message.tool_calls) {
2096
2095
  content.push({
2097
2096
  type: "tool-call",
2098
- toolCallId: (_a = toolCall.id) != null ? _a : generateId2(),
2097
+ toolCallId: (_a15 = toolCall.id) != null ? _a15 : generateId2(),
2099
2098
  toolName: toolCall.function.name,
2100
2099
  input: toolCall.function.arguments
2101
2100
  });
@@ -2165,7 +2164,7 @@ var DeepSeekChatLanguageModel = class {
2165
2164
  controller.enqueue({ type: "stream-start", warnings });
2166
2165
  },
2167
2166
  transform(chunk, controller) {
2168
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
2167
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
2169
2168
  if (options.includeRawChunks) {
2170
2169
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2171
2170
  }
@@ -2243,13 +2242,13 @@ var DeepSeekChatLanguageModel = class {
2243
2242
  const index = toolCallDelta.index;
2244
2243
  if (toolCalls[index] == null) {
2245
2244
  if (toolCallDelta.id == null) {
2246
- throw new chunkCZEJQSWB_cjs.InvalidResponseDataError({
2245
+ throw new chunkF75EQ574_cjs.InvalidResponseDataError({
2247
2246
  data: toolCallDelta,
2248
2247
  message: `Expected 'id' to be a string.`
2249
2248
  });
2250
2249
  }
2251
- if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
2252
- throw new chunkCZEJQSWB_cjs.InvalidResponseDataError({
2250
+ if (((_a15 = toolCallDelta.function) == null ? void 0 : _a15.name) == null) {
2251
+ throw new chunkF75EQ574_cjs.InvalidResponseDataError({
2253
2252
  data: toolCallDelta,
2254
2253
  message: `Expected 'function.name' to be a string.`
2255
2254
  });
@@ -2322,7 +2321,7 @@ var DeepSeekChatLanguageModel = class {
2322
2321
  }
2323
2322
  },
2324
2323
  flush(controller) {
2325
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2324
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i;
2326
2325
  if (isActiveReasoning) {
2327
2326
  controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
2328
2327
  }
@@ -2338,7 +2337,7 @@ var DeepSeekChatLanguageModel = class {
2338
2337
  });
2339
2338
  controller.enqueue({
2340
2339
  type: "tool-call",
2341
- toolCallId: (_a = toolCall.id) != null ? _a : generateId2(),
2340
+ toolCallId: (_a15 = toolCall.id) != null ? _a15 : generateId2(),
2342
2341
  toolName: toolCall.function.name,
2343
2342
  input: toolCall.function.arguments
2344
2343
  });
@@ -2370,9 +2369,9 @@ var DeepSeekChatLanguageModel = class {
2370
2369
  };
2371
2370
  var VERSION2 = "1.0.31" ;
2372
2371
  function createDeepSeek(options = {}) {
2373
- var _a;
2372
+ var _a15;
2374
2373
  const baseURL = withoutTrailingSlash2(
2375
- (_a = options.baseURL) != null ? _a : "https://api.deepseek.com"
2374
+ (_a15 = options.baseURL) != null ? _a15 : "https://api.deepseek.com"
2376
2375
  );
2377
2376
  const getHeaders = () => withUserAgentSuffix2(
2378
2377
  {
@@ -2397,10 +2396,10 @@ function createDeepSeek(options = {}) {
2397
2396
  provider.languageModel = createLanguageModel;
2398
2397
  provider.chat = createLanguageModel;
2399
2398
  provider.textEmbeddingModel = (modelId) => {
2400
- throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
2399
+ throw new chunkF75EQ574_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
2401
2400
  };
2402
2401
  provider.imageModel = (modelId) => {
2403
- throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
2402
+ throw new chunkF75EQ574_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
2404
2403
  };
2405
2404
  return provider;
2406
2405
  }
@@ -2428,7 +2427,7 @@ function convertToMistralChatMessages(prompt) {
2428
2427
  const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
2429
2428
  return {
2430
2429
  type: "image_url",
2431
- image_url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkCZEJQSWB_cjs.convertToBase64(part.data)}`
2430
+ image_url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkF75EQ574_cjs.convertToBase64(part.data)}`
2432
2431
  };
2433
2432
  } else if (part.mediaType === "application/pdf") {
2434
2433
  return {
@@ -2436,7 +2435,7 @@ function convertToMistralChatMessages(prompt) {
2436
2435
  document_url: part.data.toString()
2437
2436
  };
2438
2437
  } else {
2439
- throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
2438
+ throw new chunkF75EQ574_cjs.UnsupportedFunctionalityError({
2440
2439
  functionality: "Only images and PDF file parts are supported"
2441
2440
  });
2442
2441
  }
@@ -2577,7 +2576,7 @@ var mistralErrorDataSchema = z4.z.object({
2577
2576
  param: z4.z.string().nullable(),
2578
2577
  code: z4.z.string().nullable()
2579
2578
  });
2580
- var mistralFailedResponseHandler = chunkCZEJQSWB_cjs.createJsonErrorResponseHandler({
2579
+ var mistralFailedResponseHandler = chunkF75EQ574_cjs.createJsonErrorResponseHandler({
2581
2580
  errorSchema: mistralErrorDataSchema,
2582
2581
  errorToMessage: (data) => data.message
2583
2582
  });
@@ -2627,7 +2626,7 @@ function prepareTools2({
2627
2626
  };
2628
2627
  default: {
2629
2628
  const _exhaustiveCheck = type;
2630
- throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
2629
+ throw new chunkF75EQ574_cjs.UnsupportedFunctionalityError({
2631
2630
  functionality: `tool choice type: ${_exhaustiveCheck}`
2632
2631
  });
2633
2632
  }
@@ -2639,10 +2638,10 @@ var MistralChatLanguageModel = class {
2639
2638
  this.supportedUrls = {
2640
2639
  "application/pdf": [/^https:\/\/.*$/]
2641
2640
  };
2642
- var _a;
2641
+ var _a15;
2643
2642
  this.modelId = modelId;
2644
2643
  this.config = config;
2645
- this.generateId = (_a = config.generateId) != null ? _a : chunkCZEJQSWB_cjs.generateId;
2644
+ this.generateId = (_a15 = config.generateId) != null ? _a15 : chunkF75EQ574_cjs.generateId;
2646
2645
  }
2647
2646
  get provider() {
2648
2647
  return this.config.provider;
@@ -2662,13 +2661,13 @@ var MistralChatLanguageModel = class {
2662
2661
  tools,
2663
2662
  toolChoice
2664
2663
  }) {
2665
- var _a, _b, _c, _d;
2664
+ var _a15, _b, _c, _d;
2666
2665
  const warnings = [];
2667
- const options = (_a = await chunkCZEJQSWB_cjs.parseProviderOptions({
2666
+ const options = (_a15 = await chunkF75EQ574_cjs.parseProviderOptions({
2668
2667
  provider: "mistral",
2669
2668
  providerOptions,
2670
2669
  schema: mistralLanguageModelOptions
2671
- })) != null ? _a : {};
2670
+ })) != null ? _a15 : {};
2672
2671
  if (topK != null) {
2673
2672
  warnings.push({
2674
2673
  type: "unsupported-setting",
@@ -2696,7 +2695,7 @@ var MistralChatLanguageModel = class {
2696
2695
  const structuredOutputs = (_b = options.structuredOutputs) != null ? _b : true;
2697
2696
  const strictJsonSchema = (_c = options.strictJsonSchema) != null ? _c : false;
2698
2697
  if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && !(responseFormat == null ? void 0 : responseFormat.schema)) {
2699
- prompt = chunkCZEJQSWB_cjs.injectJsonInstructionIntoMessages({
2698
+ prompt = chunkF75EQ574_cjs.injectJsonInstructionIntoMessages({
2700
2699
  messages: prompt,
2701
2700
  schema: responseFormat.schema
2702
2701
  });
@@ -2751,12 +2750,12 @@ var MistralChatLanguageModel = class {
2751
2750
  responseHeaders,
2752
2751
  value: response,
2753
2752
  rawValue: rawResponse
2754
- } = await chunkCZEJQSWB_cjs.postJsonToApi({
2753
+ } = await chunkF75EQ574_cjs.postJsonToApi({
2755
2754
  url: `${this.config.baseURL}/chat/completions`,
2756
- headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
2755
+ headers: chunkF75EQ574_cjs.combineHeaders(this.config.headers(), options.headers),
2757
2756
  body,
2758
2757
  failedResponseHandler: mistralFailedResponseHandler,
2759
- successfulResponseHandler: chunkCZEJQSWB_cjs.createJsonResponseHandler(
2758
+ successfulResponseHandler: chunkF75EQ574_cjs.createJsonResponseHandler(
2760
2759
  mistralChatResponseSchema
2761
2760
  ),
2762
2761
  abortSignal: options.abortSignal,
@@ -2813,12 +2812,12 @@ var MistralChatLanguageModel = class {
2813
2812
  async doStream(options) {
2814
2813
  const { args, warnings } = await this.getArgs(options);
2815
2814
  const body = { ...args, stream: true };
2816
- const { responseHeaders, value: response } = await chunkCZEJQSWB_cjs.postJsonToApi({
2815
+ const { responseHeaders, value: response } = await chunkF75EQ574_cjs.postJsonToApi({
2817
2816
  url: `${this.config.baseURL}/chat/completions`,
2818
- headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
2817
+ headers: chunkF75EQ574_cjs.combineHeaders(this.config.headers(), options.headers),
2819
2818
  body,
2820
2819
  failedResponseHandler: mistralFailedResponseHandler,
2821
- successfulResponseHandler: chunkCZEJQSWB_cjs.createEventSourceResponseHandler(
2820
+ successfulResponseHandler: chunkF75EQ574_cjs.createEventSourceResponseHandler(
2822
2821
  mistralChatChunkSchema
2823
2822
  ),
2824
2823
  abortSignal: options.abortSignal,
@@ -3091,7 +3090,7 @@ var MistralEmbeddingModel = class {
3091
3090
  headers
3092
3091
  }) {
3093
3092
  if (values.length > this.maxEmbeddingsPerCall) {
3094
- throw new chunkCZEJQSWB_cjs.TooManyEmbeddingValuesForCallError({
3093
+ throw new chunkF75EQ574_cjs.TooManyEmbeddingValuesForCallError({
3095
3094
  provider: this.provider,
3096
3095
  modelId: this.modelId,
3097
3096
  maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
@@ -3102,16 +3101,16 @@ var MistralEmbeddingModel = class {
3102
3101
  responseHeaders,
3103
3102
  value: response,
3104
3103
  rawValue
3105
- } = await chunkCZEJQSWB_cjs.postJsonToApi({
3104
+ } = await chunkF75EQ574_cjs.postJsonToApi({
3106
3105
  url: `${this.config.baseURL}/embeddings`,
3107
- headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), headers),
3106
+ headers: chunkF75EQ574_cjs.combineHeaders(this.config.headers(), headers),
3108
3107
  body: {
3109
3108
  model: this.modelId,
3110
3109
  input: values,
3111
3110
  encoding_format: "float"
3112
3111
  },
3113
3112
  failedResponseHandler: mistralFailedResponseHandler,
3114
- successfulResponseHandler: chunkCZEJQSWB_cjs.createJsonResponseHandler(
3113
+ successfulResponseHandler: chunkF75EQ574_cjs.createJsonResponseHandler(
3115
3114
  MistralTextEmbeddingResponseSchema
3116
3115
  ),
3117
3116
  abortSignal,
@@ -3130,11 +3129,11 @@ var MistralTextEmbeddingResponseSchema = z4.z.object({
3130
3129
  });
3131
3130
  var VERSION3 = "2.0.24" ;
3132
3131
  function createMistral(options = {}) {
3133
- var _a;
3134
- const baseURL = (_a = chunkCZEJQSWB_cjs.withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.mistral.ai/v1";
3135
- const getHeaders = () => chunkCZEJQSWB_cjs.withUserAgentSuffix(
3132
+ var _a15;
3133
+ const baseURL = (_a15 = chunkF75EQ574_cjs.withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://api.mistral.ai/v1";
3134
+ const getHeaders = () => chunkF75EQ574_cjs.withUserAgentSuffix(
3136
3135
  {
3137
- Authorization: `Bearer ${chunkCZEJQSWB_cjs.loadApiKey({
3136
+ Authorization: `Bearer ${chunkF75EQ574_cjs.loadApiKey({
3138
3137
  apiKey: options.apiKey,
3139
3138
  environmentVariableName: "MISTRAL_API_KEY",
3140
3139
  description: "Mistral"
@@ -3170,7 +3169,7 @@ function createMistral(options = {}) {
3170
3169
  provider.textEmbedding = createEmbeddingModel;
3171
3170
  provider.textEmbeddingModel = createEmbeddingModel;
3172
3171
  provider.imageModel = (modelId) => {
3173
- throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
3172
+ throw new chunkF75EQ574_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
3174
3173
  };
3175
3174
  return provider;
3176
3175
  }
@@ -3210,7 +3209,7 @@ var createIdGenerator2 = ({
3210
3209
  return generator;
3211
3210
  }
3212
3211
  if (alphabet.includes(separator)) {
3213
- throw new chunkCZEJQSWB_cjs.InvalidArgumentError({
3212
+ throw new chunkF75EQ574_cjs.InvalidArgumentError({
3214
3213
  argument: "separator",
3215
3214
  message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
3216
3215
  });
@@ -3234,7 +3233,7 @@ function handleFetchError2({
3234
3233
  if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES2.includes(error.message.toLowerCase())) {
3235
3234
  const cause = error.cause;
3236
3235
  if (cause != null) {
3237
- return new chunkCZEJQSWB_cjs.APICallError({
3236
+ return new chunkF75EQ574_cjs.APICallError({
3238
3237
  message: `Cannot connect to API: ${cause.message}`,
3239
3238
  cause,
3240
3239
  url,
@@ -3261,23 +3260,23 @@ function loadApiKey3({
3261
3260
  return apiKey;
3262
3261
  }
3263
3262
  if (apiKey != null) {
3264
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3263
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
3265
3264
  message: `${description} API key must be a string.`
3266
3265
  });
3267
3266
  }
3268
3267
  if (typeof process === "undefined") {
3269
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3268
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
3270
3269
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
3271
3270
  });
3272
3271
  }
3273
3272
  apiKey = process.env[environmentVariableName];
3274
3273
  if (apiKey == null) {
3275
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3274
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
3276
3275
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
3277
3276
  });
3278
3277
  }
3279
3278
  if (typeof apiKey !== "string") {
3280
- throw new chunkCZEJQSWB_cjs.LoadAPIKeyError({
3279
+ throw new chunkF75EQ574_cjs.LoadAPIKeyError({
3281
3280
  message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
3282
3281
  });
3283
3282
  }
@@ -3341,7 +3340,7 @@ function standardSchemaValidator2(standardSchema) {
3341
3340
  const result = await standardSchema["~standard"].validate(value);
3342
3341
  return result.issues == null ? { success: true, value: result.value } : {
3343
3342
  success: false,
3344
- error: new chunkCZEJQSWB_cjs.TypeValidationError({
3343
+ error: new chunkF75EQ574_cjs.TypeValidationError({
3345
3344
  value,
3346
3345
  cause: result.issues
3347
3346
  })
@@ -3354,7 +3353,7 @@ async function validateTypes2({
3354
3353
  }) {
3355
3354
  const result = await safeValidateTypes2({ value, schema });
3356
3355
  if (!result.success) {
3357
- throw chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error });
3356
+ throw chunkF75EQ574_cjs.TypeValidationError.wrap({ value, cause: result.error });
3358
3357
  }
3359
3358
  return result.value;
3360
3359
  }
@@ -3373,13 +3372,13 @@ async function safeValidateTypes2({
3373
3372
  }
3374
3373
  return {
3375
3374
  success: false,
3376
- error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: result.error }),
3375
+ error: chunkF75EQ574_cjs.TypeValidationError.wrap({ value, cause: result.error }),
3377
3376
  rawValue: value
3378
3377
  };
3379
3378
  } catch (error) {
3380
3379
  return {
3381
3380
  success: false,
3382
- error: chunkCZEJQSWB_cjs.TypeValidationError.wrap({ value, cause: error }),
3381
+ error: chunkF75EQ574_cjs.TypeValidationError.wrap({ value, cause: error }),
3383
3382
  rawValue: value
3384
3383
  };
3385
3384
  }
@@ -3395,10 +3394,10 @@ async function parseJSON2({
3395
3394
  }
3396
3395
  return validateTypes2({ value, schema });
3397
3396
  } catch (error) {
3398
- if (chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) || chunkCZEJQSWB_cjs.TypeValidationError.isInstance(error)) {
3397
+ if (chunkF75EQ574_cjs.JSONParseError.isInstance(error) || chunkF75EQ574_cjs.TypeValidationError.isInstance(error)) {
3399
3398
  throw error;
3400
3399
  }
3401
- throw new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error });
3400
+ throw new chunkF75EQ574_cjs.JSONParseError({ text, cause: error });
3402
3401
  }
3403
3402
  }
3404
3403
  async function safeParseJSON2({
@@ -3414,7 +3413,7 @@ async function safeParseJSON2({
3414
3413
  } catch (error) {
3415
3414
  return {
3416
3415
  success: false,
3417
- error: chunkCZEJQSWB_cjs.JSONParseError.isInstance(error) ? error : new chunkCZEJQSWB_cjs.JSONParseError({ text, cause: error }),
3416
+ error: chunkF75EQ574_cjs.JSONParseError.isInstance(error) ? error : new chunkF75EQ574_cjs.JSONParseError({ text, cause: error }),
3418
3417
  rawValue: void 0
3419
3418
  };
3420
3419
  }
@@ -3423,7 +3422,7 @@ function parseJsonEventStream2({
3423
3422
  stream,
3424
3423
  schema
3425
3424
  }) {
3426
- return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new chunkCZEJQSWB_cjs.EventSourceParserStream()).pipeThrough(
3425
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new chunkF75EQ574_cjs.EventSourceParserStream()).pipeThrough(
3427
3426
  new TransformStream({
3428
3427
  async transform({ data }, controller) {
3429
3428
  if (data === "[DONE]") {
@@ -3484,10 +3483,10 @@ var postToApi2 = async ({
3484
3483
  requestBodyValues: body.values
3485
3484
  });
3486
3485
  } catch (error) {
3487
- if (isAbortError2(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
3486
+ if (isAbortError2(error) || chunkF75EQ574_cjs.APICallError.isInstance(error)) {
3488
3487
  throw error;
3489
3488
  }
3490
- throw new chunkCZEJQSWB_cjs.APICallError({
3489
+ throw new chunkF75EQ574_cjs.APICallError({
3491
3490
  message: "Failed to process error response",
3492
3491
  cause: error,
3493
3492
  statusCode: response.status,
@@ -3506,11 +3505,11 @@ var postToApi2 = async ({
3506
3505
  });
3507
3506
  } catch (error) {
3508
3507
  if (error instanceof Error) {
3509
- if (isAbortError2(error) || chunkCZEJQSWB_cjs.APICallError.isInstance(error)) {
3508
+ if (isAbortError2(error) || chunkF75EQ574_cjs.APICallError.isInstance(error)) {
3510
3509
  throw error;
3511
3510
  }
3512
3511
  }
3513
- throw new chunkCZEJQSWB_cjs.APICallError({
3512
+ throw new chunkF75EQ574_cjs.APICallError({
3514
3513
  message: "Failed to process successful response",
3515
3514
  cause: error,
3516
3515
  statusCode: response.status,
@@ -3533,7 +3532,7 @@ var createJsonErrorResponseHandler3 = ({
3533
3532
  if (responseBody.trim() === "") {
3534
3533
  return {
3535
3534
  responseHeaders,
3536
- value: new chunkCZEJQSWB_cjs.APICallError({
3535
+ value: new chunkF75EQ574_cjs.APICallError({
3537
3536
  message: response.statusText,
3538
3537
  url,
3539
3538
  requestBodyValues,
@@ -3551,7 +3550,7 @@ var createJsonErrorResponseHandler3 = ({
3551
3550
  });
3552
3551
  return {
3553
3552
  responseHeaders,
3554
- value: new chunkCZEJQSWB_cjs.APICallError({
3553
+ value: new chunkF75EQ574_cjs.APICallError({
3555
3554
  message: errorToMessage2(parsedError),
3556
3555
  url,
3557
3556
  requestBodyValues,
@@ -3565,7 +3564,7 @@ var createJsonErrorResponseHandler3 = ({
3565
3564
  } catch (parseError) {
3566
3565
  return {
3567
3566
  responseHeaders,
3568
- value: new chunkCZEJQSWB_cjs.APICallError({
3567
+ value: new chunkF75EQ574_cjs.APICallError({
3569
3568
  message: response.statusText,
3570
3569
  url,
3571
3570
  requestBodyValues,
@@ -3580,7 +3579,7 @@ var createJsonErrorResponseHandler3 = ({
3580
3579
  var createEventSourceResponseHandler3 = (chunkSchema) => async ({ response }) => {
3581
3580
  const responseHeaders = extractResponseHeaders2(response);
3582
3581
  if (response.body == null) {
3583
- throw new chunkCZEJQSWB_cjs.EmptyResponseBodyError({});
3582
+ throw new chunkF75EQ574_cjs.EmptyResponseBodyError({});
3584
3583
  }
3585
3584
  return {
3586
3585
  responseHeaders,
@@ -3598,7 +3597,7 @@ var createJsonResponseHandler3 = (responseSchema) => async ({ response, url, req
3598
3597
  });
3599
3598
  const responseHeaders = extractResponseHeaders2(response);
3600
3599
  if (!parsedResult.success) {
3601
- throw new chunkCZEJQSWB_cjs.APICallError({
3600
+ throw new chunkF75EQ574_cjs.APICallError({
3602
3601
  message: "Invalid JSON response",
3603
3602
  cause: parsedResult.error,
3604
3603
  statusCode: response.status,
@@ -3639,7 +3638,7 @@ function convertToPerplexityMessages(prompt) {
3639
3638
  (part) => part.type === "file" && part.mediaType.startsWith("image/")
3640
3639
  );
3641
3640
  const messageContent = content.map((part) => {
3642
- var _a;
3641
+ var _a15;
3643
3642
  switch (part.type) {
3644
3643
  case "text": {
3645
3644
  return {
@@ -3656,7 +3655,7 @@ function convertToPerplexityMessages(prompt) {
3656
3655
  } : {
3657
3656
  type: "image_url",
3658
3657
  image_url: {
3659
- url: `data:${(_a = part.mediaType) != null ? _a : "image/jpeg"};base64,${typeof part.data === "string" ? part.data : convertUint8ArrayToBase64(part.data)}`
3658
+ url: `data:${(_a15 = part.mediaType) != null ? _a15 : "image/jpeg"};base64,${typeof part.data === "string" ? part.data : convertUint8ArrayToBase64(part.data)}`
3660
3659
  }
3661
3660
  };
3662
3661
  }
@@ -3669,7 +3668,7 @@ function convertToPerplexityMessages(prompt) {
3669
3668
  break;
3670
3669
  }
3671
3670
  case "tool": {
3672
- throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
3671
+ throw new chunkF75EQ574_cjs.UnsupportedFunctionalityError({
3673
3672
  functionality: "Tool messages"
3674
3673
  });
3675
3674
  }
@@ -3713,7 +3712,7 @@ var PerplexityLanguageModel = class {
3713
3712
  seed,
3714
3713
  providerOptions
3715
3714
  }) {
3716
- var _a;
3715
+ var _a15;
3717
3716
  const warnings = [];
3718
3717
  if (topK != null) {
3719
3718
  warnings.push({
@@ -3750,7 +3749,7 @@ var PerplexityLanguageModel = class {
3750
3749
  json_schema: { schema: responseFormat.schema }
3751
3750
  } : void 0,
3752
3751
  // provider extensions
3753
- ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},
3752
+ ...(_a15 = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a15 : {},
3754
3753
  // messages:
3755
3754
  messages: convertToPerplexityMessages(prompt)
3756
3755
  },
@@ -3758,7 +3757,7 @@ var PerplexityLanguageModel = class {
3758
3757
  };
3759
3758
  }
3760
3759
  async doGenerate(options) {
3761
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3760
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3762
3761
  const { args: body, warnings } = this.getArgs(options);
3763
3762
  const {
3764
3763
  responseHeaders,
@@ -3798,7 +3797,7 @@ var PerplexityLanguageModel = class {
3798
3797
  content,
3799
3798
  finishReason: mapPerplexityFinishReason(choice.finish_reason),
3800
3799
  usage: {
3801
- inputTokens: (_a = response.usage) == null ? void 0 : _a.prompt_tokens,
3800
+ inputTokens: (_a15 = response.usage) == null ? void 0 : _a15.prompt_tokens,
3802
3801
  outputTokens: (_b = response.usage) == null ? void 0 : _b.completion_tokens,
3803
3802
  totalTokens: (_d = (_c = response.usage) == null ? void 0 : _c.total_tokens) != null ? _d : void 0
3804
3803
  },
@@ -3867,7 +3866,7 @@ var PerplexityLanguageModel = class {
3867
3866
  controller.enqueue({ type: "stream-start", warnings });
3868
3867
  },
3869
3868
  transform(chunk, controller) {
3870
- var _a, _b, _c;
3869
+ var _a15, _b, _c;
3871
3870
  if (options.includeRawChunks) {
3872
3871
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
3873
3872
  }
@@ -3881,7 +3880,7 @@ var PerplexityLanguageModel = class {
3881
3880
  type: "response-metadata",
3882
3881
  ...getResponseMetadata3(value)
3883
3882
  });
3884
- (_a = value.citations) == null ? void 0 : _a.forEach((url) => {
3883
+ (_a15 = value.citations) == null ? void 0 : _a15.forEach((url) => {
3885
3884
  controller.enqueue({
3886
3885
  type: "source",
3887
3886
  sourceType: "url",
@@ -4012,8 +4011,8 @@ var perplexityErrorSchema = z4.z.object({
4012
4011
  })
4013
4012
  });
4014
4013
  var errorToMessage = (data) => {
4015
- var _a, _b;
4016
- return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : "unknown error";
4014
+ var _a15, _b;
4015
+ return (_b = (_a15 = data.error.message) != null ? _a15 : data.error.type) != null ? _b : "unknown error";
4017
4016
  };
4018
4017
  function createPerplexity(options = {}) {
4019
4018
  const getHeaders = () => ({
@@ -4025,10 +4024,10 @@ function createPerplexity(options = {}) {
4025
4024
  ...options.headers
4026
4025
  });
4027
4026
  const createLanguageModel = (modelId) => {
4028
- var _a;
4027
+ var _a15;
4029
4028
  return new PerplexityLanguageModel(modelId, {
4030
4029
  baseURL: withoutTrailingSlash3(
4031
- (_a = options.baseURL) != null ? _a : "https://api.perplexity.ai"
4030
+ (_a15 = options.baseURL) != null ? _a15 : "https://api.perplexity.ai"
4032
4031
  ),
4033
4032
  headers: getHeaders,
4034
4033
  generateId: generateId3,
@@ -4038,10 +4037,10 @@ function createPerplexity(options = {}) {
4038
4037
  const provider = (modelId) => createLanguageModel(modelId);
4039
4038
  provider.languageModel = createLanguageModel;
4040
4039
  provider.textEmbeddingModel = (modelId) => {
4041
- throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
4040
+ throw new chunkF75EQ574_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
4042
4041
  };
4043
4042
  provider.imageModel = (modelId) => {
4044
- throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
4043
+ throw new chunkF75EQ574_cjs.NoSuchModelError({ modelId, modelType: "imageModel" });
4045
4044
  };
4046
4045
  return provider;
4047
4046
  }
@@ -4073,11 +4072,11 @@ function convertToXaiChatMessages(prompt) {
4073
4072
  return {
4074
4073
  type: "image_url",
4075
4074
  image_url: {
4076
- url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkCZEJQSWB_cjs.convertToBase64(part.data)}`
4075
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkF75EQ574_cjs.convertToBase64(part.data)}`
4077
4076
  }
4078
4077
  };
4079
4078
  } else {
4080
- throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
4079
+ throw new chunkF75EQ574_cjs.UnsupportedFunctionalityError({
4081
4080
  functionality: `file part media type ${part.mediaType}`
4082
4081
  });
4083
4082
  }
@@ -4258,7 +4257,7 @@ var xaiErrorDataSchema = z4.z.object({
4258
4257
  code: z4.z.union([z4.z.string(), z4.z.number()]).nullish()
4259
4258
  })
4260
4259
  });
4261
- var xaiFailedResponseHandler = chunkCZEJQSWB_cjs.createJsonErrorResponseHandler({
4260
+ var xaiFailedResponseHandler = chunkF75EQ574_cjs.createJsonErrorResponseHandler({
4262
4261
  errorSchema: xaiErrorDataSchema,
4263
4262
  errorToMessage: (data) => data.error.message
4264
4263
  });
@@ -4307,7 +4306,7 @@ function prepareTools3({
4307
4306
  };
4308
4307
  default: {
4309
4308
  const _exhaustiveCheck = type;
4310
- throw new chunkCZEJQSWB_cjs.UnsupportedFunctionalityError({
4309
+ throw new chunkF75EQ574_cjs.UnsupportedFunctionalityError({
4311
4310
  functionality: `tool choice type: ${_exhaustiveCheck}`
4312
4311
  });
4313
4312
  }
@@ -4340,13 +4339,13 @@ var XaiChatLanguageModel = class {
4340
4339
  tools,
4341
4340
  toolChoice
4342
4341
  }) {
4343
- var _a, _b, _c;
4342
+ var _a15, _b, _c;
4344
4343
  const warnings = [];
4345
- const options = (_a = await chunkCZEJQSWB_cjs.parseProviderOptions({
4344
+ const options = (_a15 = await chunkF75EQ574_cjs.parseProviderOptions({
4346
4345
  provider: "xai",
4347
4346
  providerOptions,
4348
4347
  schema: xaiProviderOptions
4349
- })) != null ? _a : {};
4348
+ })) != null ? _a15 : {};
4350
4349
  if (topK != null) {
4351
4350
  warnings.push({
4352
4351
  type: "unsupported-setting",
@@ -4410,7 +4409,7 @@ var XaiChatLanguageModel = class {
4410
4409
  to_date: options.searchParameters.toDate,
4411
4410
  max_search_results: options.searchParameters.maxSearchResults,
4412
4411
  sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
4413
- var _a2;
4412
+ var _a22;
4414
4413
  return {
4415
4414
  type: source.type,
4416
4415
  ...source.type === "web" && {
@@ -4421,7 +4420,7 @@ var XaiChatLanguageModel = class {
4421
4420
  },
4422
4421
  ...source.type === "x" && {
4423
4422
  excluded_x_handles: source.excludedXHandles,
4424
- included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
4423
+ included_x_handles: (_a22 = source.includedXHandles) != null ? _a22 : source.xHandles,
4425
4424
  post_favorite_count: source.postFavoriteCount,
4426
4425
  post_view_count: source.postViewCount
4427
4426
  },
@@ -4448,18 +4447,18 @@ var XaiChatLanguageModel = class {
4448
4447
  };
4449
4448
  }
4450
4449
  async doGenerate(options) {
4451
- var _a, _b, _c;
4450
+ var _a15, _b, _c;
4452
4451
  const { args: body, warnings } = await this.getArgs(options);
4453
4452
  const {
4454
4453
  responseHeaders,
4455
4454
  value: response,
4456
4455
  rawValue: rawResponse
4457
- } = await chunkCZEJQSWB_cjs.postJsonToApi({
4458
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
4459
- headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
4456
+ } = await chunkF75EQ574_cjs.postJsonToApi({
4457
+ url: `${(_a15 = this.config.baseURL) != null ? _a15 : "https://api.x.ai/v1"}/chat/completions`,
4458
+ headers: chunkF75EQ574_cjs.combineHeaders(this.config.headers(), options.headers),
4460
4459
  body,
4461
4460
  failedResponseHandler: xaiFailedResponseHandler,
4462
- successfulResponseHandler: chunkCZEJQSWB_cjs.createJsonResponseHandler(
4461
+ successfulResponseHandler: chunkF75EQ574_cjs.createJsonResponseHandler(
4463
4462
  xaiChatResponseSchema
4464
4463
  ),
4465
4464
  abortSignal: options.abortSignal,
@@ -4522,7 +4521,7 @@ var XaiChatLanguageModel = class {
4522
4521
  };
4523
4522
  }
4524
4523
  async doStream(options) {
4525
- var _a;
4524
+ var _a15;
4526
4525
  const { args, warnings } = await this.getArgs(options);
4527
4526
  const body = {
4528
4527
  ...args,
@@ -4531,12 +4530,12 @@ var XaiChatLanguageModel = class {
4531
4530
  include_usage: true
4532
4531
  }
4533
4532
  };
4534
- const { responseHeaders, value: response } = await chunkCZEJQSWB_cjs.postJsonToApi({
4535
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
4536
- headers: chunkCZEJQSWB_cjs.combineHeaders(this.config.headers(), options.headers),
4533
+ const { responseHeaders, value: response } = await chunkF75EQ574_cjs.postJsonToApi({
4534
+ url: `${(_a15 = this.config.baseURL) != null ? _a15 : "https://api.x.ai/v1"}/chat/completions`,
4535
+ headers: chunkF75EQ574_cjs.combineHeaders(this.config.headers(), options.headers),
4537
4536
  body,
4538
4537
  failedResponseHandler: xaiFailedResponseHandler,
4539
- successfulResponseHandler: chunkCZEJQSWB_cjs.createEventSourceResponseHandler(xaiChatChunkSchema),
4538
+ successfulResponseHandler: chunkF75EQ574_cjs.createEventSourceResponseHandler(xaiChatChunkSchema),
4540
4539
  abortSignal: options.abortSignal,
4541
4540
  fetch: this.config.fetch
4542
4541
  });
@@ -4557,7 +4556,7 @@ var XaiChatLanguageModel = class {
4557
4556
  controller.enqueue({ type: "stream-start", warnings });
4558
4557
  },
4559
4558
  transform(chunk, controller) {
4560
- var _a2, _b;
4559
+ var _a22, _b;
4561
4560
  if (options.includeRawChunks) {
4562
4561
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
4563
4562
  }
@@ -4587,7 +4586,7 @@ var XaiChatLanguageModel = class {
4587
4586
  usage.inputTokens = value.usage.prompt_tokens;
4588
4587
  usage.outputTokens = value.usage.completion_tokens;
4589
4588
  usage.totalTokens = value.usage.total_tokens;
4590
- usage.reasoningTokens = (_b = (_a2 = value.usage.completion_tokens_details) == null ? void 0 : _a2.reasoning_tokens) != null ? _b : void 0;
4589
+ usage.reasoningTokens = (_b = (_a22 = value.usage.completion_tokens_details) == null ? void 0 : _a22.reasoning_tokens) != null ? _b : void 0;
4591
4590
  }
4592
4591
  const choice = value.choices[0];
4593
4592
  if ((choice == null ? void 0 : choice.finish_reason) != null) {
@@ -4750,13 +4749,13 @@ var xaiErrorStructure = {
4750
4749
  errorToMessage: (data) => data.error.message
4751
4750
  };
4752
4751
  function createXai(options = {}) {
4753
- var _a;
4754
- const baseURL = chunkCZEJQSWB_cjs.withoutTrailingSlash(
4755
- (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
4752
+ var _a15;
4753
+ const baseURL = chunkF75EQ574_cjs.withoutTrailingSlash(
4754
+ (_a15 = options.baseURL) != null ? _a15 : "https://api.x.ai/v1"
4756
4755
  );
4757
- const getHeaders = () => chunkCZEJQSWB_cjs.withUserAgentSuffix(
4756
+ const getHeaders = () => chunkF75EQ574_cjs.withUserAgentSuffix(
4758
4757
  {
4759
- Authorization: `Bearer ${chunkCZEJQSWB_cjs.loadApiKey({
4758
+ Authorization: `Bearer ${chunkF75EQ574_cjs.loadApiKey({
4760
4759
  apiKey: options.apiKey,
4761
4760
  environmentVariableName: "XAI_API_KEY",
4762
4761
  description: "xAI API key"
@@ -4770,12 +4769,12 @@ function createXai(options = {}) {
4770
4769
  provider: "xai.chat",
4771
4770
  baseURL,
4772
4771
  headers: getHeaders,
4773
- generateId: chunkCZEJQSWB_cjs.generateId,
4772
+ generateId: chunkF75EQ574_cjs.generateId,
4774
4773
  fetch: options.fetch
4775
4774
  });
4776
4775
  };
4777
4776
  const createImageModel = (modelId) => {
4778
- return new chunkCZEJQSWB_cjs.OpenAICompatibleImageModel(modelId, {
4777
+ return new chunkF75EQ574_cjs.OpenAICompatibleImageModel(modelId, {
4779
4778
  provider: "xai.image",
4780
4779
  url: ({ path }) => `${baseURL}${path}`,
4781
4780
  headers: getHeaders,
@@ -4787,13 +4786,2466 @@ function createXai(options = {}) {
4787
4786
  provider.languageModel = createLanguageModel;
4788
4787
  provider.chat = createLanguageModel;
4789
4788
  provider.textEmbeddingModel = (modelId) => {
4790
- throw new chunkCZEJQSWB_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
4789
+ throw new chunkF75EQ574_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
4791
4790
  };
4792
4791
  provider.imageModel = createImageModel;
4793
4792
  provider.image = createImageModel;
4794
4793
  return provider;
4795
4794
  }
4796
4795
  createXai();
4796
+ var __defProp = Object.defineProperty;
4797
+ var __defProps = Object.defineProperties;
4798
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4799
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
4800
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4801
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
4802
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4803
+ var __spreadValues = (a, b) => {
4804
+ for (var prop in b || (b = {}))
4805
+ if (__hasOwnProp.call(b, prop))
4806
+ __defNormalProp(a, prop, b[prop]);
4807
+ if (__getOwnPropSymbols)
4808
+ for (var prop of __getOwnPropSymbols(b)) {
4809
+ if (__propIsEnum.call(b, prop))
4810
+ __defNormalProp(a, prop, b[prop]);
4811
+ }
4812
+ return a;
4813
+ };
4814
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
4815
+ var marker = "vercel.ai.error";
4816
+ var symbol = Symbol.for(marker);
4817
+ var _a;
4818
+ var _AISDKError = class _AISDKError2 extends Error {
4819
+ /**
4820
+ * Creates an AI SDK Error.
4821
+ *
4822
+ * @param {Object} params - The parameters for creating the error.
4823
+ * @param {string} params.name - The name of the error.
4824
+ * @param {string} params.message - The error message.
4825
+ * @param {unknown} [params.cause] - The underlying cause of the error.
4826
+ */
4827
+ constructor({
4828
+ name: name14,
4829
+ message,
4830
+ cause
4831
+ }) {
4832
+ super(message);
4833
+ this[_a] = true;
4834
+ this.name = name14;
4835
+ this.cause = cause;
4836
+ }
4837
+ /**
4838
+ * Checks if the given error is an AI SDK Error.
4839
+ * @param {unknown} error - The error to check.
4840
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
4841
+ */
4842
+ static isInstance(error) {
4843
+ return _AISDKError2.hasMarker(error, marker);
4844
+ }
4845
+ static hasMarker(error, marker15) {
4846
+ const markerSymbol = Symbol.for(marker15);
4847
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
4848
+ }
4849
+ };
4850
+ _a = symbol;
4851
+ var AISDKError = _AISDKError;
4852
+ var name = "AI_APICallError";
4853
+ var marker2 = `vercel.ai.error.${name}`;
4854
+ var symbol2 = Symbol.for(marker2);
4855
+ var _a2;
4856
+ var APICallError2 = class extends AISDKError {
4857
+ constructor({
4858
+ message,
4859
+ url,
4860
+ requestBodyValues,
4861
+ statusCode,
4862
+ responseHeaders,
4863
+ responseBody,
4864
+ cause,
4865
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
4866
+ statusCode === 409 || // conflict
4867
+ statusCode === 429 || // too many requests
4868
+ statusCode >= 500),
4869
+ // server error
4870
+ data
4871
+ }) {
4872
+ super({ name, message, cause });
4873
+ this[_a2] = true;
4874
+ this.url = url;
4875
+ this.requestBodyValues = requestBodyValues;
4876
+ this.statusCode = statusCode;
4877
+ this.responseHeaders = responseHeaders;
4878
+ this.responseBody = responseBody;
4879
+ this.isRetryable = isRetryable;
4880
+ this.data = data;
4881
+ }
4882
+ static isInstance(error) {
4883
+ return AISDKError.hasMarker(error, marker2);
4884
+ }
4885
+ };
4886
+ _a2 = symbol2;
4887
+ var name2 = "AI_EmptyResponseBodyError";
4888
+ var marker3 = `vercel.ai.error.${name2}`;
4889
+ var symbol3 = Symbol.for(marker3);
4890
+ var _a3;
4891
+ var EmptyResponseBodyError2 = class extends AISDKError {
4892
+ // used in isInstance
4893
+ constructor({ message = "Empty response body" } = {}) {
4894
+ super({ name: name2, message });
4895
+ this[_a3] = true;
4896
+ }
4897
+ static isInstance(error) {
4898
+ return AISDKError.hasMarker(error, marker3);
4899
+ }
4900
+ };
4901
+ _a3 = symbol3;
4902
+ function getErrorMessage(error) {
4903
+ if (error == null) {
4904
+ return "unknown error";
4905
+ }
4906
+ if (typeof error === "string") {
4907
+ return error;
4908
+ }
4909
+ if (error instanceof Error) {
4910
+ return error.message;
4911
+ }
4912
+ return JSON.stringify(error);
4913
+ }
4914
+ var name3 = "AI_InvalidArgumentError";
4915
+ var marker4 = `vercel.ai.error.${name3}`;
4916
+ var symbol4 = Symbol.for(marker4);
4917
+ var _a4;
4918
+ var InvalidArgumentError2 = class extends AISDKError {
4919
+ constructor({
4920
+ message,
4921
+ cause,
4922
+ argument
4923
+ }) {
4924
+ super({ name: name3, message, cause });
4925
+ this[_a4] = true;
4926
+ this.argument = argument;
4927
+ }
4928
+ static isInstance(error) {
4929
+ return AISDKError.hasMarker(error, marker4);
4930
+ }
4931
+ };
4932
+ _a4 = symbol4;
4933
+ var name4 = "AI_InvalidPromptError";
4934
+ var marker5 = `vercel.ai.error.${name4}`;
4935
+ var symbol5 = Symbol.for(marker5);
4936
+ var _a5;
4937
+ var InvalidPromptError = class extends AISDKError {
4938
+ constructor({
4939
+ prompt,
4940
+ message,
4941
+ cause
4942
+ }) {
4943
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
4944
+ this[_a5] = true;
4945
+ this.prompt = prompt;
4946
+ }
4947
+ static isInstance(error) {
4948
+ return AISDKError.hasMarker(error, marker5);
4949
+ }
4950
+ };
4951
+ _a5 = symbol5;
4952
+ var name5 = "AI_InvalidResponseDataError";
4953
+ var marker6 = `vercel.ai.error.${name5}`;
4954
+ var symbol6 = Symbol.for(marker6);
4955
+ var _a6;
4956
+ var InvalidResponseDataError2 = class extends AISDKError {
4957
+ constructor({
4958
+ data,
4959
+ message = `Invalid response data: ${JSON.stringify(data)}.`
4960
+ }) {
4961
+ super({ name: name5, message });
4962
+ this[_a6] = true;
4963
+ this.data = data;
4964
+ }
4965
+ static isInstance(error) {
4966
+ return AISDKError.hasMarker(error, marker6);
4967
+ }
4968
+ };
4969
+ _a6 = symbol6;
4970
+ var name6 = "AI_JSONParseError";
4971
+ var marker7 = `vercel.ai.error.${name6}`;
4972
+ var symbol7 = Symbol.for(marker7);
4973
+ var _a7;
4974
+ var JSONParseError2 = class extends AISDKError {
4975
+ constructor({ text, cause }) {
4976
+ super({
4977
+ name: name6,
4978
+ message: `JSON parsing failed: Text: ${text}.
4979
+ Error message: ${getErrorMessage(cause)}`,
4980
+ cause
4981
+ });
4982
+ this[_a7] = true;
4983
+ this.text = text;
4984
+ }
4985
+ static isInstance(error) {
4986
+ return AISDKError.hasMarker(error, marker7);
4987
+ }
4988
+ };
4989
+ _a7 = symbol7;
4990
+ var name7 = "AI_LoadAPIKeyError";
4991
+ var marker8 = `vercel.ai.error.${name7}`;
4992
+ var symbol8 = Symbol.for(marker8);
4993
+ var _a8;
4994
+ var LoadAPIKeyError2 = class extends AISDKError {
4995
+ // used in isInstance
4996
+ constructor({ message }) {
4997
+ super({ name: name7, message });
4998
+ this[_a8] = true;
4999
+ }
5000
+ static isInstance(error) {
5001
+ return AISDKError.hasMarker(error, marker8);
5002
+ }
5003
+ };
5004
+ _a8 = symbol8;
5005
+ var name9 = "AI_NoContentGeneratedError";
5006
+ var marker10 = `vercel.ai.error.${name9}`;
5007
+ var symbol10 = Symbol.for(marker10);
5008
+ var _a10;
5009
+ var NoContentGeneratedError = class extends AISDKError {
5010
+ // used in isInstance
5011
+ constructor({
5012
+ message = "No content generated."
5013
+ } = {}) {
5014
+ super({ name: name9, message });
5015
+ this[_a10] = true;
5016
+ }
5017
+ static isInstance(error) {
5018
+ return AISDKError.hasMarker(error, marker10);
5019
+ }
5020
+ };
5021
+ _a10 = symbol10;
5022
+ var name12 = "AI_TypeValidationError";
5023
+ var marker13 = `vercel.ai.error.${name12}`;
5024
+ var symbol13 = Symbol.for(marker13);
5025
+ var _a13;
5026
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
5027
+ constructor({ value, cause }) {
5028
+ super({
5029
+ name: name12,
5030
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
5031
+ Error message: ${getErrorMessage(cause)}`,
5032
+ cause
5033
+ });
5034
+ this[_a13] = true;
5035
+ this.value = value;
5036
+ }
5037
+ static isInstance(error) {
5038
+ return AISDKError.hasMarker(error, marker13);
5039
+ }
5040
+ /**
5041
+ * Wraps an error into a TypeValidationError.
5042
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
5043
+ * Otherwise, it creates a new TypeValidationError.
5044
+ *
5045
+ * @param {Object} params - The parameters for wrapping the error.
5046
+ * @param {unknown} params.value - The value that failed validation.
5047
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
5048
+ * @returns {TypeValidationError} A TypeValidationError instance.
5049
+ */
5050
+ static wrap({
5051
+ value,
5052
+ cause
5053
+ }) {
5054
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
5055
+ }
5056
+ };
5057
+ _a13 = symbol13;
5058
+ var TypeValidationError2 = _TypeValidationError;
5059
+ var name13 = "AI_UnsupportedFunctionalityError";
5060
+ var marker14 = `vercel.ai.error.${name13}`;
5061
+ var symbol14 = Symbol.for(marker14);
5062
+ var _a14;
5063
+ var UnsupportedFunctionalityError2 = class extends AISDKError {
5064
+ constructor({
5065
+ functionality,
5066
+ message = `'${functionality}' functionality not supported.`
5067
+ }) {
5068
+ super({ name: name13, message });
5069
+ this[_a14] = true;
5070
+ this.functionality = functionality;
5071
+ }
5072
+ static isInstance(error) {
5073
+ return AISDKError.hasMarker(error, marker14);
5074
+ }
5075
+ };
5076
+ _a14 = symbol14;
5077
+ var ParseError = class extends Error {
5078
+ constructor(message, options) {
5079
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
5080
+ }
5081
+ };
5082
+ function noop(_arg) {
5083
+ }
5084
+ function createParser(callbacks) {
5085
+ if (typeof callbacks == "function")
5086
+ throw new TypeError(
5087
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
5088
+ );
5089
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
5090
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
5091
+ function feed(newChunk) {
5092
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
5093
+ for (const line of complete)
5094
+ parseLine(line);
5095
+ incompleteLine = incomplete, isFirstChunk = false;
5096
+ }
5097
+ function parseLine(line) {
5098
+ if (line === "") {
5099
+ dispatchEvent();
5100
+ return;
5101
+ }
5102
+ if (line.startsWith(":")) {
5103
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
5104
+ return;
5105
+ }
5106
+ const fieldSeparatorIndex = line.indexOf(":");
5107
+ if (fieldSeparatorIndex !== -1) {
5108
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
5109
+ processField(field, value, line);
5110
+ return;
5111
+ }
5112
+ processField(line, "", line);
5113
+ }
5114
+ function processField(field, value, line) {
5115
+ switch (field) {
5116
+ case "event":
5117
+ eventType = value;
5118
+ break;
5119
+ case "data":
5120
+ data = `${data}${value}
5121
+ `;
5122
+ break;
5123
+ case "id":
5124
+ id = value.includes("\0") ? void 0 : value;
5125
+ break;
5126
+ case "retry":
5127
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
5128
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
5129
+ type: "invalid-retry",
5130
+ value,
5131
+ line
5132
+ })
5133
+ );
5134
+ break;
5135
+ default:
5136
+ onError(
5137
+ new ParseError(
5138
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
5139
+ { type: "unknown-field", field, value, line }
5140
+ )
5141
+ );
5142
+ break;
5143
+ }
5144
+ }
5145
+ function dispatchEvent() {
5146
+ data.length > 0 && onEvent({
5147
+ id,
5148
+ event: eventType || void 0,
5149
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
5150
+ // then remove the last character from the data buffer.
5151
+ data: data.endsWith(`
5152
+ `) ? data.slice(0, -1) : data
5153
+ }), id = void 0, data = "", eventType = "";
5154
+ }
5155
+ function reset(options = {}) {
5156
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
5157
+ }
5158
+ return { feed, reset };
5159
+ }
5160
+ function splitLines(chunk) {
5161
+ const lines = [];
5162
+ let incompleteLine = "", searchIndex = 0;
5163
+ for (; searchIndex < chunk.length; ) {
5164
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
5165
+ `, searchIndex);
5166
+ let lineEnd = -1;
5167
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
5168
+ incompleteLine = chunk.slice(searchIndex);
5169
+ break;
5170
+ } else {
5171
+ const line = chunk.slice(searchIndex, lineEnd);
5172
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
5173
+ ` && searchIndex++;
5174
+ }
5175
+ }
5176
+ return [lines, incompleteLine];
5177
+ }
5178
+ var EventSourceParserStream2 = class extends TransformStream {
5179
+ constructor({ onError, onRetry, onComment } = {}) {
5180
+ let parser;
5181
+ super({
5182
+ start(controller) {
5183
+ parser = createParser({
5184
+ onEvent: (event) => {
5185
+ controller.enqueue(event);
5186
+ },
5187
+ onError(error) {
5188
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
5189
+ },
5190
+ onRetry,
5191
+ onComment
5192
+ });
5193
+ },
5194
+ transform(chunk) {
5195
+ parser.feed(chunk);
5196
+ }
5197
+ });
5198
+ }
5199
+ };
5200
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
5201
+ function combineHeaders4(...headers) {
5202
+ return headers.reduce(
5203
+ (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
5204
+ {}
5205
+ );
5206
+ }
5207
+ function extractResponseHeaders3(response) {
5208
+ return Object.fromEntries([...response.headers]);
5209
+ }
5210
+ var createIdGenerator3 = ({
5211
+ prefix,
5212
+ size = 16,
5213
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
5214
+ separator = "-"
5215
+ } = {}) => {
5216
+ const generator = () => {
5217
+ const alphabetLength = alphabet.length;
5218
+ const chars = new Array(size);
5219
+ for (let i = 0; i < size; i++) {
5220
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
5221
+ }
5222
+ return chars.join("");
5223
+ };
5224
+ if (prefix == null) {
5225
+ return generator;
5226
+ }
5227
+ if (alphabet.includes(separator)) {
5228
+ throw new InvalidArgumentError2({
5229
+ argument: "separator",
5230
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
5231
+ });
5232
+ }
5233
+ return () => `${prefix}${separator}${generator()}`;
5234
+ };
5235
+ var generateId4 = createIdGenerator3();
5236
+ function isAbortError3(error) {
5237
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
5238
+ error.name === "TimeoutError");
5239
+ }
5240
+ var FETCH_FAILED_ERROR_MESSAGES3 = ["fetch failed", "failed to fetch"];
5241
+ function handleFetchError3({
5242
+ error,
5243
+ url,
5244
+ requestBodyValues
5245
+ }) {
5246
+ if (isAbortError3(error)) {
5247
+ return error;
5248
+ }
5249
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES3.includes(error.message.toLowerCase())) {
5250
+ const cause = error.cause;
5251
+ if (cause != null) {
5252
+ return new APICallError2({
5253
+ message: `Cannot connect to API: ${cause.message}`,
5254
+ cause,
5255
+ url,
5256
+ requestBodyValues,
5257
+ isRetryable: true
5258
+ // retry when network error
5259
+ });
5260
+ }
5261
+ }
5262
+ return error;
5263
+ }
5264
+ function removeUndefinedEntries2(record) {
5265
+ return Object.fromEntries(
5266
+ Object.entries(record).filter(([_key, value]) => value != null)
5267
+ );
5268
+ }
5269
+ function loadApiKey4({
5270
+ apiKey,
5271
+ environmentVariableName,
5272
+ apiKeyParameterName = "apiKey",
5273
+ description
5274
+ }) {
5275
+ if (typeof apiKey === "string") {
5276
+ return apiKey;
5277
+ }
5278
+ if (apiKey != null) {
5279
+ throw new LoadAPIKeyError2({
5280
+ message: `${description} API key must be a string.`
5281
+ });
5282
+ }
5283
+ if (typeof process === "undefined") {
5284
+ throw new LoadAPIKeyError2({
5285
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
5286
+ });
5287
+ }
5288
+ apiKey = process.env[environmentVariableName];
5289
+ if (apiKey == null) {
5290
+ throw new LoadAPIKeyError2({
5291
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
5292
+ });
5293
+ }
5294
+ if (typeof apiKey !== "string") {
5295
+ throw new LoadAPIKeyError2({
5296
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
5297
+ });
5298
+ }
5299
+ return apiKey;
5300
+ }
5301
+ var suspectProtoRx3 = /"__proto__"\s*:/;
5302
+ var suspectConstructorRx3 = /"constructor"\s*:/;
5303
+ function _parse3(text) {
5304
+ const obj = JSON.parse(text);
5305
+ if (obj === null || typeof obj !== "object") {
5306
+ return obj;
5307
+ }
5308
+ if (suspectProtoRx3.test(text) === false && suspectConstructorRx3.test(text) === false) {
5309
+ return obj;
5310
+ }
5311
+ return filter3(obj);
5312
+ }
5313
+ function filter3(obj) {
5314
+ let next = [obj];
5315
+ while (next.length) {
5316
+ const nodes = next;
5317
+ next = [];
5318
+ for (const node of nodes) {
5319
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
5320
+ throw new SyntaxError("Object contains forbidden prototype property");
5321
+ }
5322
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
5323
+ throw new SyntaxError("Object contains forbidden prototype property");
5324
+ }
5325
+ for (const key in node) {
5326
+ const value = node[key];
5327
+ if (value && typeof value === "object") {
5328
+ next.push(value);
5329
+ }
5330
+ }
5331
+ }
5332
+ }
5333
+ return obj;
5334
+ }
5335
+ function secureJsonParse3(text) {
5336
+ const { stackTraceLimit } = Error;
5337
+ Error.stackTraceLimit = 0;
5338
+ try {
5339
+ return _parse3(text);
5340
+ } finally {
5341
+ Error.stackTraceLimit = stackTraceLimit;
5342
+ }
5343
+ }
5344
+ var validatorSymbol3 = Symbol.for("vercel.ai.validator");
5345
+ function validator3(validate) {
5346
+ return { [validatorSymbol3]: true, validate };
5347
+ }
5348
+ function isValidator3(value) {
5349
+ return typeof value === "object" && value !== null && validatorSymbol3 in value && value[validatorSymbol3] === true && "validate" in value;
5350
+ }
5351
+ function asValidator3(value) {
5352
+ return isValidator3(value) ? value : standardSchemaValidator3(value);
5353
+ }
5354
+ function standardSchemaValidator3(standardSchema) {
5355
+ return validator3(async (value) => {
5356
+ const result = await standardSchema["~standard"].validate(value);
5357
+ return result.issues == null ? { success: true, value: result.value } : {
5358
+ success: false,
5359
+ error: new TypeValidationError2({
5360
+ value,
5361
+ cause: result.issues
5362
+ })
5363
+ };
5364
+ });
5365
+ }
5366
+ async function validateTypes3({
5367
+ value,
5368
+ schema
5369
+ }) {
5370
+ const result = await safeValidateTypes3({ value, schema });
5371
+ if (!result.success) {
5372
+ throw TypeValidationError2.wrap({ value, cause: result.error });
5373
+ }
5374
+ return result.value;
5375
+ }
5376
+ async function safeValidateTypes3({
5377
+ value,
5378
+ schema
5379
+ }) {
5380
+ const validator22 = asValidator3(schema);
5381
+ try {
5382
+ if (validator22.validate == null) {
5383
+ return { success: true, value, rawValue: value };
5384
+ }
5385
+ const result = await validator22.validate(value);
5386
+ if (result.success) {
5387
+ return { success: true, value: result.value, rawValue: value };
5388
+ }
5389
+ return {
5390
+ success: false,
5391
+ error: TypeValidationError2.wrap({ value, cause: result.error }),
5392
+ rawValue: value
5393
+ };
5394
+ } catch (error) {
5395
+ return {
5396
+ success: false,
5397
+ error: TypeValidationError2.wrap({ value, cause: error }),
5398
+ rawValue: value
5399
+ };
5400
+ }
5401
+ }
5402
+ async function parseJSON3({
5403
+ text,
5404
+ schema
5405
+ }) {
5406
+ try {
5407
+ const value = secureJsonParse3(text);
5408
+ if (schema == null) {
5409
+ return value;
5410
+ }
5411
+ return validateTypes3({ value, schema });
5412
+ } catch (error) {
5413
+ if (JSONParseError2.isInstance(error) || TypeValidationError2.isInstance(error)) {
5414
+ throw error;
5415
+ }
5416
+ throw new JSONParseError2({ text, cause: error });
5417
+ }
5418
+ }
5419
+ async function safeParseJSON3({
5420
+ text,
5421
+ schema
5422
+ }) {
5423
+ try {
5424
+ const value = secureJsonParse3(text);
5425
+ if (schema == null) {
5426
+ return { success: true, value, rawValue: value };
5427
+ }
5428
+ return await safeValidateTypes3({ value, schema });
5429
+ } catch (error) {
5430
+ return {
5431
+ success: false,
5432
+ error: JSONParseError2.isInstance(error) ? error : new JSONParseError2({ text, cause: error }),
5433
+ rawValue: void 0
5434
+ };
5435
+ }
5436
+ }
5437
+ function isParsableJson2(input) {
5438
+ try {
5439
+ secureJsonParse3(input);
5440
+ return true;
5441
+ } catch (e) {
5442
+ return false;
5443
+ }
5444
+ }
5445
+ function parseJsonEventStream3({
5446
+ stream,
5447
+ schema
5448
+ }) {
5449
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream2()).pipeThrough(
5450
+ new TransformStream({
5451
+ async transform({ data }, controller) {
5452
+ if (data === "[DONE]") {
5453
+ return;
5454
+ }
5455
+ controller.enqueue(await safeParseJSON3({ text: data, schema }));
5456
+ }
5457
+ })
5458
+ );
5459
+ }
5460
+ var getOriginalFetch23 = () => globalThis.fetch;
5461
+ var postJsonToApi4 = async ({
5462
+ url,
5463
+ headers,
5464
+ body,
5465
+ failedResponseHandler,
5466
+ successfulResponseHandler,
5467
+ abortSignal,
5468
+ fetch: fetch2
5469
+ }) => postToApi3({
5470
+ url,
5471
+ headers: __spreadValues({
5472
+ "Content-Type": "application/json"
5473
+ }, headers),
5474
+ body: {
5475
+ content: JSON.stringify(body),
5476
+ values: body
5477
+ },
5478
+ failedResponseHandler,
5479
+ successfulResponseHandler,
5480
+ abortSignal,
5481
+ fetch: fetch2
5482
+ });
5483
+ var postToApi3 = async ({
5484
+ url,
5485
+ headers = {},
5486
+ body,
5487
+ successfulResponseHandler,
5488
+ failedResponseHandler,
5489
+ abortSignal,
5490
+ fetch: fetch2 = getOriginalFetch23()
5491
+ }) => {
5492
+ try {
5493
+ const response = await fetch2(url, {
5494
+ method: "POST",
5495
+ headers: removeUndefinedEntries2(headers),
5496
+ body: body.content,
5497
+ signal: abortSignal
5498
+ });
5499
+ const responseHeaders = extractResponseHeaders3(response);
5500
+ if (!response.ok) {
5501
+ let errorInformation;
5502
+ try {
5503
+ errorInformation = await failedResponseHandler({
5504
+ response,
5505
+ url,
5506
+ requestBodyValues: body.values
5507
+ });
5508
+ } catch (error) {
5509
+ if (isAbortError3(error) || APICallError2.isInstance(error)) {
5510
+ throw error;
5511
+ }
5512
+ throw new APICallError2({
5513
+ message: "Failed to process error response",
5514
+ cause: error,
5515
+ statusCode: response.status,
5516
+ url,
5517
+ responseHeaders,
5518
+ requestBodyValues: body.values
5519
+ });
5520
+ }
5521
+ throw errorInformation.value;
5522
+ }
5523
+ try {
5524
+ return await successfulResponseHandler({
5525
+ response,
5526
+ url,
5527
+ requestBodyValues: body.values
5528
+ });
5529
+ } catch (error) {
5530
+ if (error instanceof Error) {
5531
+ if (isAbortError3(error) || APICallError2.isInstance(error)) {
5532
+ throw error;
5533
+ }
5534
+ }
5535
+ throw new APICallError2({
5536
+ message: "Failed to process successful response",
5537
+ cause: error,
5538
+ statusCode: response.status,
5539
+ url,
5540
+ responseHeaders,
5541
+ requestBodyValues: body.values
5542
+ });
5543
+ }
5544
+ } catch (error) {
5545
+ throw handleFetchError3({ error, url, requestBodyValues: body.values });
5546
+ }
5547
+ };
5548
+ var createJsonErrorResponseHandler4 = ({
5549
+ errorSchema,
5550
+ errorToMessage: errorToMessage2,
5551
+ isRetryable
5552
+ }) => async ({ response, url, requestBodyValues }) => {
5553
+ const responseBody = await response.text();
5554
+ const responseHeaders = extractResponseHeaders3(response);
5555
+ if (responseBody.trim() === "") {
5556
+ return {
5557
+ responseHeaders,
5558
+ value: new APICallError2({
5559
+ message: response.statusText,
5560
+ url,
5561
+ requestBodyValues,
5562
+ statusCode: response.status,
5563
+ responseHeaders,
5564
+ responseBody,
5565
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5566
+ })
5567
+ };
5568
+ }
5569
+ try {
5570
+ const parsedError = await parseJSON3({
5571
+ text: responseBody,
5572
+ schema: errorSchema
5573
+ });
5574
+ return {
5575
+ responseHeaders,
5576
+ value: new APICallError2({
5577
+ message: errorToMessage2(parsedError),
5578
+ url,
5579
+ requestBodyValues,
5580
+ statusCode: response.status,
5581
+ responseHeaders,
5582
+ responseBody,
5583
+ data: parsedError,
5584
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
5585
+ })
5586
+ };
5587
+ } catch (parseError) {
5588
+ return {
5589
+ responseHeaders,
5590
+ value: new APICallError2({
5591
+ message: response.statusText,
5592
+ url,
5593
+ requestBodyValues,
5594
+ statusCode: response.status,
5595
+ responseHeaders,
5596
+ responseBody,
5597
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5598
+ })
5599
+ };
5600
+ }
5601
+ };
5602
+ var createEventSourceResponseHandler4 = (chunkSchema) => async ({ response }) => {
5603
+ const responseHeaders = extractResponseHeaders3(response);
5604
+ if (response.body == null) {
5605
+ throw new EmptyResponseBodyError2({});
5606
+ }
5607
+ return {
5608
+ responseHeaders,
5609
+ value: parseJsonEventStream3({
5610
+ stream: response.body,
5611
+ schema: chunkSchema
5612
+ })
5613
+ };
5614
+ };
5615
+ var createJsonResponseHandler4 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
5616
+ const responseBody = await response.text();
5617
+ const parsedResult = await safeParseJSON3({
5618
+ text: responseBody,
5619
+ schema: responseSchema
5620
+ });
5621
+ const responseHeaders = extractResponseHeaders3(response);
5622
+ if (!parsedResult.success) {
5623
+ throw new APICallError2({
5624
+ message: "Invalid JSON response",
5625
+ cause: parsedResult.error,
5626
+ statusCode: response.status,
5627
+ responseHeaders,
5628
+ responseBody,
5629
+ url,
5630
+ requestBodyValues
5631
+ });
5632
+ }
5633
+ return {
5634
+ responseHeaders,
5635
+ value: parsedResult.value,
5636
+ rawValue: parsedResult.rawValue
5637
+ };
5638
+ };
5639
+ var { btoa: btoa3} = globalThis;
5640
+ function convertUint8ArrayToBase642(array) {
5641
+ let latin1string = "";
5642
+ for (let i = 0; i < array.length; i++) {
5643
+ latin1string += String.fromCodePoint(array[i]);
5644
+ }
5645
+ return btoa3(latin1string);
5646
+ }
5647
+ function withoutTrailingSlash4(url) {
5648
+ return url == null ? void 0 : url.replace(/\/$/, "");
5649
+ }
5650
+ function isDefinedOrNotNull(value) {
5651
+ return value !== null && value !== void 0;
5652
+ }
5653
+ var ReasoningFormat = /* @__PURE__ */ ((ReasoningFormat2) => {
5654
+ ReasoningFormat2["Unknown"] = "unknown";
5655
+ ReasoningFormat2["OpenAIResponsesV1"] = "openai-responses-v1";
5656
+ ReasoningFormat2["XAIResponsesV1"] = "xai-responses-v1";
5657
+ ReasoningFormat2["AnthropicClaudeV1"] = "anthropic-claude-v1";
5658
+ return ReasoningFormat2;
5659
+ })(ReasoningFormat || {});
5660
+ var CommonReasoningDetailSchema = z4.z.object({
5661
+ id: z4.z.string().nullish(),
5662
+ format: z4.z.nativeEnum(ReasoningFormat).nullish(),
5663
+ index: z4.z.number().optional()
5664
+ }).passthrough();
5665
+ var ReasoningDetailSummarySchema = z4.z.object({
5666
+ type: z4.z.literal(
5667
+ "reasoning.summary"
5668
+ /* Summary */
5669
+ ),
5670
+ summary: z4.z.string()
5671
+ }).extend(CommonReasoningDetailSchema.shape);
5672
+ var ReasoningDetailEncryptedSchema = z4.z.object({
5673
+ type: z4.z.literal(
5674
+ "reasoning.encrypted"
5675
+ /* Encrypted */
5676
+ ),
5677
+ data: z4.z.string()
5678
+ }).extend(CommonReasoningDetailSchema.shape);
5679
+ var ReasoningDetailTextSchema = z4.z.object({
5680
+ type: z4.z.literal(
5681
+ "reasoning.text"
5682
+ /* Text */
5683
+ ),
5684
+ text: z4.z.string().nullish(),
5685
+ signature: z4.z.string().nullish()
5686
+ }).extend(CommonReasoningDetailSchema.shape);
5687
+ var ReasoningDetailUnionSchema = z4.z.union([
5688
+ ReasoningDetailSummarySchema,
5689
+ ReasoningDetailEncryptedSchema,
5690
+ ReasoningDetailTextSchema
5691
+ ]);
5692
+ var ReasoningDetailsWithUnknownSchema = z4.z.union([
5693
+ ReasoningDetailUnionSchema,
5694
+ z4.z.unknown().transform(() => null)
5695
+ ]);
5696
+ var ReasoningDetailArraySchema = z4.z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
5697
+ z4.z.union([
5698
+ z4.z.object({
5699
+ delta: z4.z.object({
5700
+ reasoning_details: z4.z.array(ReasoningDetailsWithUnknownSchema)
5701
+ })
5702
+ }).transform(
5703
+ (data) => data.delta.reasoning_details.filter(isDefinedOrNotNull)
5704
+ ),
5705
+ z4.z.object({
5706
+ message: z4.z.object({
5707
+ reasoning_details: z4.z.array(ReasoningDetailsWithUnknownSchema)
5708
+ })
5709
+ }).transform(
5710
+ (data) => data.message.reasoning_details.filter(isDefinedOrNotNull)
5711
+ ),
5712
+ z4.z.object({
5713
+ text: z4.z.string(),
5714
+ reasoning_details: z4.z.array(ReasoningDetailsWithUnknownSchema)
5715
+ }).transform((data) => data.reasoning_details.filter(isDefinedOrNotNull))
5716
+ ]);
5717
+ var OpenRouterErrorResponseSchema = z4.z.object({
5718
+ error: z4.z.object({
5719
+ code: z4.z.union([z4.z.string(), z4.z.number()]).nullable().optional().default(null),
5720
+ message: z4.z.string(),
5721
+ type: z4.z.string().nullable().optional().default(null),
5722
+ param: z4.z.any().nullable().optional().default(null)
5723
+ }).passthrough()
5724
+ }).passthrough();
5725
+ var openrouterFailedResponseHandler = createJsonErrorResponseHandler4({
5726
+ errorSchema: OpenRouterErrorResponseSchema,
5727
+ errorToMessage: (data) => data.error.message
5728
+ });
5729
+ var OpenRouterProviderMetadataSchema = z4.z.object({
5730
+ provider: z4.z.string(),
5731
+ reasoning_details: z4.z.array(ReasoningDetailUnionSchema).optional(),
5732
+ usage: z4.z.object({
5733
+ promptTokens: z4.z.number(),
5734
+ promptTokensDetails: z4.z.object({
5735
+ cachedTokens: z4.z.number()
5736
+ }).passthrough().optional(),
5737
+ completionTokens: z4.z.number(),
5738
+ completionTokensDetails: z4.z.object({
5739
+ reasoningTokens: z4.z.number()
5740
+ }).passthrough().optional(),
5741
+ totalTokens: z4.z.number(),
5742
+ cost: z4.z.number().optional(),
5743
+ costDetails: z4.z.object({
5744
+ upstreamInferenceCost: z4.z.number()
5745
+ }).passthrough()
5746
+ }).passthrough()
5747
+ }).passthrough();
5748
+ var OpenRouterProviderOptionsSchema = z4.z.object({
5749
+ openrouter: z4.z.object({
5750
+ reasoning_details: z4.z.array(ReasoningDetailUnionSchema).optional()
5751
+ }).optional()
5752
+ }).optional();
5753
+ function mapOpenRouterFinishReason(finishReason) {
5754
+ switch (finishReason) {
5755
+ case "stop":
5756
+ return "stop";
5757
+ case "length":
5758
+ return "length";
5759
+ case "content_filter":
5760
+ return "content-filter";
5761
+ case "function_call":
5762
+ case "tool_calls":
5763
+ return "tool-calls";
5764
+ default:
5765
+ return "unknown";
5766
+ }
5767
+ }
5768
+ function isUrl({
5769
+ url,
5770
+ protocols
5771
+ }) {
5772
+ try {
5773
+ const urlObj = new URL(url);
5774
+ return protocols.has(urlObj.protocol);
5775
+ } catch (_) {
5776
+ return false;
5777
+ }
5778
+ }
5779
+ function getFileUrl({
5780
+ part,
5781
+ defaultMediaType
5782
+ }) {
5783
+ var _a15, _b;
5784
+ if (part.data instanceof Uint8Array) {
5785
+ const base64 = convertUint8ArrayToBase642(part.data);
5786
+ return `data:${(_a15 = part.mediaType) != null ? _a15 : defaultMediaType};base64,${base64}`;
5787
+ }
5788
+ const stringUrl = part.data.toString();
5789
+ if (isUrl({
5790
+ url: stringUrl,
5791
+ protocols: /* @__PURE__ */ new Set(["http:", "https:"])
5792
+ })) {
5793
+ return stringUrl;
5794
+ }
5795
+ return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b = part.mediaType) != null ? _b : defaultMediaType};base64,${stringUrl}`;
5796
+ }
5797
+ function getMediaType(dataUrl, defaultMediaType) {
5798
+ var _a15;
5799
+ const match = dataUrl.match(/^data:([^;]+)/);
5800
+ return match ? (_a15 = match[1]) != null ? _a15 : defaultMediaType : defaultMediaType;
5801
+ }
5802
+ function getBase64FromDataUrl(dataUrl) {
5803
+ const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
5804
+ return match ? match[1] : dataUrl;
5805
+ }
5806
+ function getCacheControl(providerMetadata) {
5807
+ var _a15, _b, _c;
5808
+ const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
5809
+ const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
5810
+ 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;
5811
+ }
5812
+ function convertToOpenRouterChatMessages(prompt) {
5813
+ var _a15, _b, _c, _d, _e;
5814
+ const messages = [];
5815
+ for (const { role, content, providerOptions } of prompt) {
5816
+ switch (role) {
5817
+ case "system": {
5818
+ messages.push({
5819
+ role: "system",
5820
+ content,
5821
+ cache_control: getCacheControl(providerOptions)
5822
+ });
5823
+ break;
5824
+ }
5825
+ case "user": {
5826
+ if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
5827
+ const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
5828
+ const contentWithCacheControl = cacheControl ? [
5829
+ {
5830
+ type: "text",
5831
+ text: content[0].text,
5832
+ cache_control: cacheControl
5833
+ }
5834
+ ] : content[0].text;
5835
+ messages.push({
5836
+ role: "user",
5837
+ content: contentWithCacheControl
5838
+ });
5839
+ break;
5840
+ }
5841
+ const messageCacheControl = getCacheControl(providerOptions);
5842
+ const contentParts = content.map(
5843
+ (part) => {
5844
+ var _a16, _b2, _c2, _d2, _e2, _f;
5845
+ const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
5846
+ switch (part.type) {
5847
+ case "text":
5848
+ return {
5849
+ type: "text",
5850
+ text: part.text,
5851
+ // For text parts, only use part-specific cache control
5852
+ cache_control: cacheControl
5853
+ };
5854
+ case "file": {
5855
+ if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
5856
+ const url = getFileUrl({
5857
+ part,
5858
+ defaultMediaType: "image/jpeg"
5859
+ });
5860
+ return {
5861
+ type: "image_url",
5862
+ image_url: {
5863
+ url
5864
+ },
5865
+ // For image parts, use part-specific or message-level cache control
5866
+ cache_control: cacheControl
5867
+ };
5868
+ }
5869
+ const fileName = String(
5870
+ (_f = (_e2 = (_d2 = (_c2 = part.providerOptions) == null ? void 0 : _c2.openrouter) == null ? void 0 : _d2.filename) != null ? _e2 : part.filename) != null ? _f : ""
5871
+ );
5872
+ const fileData = getFileUrl({
5873
+ part,
5874
+ defaultMediaType: "application/pdf"
5875
+ });
5876
+ if (isUrl({
5877
+ url: fileData,
5878
+ protocols: /* @__PURE__ */ new Set(["http:", "https:"])
5879
+ })) {
5880
+ return {
5881
+ type: "file",
5882
+ file: {
5883
+ filename: fileName,
5884
+ file_data: fileData
5885
+ }
5886
+ };
5887
+ }
5888
+ return {
5889
+ type: "file",
5890
+ file: {
5891
+ filename: fileName,
5892
+ file_data: fileData
5893
+ },
5894
+ cache_control: cacheControl
5895
+ };
5896
+ }
5897
+ default: {
5898
+ return {
5899
+ type: "text",
5900
+ text: "",
5901
+ cache_control: cacheControl
5902
+ };
5903
+ }
5904
+ }
5905
+ }
5906
+ );
5907
+ messages.push({
5908
+ role: "user",
5909
+ content: contentParts
5910
+ });
5911
+ break;
5912
+ }
5913
+ case "assistant": {
5914
+ let text = "";
5915
+ let reasoning = "";
5916
+ const toolCalls = [];
5917
+ for (const part of content) {
5918
+ switch (part.type) {
5919
+ case "text": {
5920
+ text += part.text;
5921
+ break;
5922
+ }
5923
+ case "tool-call": {
5924
+ toolCalls.push({
5925
+ id: part.toolCallId,
5926
+ type: "function",
5927
+ function: {
5928
+ name: part.toolName,
5929
+ arguments: JSON.stringify(part.input)
5930
+ }
5931
+ });
5932
+ break;
5933
+ }
5934
+ case "reasoning": {
5935
+ reasoning += part.text;
5936
+ break;
5937
+ }
5938
+ }
5939
+ }
5940
+ const parsedProviderOptions = OpenRouterProviderOptionsSchema.safeParse(providerOptions);
5941
+ const preservedReasoningDetails = parsedProviderOptions.success ? (_d = (_c = parsedProviderOptions.data) == null ? void 0 : _c.openrouter) == null ? void 0 : _d.reasoning_details : void 0;
5942
+ messages.push({
5943
+ role: "assistant",
5944
+ content: text,
5945
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
5946
+ reasoning: reasoning || void 0,
5947
+ // Only include reasoning_details if we have the preserved original version
5948
+ reasoning_details: preservedReasoningDetails && Array.isArray(preservedReasoningDetails) && preservedReasoningDetails.length > 0 ? preservedReasoningDetails : void 0,
5949
+ cache_control: getCacheControl(providerOptions)
5950
+ });
5951
+ break;
5952
+ }
5953
+ case "tool": {
5954
+ for (const toolResponse of content) {
5955
+ const content2 = getToolResultContent(toolResponse);
5956
+ messages.push({
5957
+ role: "tool",
5958
+ tool_call_id: toolResponse.toolCallId,
5959
+ content: content2,
5960
+ cache_control: (_e = getCacheControl(providerOptions)) != null ? _e : getCacheControl(toolResponse.providerOptions)
5961
+ });
5962
+ }
5963
+ break;
5964
+ }
5965
+ }
5966
+ }
5967
+ return messages;
5968
+ }
5969
+ function getToolResultContent(input) {
5970
+ return input.output.type === "text" ? input.output.value : JSON.stringify(input.output.value);
5971
+ }
5972
+ z4.z.union([
5973
+ z4.z.literal("auto"),
5974
+ z4.z.literal("none"),
5975
+ z4.z.literal("required"),
5976
+ z4.z.object({
5977
+ type: z4.z.literal("function"),
5978
+ function: z4.z.object({
5979
+ name: z4.z.string()
5980
+ })
5981
+ })
5982
+ ]);
5983
+ function getChatCompletionToolChoice(toolChoice) {
5984
+ switch (toolChoice.type) {
5985
+ case "auto":
5986
+ case "none":
5987
+ case "required":
5988
+ return toolChoice.type;
5989
+ case "tool": {
5990
+ return {
5991
+ type: "function",
5992
+ function: { name: toolChoice.toolName }
5993
+ };
5994
+ }
5995
+ default: {
5996
+ throw new InvalidArgumentError2({
5997
+ argument: "toolChoice",
5998
+ message: `Invalid tool choice type: ${JSON.stringify(toolChoice)}`
5999
+ });
6000
+ }
6001
+ }
6002
+ }
6003
+ var ImageResponseSchema = z4.z.object({
6004
+ type: z4.z.literal("image_url"),
6005
+ image_url: z4.z.object({
6006
+ url: z4.z.string()
6007
+ }).passthrough()
6008
+ }).passthrough();
6009
+ var ImageResponseWithUnknownSchema = z4.z.union([
6010
+ ImageResponseSchema,
6011
+ z4.z.unknown().transform(() => null)
6012
+ ]);
6013
+ var ImageResponseArraySchema = z4.z.array(ImageResponseWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
6014
+ var OpenRouterChatCompletionBaseResponseSchema = z4.z.object({
6015
+ id: z4.z.string().optional(),
6016
+ model: z4.z.string().optional(),
6017
+ provider: z4.z.string().optional(),
6018
+ usage: z4.z.object({
6019
+ prompt_tokens: z4.z.number(),
6020
+ prompt_tokens_details: z4.z.object({
6021
+ cached_tokens: z4.z.number()
6022
+ }).passthrough().nullish(),
6023
+ completion_tokens: z4.z.number(),
6024
+ completion_tokens_details: z4.z.object({
6025
+ reasoning_tokens: z4.z.number()
6026
+ }).passthrough().nullish(),
6027
+ total_tokens: z4.z.number(),
6028
+ cost: z4.z.number().optional(),
6029
+ cost_details: z4.z.object({
6030
+ upstream_inference_cost: z4.z.number().nullish()
6031
+ }).passthrough().nullish()
6032
+ }).passthrough().nullish()
6033
+ }).passthrough();
6034
+ var OpenRouterNonStreamChatCompletionResponseSchema = z4.z.union([
6035
+ // Success response with choices
6036
+ OpenRouterChatCompletionBaseResponseSchema.extend({
6037
+ choices: z4.z.array(
6038
+ z4.z.object({
6039
+ message: z4.z.object({
6040
+ role: z4.z.literal("assistant"),
6041
+ content: z4.z.string().nullable().optional(),
6042
+ reasoning: z4.z.string().nullable().optional(),
6043
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
6044
+ images: ImageResponseArraySchema.nullish(),
6045
+ tool_calls: z4.z.array(
6046
+ z4.z.object({
6047
+ id: z4.z.string().optional().nullable(),
6048
+ type: z4.z.literal("function"),
6049
+ function: z4.z.object({
6050
+ name: z4.z.string(),
6051
+ arguments: z4.z.string()
6052
+ }).passthrough()
6053
+ }).passthrough()
6054
+ ).optional(),
6055
+ annotations: z4.z.array(
6056
+ z4.z.union([
6057
+ // URL citation from web search
6058
+ z4.z.object({
6059
+ type: z4.z.literal("url_citation"),
6060
+ url_citation: z4.z.object({
6061
+ end_index: z4.z.number(),
6062
+ start_index: z4.z.number(),
6063
+ title: z4.z.string(),
6064
+ url: z4.z.string(),
6065
+ content: z4.z.string().optional()
6066
+ }).passthrough()
6067
+ }).passthrough(),
6068
+ // File annotation from FileParserPlugin (old format)
6069
+ z4.z.object({
6070
+ type: z4.z.literal("file_annotation"),
6071
+ file_annotation: z4.z.object({
6072
+ file_id: z4.z.string(),
6073
+ quote: z4.z.string().optional()
6074
+ }).passthrough()
6075
+ }).passthrough(),
6076
+ // File annotation from FileParserPlugin (new format)
6077
+ z4.z.object({
6078
+ type: z4.z.literal("file"),
6079
+ file: z4.z.object({
6080
+ hash: z4.z.string(),
6081
+ name: z4.z.string(),
6082
+ content: z4.z.array(
6083
+ z4.z.object({
6084
+ type: z4.z.string(),
6085
+ text: z4.z.string()
6086
+ }).passthrough()
6087
+ ).optional()
6088
+ }).passthrough()
6089
+ }).passthrough()
6090
+ ])
6091
+ ).nullish()
6092
+ }).passthrough(),
6093
+ index: z4.z.number().nullish(),
6094
+ logprobs: z4.z.object({
6095
+ content: z4.z.array(
6096
+ z4.z.object({
6097
+ token: z4.z.string(),
6098
+ logprob: z4.z.number(),
6099
+ top_logprobs: z4.z.array(
6100
+ z4.z.object({
6101
+ token: z4.z.string(),
6102
+ logprob: z4.z.number()
6103
+ }).passthrough()
6104
+ )
6105
+ }).passthrough()
6106
+ ).nullable()
6107
+ }).passthrough().nullable().optional(),
6108
+ finish_reason: z4.z.string().optional().nullable()
6109
+ }).passthrough()
6110
+ )
6111
+ }),
6112
+ // Error response (HTTP 200 with error payload)
6113
+ OpenRouterErrorResponseSchema.extend({
6114
+ user_id: z4.z.string().optional()
6115
+ })
6116
+ ]);
6117
+ var OpenRouterStreamChatCompletionChunkSchema = z4.z.union([
6118
+ OpenRouterChatCompletionBaseResponseSchema.extend({
6119
+ choices: z4.z.array(
6120
+ z4.z.object({
6121
+ delta: z4.z.object({
6122
+ role: z4.z.enum(["assistant"]).optional(),
6123
+ content: z4.z.string().nullish(),
6124
+ reasoning: z4.z.string().nullish().optional(),
6125
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
6126
+ images: ImageResponseArraySchema.nullish(),
6127
+ tool_calls: z4.z.array(
6128
+ z4.z.object({
6129
+ index: z4.z.number().nullish(),
6130
+ id: z4.z.string().nullish(),
6131
+ type: z4.z.literal("function").optional(),
6132
+ function: z4.z.object({
6133
+ name: z4.z.string().nullish(),
6134
+ arguments: z4.z.string().nullish()
6135
+ }).passthrough()
6136
+ }).passthrough()
6137
+ ).nullish(),
6138
+ annotations: z4.z.array(
6139
+ z4.z.union([
6140
+ // URL citation from web search
6141
+ z4.z.object({
6142
+ type: z4.z.literal("url_citation"),
6143
+ url_citation: z4.z.object({
6144
+ end_index: z4.z.number(),
6145
+ start_index: z4.z.number(),
6146
+ title: z4.z.string(),
6147
+ url: z4.z.string(),
6148
+ content: z4.z.string().optional()
6149
+ }).passthrough()
6150
+ }).passthrough(),
6151
+ // File annotation from FileParserPlugin (old format)
6152
+ z4.z.object({
6153
+ type: z4.z.literal("file_annotation"),
6154
+ file_annotation: z4.z.object({
6155
+ file_id: z4.z.string(),
6156
+ quote: z4.z.string().optional()
6157
+ }).passthrough()
6158
+ }).passthrough(),
6159
+ // File annotation from FileParserPlugin (new format)
6160
+ z4.z.object({
6161
+ type: z4.z.literal("file"),
6162
+ file: z4.z.object({
6163
+ hash: z4.z.string(),
6164
+ name: z4.z.string(),
6165
+ content: z4.z.array(
6166
+ z4.z.object({
6167
+ type: z4.z.string(),
6168
+ text: z4.z.string()
6169
+ }).passthrough()
6170
+ ).optional()
6171
+ }).passthrough()
6172
+ }).passthrough()
6173
+ ])
6174
+ ).nullish()
6175
+ }).passthrough().nullish(),
6176
+ logprobs: z4.z.object({
6177
+ content: z4.z.array(
6178
+ z4.z.object({
6179
+ token: z4.z.string(),
6180
+ logprob: z4.z.number(),
6181
+ top_logprobs: z4.z.array(
6182
+ z4.z.object({
6183
+ token: z4.z.string(),
6184
+ logprob: z4.z.number()
6185
+ }).passthrough()
6186
+ )
6187
+ }).passthrough()
6188
+ ).nullable()
6189
+ }).passthrough().nullish(),
6190
+ finish_reason: z4.z.string().nullable().optional(),
6191
+ index: z4.z.number().nullish()
6192
+ }).passthrough()
6193
+ )
6194
+ }),
6195
+ OpenRouterErrorResponseSchema
6196
+ ]);
6197
+ var OpenRouterChatLanguageModel = class {
6198
+ constructor(modelId, settings, config) {
6199
+ this.specificationVersion = "v2";
6200
+ this.provider = "openrouter";
6201
+ this.defaultObjectGenerationMode = "tool";
6202
+ this.supportedUrls = {
6203
+ "image/*": [
6204
+ /^data:image\/[a-zA-Z]+;base64,/,
6205
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
6206
+ ],
6207
+ // 'text/*': [/^data:text\//, /^https?:\/\/.+$/],
6208
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
6209
+ };
6210
+ this.modelId = modelId;
6211
+ this.settings = settings;
6212
+ this.config = config;
6213
+ }
6214
+ getArgs({
6215
+ prompt,
6216
+ maxOutputTokens,
6217
+ temperature,
6218
+ topP,
6219
+ frequencyPenalty,
6220
+ presencePenalty,
6221
+ seed,
6222
+ stopSequences,
6223
+ responseFormat,
6224
+ topK,
6225
+ tools,
6226
+ toolChoice
6227
+ }) {
6228
+ var _a15;
6229
+ const baseArgs = __spreadValues(__spreadValues({
6230
+ // model id:
6231
+ model: this.modelId,
6232
+ models: this.settings.models,
6233
+ // model specific settings:
6234
+ logit_bias: this.settings.logitBias,
6235
+ logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
6236
+ top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
6237
+ user: this.settings.user,
6238
+ parallel_tool_calls: this.settings.parallelToolCalls,
6239
+ // standardized settings:
6240
+ max_tokens: maxOutputTokens,
6241
+ temperature,
6242
+ top_p: topP,
6243
+ frequency_penalty: frequencyPenalty,
6244
+ presence_penalty: presencePenalty,
6245
+ seed,
6246
+ stop: stopSequences,
6247
+ response_format: responseFormat,
6248
+ top_k: topK,
6249
+ // messages:
6250
+ messages: convertToOpenRouterChatMessages(prompt),
6251
+ // OpenRouter specific settings:
6252
+ include_reasoning: this.settings.includeReasoning,
6253
+ reasoning: this.settings.reasoning,
6254
+ usage: this.settings.usage,
6255
+ // Web search settings:
6256
+ plugins: this.settings.plugins,
6257
+ web_search_options: this.settings.web_search_options,
6258
+ // Provider routing settings:
6259
+ provider: this.settings.provider
6260
+ }, this.config.extraBody), this.settings.extraBody);
6261
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null) {
6262
+ return __spreadProps(__spreadValues({}, baseArgs), {
6263
+ response_format: {
6264
+ type: "json_schema",
6265
+ json_schema: __spreadValues({
6266
+ schema: responseFormat.schema,
6267
+ strict: true,
6268
+ name: (_a15 = responseFormat.name) != null ? _a15 : "response"
6269
+ }, responseFormat.description && {
6270
+ description: responseFormat.description
6271
+ })
6272
+ }
6273
+ });
6274
+ }
6275
+ if (tools && tools.length > 0) {
6276
+ const mappedTools = tools.filter((tool) => tool.type === "function").map((tool) => ({
6277
+ type: "function",
6278
+ function: {
6279
+ name: tool.name,
6280
+ description: tool.description,
6281
+ parameters: tool.inputSchema
6282
+ }
6283
+ }));
6284
+ return __spreadProps(__spreadValues({}, baseArgs), {
6285
+ tools: mappedTools,
6286
+ tool_choice: toolChoice ? getChatCompletionToolChoice(toolChoice) : void 0
6287
+ });
6288
+ }
6289
+ return baseArgs;
6290
+ }
6291
+ async doGenerate(options) {
6292
+ 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, _y;
6293
+ const providerOptions = options.providerOptions || {};
6294
+ const openrouterOptions = providerOptions.openrouter || {};
6295
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
6296
+ const { value: responseValue, responseHeaders } = await postJsonToApi4({
6297
+ url: this.config.url({
6298
+ path: "/chat/completions",
6299
+ modelId: this.modelId
6300
+ }),
6301
+ headers: combineHeaders4(this.config.headers(), options.headers),
6302
+ body: args,
6303
+ failedResponseHandler: openrouterFailedResponseHandler,
6304
+ successfulResponseHandler: createJsonResponseHandler4(
6305
+ OpenRouterNonStreamChatCompletionResponseSchema
6306
+ ),
6307
+ abortSignal: options.abortSignal,
6308
+ fetch: this.config.fetch
6309
+ });
6310
+ if ("error" in responseValue) {
6311
+ const errorData = responseValue.error;
6312
+ throw new APICallError2({
6313
+ message: errorData.message,
6314
+ url: this.config.url({
6315
+ path: "/chat/completions",
6316
+ modelId: this.modelId
6317
+ }),
6318
+ requestBodyValues: args,
6319
+ statusCode: 200,
6320
+ responseHeaders,
6321
+ data: errorData
6322
+ });
6323
+ }
6324
+ const response = responseValue;
6325
+ const choice = response.choices[0];
6326
+ if (!choice) {
6327
+ throw new NoContentGeneratedError({
6328
+ message: "No choice in response"
6329
+ });
6330
+ }
6331
+ const usageInfo = response.usage ? {
6332
+ inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
6333
+ outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
6334
+ totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
6335
+ reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
6336
+ cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
6337
+ } : {
6338
+ inputTokens: 0,
6339
+ outputTokens: 0,
6340
+ totalTokens: 0,
6341
+ reasoningTokens: 0,
6342
+ cachedInputTokens: 0
6343
+ };
6344
+ const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
6345
+ const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
6346
+ switch (detail.type) {
6347
+ case "reasoning.text": {
6348
+ if (detail.text) {
6349
+ return {
6350
+ type: "reasoning",
6351
+ text: detail.text
6352
+ };
6353
+ }
6354
+ break;
6355
+ }
6356
+ case "reasoning.summary": {
6357
+ if (detail.summary) {
6358
+ return {
6359
+ type: "reasoning",
6360
+ text: detail.summary
6361
+ };
6362
+ }
6363
+ break;
6364
+ }
6365
+ case "reasoning.encrypted": {
6366
+ if (detail.data) {
6367
+ return {
6368
+ type: "reasoning",
6369
+ text: "[REDACTED]"
6370
+ };
6371
+ }
6372
+ break;
6373
+ }
6374
+ }
6375
+ return null;
6376
+ }).filter((p) => p !== null) : choice.message.reasoning ? [
6377
+ {
6378
+ type: "reasoning",
6379
+ text: choice.message.reasoning
6380
+ }
6381
+ ] : [];
6382
+ const content = [];
6383
+ content.push(...reasoning);
6384
+ if (choice.message.content) {
6385
+ content.push({
6386
+ type: "text",
6387
+ text: choice.message.content
6388
+ });
6389
+ }
6390
+ if (choice.message.tool_calls) {
6391
+ for (const toolCall of choice.message.tool_calls) {
6392
+ content.push({
6393
+ type: "tool-call",
6394
+ toolCallId: (_j = toolCall.id) != null ? _j : generateId4(),
6395
+ toolName: toolCall.function.name,
6396
+ input: toolCall.function.arguments
6397
+ });
6398
+ }
6399
+ }
6400
+ if (choice.message.images) {
6401
+ for (const image of choice.message.images) {
6402
+ content.push({
6403
+ type: "file",
6404
+ mediaType: getMediaType(image.image_url.url, "image/jpeg"),
6405
+ data: getBase64FromDataUrl(image.image_url.url)
6406
+ });
6407
+ }
6408
+ }
6409
+ if (choice.message.annotations) {
6410
+ for (const annotation of choice.message.annotations) {
6411
+ if (annotation.type === "url_citation") {
6412
+ content.push({
6413
+ type: "source",
6414
+ sourceType: "url",
6415
+ id: annotation.url_citation.url,
6416
+ url: annotation.url_citation.url,
6417
+ title: annotation.url_citation.title,
6418
+ providerMetadata: {
6419
+ openrouter: {
6420
+ content: annotation.url_citation.content || ""
6421
+ }
6422
+ }
6423
+ });
6424
+ }
6425
+ }
6426
+ }
6427
+ return {
6428
+ content,
6429
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
6430
+ usage: usageInfo,
6431
+ warnings: [],
6432
+ providerMetadata: {
6433
+ openrouter: OpenRouterProviderMetadataSchema.parse({
6434
+ provider: (_k = response.provider) != null ? _k : "",
6435
+ reasoning_details: (_l = choice.message.reasoning_details) != null ? _l : [],
6436
+ usage: {
6437
+ promptTokens: (_m = usageInfo.inputTokens) != null ? _m : 0,
6438
+ completionTokens: (_n = usageInfo.outputTokens) != null ? _n : 0,
6439
+ totalTokens: (_o = usageInfo.totalTokens) != null ? _o : 0,
6440
+ cost: (_p = response.usage) == null ? void 0 : _p.cost,
6441
+ promptTokensDetails: {
6442
+ cachedTokens: (_s = (_r = (_q = response.usage) == null ? void 0 : _q.prompt_tokens_details) == null ? void 0 : _r.cached_tokens) != null ? _s : 0
6443
+ },
6444
+ completionTokensDetails: {
6445
+ reasoningTokens: (_v = (_u = (_t = response.usage) == null ? void 0 : _t.completion_tokens_details) == null ? void 0 : _u.reasoning_tokens) != null ? _v : 0
6446
+ },
6447
+ costDetails: {
6448
+ upstreamInferenceCost: (_y = (_x = (_w = response.usage) == null ? void 0 : _w.cost_details) == null ? void 0 : _x.upstream_inference_cost) != null ? _y : 0
6449
+ }
6450
+ }
6451
+ })
6452
+ },
6453
+ request: { body: args },
6454
+ response: {
6455
+ id: response.id,
6456
+ modelId: response.model,
6457
+ headers: responseHeaders
6458
+ }
6459
+ };
6460
+ }
6461
+ async doStream(options) {
6462
+ var _a15;
6463
+ const providerOptions = options.providerOptions || {};
6464
+ const openrouterOptions = providerOptions.openrouter || {};
6465
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
6466
+ const { value: response, responseHeaders } = await postJsonToApi4({
6467
+ url: this.config.url({
6468
+ path: "/chat/completions",
6469
+ modelId: this.modelId
6470
+ }),
6471
+ headers: combineHeaders4(this.config.headers(), options.headers),
6472
+ body: __spreadProps(__spreadValues({}, args), {
6473
+ stream: true,
6474
+ // only include stream_options when in strict compatibility mode:
6475
+ stream_options: this.config.compatibility === "strict" ? __spreadValues({
6476
+ include_usage: true
6477
+ }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
6478
+ }),
6479
+ failedResponseHandler: openrouterFailedResponseHandler,
6480
+ successfulResponseHandler: createEventSourceResponseHandler4(
6481
+ OpenRouterStreamChatCompletionChunkSchema
6482
+ ),
6483
+ abortSignal: options.abortSignal,
6484
+ fetch: this.config.fetch
6485
+ });
6486
+ const toolCalls = [];
6487
+ let finishReason = "other";
6488
+ const usage = {
6489
+ inputTokens: Number.NaN,
6490
+ outputTokens: Number.NaN,
6491
+ totalTokens: Number.NaN,
6492
+ reasoningTokens: Number.NaN,
6493
+ cachedInputTokens: Number.NaN
6494
+ };
6495
+ const openrouterUsage = {};
6496
+ const accumulatedReasoningDetails = [];
6497
+ let textStarted = false;
6498
+ let reasoningStarted = false;
6499
+ let textId;
6500
+ let reasoningId;
6501
+ let openrouterResponseId;
6502
+ let provider;
6503
+ return {
6504
+ stream: response.pipeThrough(
6505
+ new TransformStream({
6506
+ transform(chunk, controller) {
6507
+ var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
6508
+ if (!chunk.success) {
6509
+ finishReason = "error";
6510
+ controller.enqueue({ type: "error", error: chunk.error });
6511
+ return;
6512
+ }
6513
+ const value = chunk.value;
6514
+ if ("error" in value) {
6515
+ finishReason = "error";
6516
+ controller.enqueue({ type: "error", error: value.error });
6517
+ return;
6518
+ }
6519
+ if (value.provider) {
6520
+ provider = value.provider;
6521
+ }
6522
+ if (value.id) {
6523
+ openrouterResponseId = value.id;
6524
+ controller.enqueue({
6525
+ type: "response-metadata",
6526
+ id: value.id
6527
+ });
6528
+ }
6529
+ if (value.model) {
6530
+ controller.enqueue({
6531
+ type: "response-metadata",
6532
+ modelId: value.model
6533
+ });
6534
+ }
6535
+ if (value.usage != null) {
6536
+ usage.inputTokens = value.usage.prompt_tokens;
6537
+ usage.outputTokens = value.usage.completion_tokens;
6538
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
6539
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
6540
+ if (value.usage.prompt_tokens_details) {
6541
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
6542
+ usage.cachedInputTokens = cachedInputTokens;
6543
+ openrouterUsage.promptTokensDetails = {
6544
+ cachedTokens: cachedInputTokens
6545
+ };
6546
+ }
6547
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
6548
+ if (value.usage.completion_tokens_details) {
6549
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
6550
+ usage.reasoningTokens = reasoningTokens;
6551
+ openrouterUsage.completionTokensDetails = {
6552
+ reasoningTokens
6553
+ };
6554
+ }
6555
+ openrouterUsage.cost = value.usage.cost;
6556
+ openrouterUsage.totalTokens = value.usage.total_tokens;
6557
+ }
6558
+ const choice = value.choices[0];
6559
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
6560
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
6561
+ }
6562
+ if ((choice == null ? void 0 : choice.delta) == null) {
6563
+ return;
6564
+ }
6565
+ const delta = choice.delta;
6566
+ const emitReasoningChunk = (chunkText) => {
6567
+ if (!reasoningStarted) {
6568
+ reasoningId = openrouterResponseId || generateId4();
6569
+ controller.enqueue({
6570
+ type: "reasoning-start",
6571
+ id: reasoningId
6572
+ });
6573
+ reasoningStarted = true;
6574
+ }
6575
+ controller.enqueue({
6576
+ type: "reasoning-delta",
6577
+ delta: chunkText,
6578
+ id: reasoningId || generateId4()
6579
+ });
6580
+ };
6581
+ if (delta.reasoning_details && delta.reasoning_details.length > 0) {
6582
+ accumulatedReasoningDetails.push(...delta.reasoning_details);
6583
+ for (const detail of delta.reasoning_details) {
6584
+ switch (detail.type) {
6585
+ case "reasoning.text": {
6586
+ if (detail.text) {
6587
+ emitReasoningChunk(detail.text);
6588
+ }
6589
+ break;
6590
+ }
6591
+ case "reasoning.encrypted": {
6592
+ if (detail.data) {
6593
+ emitReasoningChunk("[REDACTED]");
6594
+ }
6595
+ break;
6596
+ }
6597
+ case "reasoning.summary": {
6598
+ if (detail.summary) {
6599
+ emitReasoningChunk(detail.summary);
6600
+ }
6601
+ break;
6602
+ }
6603
+ }
6604
+ }
6605
+ } else if (delta.reasoning) {
6606
+ emitReasoningChunk(delta.reasoning);
6607
+ }
6608
+ if (delta.content) {
6609
+ if (reasoningStarted && !textStarted) {
6610
+ controller.enqueue({
6611
+ type: "reasoning-end",
6612
+ id: reasoningId || generateId4()
6613
+ });
6614
+ reasoningStarted = false;
6615
+ }
6616
+ if (!textStarted) {
6617
+ textId = openrouterResponseId || generateId4();
6618
+ controller.enqueue({
6619
+ type: "text-start",
6620
+ id: textId
6621
+ });
6622
+ textStarted = true;
6623
+ }
6624
+ controller.enqueue({
6625
+ type: "text-delta",
6626
+ delta: delta.content,
6627
+ id: textId || generateId4()
6628
+ });
6629
+ }
6630
+ if (delta.annotations) {
6631
+ for (const annotation of delta.annotations) {
6632
+ if (annotation.type === "url_citation") {
6633
+ controller.enqueue({
6634
+ type: "source",
6635
+ sourceType: "url",
6636
+ id: annotation.url_citation.url,
6637
+ url: annotation.url_citation.url,
6638
+ title: annotation.url_citation.title,
6639
+ providerMetadata: {
6640
+ openrouter: {
6641
+ content: annotation.url_citation.content || ""
6642
+ }
6643
+ }
6644
+ });
6645
+ }
6646
+ }
6647
+ }
6648
+ if (delta.tool_calls != null) {
6649
+ for (const toolCallDelta of delta.tool_calls) {
6650
+ const index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length - 1;
6651
+ if (toolCalls[index] == null) {
6652
+ if (toolCallDelta.type !== "function") {
6653
+ throw new InvalidResponseDataError2({
6654
+ data: toolCallDelta,
6655
+ message: `Expected 'function' type.`
6656
+ });
6657
+ }
6658
+ if (toolCallDelta.id == null) {
6659
+ throw new InvalidResponseDataError2({
6660
+ data: toolCallDelta,
6661
+ message: `Expected 'id' to be a string.`
6662
+ });
6663
+ }
6664
+ if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) {
6665
+ throw new InvalidResponseDataError2({
6666
+ data: toolCallDelta,
6667
+ message: `Expected 'function.name' to be a string.`
6668
+ });
6669
+ }
6670
+ toolCalls[index] = {
6671
+ id: toolCallDelta.id,
6672
+ type: "function",
6673
+ function: {
6674
+ name: toolCallDelta.function.name,
6675
+ arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
6676
+ },
6677
+ inputStarted: false,
6678
+ sent: false
6679
+ };
6680
+ const toolCall2 = toolCalls[index];
6681
+ if (toolCall2 == null) {
6682
+ throw new InvalidResponseDataError2({
6683
+ data: { index, toolCallsLength: toolCalls.length },
6684
+ message: `Tool call at index ${index} is missing after creation.`
6685
+ });
6686
+ }
6687
+ if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null && isParsableJson2(toolCall2.function.arguments)) {
6688
+ toolCall2.inputStarted = true;
6689
+ controller.enqueue({
6690
+ type: "tool-input-start",
6691
+ id: toolCall2.id,
6692
+ toolName: toolCall2.function.name
6693
+ });
6694
+ controller.enqueue({
6695
+ type: "tool-input-delta",
6696
+ id: toolCall2.id,
6697
+ delta: toolCall2.function.arguments
6698
+ });
6699
+ controller.enqueue({
6700
+ type: "tool-input-end",
6701
+ id: toolCall2.id
6702
+ });
6703
+ controller.enqueue({
6704
+ type: "tool-call",
6705
+ toolCallId: toolCall2.id,
6706
+ toolName: toolCall2.function.name,
6707
+ input: toolCall2.function.arguments
6708
+ });
6709
+ toolCall2.sent = true;
6710
+ }
6711
+ continue;
6712
+ }
6713
+ const toolCall = toolCalls[index];
6714
+ if (toolCall == null) {
6715
+ throw new InvalidResponseDataError2({
6716
+ data: {
6717
+ index,
6718
+ toolCallsLength: toolCalls.length,
6719
+ toolCallDelta
6720
+ },
6721
+ message: `Tool call at index ${index} is missing during merge.`
6722
+ });
6723
+ }
6724
+ if (!toolCall.inputStarted) {
6725
+ toolCall.inputStarted = true;
6726
+ controller.enqueue({
6727
+ type: "tool-input-start",
6728
+ id: toolCall.id,
6729
+ toolName: toolCall.function.name
6730
+ });
6731
+ }
6732
+ if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
6733
+ toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
6734
+ }
6735
+ controller.enqueue({
6736
+ type: "tool-input-delta",
6737
+ id: toolCall.id,
6738
+ delta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
6739
+ });
6740
+ if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson2(toolCall.function.arguments)) {
6741
+ controller.enqueue({
6742
+ type: "tool-call",
6743
+ toolCallId: (_n = toolCall.id) != null ? _n : generateId4(),
6744
+ toolName: toolCall.function.name,
6745
+ input: toolCall.function.arguments
6746
+ });
6747
+ toolCall.sent = true;
6748
+ }
6749
+ }
6750
+ }
6751
+ if (delta.images != null) {
6752
+ for (const image of delta.images) {
6753
+ controller.enqueue({
6754
+ type: "file",
6755
+ mediaType: getMediaType(image.image_url.url, "image/jpeg"),
6756
+ data: getBase64FromDataUrl(image.image_url.url)
6757
+ });
6758
+ }
6759
+ }
6760
+ },
6761
+ flush(controller) {
6762
+ var _a16;
6763
+ if (finishReason === "tool-calls") {
6764
+ for (const toolCall of toolCalls) {
6765
+ if (toolCall && !toolCall.sent) {
6766
+ controller.enqueue({
6767
+ type: "tool-call",
6768
+ toolCallId: (_a16 = toolCall.id) != null ? _a16 : generateId4(),
6769
+ toolName: toolCall.function.name,
6770
+ // Coerce invalid arguments to an empty JSON object
6771
+ input: isParsableJson2(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
6772
+ });
6773
+ toolCall.sent = true;
6774
+ }
6775
+ }
6776
+ }
6777
+ if (reasoningStarted) {
6778
+ controller.enqueue({
6779
+ type: "reasoning-end",
6780
+ id: reasoningId || generateId4()
6781
+ });
6782
+ }
6783
+ if (textStarted) {
6784
+ controller.enqueue({
6785
+ type: "text-end",
6786
+ id: textId || generateId4()
6787
+ });
6788
+ }
6789
+ const openrouterMetadata = {
6790
+ usage: openrouterUsage
6791
+ };
6792
+ if (provider !== void 0) {
6793
+ openrouterMetadata.provider = provider;
6794
+ }
6795
+ if (accumulatedReasoningDetails.length > 0) {
6796
+ openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
6797
+ }
6798
+ controller.enqueue({
6799
+ type: "finish",
6800
+ finishReason,
6801
+ usage,
6802
+ providerMetadata: {
6803
+ openrouter: openrouterMetadata
6804
+ }
6805
+ });
6806
+ }
6807
+ })
6808
+ ),
6809
+ warnings: [],
6810
+ request: { body: args },
6811
+ response: { headers: responseHeaders }
6812
+ };
6813
+ }
6814
+ };
6815
+ function convertToOpenRouterCompletionPrompt({
6816
+ prompt,
6817
+ inputFormat,
6818
+ user = "user",
6819
+ assistant = "assistant"
6820
+ }) {
6821
+ 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") {
6822
+ return { prompt: prompt[0].content[0].text };
6823
+ }
6824
+ let text = "";
6825
+ if (prompt[0] && prompt[0].role === "system") {
6826
+ text += `${prompt[0].content}
6827
+
6828
+ `;
6829
+ prompt = prompt.slice(1);
6830
+ }
6831
+ for (const { role, content } of prompt) {
6832
+ switch (role) {
6833
+ case "system": {
6834
+ throw new InvalidPromptError({
6835
+ message: `Unexpected system message in prompt: ${content}`,
6836
+ prompt
6837
+ });
6838
+ }
6839
+ case "user": {
6840
+ const userMessage = content.map((part) => {
6841
+ switch (part.type) {
6842
+ case "text": {
6843
+ return part.text;
6844
+ }
6845
+ case "file": {
6846
+ throw new UnsupportedFunctionalityError2({
6847
+ functionality: "file attachments"
6848
+ });
6849
+ }
6850
+ default: {
6851
+ return "";
6852
+ }
6853
+ }
6854
+ }).join("");
6855
+ text += `${user}:
6856
+ ${userMessage}
6857
+
6858
+ `;
6859
+ break;
6860
+ }
6861
+ case "assistant": {
6862
+ const assistantMessage = content.map(
6863
+ (part) => {
6864
+ switch (part.type) {
6865
+ case "text": {
6866
+ return part.text;
6867
+ }
6868
+ case "tool-call": {
6869
+ throw new UnsupportedFunctionalityError2({
6870
+ functionality: "tool-call messages"
6871
+ });
6872
+ }
6873
+ case "tool-result": {
6874
+ throw new UnsupportedFunctionalityError2({
6875
+ functionality: "tool-result messages"
6876
+ });
6877
+ }
6878
+ case "reasoning": {
6879
+ throw new UnsupportedFunctionalityError2({
6880
+ functionality: "reasoning messages"
6881
+ });
6882
+ }
6883
+ case "file": {
6884
+ throw new UnsupportedFunctionalityError2({
6885
+ functionality: "file attachments"
6886
+ });
6887
+ }
6888
+ default: {
6889
+ return "";
6890
+ }
6891
+ }
6892
+ }
6893
+ ).join("");
6894
+ text += `${assistant}:
6895
+ ${assistantMessage}
6896
+
6897
+ `;
6898
+ break;
6899
+ }
6900
+ case "tool": {
6901
+ throw new UnsupportedFunctionalityError2({
6902
+ functionality: "tool messages"
6903
+ });
6904
+ }
6905
+ }
6906
+ }
6907
+ text += `${assistant}:
6908
+ `;
6909
+ return {
6910
+ prompt: text
6911
+ };
6912
+ }
6913
+ var OpenRouterCompletionChunkSchema = z4.z.union([
6914
+ z4.z.object({
6915
+ id: z4.z.string().optional(),
6916
+ model: z4.z.string().optional(),
6917
+ choices: z4.z.array(
6918
+ z4.z.object({
6919
+ text: z4.z.string(),
6920
+ reasoning: z4.z.string().nullish().optional(),
6921
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
6922
+ finish_reason: z4.z.string().nullish(),
6923
+ index: z4.z.number().nullish(),
6924
+ logprobs: z4.z.object({
6925
+ tokens: z4.z.array(z4.z.string()),
6926
+ token_logprobs: z4.z.array(z4.z.number()),
6927
+ top_logprobs: z4.z.array(z4.z.record(z4.z.string(), z4.z.number())).nullable()
6928
+ }).passthrough().nullable().optional()
6929
+ }).passthrough()
6930
+ ),
6931
+ usage: z4.z.object({
6932
+ prompt_tokens: z4.z.number(),
6933
+ prompt_tokens_details: z4.z.object({
6934
+ cached_tokens: z4.z.number()
6935
+ }).passthrough().nullish(),
6936
+ completion_tokens: z4.z.number(),
6937
+ completion_tokens_details: z4.z.object({
6938
+ reasoning_tokens: z4.z.number()
6939
+ }).passthrough().nullish(),
6940
+ total_tokens: z4.z.number(),
6941
+ cost: z4.z.number().optional()
6942
+ }).passthrough().nullish()
6943
+ }).passthrough(),
6944
+ OpenRouterErrorResponseSchema
6945
+ ]);
6946
+ var OpenRouterCompletionLanguageModel = class {
6947
+ constructor(modelId, settings, config) {
6948
+ this.specificationVersion = "v2";
6949
+ this.provider = "openrouter";
6950
+ this.supportedUrls = {
6951
+ "image/*": [
6952
+ /^data:image\/[a-zA-Z]+;base64,/,
6953
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
6954
+ ],
6955
+ "text/*": [/^data:text\//, /^https?:\/\/.+$/],
6956
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
6957
+ };
6958
+ this.defaultObjectGenerationMode = void 0;
6959
+ this.modelId = modelId;
6960
+ this.settings = settings;
6961
+ this.config = config;
6962
+ }
6963
+ getArgs({
6964
+ prompt,
6965
+ maxOutputTokens,
6966
+ temperature,
6967
+ topP,
6968
+ frequencyPenalty,
6969
+ presencePenalty,
6970
+ seed,
6971
+ responseFormat,
6972
+ topK,
6973
+ stopSequences,
6974
+ tools,
6975
+ toolChoice
6976
+ }) {
6977
+ const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
6978
+ prompt,
6979
+ inputFormat: "prompt"
6980
+ });
6981
+ if (tools == null ? void 0 : tools.length) {
6982
+ throw new UnsupportedFunctionalityError2({
6983
+ functionality: "tools"
6984
+ });
6985
+ }
6986
+ if (toolChoice) {
6987
+ throw new UnsupportedFunctionalityError2({
6988
+ functionality: "toolChoice"
6989
+ });
6990
+ }
6991
+ return __spreadValues(__spreadValues({
6992
+ // model id:
6993
+ model: this.modelId,
6994
+ models: this.settings.models,
6995
+ // model specific settings:
6996
+ logit_bias: this.settings.logitBias,
6997
+ logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
6998
+ suffix: this.settings.suffix,
6999
+ user: this.settings.user,
7000
+ // standardized settings:
7001
+ max_tokens: maxOutputTokens,
7002
+ temperature,
7003
+ top_p: topP,
7004
+ frequency_penalty: frequencyPenalty,
7005
+ presence_penalty: presencePenalty,
7006
+ seed,
7007
+ stop: stopSequences,
7008
+ response_format: responseFormat,
7009
+ top_k: topK,
7010
+ // prompt:
7011
+ prompt: completionPrompt,
7012
+ // OpenRouter specific settings:
7013
+ include_reasoning: this.settings.includeReasoning,
7014
+ reasoning: this.settings.reasoning
7015
+ }, this.config.extraBody), this.settings.extraBody);
7016
+ }
7017
+ async doGenerate(options) {
7018
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
7019
+ const providerOptions = options.providerOptions || {};
7020
+ const openrouterOptions = providerOptions.openrouter || {};
7021
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
7022
+ const { value: response, responseHeaders } = await postJsonToApi4({
7023
+ url: this.config.url({
7024
+ path: "/completions",
7025
+ modelId: this.modelId
7026
+ }),
7027
+ headers: combineHeaders4(this.config.headers(), options.headers),
7028
+ body: args,
7029
+ failedResponseHandler: openrouterFailedResponseHandler,
7030
+ successfulResponseHandler: createJsonResponseHandler4(
7031
+ OpenRouterCompletionChunkSchema
7032
+ ),
7033
+ abortSignal: options.abortSignal,
7034
+ fetch: this.config.fetch
7035
+ });
7036
+ if ("error" in response) {
7037
+ const errorData = response.error;
7038
+ throw new APICallError2({
7039
+ message: errorData.message,
7040
+ url: this.config.url({
7041
+ path: "/completions",
7042
+ modelId: this.modelId
7043
+ }),
7044
+ requestBodyValues: args,
7045
+ statusCode: 200,
7046
+ responseHeaders,
7047
+ data: errorData
7048
+ });
7049
+ }
7050
+ const choice = response.choices[0];
7051
+ if (!choice) {
7052
+ throw new NoContentGeneratedError({
7053
+ message: "No choice in OpenRouter completion response"
7054
+ });
7055
+ }
7056
+ return {
7057
+ content: [
7058
+ {
7059
+ type: "text",
7060
+ text: (_a15 = choice.text) != null ? _a15 : ""
7061
+ }
7062
+ ],
7063
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
7064
+ usage: {
7065
+ inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
7066
+ outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
7067
+ 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),
7068
+ reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
7069
+ cachedInputTokens: (_o = (_n = (_m = response.usage) == null ? void 0 : _m.prompt_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : 0
7070
+ },
7071
+ warnings: [],
7072
+ response: {
7073
+ headers: responseHeaders
7074
+ }
7075
+ };
7076
+ }
7077
+ async doStream(options) {
7078
+ const providerOptions = options.providerOptions || {};
7079
+ const openrouterOptions = providerOptions.openrouter || {};
7080
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
7081
+ const { value: response, responseHeaders } = await postJsonToApi4({
7082
+ url: this.config.url({
7083
+ path: "/completions",
7084
+ modelId: this.modelId
7085
+ }),
7086
+ headers: combineHeaders4(this.config.headers(), options.headers),
7087
+ body: __spreadProps(__spreadValues({}, args), {
7088
+ stream: true,
7089
+ // only include stream_options when in strict compatibility mode:
7090
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
7091
+ }),
7092
+ failedResponseHandler: openrouterFailedResponseHandler,
7093
+ successfulResponseHandler: createEventSourceResponseHandler4(
7094
+ OpenRouterCompletionChunkSchema
7095
+ ),
7096
+ abortSignal: options.abortSignal,
7097
+ fetch: this.config.fetch
7098
+ });
7099
+ let finishReason = "other";
7100
+ const usage = {
7101
+ inputTokens: Number.NaN,
7102
+ outputTokens: Number.NaN,
7103
+ totalTokens: Number.NaN,
7104
+ reasoningTokens: Number.NaN,
7105
+ cachedInputTokens: Number.NaN
7106
+ };
7107
+ const openrouterUsage = {};
7108
+ return {
7109
+ stream: response.pipeThrough(
7110
+ new TransformStream({
7111
+ transform(chunk, controller) {
7112
+ var _a15, _b;
7113
+ if (!chunk.success) {
7114
+ finishReason = "error";
7115
+ controller.enqueue({ type: "error", error: chunk.error });
7116
+ return;
7117
+ }
7118
+ const value = chunk.value;
7119
+ if ("error" in value) {
7120
+ finishReason = "error";
7121
+ controller.enqueue({ type: "error", error: value.error });
7122
+ return;
7123
+ }
7124
+ if (value.usage != null) {
7125
+ usage.inputTokens = value.usage.prompt_tokens;
7126
+ usage.outputTokens = value.usage.completion_tokens;
7127
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
7128
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
7129
+ if (value.usage.prompt_tokens_details) {
7130
+ const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
7131
+ usage.cachedInputTokens = cachedInputTokens;
7132
+ openrouterUsage.promptTokensDetails = {
7133
+ cachedTokens: cachedInputTokens
7134
+ };
7135
+ }
7136
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
7137
+ if (value.usage.completion_tokens_details) {
7138
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
7139
+ usage.reasoningTokens = reasoningTokens;
7140
+ openrouterUsage.completionTokensDetails = {
7141
+ reasoningTokens
7142
+ };
7143
+ }
7144
+ openrouterUsage.cost = value.usage.cost;
7145
+ openrouterUsage.totalTokens = value.usage.total_tokens;
7146
+ }
7147
+ const choice = value.choices[0];
7148
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
7149
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
7150
+ }
7151
+ if ((choice == null ? void 0 : choice.text) != null) {
7152
+ controller.enqueue({
7153
+ type: "text-delta",
7154
+ delta: choice.text,
7155
+ id: generateId4()
7156
+ });
7157
+ }
7158
+ },
7159
+ flush(controller) {
7160
+ controller.enqueue({
7161
+ type: "finish",
7162
+ finishReason,
7163
+ usage,
7164
+ providerMetadata: {
7165
+ openrouter: {
7166
+ usage: openrouterUsage
7167
+ }
7168
+ }
7169
+ });
7170
+ }
7171
+ })
7172
+ ),
7173
+ response: {
7174
+ headers: responseHeaders
7175
+ }
7176
+ };
7177
+ }
7178
+ };
7179
+ function removeUndefinedEntries22(record) {
7180
+ return Object.fromEntries(
7181
+ Object.entries(record).filter(([, value]) => value !== null)
7182
+ );
7183
+ }
7184
+ function withUserAgentSuffix3(headers, ...userAgentSuffixParts) {
7185
+ const cleanedHeaders = removeUndefinedEntries22(
7186
+ headers != null ? headers : {}
7187
+ );
7188
+ const currentUserAgentHeader = cleanedHeaders["user-agent"] || "";
7189
+ const newUserAgent = [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ");
7190
+ return __spreadProps(__spreadValues({}, cleanedHeaders), {
7191
+ "user-agent": newUserAgent
7192
+ });
7193
+ }
7194
+ var VERSION5 = "1.2.3";
7195
+ function createOpenRouter(options = {}) {
7196
+ var _a15, _b, _c;
7197
+ const baseURL = (_b = withoutTrailingSlash4((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
7198
+ const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
7199
+ const getHeaders = () => withUserAgentSuffix3(
7200
+ __spreadValues({
7201
+ Authorization: `Bearer ${loadApiKey4({
7202
+ apiKey: options.apiKey,
7203
+ environmentVariableName: "OPENROUTER_API_KEY",
7204
+ description: "OpenRouter"
7205
+ })}`
7206
+ }, options.headers),
7207
+ `ai-sdk/openrouter/${VERSION5}`
7208
+ );
7209
+ const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
7210
+ provider: "openrouter.chat",
7211
+ url: ({ path }) => `${baseURL}${path}`,
7212
+ headers: getHeaders,
7213
+ compatibility,
7214
+ fetch: options.fetch,
7215
+ extraBody: options.extraBody
7216
+ });
7217
+ const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
7218
+ provider: "openrouter.completion",
7219
+ url: ({ path }) => `${baseURL}${path}`,
7220
+ headers: getHeaders,
7221
+ compatibility,
7222
+ fetch: options.fetch,
7223
+ extraBody: options.extraBody
7224
+ });
7225
+ const createLanguageModel = (modelId, settings) => {
7226
+ if (new.target) {
7227
+ throw new Error(
7228
+ "The OpenRouter model function cannot be called with the new keyword."
7229
+ );
7230
+ }
7231
+ if (modelId === "openai/gpt-3.5-turbo-instruct") {
7232
+ return createCompletionModel(
7233
+ modelId,
7234
+ settings
7235
+ );
7236
+ }
7237
+ return createChatModel(modelId, settings);
7238
+ };
7239
+ const provider = (modelId, settings) => createLanguageModel(modelId, settings);
7240
+ provider.languageModel = createLanguageModel;
7241
+ provider.chat = createChatModel;
7242
+ provider.completion = createCompletionModel;
7243
+ return provider;
7244
+ }
7245
+ createOpenRouter({
7246
+ compatibility: "strict"
7247
+ // strict for OpenRouter API
7248
+ });
4797
7249
 
4798
7250
  // src/llm/model/gateway-resolver.ts
4799
7251
  function parseModelRouterId(routerId, gatewayPrefix) {
@@ -4864,7 +7316,7 @@ var OPENAI_COMPATIBLE_OVERRIDES = {
4864
7316
  apiKeyEnvVar: "AI_GATEWAY_API_KEY"
4865
7317
  }
4866
7318
  };
4867
- var ModelsDevGateway = class extends chunkCZEJQSWB_cjs.MastraModelGateway {
7319
+ var ModelsDevGateway = class extends chunkF75EQ574_cjs.MastraModelGateway {
4868
7320
  id = "models.dev";
4869
7321
  name = "models.dev";
4870
7322
  providerConfigs = {};
@@ -4944,18 +7396,18 @@ var ModelsDevGateway = class extends chunkCZEJQSWB_cjs.MastraModelGateway {
4944
7396
  const baseURL = this.buildUrl(`${providerId}/${modelId}`);
4945
7397
  switch (providerId) {
4946
7398
  case "openai":
4947
- return chunkCZEJQSWB_cjs.createOpenAI({ apiKey }).responses(modelId);
7399
+ return chunkF75EQ574_cjs.createOpenAI({ apiKey }).responses(modelId);
4948
7400
  case "gemini":
4949
7401
  case "google":
4950
- return chunkCZEJQSWB_cjs.createGoogleGenerativeAI({
7402
+ return chunkF75EQ574_cjs.createGoogleGenerativeAI({
4951
7403
  apiKey
4952
7404
  }).chat(modelId);
4953
7405
  case "anthropic":
4954
- return chunkCZEJQSWB_cjs.createAnthropic({ apiKey })(modelId);
7406
+ return chunkF75EQ574_cjs.createAnthropic({ apiKey })(modelId);
4955
7407
  case "mistral":
4956
7408
  return createMistral({ apiKey })(modelId);
4957
7409
  case "openrouter":
4958
- return aiSdkProviderV5.createOpenRouter({ apiKey, headers })(modelId);
7410
+ return createOpenRouter({ apiKey, headers })(modelId);
4959
7411
  case "xai":
4960
7412
  return createXai({
4961
7413
  apiKey
@@ -4968,7 +7420,7 @@ var ModelsDevGateway = class extends chunkCZEJQSWB_cjs.MastraModelGateway {
4968
7420
  return createPerplexity({ apiKey })(modelId);
4969
7421
  default:
4970
7422
  if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
4971
- return chunkCZEJQSWB_cjs.createOpenAICompatible({ name: providerId, apiKey, baseURL, supportsStructuredOutputs: true }).chatModel(
7423
+ return chunkF75EQ574_cjs.createOpenAICompatible({ name: providerId, apiKey, baseURL, supportsStructuredOutputs: true }).chatModel(
4972
7424
  modelId
4973
7425
  );
4974
7426
  }
@@ -4977,5 +7429,5 @@ var ModelsDevGateway = class extends chunkCZEJQSWB_cjs.MastraModelGateway {
4977
7429
 
4978
7430
  exports.ModelsDevGateway = ModelsDevGateway;
4979
7431
  exports.parseModelRouterId = parseModelRouterId;
4980
- //# sourceMappingURL=chunk-MRFUISXC.cjs.map
4981
- //# sourceMappingURL=chunk-MRFUISXC.cjs.map
7432
+ //# sourceMappingURL=chunk-EGHGFLL3.cjs.map
7433
+ //# sourceMappingURL=chunk-EGHGFLL3.cjs.map