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

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 (394) hide show
  1. package/CHANGELOG.md +173 -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 +1 -1
  9. package/dist/agent/agent.d.ts.map +1 -1
  10. package/dist/agent/agent.types.d.ts +5 -1
  11. package/dist/agent/agent.types.d.ts.map +1 -1
  12. package/dist/agent/index.cjs +9 -9
  13. package/dist/agent/index.js +2 -2
  14. package/dist/agent/message-list/index.cjs +3 -3
  15. package/dist/agent/message-list/index.d.ts +4 -3
  16. package/dist/agent/message-list/index.d.ts.map +1 -1
  17. package/dist/agent/message-list/index.js +1 -1
  18. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +1 -1
  19. package/dist/agent/message-list/prompt/invalid-content-error.d.ts +1 -1
  20. package/dist/agent/message-list/types.d.ts +3 -3
  21. package/dist/agent/message-list/types.d.ts.map +1 -1
  22. package/dist/agent/message-list/utils/ai-v4-v5/core-model-message.d.ts +1 -1
  23. package/dist/agent/message-list/utils/ai-v4-v5/ui-message.d.ts +1 -1
  24. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts +2 -2
  25. package/dist/agent/message-list/utils/ai-v5/gemini-compatibility.d.ts.map +1 -1
  26. package/dist/agent/message-list/utils/convert-messages.d.ts +2 -2
  27. package/dist/agent/message-list/utils/convert-messages.d.ts.map +1 -1
  28. package/dist/agent/types.d.ts +3 -3
  29. package/dist/agent/utils.d.ts +3 -3
  30. package/dist/agent/utils.d.ts.map +1 -1
  31. package/dist/agent/workflows/prepare-stream/index.d.ts +2 -1
  32. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  33. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  34. package/dist/agent/workflows/prepare-stream/stream-step.d.ts +3 -1
  35. package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
  36. package/dist/bundler/types.d.ts +14 -1
  37. package/dist/bundler/types.d.ts.map +1 -1
  38. package/dist/{chunk-U3XOLEPX.js → chunk-2IU4RGU5.js} +6 -32
  39. package/dist/chunk-2IU4RGU5.js.map +1 -0
  40. package/dist/chunk-2SQB3WBT.js +4574 -0
  41. package/dist/chunk-2SQB3WBT.js.map +1 -0
  42. package/dist/{chunk-THZTRBFS.js → chunk-373OC54J.js} +8 -8
  43. package/dist/chunk-373OC54J.js.map +1 -0
  44. package/dist/{chunk-F2GAJSBI.js → chunk-4BC5FUAO.js} +8 -6
  45. package/dist/{chunk-F2GAJSBI.js.map → chunk-4BC5FUAO.js.map} +1 -1
  46. package/dist/chunk-55VPMN3N.js +250 -0
  47. package/dist/chunk-55VPMN3N.js.map +1 -0
  48. package/dist/{chunk-QM5SRDJX.js → chunk-5PTZG26U.js} +66 -84
  49. package/dist/chunk-5PTZG26U.js.map +1 -0
  50. package/dist/chunk-5VZGJTPR.js +4837 -0
  51. package/dist/chunk-5VZGJTPR.js.map +1 -0
  52. package/dist/{chunk-C36YRTZ6.js → chunk-62Q7K656.js} +6 -7
  53. package/dist/chunk-62Q7K656.js.map +1 -0
  54. package/dist/chunk-6PMMP3FR.js +7 -0
  55. package/dist/chunk-6PMMP3FR.js.map +1 -0
  56. package/dist/{chunk-DZUJEN5N.cjs → chunk-6SZKM6EC.cjs} +10 -3
  57. package/dist/{chunk-DZUJEN5N.cjs.map → chunk-6SZKM6EC.cjs.map} +1 -1
  58. package/dist/{chunk-5WRI5ZAA.js → chunk-7D4SUZUM.js} +10 -4
  59. package/dist/{chunk-5WRI5ZAA.js.map → chunk-7D4SUZUM.js.map} +1 -1
  60. package/dist/{chunk-YWMMBIOM.cjs → chunk-7HEAVZRS.cjs} +15 -15
  61. package/dist/{chunk-YWMMBIOM.cjs.map → chunk-7HEAVZRS.cjs.map} +1 -1
  62. package/dist/{chunk-BUKY6CTR.cjs → chunk-AGHLXC4I.cjs} +106 -36
  63. package/dist/chunk-AGHLXC4I.cjs.map +1 -0
  64. package/dist/{chunk-PK2A5WBG.js → chunk-ARAQIW6E.js} +222 -604
  65. package/dist/chunk-ARAQIW6E.js.map +1 -0
  66. package/dist/{chunk-US2U7ECW.js → chunk-BQDZIQ3G.js} +156 -90
  67. package/dist/chunk-BQDZIQ3G.js.map +1 -0
  68. package/dist/chunk-D22XABFZ.js +79 -0
  69. package/dist/chunk-D22XABFZ.js.map +1 -0
  70. package/dist/{chunk-2ULLRN4Y.js → chunk-E5BQRAJK.js} +943 -626
  71. package/dist/chunk-E5BQRAJK.js.map +1 -0
  72. package/dist/chunk-FST2G2FQ.cjs +84 -0
  73. package/dist/chunk-FST2G2FQ.cjs.map +1 -0
  74. package/dist/chunk-FVQTJUBD.cjs +2120 -0
  75. package/dist/chunk-FVQTJUBD.cjs.map +1 -0
  76. package/dist/chunk-G6E6V2Z4.js +2070 -0
  77. package/dist/chunk-G6E6V2Z4.js.map +1 -0
  78. package/dist/{chunk-7P6BNIJH.js → chunk-GIWC35YQ.js} +105 -35
  79. package/dist/chunk-GIWC35YQ.js.map +1 -0
  80. package/dist/{chunk-4JKEUSCC.cjs → chunk-H4VUIOWU.cjs} +22 -20
  81. package/dist/chunk-H4VUIOWU.cjs.map +1 -0
  82. package/dist/{chunk-TWH4PTDG.cjs → chunk-HWMMIRIF.cjs} +32 -27
  83. package/dist/chunk-HWMMIRIF.cjs.map +1 -0
  84. package/dist/chunk-IXZ2T2QX.cjs +448 -0
  85. package/dist/chunk-IXZ2T2QX.cjs.map +1 -0
  86. package/dist/chunk-L3NKIMF5.cjs +10 -0
  87. package/dist/chunk-L3NKIMF5.cjs.map +1 -0
  88. package/dist/chunk-L4JCRWDY.cjs +252 -0
  89. package/dist/chunk-L4JCRWDY.cjs.map +1 -0
  90. package/dist/{chunk-BJXKH4LG.cjs → chunk-LGB4VNZI.cjs} +43 -78
  91. package/dist/chunk-LGB4VNZI.cjs.map +1 -0
  92. package/dist/{chunk-PG5H6QIO.cjs → chunk-MLKE7HRS.cjs} +41 -21
  93. package/dist/chunk-MLKE7HRS.cjs.map +1 -0
  94. package/dist/{chunk-OEIVMCWX.js → chunk-MRRFTNF4.js} +2537 -84
  95. package/dist/chunk-MRRFTNF4.js.map +1 -0
  96. package/dist/chunk-MXBVP7HX.cjs +4842 -0
  97. package/dist/chunk-MXBVP7HX.cjs.map +1 -0
  98. package/dist/chunk-NESKUIRE.cjs +4586 -0
  99. package/dist/chunk-NESKUIRE.cjs.map +1 -0
  100. package/dist/{chunk-SVLMF4UZ.cjs → chunk-NIOEY3N3.cjs} +66 -85
  101. package/dist/chunk-NIOEY3N3.cjs.map +1 -0
  102. package/dist/{chunk-CZEJQSWB.cjs → chunk-OWIEOL55.cjs} +295 -677
  103. package/dist/chunk-OWIEOL55.cjs.map +1 -0
  104. package/dist/{chunk-WTSZBHIZ.cjs → chunk-PJAK4U6R.cjs} +24 -24
  105. package/dist/{chunk-WTSZBHIZ.cjs.map → chunk-PJAK4U6R.cjs.map} +1 -1
  106. package/dist/{chunk-52RSUALV.cjs → chunk-R5AJGM55.cjs} +1314 -995
  107. package/dist/chunk-R5AJGM55.cjs.map +1 -0
  108. package/dist/{chunk-IVV5TOMD.js → chunk-RCJLMMTO.js} +32 -12
  109. package/dist/chunk-RCJLMMTO.js.map +1 -0
  110. package/dist/{chunk-S73Z3PBJ.cjs → chunk-SZYSDJTN.cjs} +27 -28
  111. package/dist/chunk-SZYSDJTN.cjs.map +1 -0
  112. package/dist/{chunk-YC6PJEPH.cjs → chunk-U4CSOY6T.cjs} +188 -122
  113. package/dist/chunk-U4CSOY6T.cjs.map +1 -0
  114. package/dist/chunk-UBSPZTQX.js +434 -0
  115. package/dist/chunk-UBSPZTQX.js.map +1 -0
  116. package/dist/{chunk-SCUWP4II.cjs → chunk-VEPP75C4.cjs} +47 -74
  117. package/dist/chunk-VEPP75C4.cjs.map +1 -0
  118. package/dist/{chunk-JIGDJK2O.js → chunk-VETAQUW3.js} +4 -39
  119. package/dist/chunk-VETAQUW3.js.map +1 -0
  120. package/dist/{chunk-Z57R5WS4.js → chunk-WPTTKULS.js} +4 -4
  121. package/dist/{chunk-Z57R5WS4.js.map → chunk-WPTTKULS.js.map} +1 -1
  122. package/dist/{chunk-O2BJW7YA.js → chunk-WYGUWVTF.js} +5 -5
  123. package/dist/{chunk-O2BJW7YA.js.map → chunk-WYGUWVTF.js.map} +1 -1
  124. package/dist/{chunk-SXNQRJQD.js → chunk-WYWRMIQC.js} +127 -22
  125. package/dist/chunk-WYWRMIQC.js.map +1 -0
  126. package/dist/{chunk-5Q6WAYEY.cjs → chunk-X6IBA7FP.cjs} +137 -50
  127. package/dist/chunk-X6IBA7FP.cjs.map +1 -0
  128. package/dist/{chunk-MRFUISXC.cjs → chunk-Y7MZ5LJT.cjs} +2632 -179
  129. package/dist/chunk-Y7MZ5LJT.cjs.map +1 -0
  130. package/dist/{chunk-JJ5O45LH.js → chunk-YPLZDWG7.js} +32 -27
  131. package/dist/chunk-YPLZDWG7.js.map +1 -0
  132. package/dist/{chunk-MGCGWPQJ.cjs → chunk-Z55SJVEC.cjs} +8 -8
  133. package/dist/chunk-Z55SJVEC.cjs.map +1 -0
  134. package/dist/error/index.cjs +6 -6
  135. package/dist/error/index.d.ts +26 -20
  136. package/dist/error/index.d.ts.map +1 -1
  137. package/dist/error/index.js +1 -1
  138. package/dist/error/utils.d.ts +19 -5
  139. package/dist/error/utils.d.ts.map +1 -1
  140. package/dist/evals/index.cjs +4 -4
  141. package/dist/evals/index.js +1 -1
  142. package/dist/evals/run/index.d.ts +1 -1
  143. package/dist/evals/scoreTraces/index.cjs +8 -8
  144. package/dist/evals/scoreTraces/index.js +2 -2
  145. package/dist/evals/types.d.ts +1 -1
  146. package/dist/events/event-emitter.d.ts +6 -1
  147. package/dist/events/event-emitter.d.ts.map +1 -1
  148. package/dist/index.cjs +2 -2
  149. package/dist/index.js +1 -1
  150. package/dist/integration/index.cjs +2 -2
  151. package/dist/integration/index.js +1 -1
  152. package/dist/llm/index.cjs +15 -15
  153. package/dist/llm/index.d.ts +2 -2
  154. package/dist/llm/index.d.ts.map +1 -1
  155. package/dist/llm/index.js +5 -5
  156. package/dist/llm/model/aisdk/v5/model.d.ts +1 -1
  157. package/dist/llm/model/base.types.d.ts +2 -2
  158. package/dist/llm/model/model.d.ts +1 -1
  159. package/dist/llm/model/model.d.ts.map +1 -1
  160. package/dist/llm/model/model.loop.d.ts +2 -2
  161. package/dist/llm/model/model.loop.d.ts.map +1 -1
  162. package/dist/llm/model/model.loop.types.d.ts +1 -1
  163. package/dist/llm/model/model.loop.types.d.ts.map +1 -1
  164. package/dist/llm/model/provider-types.generated.d.ts +51 -11
  165. package/dist/llm/model/shared.types.d.ts +1 -1
  166. package/dist/loop/index.cjs +2 -2
  167. package/dist/loop/index.js +1 -1
  168. package/dist/loop/loop.d.ts +2 -2
  169. package/dist/loop/loop.d.ts.map +1 -1
  170. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts +1 -1
  171. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts.map +1 -1
  172. package/dist/loop/test-utils/options.d.ts.map +1 -1
  173. package/dist/loop/test-utils/streamObject.d.ts +1 -1
  174. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  175. package/dist/loop/test-utils/tools.d.ts.map +1 -1
  176. package/dist/loop/types.d.ts +3 -1
  177. package/dist/loop/types.d.ts.map +1 -1
  178. package/dist/loop/workflows/agentic-execution/index.d.ts +13 -13
  179. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  180. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +10 -10
  181. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  182. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +5 -5
  183. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  184. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +22 -21
  185. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  186. package/dist/loop/workflows/agentic-loop/index.d.ts +13 -13
  187. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  188. package/dist/loop/workflows/schema.d.ts +6 -6
  189. package/dist/loop/workflows/schema.d.ts.map +1 -1
  190. package/dist/loop/workflows/stream.d.ts +2 -2
  191. package/dist/loop/workflows/stream.d.ts.map +1 -1
  192. package/dist/mastra/index.cjs +2 -2
  193. package/dist/mastra/index.js +1 -1
  194. package/dist/mcp/index.cjs +4 -4
  195. package/dist/mcp/index.js +1 -1
  196. package/dist/memory/index.cjs +6 -6
  197. package/dist/memory/index.js +1 -1
  198. package/dist/memory/memory.d.ts +1 -1
  199. package/dist/memory/types.d.ts +3 -3
  200. package/dist/memory/types.d.ts.map +1 -1
  201. package/dist/models-dev-D3EKFGAO.cjs +12 -0
  202. package/dist/{models-dev-EO3SUIY2.cjs.map → models-dev-D3EKFGAO.cjs.map} +1 -1
  203. package/dist/models-dev-EO22XOXQ.js +3 -0
  204. package/dist/{models-dev-23RN2WHG.js.map → models-dev-EO22XOXQ.js.map} +1 -1
  205. package/dist/netlify-AE4LNCAI.js +3 -0
  206. package/dist/{netlify-GXJ5D5DD.js.map → netlify-AE4LNCAI.js.map} +1 -1
  207. package/dist/netlify-WE42TZIT.cjs +12 -0
  208. package/dist/{netlify-KJLY3GFS.cjs.map → netlify-WE42TZIT.cjs.map} +1 -1
  209. package/dist/processors/index.cjs +37 -37
  210. package/dist/processors/index.d.ts +2 -2
  211. package/dist/processors/index.d.ts.map +1 -1
  212. package/dist/processors/index.js +1 -1
  213. package/dist/processors/step-schema.d.ts +1267 -1267
  214. package/dist/processors/step-schema.d.ts.map +1 -1
  215. package/dist/provider-registry-6LF3NGC5.js +3 -0
  216. package/dist/{provider-registry-F67Y6OF2.js.map → provider-registry-6LF3NGC5.js.map} +1 -1
  217. package/dist/provider-registry-73FKMXJV.cjs +40 -0
  218. package/dist/{provider-registry-3TG2KUD2.cjs.map → provider-registry-73FKMXJV.cjs.map} +1 -1
  219. package/dist/provider-registry.json +100 -30
  220. package/dist/{registry-generator-UMTNPBJX.js → registry-generator-AVQXI3GX.js} +2 -2
  221. package/dist/{registry-generator-UMTNPBJX.js.map → registry-generator-AVQXI3GX.js.map} +1 -1
  222. package/dist/{registry-generator-34SC4TAU.cjs → registry-generator-KOFNIIWJ.cjs} +2 -2
  223. package/dist/{registry-generator-34SC4TAU.cjs.map → registry-generator-KOFNIIWJ.cjs.map} +1 -1
  224. package/dist/relevance/index.cjs +2 -2
  225. package/dist/relevance/index.js +1 -1
  226. package/dist/server/index.cjs +5 -5
  227. package/dist/server/index.js +1 -1
  228. package/dist/storage/base.d.ts +2 -10
  229. package/dist/storage/base.d.ts.map +1 -1
  230. package/dist/storage/domains/workflows/base.d.ts +2 -8
  231. package/dist/storage/domains/workflows/base.d.ts.map +1 -1
  232. package/dist/storage/domains/workflows/inmemory.d.ts +2 -8
  233. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  234. package/dist/storage/index.cjs +38 -38
  235. package/dist/storage/index.js +1 -1
  236. package/dist/storage/mock.d.ts +2 -8
  237. package/dist/storage/mock.d.ts.map +1 -1
  238. package/dist/storage/types.d.ts +9 -1
  239. package/dist/storage/types.d.ts.map +1 -1
  240. package/dist/stream/RunOutput.d.ts +1 -1
  241. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  242. package/dist/stream/aisdk/v5/compat/content.d.ts +1 -1
  243. package/dist/stream/aisdk/v5/compat/content.d.ts.map +1 -1
  244. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts +1 -1
  245. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
  246. package/dist/stream/aisdk/v5/compat/ui-message.d.ts +1 -1
  247. package/dist/stream/aisdk/v5/compat/ui-message.d.ts.map +1 -1
  248. package/dist/stream/aisdk/v5/compat/validation.d.ts +1 -1
  249. package/dist/stream/aisdk/v5/compat/validation.d.ts.map +1 -1
  250. package/dist/stream/aisdk/v5/execute.d.ts +2 -2
  251. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  252. package/dist/stream/aisdk/v5/input.d.ts +1 -1
  253. package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
  254. package/dist/stream/aisdk/v5/output-helpers.d.ts +12 -27
  255. package/dist/stream/aisdk/v5/output-helpers.d.ts.map +1 -1
  256. package/dist/stream/aisdk/v5/output.d.ts +41 -91
  257. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  258. package/dist/stream/aisdk/v5/transform.d.ts +1 -1
  259. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  260. package/dist/stream/base/input.d.ts +1 -1
  261. package/dist/stream/base/output.d.ts +9 -31
  262. package/dist/stream/base/output.d.ts.map +1 -1
  263. package/dist/stream/base/schema.d.ts +2 -2
  264. package/dist/stream/base/schema.d.ts.map +1 -1
  265. package/dist/stream/index.cjs +12 -12
  266. package/dist/stream/index.js +2 -2
  267. package/dist/stream/types.d.ts +3 -2
  268. package/dist/stream/types.d.ts.map +1 -1
  269. package/dist/test-utils/llm-mock.cjs +14587 -14
  270. package/dist/test-utils/llm-mock.cjs.map +1 -1
  271. package/dist/test-utils/llm-mock.d.ts +3 -3
  272. package/dist/test-utils/llm-mock.d.ts.map +1 -1
  273. package/dist/test-utils/llm-mock.js +14577 -4
  274. package/dist/test-utils/llm-mock.js.map +1 -1
  275. package/dist/token-6GSAFR2W-SGVIXFCP.cjs +63 -0
  276. package/dist/token-6GSAFR2W-SGVIXFCP.cjs.map +1 -0
  277. package/dist/token-6GSAFR2W-SPYPLMBM.js +61 -0
  278. package/dist/token-6GSAFR2W-SPYPLMBM.js.map +1 -0
  279. package/dist/token-util-NEHG7TUY-7GMW5FXI.cjs +10 -0
  280. package/dist/token-util-NEHG7TUY-7GMW5FXI.cjs.map +1 -0
  281. package/dist/token-util-NEHG7TUY-JRJTGTAB.js +8 -0
  282. package/dist/token-util-NEHG7TUY-JRJTGTAB.js.map +1 -0
  283. package/dist/tools/index.cjs +4 -4
  284. package/dist/tools/index.js +1 -1
  285. package/dist/tools/is-vercel-tool.cjs +2 -2
  286. package/dist/tools/is-vercel-tool.js +1 -1
  287. package/dist/tools/tool-builder/builder.d.ts +2 -1
  288. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  289. package/dist/tools/tool.d.ts.map +1 -1
  290. package/dist/tools/types.d.ts +5 -5
  291. package/dist/tools/types.d.ts.map +1 -1
  292. package/dist/utils.cjs +22 -22
  293. package/dist/utils.d.ts +3 -3
  294. package/dist/utils.d.ts.map +1 -1
  295. package/dist/utils.js +1 -1
  296. package/dist/vector/embed.d.ts +2 -2
  297. package/dist/vector/embed.d.ts.map +1 -1
  298. package/dist/vector/index.cjs +11 -11
  299. package/dist/vector/index.js +3 -3
  300. package/dist/vector/vector.d.ts +1 -1
  301. package/dist/voice/aisdk/speech.d.ts +1 -1
  302. package/dist/voice/aisdk/speech.d.ts.map +1 -1
  303. package/dist/voice/aisdk/transcription.d.ts +1 -1
  304. package/dist/voice/aisdk/transcription.d.ts.map +1 -1
  305. package/dist/voice/composite-voice.d.ts +1 -1
  306. package/dist/voice/composite-voice.d.ts.map +1 -1
  307. package/dist/voice/index.cjs +6 -6
  308. package/dist/voice/index.js +1 -1
  309. package/dist/workflows/constants.cjs +4 -4
  310. package/dist/workflows/constants.d.ts +1 -1
  311. package/dist/workflows/constants.d.ts.map +1 -1
  312. package/dist/workflows/constants.js +1 -1
  313. package/dist/workflows/default.d.ts +9 -16
  314. package/dist/workflows/default.d.ts.map +1 -1
  315. package/dist/workflows/evented/execution-engine.d.ts +3 -2
  316. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  317. package/dist/workflows/evented/index.cjs +10 -10
  318. package/dist/workflows/evented/index.js +1 -1
  319. package/dist/workflows/evented/step-executor.d.ts +1 -1
  320. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  321. package/dist/workflows/evented/workflow-event-processor/index.d.ts +1 -1
  322. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  323. package/dist/workflows/evented/workflow.d.ts +15 -0
  324. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  325. package/dist/workflows/execution-engine.d.ts +25 -2
  326. package/dist/workflows/execution-engine.d.ts.map +1 -1
  327. package/dist/workflows/handlers/control-flow.d.ts +6 -5
  328. package/dist/workflows/handlers/control-flow.d.ts.map +1 -1
  329. package/dist/workflows/handlers/entry.d.ts +5 -3
  330. package/dist/workflows/handlers/entry.d.ts.map +1 -1
  331. package/dist/workflows/handlers/sleep.d.ts +4 -3
  332. package/dist/workflows/handlers/sleep.d.ts.map +1 -1
  333. package/dist/workflows/handlers/step.d.ts +5 -3
  334. package/dist/workflows/handlers/step.d.ts.map +1 -1
  335. package/dist/workflows/index.cjs +26 -22
  336. package/dist/workflows/index.js +1 -1
  337. package/dist/workflows/step.d.ts +5 -4
  338. package/dist/workflows/step.d.ts.map +1 -1
  339. package/dist/workflows/types.d.ts +66 -14
  340. package/dist/workflows/types.d.ts.map +1 -1
  341. package/dist/workflows/utils.d.ts +11 -0
  342. package/dist/workflows/utils.d.ts.map +1 -1
  343. package/dist/workflows/workflow.d.ts +26 -8
  344. package/dist/workflows/workflow.d.ts.map +1 -1
  345. package/package.json +12 -11
  346. package/src/llm/model/provider-types.generated.d.ts +51 -11
  347. package/dist/agent/__tests__/mock-model.d.ts +0 -8
  348. package/dist/agent/__tests__/mock-model.d.ts.map +0 -1
  349. package/dist/agent/agent-types.test-d.d.ts +0 -2
  350. package/dist/agent/agent-types.test-d.d.ts.map +0 -1
  351. package/dist/ai-sdk.types.d.ts +0 -4705
  352. package/dist/chunk-2ULLRN4Y.js.map +0 -1
  353. package/dist/chunk-3E3ILV6T.cjs +0 -518
  354. package/dist/chunk-3E3ILV6T.cjs.map +0 -1
  355. package/dist/chunk-4JKEUSCC.cjs.map +0 -1
  356. package/dist/chunk-52RSUALV.cjs.map +0 -1
  357. package/dist/chunk-5PAEYE3Q.js +0 -513
  358. package/dist/chunk-5PAEYE3Q.js.map +0 -1
  359. package/dist/chunk-5Q6WAYEY.cjs.map +0 -1
  360. package/dist/chunk-7P6BNIJH.js.map +0 -1
  361. package/dist/chunk-ABJOUEVA.cjs +0 -10
  362. package/dist/chunk-ABJOUEVA.cjs.map +0 -1
  363. package/dist/chunk-BJXKH4LG.cjs.map +0 -1
  364. package/dist/chunk-BUKY6CTR.cjs.map +0 -1
  365. package/dist/chunk-C36YRTZ6.js.map +0 -1
  366. package/dist/chunk-CZEJQSWB.cjs.map +0 -1
  367. package/dist/chunk-IVV5TOMD.js.map +0 -1
  368. package/dist/chunk-JIGDJK2O.js.map +0 -1
  369. package/dist/chunk-JJ5O45LH.js.map +0 -1
  370. package/dist/chunk-MGCGWPQJ.cjs.map +0 -1
  371. package/dist/chunk-MRFUISXC.cjs.map +0 -1
  372. package/dist/chunk-NLNKQD2T.js +0 -7
  373. package/dist/chunk-NLNKQD2T.js.map +0 -1
  374. package/dist/chunk-OEIVMCWX.js.map +0 -1
  375. package/dist/chunk-PG5H6QIO.cjs.map +0 -1
  376. package/dist/chunk-PK2A5WBG.js.map +0 -1
  377. package/dist/chunk-QM5SRDJX.js.map +0 -1
  378. package/dist/chunk-S73Z3PBJ.cjs.map +0 -1
  379. package/dist/chunk-SCUWP4II.cjs.map +0 -1
  380. package/dist/chunk-SVLMF4UZ.cjs.map +0 -1
  381. package/dist/chunk-SXNQRJQD.js.map +0 -1
  382. package/dist/chunk-THZTRBFS.js.map +0 -1
  383. package/dist/chunk-TWH4PTDG.cjs.map +0 -1
  384. package/dist/chunk-U3XOLEPX.js.map +0 -1
  385. package/dist/chunk-US2U7ECW.js.map +0 -1
  386. package/dist/chunk-YC6PJEPH.cjs.map +0 -1
  387. package/dist/models-dev-23RN2WHG.js +0 -3
  388. package/dist/models-dev-EO3SUIY2.cjs +0 -12
  389. package/dist/netlify-GXJ5D5DD.js +0 -3
  390. package/dist/netlify-KJLY3GFS.cjs +0 -12
  391. package/dist/provider-registry-3TG2KUD2.cjs +0 -40
  392. package/dist/provider-registry-F67Y6OF2.js +0 -3
  393. package/dist/tools/tool-stream-types.test-d.d.ts +0 -2
  394. package/dist/tools/tool-stream-types.test-d.d.ts.map +0 -1
@@ -1,8 +1,8 @@
1
- import { createJsonErrorResponseHandler, InvalidArgumentError, withoutTrailingSlash, generateId, withUserAgentSuffix, InvalidResponseDataError, parseProviderOptions, injectJsonInstructionIntoMessages, postJsonToApi, createJsonResponseHandler, combineHeaders, createEventSourceResponseHandler, loadApiKey, APICallError, UnsupportedFunctionalityError, LoadAPIKeyError, convertToBase64, JSONParseError, TypeValidationError, EmptyResponseBodyError, EventSourceParserStream, NoSuchModelError, MastraModelGateway, createOpenAICompatible, createAnthropic, createGoogleGenerativeAI, createOpenAI, TooManyEmbeddingValuesForCallError, OpenAICompatibleImageModel } from './chunk-PK2A5WBG.js';
1
+ import { createJsonErrorResponseHandler, withoutTrailingSlash, generateId, withUserAgentSuffix, parseProviderOptions, injectJsonInstructionIntoMessages, postJsonToApi, createJsonResponseHandler, combineHeaders, createEventSourceResponseHandler, loadApiKey, convertToBase64, MastraModelGateway, createOpenAICompatible, createAnthropic, createGoogleGenerativeAI, createOpenAI, OpenAICompatibleImageModel } from './chunk-ARAQIW6E.js';
2
+ import { InvalidArgumentError, InvalidResponseDataError, APICallError, UnsupportedFunctionalityError, LoadAPIKeyError, JSONParseError, TypeValidationError, EmptyResponseBodyError, EventSourceParserStream, NoSuchModelError, TooManyEmbeddingValuesForCallError } from './chunk-UBSPZTQX.js';
2
3
  import * as z4 from 'zod/v4';
3
4
  import { z } from 'zod/v4';
4
5
  import { ZodFirstPartyTypeKind } from 'zod/v3';
5
- import { createOpenRouter } from '@openrouter/ai-sdk-provider-v5';
6
6
 
7
7
  function combineHeaders2(...headers) {
8
8
  return headers.reduce(
@@ -71,11 +71,11 @@ function handleFetchError({
71
71
  return error;
72
72
  }
73
73
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
74
- var _a, _b, _c;
74
+ var _a15, _b, _c;
75
75
  if (globalThisAny.window) {
76
76
  return `runtime/browser`;
77
77
  }
78
- if ((_a = globalThisAny.navigator) == null ? void 0 : _a.userAgent) {
78
+ if ((_a15 = globalThisAny.navigator) == null ? void 0 : _a15.userAgent) {
79
79
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
80
80
  }
81
81
  if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) {
@@ -559,11 +559,11 @@ function parseAnyDef() {
559
559
  return {};
560
560
  }
561
561
  function parseArrayDef(def, refs) {
562
- var _a, _b, _c;
562
+ var _a15, _b, _c;
563
563
  const res = {
564
564
  type: "array"
565
565
  };
566
- if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
566
+ if (((_a15 = def.type) == null ? void 0 : _a15._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
567
567
  res.items = parseDef(def.type._def, {
568
568
  ...refs,
569
569
  currentPath: [...refs.currentPath, "items"]
@@ -922,8 +922,8 @@ function escapeNonAlphaNumeric(source) {
922
922
  return result;
923
923
  }
924
924
  function addFormat(schema, value, message, refs) {
925
- var _a;
926
- if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
925
+ var _a15;
926
+ if (schema.format || ((_a15 = schema.anyOf) == null ? void 0 : _a15.some((x) => x.format))) {
927
927
  if (!schema.anyOf) {
928
928
  schema.anyOf = [];
929
929
  }
@@ -942,8 +942,8 @@ function addFormat(schema, value, message, refs) {
942
942
  }
943
943
  }
944
944
  function addPattern(schema, regex, message, refs) {
945
- var _a;
946
- if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
945
+ var _a15;
946
+ if (schema.pattern || ((_a15 = schema.allOf) == null ? void 0 : _a15.some((x) => x.pattern))) {
947
947
  if (!schema.allOf) {
948
948
  schema.allOf = [];
949
949
  }
@@ -962,7 +962,7 @@ function addPattern(schema, regex, message, refs) {
962
962
  }
963
963
  }
964
964
  function stringifyRegExpWithFlags(regex, refs) {
965
- var _a;
965
+ var _a15;
966
966
  if (!refs.applyRegexFlags || !regex.flags) {
967
967
  return regex.source;
968
968
  }
@@ -992,7 +992,7 @@ function stringifyRegExpWithFlags(regex, refs) {
992
992
  pattern += source[i];
993
993
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
994
994
  inCharRange = false;
995
- } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
995
+ } else if (source[i + 1] === "-" && ((_a15 = source[i + 2]) == null ? void 0 : _a15.match(/[a-z]/))) {
996
996
  pattern += source[i];
997
997
  inCharRange = true;
998
998
  } else {
@@ -1034,13 +1034,13 @@ function stringifyRegExpWithFlags(regex, refs) {
1034
1034
  return pattern;
1035
1035
  }
1036
1036
  function parseRecordDef(def, refs) {
1037
- var _a, _b, _c, _d, _e, _f;
1037
+ var _a15, _b, _c, _d, _e, _f;
1038
1038
  const schema = {
1039
1039
  type: "object",
1040
- additionalProperties: (_a = parseDef(def.valueType._def, {
1040
+ additionalProperties: (_a15 = parseDef(def.valueType._def, {
1041
1041
  ...refs,
1042
1042
  currentPath: [...refs.currentPath, "additionalProperties"]
1043
- })) != null ? _a : refs.allowedAdditionalProperties
1043
+ })) != null ? _a15 : refs.allowedAdditionalProperties
1044
1044
  };
1045
1045
  if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1046
1046
  const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
@@ -1297,8 +1297,8 @@ function safeIsOptional(schema) {
1297
1297
  }
1298
1298
  }
1299
1299
  var parseOptionalDef = (def, refs) => {
1300
- var _a;
1301
- if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
1300
+ var _a15;
1301
+ if (refs.currentPath.toString() === ((_a15 = refs.propertyPath) == null ? void 0 : _a15.toString())) {
1302
1302
  return parseDef(def.innerType._def, refs);
1303
1303
  }
1304
1304
  const innerSchema = parseDef(def.innerType._def, {
@@ -1468,10 +1468,10 @@ var selectParser = (def, typeName, refs) => {
1468
1468
  }
1469
1469
  };
1470
1470
  function parseDef(def, refs, forceResolution = false) {
1471
- var _a;
1471
+ var _a15;
1472
1472
  const seenItem = refs.seen.get(def);
1473
1473
  if (refs.override) {
1474
- const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(
1474
+ const overrideResult = (_a15 = refs.override) == null ? void 0 : _a15.call(
1475
1475
  refs,
1476
1476
  def,
1477
1477
  refs,
@@ -1537,11 +1537,11 @@ var getRefs = (options) => {
1537
1537
  currentPath,
1538
1538
  propertyPath: void 0,
1539
1539
  seen: new Map(
1540
- Object.entries(_options.definitions).map(([name, def]) => [
1540
+ Object.entries(_options.definitions).map(([name14, def]) => [
1541
1541
  def._def,
1542
1542
  {
1543
1543
  def: def._def,
1544
- path: [..._options.basePath, _options.definitionPath, name],
1544
+ path: [..._options.basePath, _options.definitionPath, name14],
1545
1545
  // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1546
1546
  jsonSchema: void 0
1547
1547
  }
@@ -1550,50 +1550,50 @@ var getRefs = (options) => {
1550
1550
  };
1551
1551
  };
1552
1552
  var zodToJsonSchema = (schema, options) => {
1553
- var _a;
1553
+ var _a15;
1554
1554
  const refs = getRefs(options);
1555
1555
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1556
- (acc, [name2, schema2]) => {
1557
- var _a2;
1556
+ (acc, [name22, schema2]) => {
1557
+ var _a22;
1558
1558
  return {
1559
1559
  ...acc,
1560
- [name2]: (_a2 = parseDef(
1560
+ [name22]: (_a22 = parseDef(
1561
1561
  schema2._def,
1562
1562
  {
1563
1563
  ...refs,
1564
- currentPath: [...refs.basePath, refs.definitionPath, name2]
1564
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
1565
1565
  },
1566
1566
  true
1567
- )) != null ? _a2 : parseAnyDef()
1567
+ )) != null ? _a22 : parseAnyDef()
1568
1568
  };
1569
1569
  },
1570
1570
  {}
1571
1571
  ) : void 0;
1572
- const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1573
- const main = (_a = parseDef(
1572
+ const name14 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1573
+ const main = (_a15 = parseDef(
1574
1574
  schema._def,
1575
- name === void 0 ? refs : {
1575
+ name14 === void 0 ? refs : {
1576
1576
  ...refs,
1577
- currentPath: [...refs.basePath, refs.definitionPath, name]
1577
+ currentPath: [...refs.basePath, refs.definitionPath, name14]
1578
1578
  },
1579
1579
  false
1580
- )) != null ? _a : parseAnyDef();
1580
+ )) != null ? _a15 : parseAnyDef();
1581
1581
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1582
1582
  if (title !== void 0) {
1583
1583
  main.title = title;
1584
1584
  }
1585
- const combined = name === void 0 ? definitions ? {
1585
+ const combined = name14 === void 0 ? definitions ? {
1586
1586
  ...main,
1587
1587
  [refs.definitionPath]: definitions
1588
1588
  } : main : {
1589
1589
  $ref: [
1590
1590
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1591
1591
  refs.definitionPath,
1592
- name
1592
+ name14
1593
1593
  ].join("/"),
1594
1594
  [refs.definitionPath]: {
1595
1595
  ...definitions,
1596
- [name]: main
1596
+ [name14]: main
1597
1597
  }
1598
1598
  };
1599
1599
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -1601,8 +1601,8 @@ var zodToJsonSchema = (schema, options) => {
1601
1601
  };
1602
1602
  var zod_to_json_schema_default = zodToJsonSchema;
1603
1603
  function zod3Schema(zodSchema2, options) {
1604
- var _a;
1605
- const useReferences = (_a = void 0 ) != null ? _a : false;
1604
+ var _a15;
1605
+ const useReferences = (_a15 = void 0 ) != null ? _a15 : false;
1606
1606
  return jsonSchema(
1607
1607
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1608
1608
  () => zod_to_json_schema_default(zodSchema2, {
@@ -1617,8 +1617,8 @@ function zod3Schema(zodSchema2, options) {
1617
1617
  );
1618
1618
  }
1619
1619
  function zod4Schema(zodSchema2, options) {
1620
- var _a;
1621
- const useReferences = (_a = void 0 ) != null ? _a : false;
1620
+ var _a15;
1621
+ const useReferences = (_a15 = void 0 ) != null ? _a15 : false;
1622
1622
  return jsonSchema(
1623
1623
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1624
1624
  () => z4.toJSONSchema(zodSchema2, {
@@ -1998,12 +1998,12 @@ var DeepSeekChatLanguageModel = class {
1998
1998
  toolChoice,
1999
1999
  seed
2000
2000
  }) {
2001
- var _a, _b;
2002
- const deepseekOptions = (_a = await parseProviderOptions2({
2001
+ var _a15, _b;
2002
+ const deepseekOptions = (_a15 = await parseProviderOptions2({
2003
2003
  provider: this.providerOptionsName,
2004
2004
  providerOptions,
2005
2005
  schema: deepseekChatOptions
2006
- })) != null ? _a : {};
2006
+ })) != null ? _a15 : {};
2007
2007
  const { messages, warnings } = convertToDeepSeekChatMessages({
2008
2008
  prompt,
2009
2009
  responseFormat
@@ -2041,7 +2041,7 @@ var DeepSeekChatLanguageModel = class {
2041
2041
  };
2042
2042
  }
2043
2043
  async doGenerate(options) {
2044
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2044
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2045
2045
  const { args, warnings } = await this.getArgs({ ...options });
2046
2046
  const {
2047
2047
  responseHeaders,
@@ -2074,7 +2074,7 @@ var DeepSeekChatLanguageModel = class {
2074
2074
  for (const toolCall of choice.message.tool_calls) {
2075
2075
  content.push({
2076
2076
  type: "tool-call",
2077
- toolCallId: (_a = toolCall.id) != null ? _a : generateId2(),
2077
+ toolCallId: (_a15 = toolCall.id) != null ? _a15 : generateId2(),
2078
2078
  toolName: toolCall.function.name,
2079
2079
  input: toolCall.function.arguments
2080
2080
  });
@@ -2144,7 +2144,7 @@ var DeepSeekChatLanguageModel = class {
2144
2144
  controller.enqueue({ type: "stream-start", warnings });
2145
2145
  },
2146
2146
  transform(chunk, controller) {
2147
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
2147
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
2148
2148
  if (options.includeRawChunks) {
2149
2149
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2150
2150
  }
@@ -2227,7 +2227,7 @@ var DeepSeekChatLanguageModel = class {
2227
2227
  message: `Expected 'id' to be a string.`
2228
2228
  });
2229
2229
  }
2230
- if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
2230
+ if (((_a15 = toolCallDelta.function) == null ? void 0 : _a15.name) == null) {
2231
2231
  throw new InvalidResponseDataError({
2232
2232
  data: toolCallDelta,
2233
2233
  message: `Expected 'function.name' to be a string.`
@@ -2301,7 +2301,7 @@ var DeepSeekChatLanguageModel = class {
2301
2301
  }
2302
2302
  },
2303
2303
  flush(controller) {
2304
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2304
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i;
2305
2305
  if (isActiveReasoning) {
2306
2306
  controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
2307
2307
  }
@@ -2317,7 +2317,7 @@ var DeepSeekChatLanguageModel = class {
2317
2317
  });
2318
2318
  controller.enqueue({
2319
2319
  type: "tool-call",
2320
- toolCallId: (_a = toolCall.id) != null ? _a : generateId2(),
2320
+ toolCallId: (_a15 = toolCall.id) != null ? _a15 : generateId2(),
2321
2321
  toolName: toolCall.function.name,
2322
2322
  input: toolCall.function.arguments
2323
2323
  });
@@ -2349,9 +2349,9 @@ var DeepSeekChatLanguageModel = class {
2349
2349
  };
2350
2350
  var VERSION2 = "1.0.31" ;
2351
2351
  function createDeepSeek(options = {}) {
2352
- var _a;
2352
+ var _a15;
2353
2353
  const baseURL = withoutTrailingSlash2(
2354
- (_a = options.baseURL) != null ? _a : "https://api.deepseek.com"
2354
+ (_a15 = options.baseURL) != null ? _a15 : "https://api.deepseek.com"
2355
2355
  );
2356
2356
  const getHeaders = () => withUserAgentSuffix2(
2357
2357
  {
@@ -2618,10 +2618,10 @@ var MistralChatLanguageModel = class {
2618
2618
  this.supportedUrls = {
2619
2619
  "application/pdf": [/^https:\/\/.*$/]
2620
2620
  };
2621
- var _a;
2621
+ var _a15;
2622
2622
  this.modelId = modelId;
2623
2623
  this.config = config;
2624
- this.generateId = (_a = config.generateId) != null ? _a : generateId;
2624
+ this.generateId = (_a15 = config.generateId) != null ? _a15 : generateId;
2625
2625
  }
2626
2626
  get provider() {
2627
2627
  return this.config.provider;
@@ -2641,13 +2641,13 @@ var MistralChatLanguageModel = class {
2641
2641
  tools,
2642
2642
  toolChoice
2643
2643
  }) {
2644
- var _a, _b, _c, _d;
2644
+ var _a15, _b, _c, _d;
2645
2645
  const warnings = [];
2646
- const options = (_a = await parseProviderOptions({
2646
+ const options = (_a15 = await parseProviderOptions({
2647
2647
  provider: "mistral",
2648
2648
  providerOptions,
2649
2649
  schema: mistralLanguageModelOptions
2650
- })) != null ? _a : {};
2650
+ })) != null ? _a15 : {};
2651
2651
  if (topK != null) {
2652
2652
  warnings.push({
2653
2653
  type: "unsupported-setting",
@@ -3109,8 +3109,8 @@ var MistralTextEmbeddingResponseSchema = z.object({
3109
3109
  });
3110
3110
  var VERSION3 = "2.0.24" ;
3111
3111
  function createMistral(options = {}) {
3112
- var _a;
3113
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.mistral.ai/v1";
3112
+ var _a15;
3113
+ const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://api.mistral.ai/v1";
3114
3114
  const getHeaders = () => withUserAgentSuffix(
3115
3115
  {
3116
3116
  Authorization: `Bearer ${loadApiKey({
@@ -3618,7 +3618,7 @@ function convertToPerplexityMessages(prompt) {
3618
3618
  (part) => part.type === "file" && part.mediaType.startsWith("image/")
3619
3619
  );
3620
3620
  const messageContent = content.map((part) => {
3621
- var _a;
3621
+ var _a15;
3622
3622
  switch (part.type) {
3623
3623
  case "text": {
3624
3624
  return {
@@ -3635,7 +3635,7 @@ function convertToPerplexityMessages(prompt) {
3635
3635
  } : {
3636
3636
  type: "image_url",
3637
3637
  image_url: {
3638
- url: `data:${(_a = part.mediaType) != null ? _a : "image/jpeg"};base64,${typeof part.data === "string" ? part.data : convertUint8ArrayToBase64(part.data)}`
3638
+ url: `data:${(_a15 = part.mediaType) != null ? _a15 : "image/jpeg"};base64,${typeof part.data === "string" ? part.data : convertUint8ArrayToBase64(part.data)}`
3639
3639
  }
3640
3640
  };
3641
3641
  }
@@ -3692,7 +3692,7 @@ var PerplexityLanguageModel = class {
3692
3692
  seed,
3693
3693
  providerOptions
3694
3694
  }) {
3695
- var _a;
3695
+ var _a15;
3696
3696
  const warnings = [];
3697
3697
  if (topK != null) {
3698
3698
  warnings.push({
@@ -3729,7 +3729,7 @@ var PerplexityLanguageModel = class {
3729
3729
  json_schema: { schema: responseFormat.schema }
3730
3730
  } : void 0,
3731
3731
  // provider extensions
3732
- ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},
3732
+ ...(_a15 = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a15 : {},
3733
3733
  // messages:
3734
3734
  messages: convertToPerplexityMessages(prompt)
3735
3735
  },
@@ -3737,7 +3737,7 @@ var PerplexityLanguageModel = class {
3737
3737
  };
3738
3738
  }
3739
3739
  async doGenerate(options) {
3740
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3740
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3741
3741
  const { args: body, warnings } = this.getArgs(options);
3742
3742
  const {
3743
3743
  responseHeaders,
@@ -3777,7 +3777,7 @@ var PerplexityLanguageModel = class {
3777
3777
  content,
3778
3778
  finishReason: mapPerplexityFinishReason(choice.finish_reason),
3779
3779
  usage: {
3780
- inputTokens: (_a = response.usage) == null ? void 0 : _a.prompt_tokens,
3780
+ inputTokens: (_a15 = response.usage) == null ? void 0 : _a15.prompt_tokens,
3781
3781
  outputTokens: (_b = response.usage) == null ? void 0 : _b.completion_tokens,
3782
3782
  totalTokens: (_d = (_c = response.usage) == null ? void 0 : _c.total_tokens) != null ? _d : void 0
3783
3783
  },
@@ -3846,7 +3846,7 @@ var PerplexityLanguageModel = class {
3846
3846
  controller.enqueue({ type: "stream-start", warnings });
3847
3847
  },
3848
3848
  transform(chunk, controller) {
3849
- var _a, _b, _c;
3849
+ var _a15, _b, _c;
3850
3850
  if (options.includeRawChunks) {
3851
3851
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
3852
3852
  }
@@ -3860,7 +3860,7 @@ var PerplexityLanguageModel = class {
3860
3860
  type: "response-metadata",
3861
3861
  ...getResponseMetadata3(value)
3862
3862
  });
3863
- (_a = value.citations) == null ? void 0 : _a.forEach((url) => {
3863
+ (_a15 = value.citations) == null ? void 0 : _a15.forEach((url) => {
3864
3864
  controller.enqueue({
3865
3865
  type: "source",
3866
3866
  sourceType: "url",
@@ -3991,8 +3991,8 @@ var perplexityErrorSchema = z.object({
3991
3991
  })
3992
3992
  });
3993
3993
  var errorToMessage = (data) => {
3994
- var _a, _b;
3995
- return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : "unknown error";
3994
+ var _a15, _b;
3995
+ return (_b = (_a15 = data.error.message) != null ? _a15 : data.error.type) != null ? _b : "unknown error";
3996
3996
  };
3997
3997
  function createPerplexity(options = {}) {
3998
3998
  const getHeaders = () => ({
@@ -4004,10 +4004,10 @@ function createPerplexity(options = {}) {
4004
4004
  ...options.headers
4005
4005
  });
4006
4006
  const createLanguageModel = (modelId) => {
4007
- var _a;
4007
+ var _a15;
4008
4008
  return new PerplexityLanguageModel(modelId, {
4009
4009
  baseURL: withoutTrailingSlash3(
4010
- (_a = options.baseURL) != null ? _a : "https://api.perplexity.ai"
4010
+ (_a15 = options.baseURL) != null ? _a15 : "https://api.perplexity.ai"
4011
4011
  ),
4012
4012
  headers: getHeaders,
4013
4013
  generateId: generateId3,
@@ -4319,13 +4319,13 @@ var XaiChatLanguageModel = class {
4319
4319
  tools,
4320
4320
  toolChoice
4321
4321
  }) {
4322
- var _a, _b, _c;
4322
+ var _a15, _b, _c;
4323
4323
  const warnings = [];
4324
- const options = (_a = await parseProviderOptions({
4324
+ const options = (_a15 = await parseProviderOptions({
4325
4325
  provider: "xai",
4326
4326
  providerOptions,
4327
4327
  schema: xaiProviderOptions
4328
- })) != null ? _a : {};
4328
+ })) != null ? _a15 : {};
4329
4329
  if (topK != null) {
4330
4330
  warnings.push({
4331
4331
  type: "unsupported-setting",
@@ -4389,7 +4389,7 @@ var XaiChatLanguageModel = class {
4389
4389
  to_date: options.searchParameters.toDate,
4390
4390
  max_search_results: options.searchParameters.maxSearchResults,
4391
4391
  sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
4392
- var _a2;
4392
+ var _a22;
4393
4393
  return {
4394
4394
  type: source.type,
4395
4395
  ...source.type === "web" && {
@@ -4400,7 +4400,7 @@ var XaiChatLanguageModel = class {
4400
4400
  },
4401
4401
  ...source.type === "x" && {
4402
4402
  excluded_x_handles: source.excludedXHandles,
4403
- included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
4403
+ included_x_handles: (_a22 = source.includedXHandles) != null ? _a22 : source.xHandles,
4404
4404
  post_favorite_count: source.postFavoriteCount,
4405
4405
  post_view_count: source.postViewCount
4406
4406
  },
@@ -4427,14 +4427,14 @@ var XaiChatLanguageModel = class {
4427
4427
  };
4428
4428
  }
4429
4429
  async doGenerate(options) {
4430
- var _a, _b, _c;
4430
+ var _a15, _b, _c;
4431
4431
  const { args: body, warnings } = await this.getArgs(options);
4432
4432
  const {
4433
4433
  responseHeaders,
4434
4434
  value: response,
4435
4435
  rawValue: rawResponse
4436
4436
  } = await postJsonToApi({
4437
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
4437
+ url: `${(_a15 = this.config.baseURL) != null ? _a15 : "https://api.x.ai/v1"}/chat/completions`,
4438
4438
  headers: combineHeaders(this.config.headers(), options.headers),
4439
4439
  body,
4440
4440
  failedResponseHandler: xaiFailedResponseHandler,
@@ -4501,7 +4501,7 @@ var XaiChatLanguageModel = class {
4501
4501
  };
4502
4502
  }
4503
4503
  async doStream(options) {
4504
- var _a;
4504
+ var _a15;
4505
4505
  const { args, warnings } = await this.getArgs(options);
4506
4506
  const body = {
4507
4507
  ...args,
@@ -4511,7 +4511,7 @@ var XaiChatLanguageModel = class {
4511
4511
  }
4512
4512
  };
4513
4513
  const { responseHeaders, value: response } = await postJsonToApi({
4514
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
4514
+ url: `${(_a15 = this.config.baseURL) != null ? _a15 : "https://api.x.ai/v1"}/chat/completions`,
4515
4515
  headers: combineHeaders(this.config.headers(), options.headers),
4516
4516
  body,
4517
4517
  failedResponseHandler: xaiFailedResponseHandler,
@@ -4536,7 +4536,7 @@ var XaiChatLanguageModel = class {
4536
4536
  controller.enqueue({ type: "stream-start", warnings });
4537
4537
  },
4538
4538
  transform(chunk, controller) {
4539
- var _a2, _b;
4539
+ var _a22, _b;
4540
4540
  if (options.includeRawChunks) {
4541
4541
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
4542
4542
  }
@@ -4566,7 +4566,7 @@ var XaiChatLanguageModel = class {
4566
4566
  usage.inputTokens = value.usage.prompt_tokens;
4567
4567
  usage.outputTokens = value.usage.completion_tokens;
4568
4568
  usage.totalTokens = value.usage.total_tokens;
4569
- usage.reasoningTokens = (_b = (_a2 = value.usage.completion_tokens_details) == null ? void 0 : _a2.reasoning_tokens) != null ? _b : void 0;
4569
+ usage.reasoningTokens = (_b = (_a22 = value.usage.completion_tokens_details) == null ? void 0 : _a22.reasoning_tokens) != null ? _b : void 0;
4570
4570
  }
4571
4571
  const choice = value.choices[0];
4572
4572
  if ((choice == null ? void 0 : choice.finish_reason) != null) {
@@ -4729,9 +4729,9 @@ var xaiErrorStructure = {
4729
4729
  errorToMessage: (data) => data.error.message
4730
4730
  };
4731
4731
  function createXai(options = {}) {
4732
- var _a;
4732
+ var _a15;
4733
4733
  const baseURL = withoutTrailingSlash(
4734
- (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
4734
+ (_a15 = options.baseURL) != null ? _a15 : "https://api.x.ai/v1"
4735
4735
  );
4736
4736
  const getHeaders = () => withUserAgentSuffix(
4737
4737
  {
@@ -4773,6 +4773,2459 @@ function createXai(options = {}) {
4773
4773
  return provider;
4774
4774
  }
4775
4775
  createXai();
4776
+ var __defProp = Object.defineProperty;
4777
+ var __defProps = Object.defineProperties;
4778
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4779
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
4780
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4781
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
4782
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4783
+ var __spreadValues = (a, b) => {
4784
+ for (var prop in b || (b = {}))
4785
+ if (__hasOwnProp.call(b, prop))
4786
+ __defNormalProp(a, prop, b[prop]);
4787
+ if (__getOwnPropSymbols)
4788
+ for (var prop of __getOwnPropSymbols(b)) {
4789
+ if (__propIsEnum.call(b, prop))
4790
+ __defNormalProp(a, prop, b[prop]);
4791
+ }
4792
+ return a;
4793
+ };
4794
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
4795
+ var marker = "vercel.ai.error";
4796
+ var symbol = Symbol.for(marker);
4797
+ var _a;
4798
+ var _AISDKError = class _AISDKError2 extends Error {
4799
+ /**
4800
+ * Creates an AI SDK Error.
4801
+ *
4802
+ * @param {Object} params - The parameters for creating the error.
4803
+ * @param {string} params.name - The name of the error.
4804
+ * @param {string} params.message - The error message.
4805
+ * @param {unknown} [params.cause] - The underlying cause of the error.
4806
+ */
4807
+ constructor({
4808
+ name: name14,
4809
+ message,
4810
+ cause
4811
+ }) {
4812
+ super(message);
4813
+ this[_a] = true;
4814
+ this.name = name14;
4815
+ this.cause = cause;
4816
+ }
4817
+ /**
4818
+ * Checks if the given error is an AI SDK Error.
4819
+ * @param {unknown} error - The error to check.
4820
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
4821
+ */
4822
+ static isInstance(error) {
4823
+ return _AISDKError2.hasMarker(error, marker);
4824
+ }
4825
+ static hasMarker(error, marker15) {
4826
+ const markerSymbol = Symbol.for(marker15);
4827
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
4828
+ }
4829
+ };
4830
+ _a = symbol;
4831
+ var AISDKError = _AISDKError;
4832
+ var name = "AI_APICallError";
4833
+ var marker2 = `vercel.ai.error.${name}`;
4834
+ var symbol2 = Symbol.for(marker2);
4835
+ var _a2;
4836
+ var APICallError2 = class extends AISDKError {
4837
+ constructor({
4838
+ message,
4839
+ url,
4840
+ requestBodyValues,
4841
+ statusCode,
4842
+ responseHeaders,
4843
+ responseBody,
4844
+ cause,
4845
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
4846
+ statusCode === 409 || // conflict
4847
+ statusCode === 429 || // too many requests
4848
+ statusCode >= 500),
4849
+ // server error
4850
+ data
4851
+ }) {
4852
+ super({ name, message, cause });
4853
+ this[_a2] = true;
4854
+ this.url = url;
4855
+ this.requestBodyValues = requestBodyValues;
4856
+ this.statusCode = statusCode;
4857
+ this.responseHeaders = responseHeaders;
4858
+ this.responseBody = responseBody;
4859
+ this.isRetryable = isRetryable;
4860
+ this.data = data;
4861
+ }
4862
+ static isInstance(error) {
4863
+ return AISDKError.hasMarker(error, marker2);
4864
+ }
4865
+ };
4866
+ _a2 = symbol2;
4867
+ var name2 = "AI_EmptyResponseBodyError";
4868
+ var marker3 = `vercel.ai.error.${name2}`;
4869
+ var symbol3 = Symbol.for(marker3);
4870
+ var _a3;
4871
+ var EmptyResponseBodyError2 = class extends AISDKError {
4872
+ // used in isInstance
4873
+ constructor({ message = "Empty response body" } = {}) {
4874
+ super({ name: name2, message });
4875
+ this[_a3] = true;
4876
+ }
4877
+ static isInstance(error) {
4878
+ return AISDKError.hasMarker(error, marker3);
4879
+ }
4880
+ };
4881
+ _a3 = symbol3;
4882
+ function getErrorMessage(error) {
4883
+ if (error == null) {
4884
+ return "unknown error";
4885
+ }
4886
+ if (typeof error === "string") {
4887
+ return error;
4888
+ }
4889
+ if (error instanceof Error) {
4890
+ return error.message;
4891
+ }
4892
+ return JSON.stringify(error);
4893
+ }
4894
+ var name3 = "AI_InvalidArgumentError";
4895
+ var marker4 = `vercel.ai.error.${name3}`;
4896
+ var symbol4 = Symbol.for(marker4);
4897
+ var _a4;
4898
+ var InvalidArgumentError2 = class extends AISDKError {
4899
+ constructor({
4900
+ message,
4901
+ cause,
4902
+ argument
4903
+ }) {
4904
+ super({ name: name3, message, cause });
4905
+ this[_a4] = true;
4906
+ this.argument = argument;
4907
+ }
4908
+ static isInstance(error) {
4909
+ return AISDKError.hasMarker(error, marker4);
4910
+ }
4911
+ };
4912
+ _a4 = symbol4;
4913
+ var name4 = "AI_InvalidPromptError";
4914
+ var marker5 = `vercel.ai.error.${name4}`;
4915
+ var symbol5 = Symbol.for(marker5);
4916
+ var _a5;
4917
+ var InvalidPromptError = class extends AISDKError {
4918
+ constructor({
4919
+ prompt,
4920
+ message,
4921
+ cause
4922
+ }) {
4923
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
4924
+ this[_a5] = true;
4925
+ this.prompt = prompt;
4926
+ }
4927
+ static isInstance(error) {
4928
+ return AISDKError.hasMarker(error, marker5);
4929
+ }
4930
+ };
4931
+ _a5 = symbol5;
4932
+ var name5 = "AI_InvalidResponseDataError";
4933
+ var marker6 = `vercel.ai.error.${name5}`;
4934
+ var symbol6 = Symbol.for(marker6);
4935
+ var _a6;
4936
+ var InvalidResponseDataError2 = class extends AISDKError {
4937
+ constructor({
4938
+ data,
4939
+ message = `Invalid response data: ${JSON.stringify(data)}.`
4940
+ }) {
4941
+ super({ name: name5, message });
4942
+ this[_a6] = true;
4943
+ this.data = data;
4944
+ }
4945
+ static isInstance(error) {
4946
+ return AISDKError.hasMarker(error, marker6);
4947
+ }
4948
+ };
4949
+ _a6 = symbol6;
4950
+ var name6 = "AI_JSONParseError";
4951
+ var marker7 = `vercel.ai.error.${name6}`;
4952
+ var symbol7 = Symbol.for(marker7);
4953
+ var _a7;
4954
+ var JSONParseError2 = class extends AISDKError {
4955
+ constructor({ text, cause }) {
4956
+ super({
4957
+ name: name6,
4958
+ message: `JSON parsing failed: Text: ${text}.
4959
+ Error message: ${getErrorMessage(cause)}`,
4960
+ cause
4961
+ });
4962
+ this[_a7] = true;
4963
+ this.text = text;
4964
+ }
4965
+ static isInstance(error) {
4966
+ return AISDKError.hasMarker(error, marker7);
4967
+ }
4968
+ };
4969
+ _a7 = symbol7;
4970
+ var name7 = "AI_LoadAPIKeyError";
4971
+ var marker8 = `vercel.ai.error.${name7}`;
4972
+ var symbol8 = Symbol.for(marker8);
4973
+ var _a8;
4974
+ var LoadAPIKeyError2 = class extends AISDKError {
4975
+ // used in isInstance
4976
+ constructor({ message }) {
4977
+ super({ name: name7, message });
4978
+ this[_a8] = true;
4979
+ }
4980
+ static isInstance(error) {
4981
+ return AISDKError.hasMarker(error, marker8);
4982
+ }
4983
+ };
4984
+ _a8 = symbol8;
4985
+ var name9 = "AI_NoContentGeneratedError";
4986
+ var marker10 = `vercel.ai.error.${name9}`;
4987
+ var symbol10 = Symbol.for(marker10);
4988
+ var _a10;
4989
+ var NoContentGeneratedError = class extends AISDKError {
4990
+ // used in isInstance
4991
+ constructor({
4992
+ message = "No content generated."
4993
+ } = {}) {
4994
+ super({ name: name9, message });
4995
+ this[_a10] = true;
4996
+ }
4997
+ static isInstance(error) {
4998
+ return AISDKError.hasMarker(error, marker10);
4999
+ }
5000
+ };
5001
+ _a10 = symbol10;
5002
+ var name12 = "AI_TypeValidationError";
5003
+ var marker13 = `vercel.ai.error.${name12}`;
5004
+ var symbol13 = Symbol.for(marker13);
5005
+ var _a13;
5006
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
5007
+ constructor({ value, cause }) {
5008
+ super({
5009
+ name: name12,
5010
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
5011
+ Error message: ${getErrorMessage(cause)}`,
5012
+ cause
5013
+ });
5014
+ this[_a13] = true;
5015
+ this.value = value;
5016
+ }
5017
+ static isInstance(error) {
5018
+ return AISDKError.hasMarker(error, marker13);
5019
+ }
5020
+ /**
5021
+ * Wraps an error into a TypeValidationError.
5022
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
5023
+ * Otherwise, it creates a new TypeValidationError.
5024
+ *
5025
+ * @param {Object} params - The parameters for wrapping the error.
5026
+ * @param {unknown} params.value - The value that failed validation.
5027
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
5028
+ * @returns {TypeValidationError} A TypeValidationError instance.
5029
+ */
5030
+ static wrap({
5031
+ value,
5032
+ cause
5033
+ }) {
5034
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
5035
+ }
5036
+ };
5037
+ _a13 = symbol13;
5038
+ var TypeValidationError2 = _TypeValidationError;
5039
+ var name13 = "AI_UnsupportedFunctionalityError";
5040
+ var marker14 = `vercel.ai.error.${name13}`;
5041
+ var symbol14 = Symbol.for(marker14);
5042
+ var _a14;
5043
+ var UnsupportedFunctionalityError2 = class extends AISDKError {
5044
+ constructor({
5045
+ functionality,
5046
+ message = `'${functionality}' functionality not supported.`
5047
+ }) {
5048
+ super({ name: name13, message });
5049
+ this[_a14] = true;
5050
+ this.functionality = functionality;
5051
+ }
5052
+ static isInstance(error) {
5053
+ return AISDKError.hasMarker(error, marker14);
5054
+ }
5055
+ };
5056
+ _a14 = symbol14;
5057
+ var ParseError = class extends Error {
5058
+ constructor(message, options) {
5059
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
5060
+ }
5061
+ };
5062
+ function noop(_arg) {
5063
+ }
5064
+ function createParser(callbacks) {
5065
+ if (typeof callbacks == "function")
5066
+ throw new TypeError(
5067
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
5068
+ );
5069
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
5070
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
5071
+ function feed(newChunk) {
5072
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
5073
+ for (const line of complete)
5074
+ parseLine(line);
5075
+ incompleteLine = incomplete, isFirstChunk = false;
5076
+ }
5077
+ function parseLine(line) {
5078
+ if (line === "") {
5079
+ dispatchEvent();
5080
+ return;
5081
+ }
5082
+ if (line.startsWith(":")) {
5083
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
5084
+ return;
5085
+ }
5086
+ const fieldSeparatorIndex = line.indexOf(":");
5087
+ if (fieldSeparatorIndex !== -1) {
5088
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
5089
+ processField(field, value, line);
5090
+ return;
5091
+ }
5092
+ processField(line, "", line);
5093
+ }
5094
+ function processField(field, value, line) {
5095
+ switch (field) {
5096
+ case "event":
5097
+ eventType = value;
5098
+ break;
5099
+ case "data":
5100
+ data = `${data}${value}
5101
+ `;
5102
+ break;
5103
+ case "id":
5104
+ id = value.includes("\0") ? void 0 : value;
5105
+ break;
5106
+ case "retry":
5107
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
5108
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
5109
+ type: "invalid-retry",
5110
+ value,
5111
+ line
5112
+ })
5113
+ );
5114
+ break;
5115
+ default:
5116
+ onError(
5117
+ new ParseError(
5118
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
5119
+ { type: "unknown-field", field, value, line }
5120
+ )
5121
+ );
5122
+ break;
5123
+ }
5124
+ }
5125
+ function dispatchEvent() {
5126
+ data.length > 0 && onEvent({
5127
+ id,
5128
+ event: eventType || void 0,
5129
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
5130
+ // then remove the last character from the data buffer.
5131
+ data: data.endsWith(`
5132
+ `) ? data.slice(0, -1) : data
5133
+ }), id = void 0, data = "", eventType = "";
5134
+ }
5135
+ function reset(options = {}) {
5136
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
5137
+ }
5138
+ return { feed, reset };
5139
+ }
5140
+ function splitLines(chunk) {
5141
+ const lines = [];
5142
+ let incompleteLine = "", searchIndex = 0;
5143
+ for (; searchIndex < chunk.length; ) {
5144
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
5145
+ `, searchIndex);
5146
+ let lineEnd = -1;
5147
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
5148
+ incompleteLine = chunk.slice(searchIndex);
5149
+ break;
5150
+ } else {
5151
+ const line = chunk.slice(searchIndex, lineEnd);
5152
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
5153
+ ` && searchIndex++;
5154
+ }
5155
+ }
5156
+ return [lines, incompleteLine];
5157
+ }
5158
+ var EventSourceParserStream2 = class extends TransformStream {
5159
+ constructor({ onError, onRetry, onComment } = {}) {
5160
+ let parser;
5161
+ super({
5162
+ start(controller) {
5163
+ parser = createParser({
5164
+ onEvent: (event) => {
5165
+ controller.enqueue(event);
5166
+ },
5167
+ onError(error) {
5168
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
5169
+ },
5170
+ onRetry,
5171
+ onComment
5172
+ });
5173
+ },
5174
+ transform(chunk) {
5175
+ parser.feed(chunk);
5176
+ }
5177
+ });
5178
+ }
5179
+ };
5180
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
5181
+ function combineHeaders4(...headers) {
5182
+ return headers.reduce(
5183
+ (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
5184
+ {}
5185
+ );
5186
+ }
5187
+ function extractResponseHeaders3(response) {
5188
+ return Object.fromEntries([...response.headers]);
5189
+ }
5190
+ var createIdGenerator3 = ({
5191
+ prefix,
5192
+ size = 16,
5193
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
5194
+ separator = "-"
5195
+ } = {}) => {
5196
+ const generator = () => {
5197
+ const alphabetLength = alphabet.length;
5198
+ const chars = new Array(size);
5199
+ for (let i = 0; i < size; i++) {
5200
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
5201
+ }
5202
+ return chars.join("");
5203
+ };
5204
+ if (prefix == null) {
5205
+ return generator;
5206
+ }
5207
+ if (alphabet.includes(separator)) {
5208
+ throw new InvalidArgumentError2({
5209
+ argument: "separator",
5210
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
5211
+ });
5212
+ }
5213
+ return () => `${prefix}${separator}${generator()}`;
5214
+ };
5215
+ var generateId4 = createIdGenerator3();
5216
+ function isAbortError3(error) {
5217
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
5218
+ error.name === "TimeoutError");
5219
+ }
5220
+ var FETCH_FAILED_ERROR_MESSAGES3 = ["fetch failed", "failed to fetch"];
5221
+ function handleFetchError3({
5222
+ error,
5223
+ url,
5224
+ requestBodyValues
5225
+ }) {
5226
+ if (isAbortError3(error)) {
5227
+ return error;
5228
+ }
5229
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES3.includes(error.message.toLowerCase())) {
5230
+ const cause = error.cause;
5231
+ if (cause != null) {
5232
+ return new APICallError2({
5233
+ message: `Cannot connect to API: ${cause.message}`,
5234
+ cause,
5235
+ url,
5236
+ requestBodyValues,
5237
+ isRetryable: true
5238
+ // retry when network error
5239
+ });
5240
+ }
5241
+ }
5242
+ return error;
5243
+ }
5244
+ function removeUndefinedEntries2(record) {
5245
+ return Object.fromEntries(
5246
+ Object.entries(record).filter(([_key, value]) => value != null)
5247
+ );
5248
+ }
5249
+ function loadApiKey4({
5250
+ apiKey,
5251
+ environmentVariableName,
5252
+ apiKeyParameterName = "apiKey",
5253
+ description
5254
+ }) {
5255
+ if (typeof apiKey === "string") {
5256
+ return apiKey;
5257
+ }
5258
+ if (apiKey != null) {
5259
+ throw new LoadAPIKeyError2({
5260
+ message: `${description} API key must be a string.`
5261
+ });
5262
+ }
5263
+ if (typeof process === "undefined") {
5264
+ throw new LoadAPIKeyError2({
5265
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
5266
+ });
5267
+ }
5268
+ apiKey = process.env[environmentVariableName];
5269
+ if (apiKey == null) {
5270
+ throw new LoadAPIKeyError2({
5271
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
5272
+ });
5273
+ }
5274
+ if (typeof apiKey !== "string") {
5275
+ throw new LoadAPIKeyError2({
5276
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
5277
+ });
5278
+ }
5279
+ return apiKey;
5280
+ }
5281
+ var suspectProtoRx3 = /"__proto__"\s*:/;
5282
+ var suspectConstructorRx3 = /"constructor"\s*:/;
5283
+ function _parse3(text) {
5284
+ const obj = JSON.parse(text);
5285
+ if (obj === null || typeof obj !== "object") {
5286
+ return obj;
5287
+ }
5288
+ if (suspectProtoRx3.test(text) === false && suspectConstructorRx3.test(text) === false) {
5289
+ return obj;
5290
+ }
5291
+ return filter3(obj);
5292
+ }
5293
+ function filter3(obj) {
5294
+ let next = [obj];
5295
+ while (next.length) {
5296
+ const nodes = next;
5297
+ next = [];
5298
+ for (const node of nodes) {
5299
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
5300
+ throw new SyntaxError("Object contains forbidden prototype property");
5301
+ }
5302
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
5303
+ throw new SyntaxError("Object contains forbidden prototype property");
5304
+ }
5305
+ for (const key in node) {
5306
+ const value = node[key];
5307
+ if (value && typeof value === "object") {
5308
+ next.push(value);
5309
+ }
5310
+ }
5311
+ }
5312
+ }
5313
+ return obj;
5314
+ }
5315
+ function secureJsonParse3(text) {
5316
+ const { stackTraceLimit } = Error;
5317
+ Error.stackTraceLimit = 0;
5318
+ try {
5319
+ return _parse3(text);
5320
+ } finally {
5321
+ Error.stackTraceLimit = stackTraceLimit;
5322
+ }
5323
+ }
5324
+ var validatorSymbol3 = Symbol.for("vercel.ai.validator");
5325
+ function validator3(validate) {
5326
+ return { [validatorSymbol3]: true, validate };
5327
+ }
5328
+ function isValidator3(value) {
5329
+ return typeof value === "object" && value !== null && validatorSymbol3 in value && value[validatorSymbol3] === true && "validate" in value;
5330
+ }
5331
+ function asValidator3(value) {
5332
+ return isValidator3(value) ? value : standardSchemaValidator3(value);
5333
+ }
5334
+ function standardSchemaValidator3(standardSchema) {
5335
+ return validator3(async (value) => {
5336
+ const result = await standardSchema["~standard"].validate(value);
5337
+ return result.issues == null ? { success: true, value: result.value } : {
5338
+ success: false,
5339
+ error: new TypeValidationError2({
5340
+ value,
5341
+ cause: result.issues
5342
+ })
5343
+ };
5344
+ });
5345
+ }
5346
+ async function validateTypes3({
5347
+ value,
5348
+ schema
5349
+ }) {
5350
+ const result = await safeValidateTypes3({ value, schema });
5351
+ if (!result.success) {
5352
+ throw TypeValidationError2.wrap({ value, cause: result.error });
5353
+ }
5354
+ return result.value;
5355
+ }
5356
+ async function safeValidateTypes3({
5357
+ value,
5358
+ schema
5359
+ }) {
5360
+ const validator22 = asValidator3(schema);
5361
+ try {
5362
+ if (validator22.validate == null) {
5363
+ return { success: true, value, rawValue: value };
5364
+ }
5365
+ const result = await validator22.validate(value);
5366
+ if (result.success) {
5367
+ return { success: true, value: result.value, rawValue: value };
5368
+ }
5369
+ return {
5370
+ success: false,
5371
+ error: TypeValidationError2.wrap({ value, cause: result.error }),
5372
+ rawValue: value
5373
+ };
5374
+ } catch (error) {
5375
+ return {
5376
+ success: false,
5377
+ error: TypeValidationError2.wrap({ value, cause: error }),
5378
+ rawValue: value
5379
+ };
5380
+ }
5381
+ }
5382
+ async function parseJSON3({
5383
+ text,
5384
+ schema
5385
+ }) {
5386
+ try {
5387
+ const value = secureJsonParse3(text);
5388
+ if (schema == null) {
5389
+ return value;
5390
+ }
5391
+ return validateTypes3({ value, schema });
5392
+ } catch (error) {
5393
+ if (JSONParseError2.isInstance(error) || TypeValidationError2.isInstance(error)) {
5394
+ throw error;
5395
+ }
5396
+ throw new JSONParseError2({ text, cause: error });
5397
+ }
5398
+ }
5399
+ async function safeParseJSON3({
5400
+ text,
5401
+ schema
5402
+ }) {
5403
+ try {
5404
+ const value = secureJsonParse3(text);
5405
+ if (schema == null) {
5406
+ return { success: true, value, rawValue: value };
5407
+ }
5408
+ return await safeValidateTypes3({ value, schema });
5409
+ } catch (error) {
5410
+ return {
5411
+ success: false,
5412
+ error: JSONParseError2.isInstance(error) ? error : new JSONParseError2({ text, cause: error }),
5413
+ rawValue: void 0
5414
+ };
5415
+ }
5416
+ }
5417
+ function isParsableJson2(input) {
5418
+ try {
5419
+ secureJsonParse3(input);
5420
+ return true;
5421
+ } catch (e) {
5422
+ return false;
5423
+ }
5424
+ }
5425
+ function parseJsonEventStream3({
5426
+ stream,
5427
+ schema
5428
+ }) {
5429
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream2()).pipeThrough(
5430
+ new TransformStream({
5431
+ async transform({ data }, controller) {
5432
+ if (data === "[DONE]") {
5433
+ return;
5434
+ }
5435
+ controller.enqueue(await safeParseJSON3({ text: data, schema }));
5436
+ }
5437
+ })
5438
+ );
5439
+ }
5440
+ var getOriginalFetch23 = () => globalThis.fetch;
5441
+ var postJsonToApi4 = async ({
5442
+ url,
5443
+ headers,
5444
+ body,
5445
+ failedResponseHandler,
5446
+ successfulResponseHandler,
5447
+ abortSignal,
5448
+ fetch: fetch2
5449
+ }) => postToApi3({
5450
+ url,
5451
+ headers: __spreadValues({
5452
+ "Content-Type": "application/json"
5453
+ }, headers),
5454
+ body: {
5455
+ content: JSON.stringify(body),
5456
+ values: body
5457
+ },
5458
+ failedResponseHandler,
5459
+ successfulResponseHandler,
5460
+ abortSignal,
5461
+ fetch: fetch2
5462
+ });
5463
+ var postToApi3 = async ({
5464
+ url,
5465
+ headers = {},
5466
+ body,
5467
+ successfulResponseHandler,
5468
+ failedResponseHandler,
5469
+ abortSignal,
5470
+ fetch: fetch2 = getOriginalFetch23()
5471
+ }) => {
5472
+ try {
5473
+ const response = await fetch2(url, {
5474
+ method: "POST",
5475
+ headers: removeUndefinedEntries2(headers),
5476
+ body: body.content,
5477
+ signal: abortSignal
5478
+ });
5479
+ const responseHeaders = extractResponseHeaders3(response);
5480
+ if (!response.ok) {
5481
+ let errorInformation;
5482
+ try {
5483
+ errorInformation = await failedResponseHandler({
5484
+ response,
5485
+ url,
5486
+ requestBodyValues: body.values
5487
+ });
5488
+ } catch (error) {
5489
+ if (isAbortError3(error) || APICallError2.isInstance(error)) {
5490
+ throw error;
5491
+ }
5492
+ throw new APICallError2({
5493
+ message: "Failed to process error response",
5494
+ cause: error,
5495
+ statusCode: response.status,
5496
+ url,
5497
+ responseHeaders,
5498
+ requestBodyValues: body.values
5499
+ });
5500
+ }
5501
+ throw errorInformation.value;
5502
+ }
5503
+ try {
5504
+ return await successfulResponseHandler({
5505
+ response,
5506
+ url,
5507
+ requestBodyValues: body.values
5508
+ });
5509
+ } catch (error) {
5510
+ if (error instanceof Error) {
5511
+ if (isAbortError3(error) || APICallError2.isInstance(error)) {
5512
+ throw error;
5513
+ }
5514
+ }
5515
+ throw new APICallError2({
5516
+ message: "Failed to process successful response",
5517
+ cause: error,
5518
+ statusCode: response.status,
5519
+ url,
5520
+ responseHeaders,
5521
+ requestBodyValues: body.values
5522
+ });
5523
+ }
5524
+ } catch (error) {
5525
+ throw handleFetchError3({ error, url, requestBodyValues: body.values });
5526
+ }
5527
+ };
5528
+ var createJsonErrorResponseHandler4 = ({
5529
+ errorSchema,
5530
+ errorToMessage: errorToMessage2,
5531
+ isRetryable
5532
+ }) => async ({ response, url, requestBodyValues }) => {
5533
+ const responseBody = await response.text();
5534
+ const responseHeaders = extractResponseHeaders3(response);
5535
+ if (responseBody.trim() === "") {
5536
+ return {
5537
+ responseHeaders,
5538
+ value: new APICallError2({
5539
+ message: response.statusText,
5540
+ url,
5541
+ requestBodyValues,
5542
+ statusCode: response.status,
5543
+ responseHeaders,
5544
+ responseBody,
5545
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5546
+ })
5547
+ };
5548
+ }
5549
+ try {
5550
+ const parsedError = await parseJSON3({
5551
+ text: responseBody,
5552
+ schema: errorSchema
5553
+ });
5554
+ return {
5555
+ responseHeaders,
5556
+ value: new APICallError2({
5557
+ message: errorToMessage2(parsedError),
5558
+ url,
5559
+ requestBodyValues,
5560
+ statusCode: response.status,
5561
+ responseHeaders,
5562
+ responseBody,
5563
+ data: parsedError,
5564
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
5565
+ })
5566
+ };
5567
+ } catch (parseError) {
5568
+ return {
5569
+ responseHeaders,
5570
+ value: new APICallError2({
5571
+ message: response.statusText,
5572
+ url,
5573
+ requestBodyValues,
5574
+ statusCode: response.status,
5575
+ responseHeaders,
5576
+ responseBody,
5577
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
5578
+ })
5579
+ };
5580
+ }
5581
+ };
5582
+ var createEventSourceResponseHandler4 = (chunkSchema) => async ({ response }) => {
5583
+ const responseHeaders = extractResponseHeaders3(response);
5584
+ if (response.body == null) {
5585
+ throw new EmptyResponseBodyError2({});
5586
+ }
5587
+ return {
5588
+ responseHeaders,
5589
+ value: parseJsonEventStream3({
5590
+ stream: response.body,
5591
+ schema: chunkSchema
5592
+ })
5593
+ };
5594
+ };
5595
+ var createJsonResponseHandler4 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
5596
+ const responseBody = await response.text();
5597
+ const parsedResult = await safeParseJSON3({
5598
+ text: responseBody,
5599
+ schema: responseSchema
5600
+ });
5601
+ const responseHeaders = extractResponseHeaders3(response);
5602
+ if (!parsedResult.success) {
5603
+ throw new APICallError2({
5604
+ message: "Invalid JSON response",
5605
+ cause: parsedResult.error,
5606
+ statusCode: response.status,
5607
+ responseHeaders,
5608
+ responseBody,
5609
+ url,
5610
+ requestBodyValues
5611
+ });
5612
+ }
5613
+ return {
5614
+ responseHeaders,
5615
+ value: parsedResult.value,
5616
+ rawValue: parsedResult.rawValue
5617
+ };
5618
+ };
5619
+ var { btoa: btoa3} = globalThis;
5620
+ function convertUint8ArrayToBase642(array) {
5621
+ let latin1string = "";
5622
+ for (let i = 0; i < array.length; i++) {
5623
+ latin1string += String.fromCodePoint(array[i]);
5624
+ }
5625
+ return btoa3(latin1string);
5626
+ }
5627
+ function withoutTrailingSlash4(url) {
5628
+ return url == null ? void 0 : url.replace(/\/$/, "");
5629
+ }
5630
+ function isDefinedOrNotNull(value) {
5631
+ return value !== null && value !== void 0;
5632
+ }
5633
+ var ReasoningFormat = /* @__PURE__ */ ((ReasoningFormat2) => {
5634
+ ReasoningFormat2["Unknown"] = "unknown";
5635
+ ReasoningFormat2["OpenAIResponsesV1"] = "openai-responses-v1";
5636
+ ReasoningFormat2["XAIResponsesV1"] = "xai-responses-v1";
5637
+ ReasoningFormat2["AnthropicClaudeV1"] = "anthropic-claude-v1";
5638
+ return ReasoningFormat2;
5639
+ })(ReasoningFormat || {});
5640
+ var CommonReasoningDetailSchema = z.object({
5641
+ id: z.string().nullish(),
5642
+ format: z.nativeEnum(ReasoningFormat).nullish(),
5643
+ index: z.number().optional()
5644
+ }).passthrough();
5645
+ var ReasoningDetailSummarySchema = z.object({
5646
+ type: z.literal(
5647
+ "reasoning.summary"
5648
+ /* Summary */
5649
+ ),
5650
+ summary: z.string()
5651
+ }).extend(CommonReasoningDetailSchema.shape);
5652
+ var ReasoningDetailEncryptedSchema = z.object({
5653
+ type: z.literal(
5654
+ "reasoning.encrypted"
5655
+ /* Encrypted */
5656
+ ),
5657
+ data: z.string()
5658
+ }).extend(CommonReasoningDetailSchema.shape);
5659
+ var ReasoningDetailTextSchema = z.object({
5660
+ type: z.literal(
5661
+ "reasoning.text"
5662
+ /* Text */
5663
+ ),
5664
+ text: z.string().nullish(),
5665
+ signature: z.string().nullish()
5666
+ }).extend(CommonReasoningDetailSchema.shape);
5667
+ var ReasoningDetailUnionSchema = z.union([
5668
+ ReasoningDetailSummarySchema,
5669
+ ReasoningDetailEncryptedSchema,
5670
+ ReasoningDetailTextSchema
5671
+ ]);
5672
+ var ReasoningDetailsWithUnknownSchema = z.union([
5673
+ ReasoningDetailUnionSchema,
5674
+ z.unknown().transform(() => null)
5675
+ ]);
5676
+ var ReasoningDetailArraySchema = z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
5677
+ z.union([
5678
+ z.object({
5679
+ delta: z.object({
5680
+ reasoning_details: z.array(ReasoningDetailsWithUnknownSchema)
5681
+ })
5682
+ }).transform(
5683
+ (data) => data.delta.reasoning_details.filter(isDefinedOrNotNull)
5684
+ ),
5685
+ z.object({
5686
+ message: z.object({
5687
+ reasoning_details: z.array(ReasoningDetailsWithUnknownSchema)
5688
+ })
5689
+ }).transform(
5690
+ (data) => data.message.reasoning_details.filter(isDefinedOrNotNull)
5691
+ ),
5692
+ z.object({
5693
+ text: z.string(),
5694
+ reasoning_details: z.array(ReasoningDetailsWithUnknownSchema)
5695
+ }).transform((data) => data.reasoning_details.filter(isDefinedOrNotNull))
5696
+ ]);
5697
+ var OpenRouterErrorResponseSchema = z.object({
5698
+ error: z.object({
5699
+ code: z.union([z.string(), z.number()]).nullable().optional().default(null),
5700
+ message: z.string(),
5701
+ type: z.string().nullable().optional().default(null),
5702
+ param: z.any().nullable().optional().default(null)
5703
+ }).passthrough()
5704
+ }).passthrough();
5705
+ var openrouterFailedResponseHandler = createJsonErrorResponseHandler4({
5706
+ errorSchema: OpenRouterErrorResponseSchema,
5707
+ errorToMessage: (data) => data.error.message
5708
+ });
5709
+ var OpenRouterProviderMetadataSchema = z.object({
5710
+ provider: z.string(),
5711
+ reasoning_details: z.array(ReasoningDetailUnionSchema).optional(),
5712
+ usage: z.object({
5713
+ promptTokens: z.number(),
5714
+ promptTokensDetails: z.object({
5715
+ cachedTokens: z.number()
5716
+ }).passthrough().optional(),
5717
+ completionTokens: z.number(),
5718
+ completionTokensDetails: z.object({
5719
+ reasoningTokens: z.number()
5720
+ }).passthrough().optional(),
5721
+ totalTokens: z.number(),
5722
+ cost: z.number().optional(),
5723
+ costDetails: z.object({
5724
+ upstreamInferenceCost: z.number()
5725
+ }).passthrough()
5726
+ }).passthrough()
5727
+ }).passthrough();
5728
+ var OpenRouterProviderOptionsSchema = z.object({
5729
+ openrouter: z.object({
5730
+ reasoning_details: z.array(ReasoningDetailUnionSchema).optional()
5731
+ }).optional()
5732
+ }).optional();
5733
+ function mapOpenRouterFinishReason(finishReason) {
5734
+ switch (finishReason) {
5735
+ case "stop":
5736
+ return "stop";
5737
+ case "length":
5738
+ return "length";
5739
+ case "content_filter":
5740
+ return "content-filter";
5741
+ case "function_call":
5742
+ case "tool_calls":
5743
+ return "tool-calls";
5744
+ default:
5745
+ return "unknown";
5746
+ }
5747
+ }
5748
+ function isUrl({
5749
+ url,
5750
+ protocols
5751
+ }) {
5752
+ try {
5753
+ const urlObj = new URL(url);
5754
+ return protocols.has(urlObj.protocol);
5755
+ } catch (_) {
5756
+ return false;
5757
+ }
5758
+ }
5759
+ function getFileUrl({
5760
+ part,
5761
+ defaultMediaType
5762
+ }) {
5763
+ var _a15, _b;
5764
+ if (part.data instanceof Uint8Array) {
5765
+ const base64 = convertUint8ArrayToBase642(part.data);
5766
+ return `data:${(_a15 = part.mediaType) != null ? _a15 : defaultMediaType};base64,${base64}`;
5767
+ }
5768
+ const stringUrl = part.data.toString();
5769
+ if (isUrl({
5770
+ url: stringUrl,
5771
+ protocols: /* @__PURE__ */ new Set(["http:", "https:"])
5772
+ })) {
5773
+ return stringUrl;
5774
+ }
5775
+ return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b = part.mediaType) != null ? _b : defaultMediaType};base64,${stringUrl}`;
5776
+ }
5777
+ function getMediaType(dataUrl, defaultMediaType) {
5778
+ var _a15;
5779
+ const match = dataUrl.match(/^data:([^;]+)/);
5780
+ return match ? (_a15 = match[1]) != null ? _a15 : defaultMediaType : defaultMediaType;
5781
+ }
5782
+ function getBase64FromDataUrl(dataUrl) {
5783
+ const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
5784
+ return match ? match[1] : dataUrl;
5785
+ }
5786
+ function getCacheControl(providerMetadata) {
5787
+ var _a15, _b, _c;
5788
+ const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
5789
+ const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
5790
+ 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;
5791
+ }
5792
+ function convertToOpenRouterChatMessages(prompt) {
5793
+ var _a15, _b, _c, _d, _e;
5794
+ const messages = [];
5795
+ for (const { role, content, providerOptions } of prompt) {
5796
+ switch (role) {
5797
+ case "system": {
5798
+ messages.push({
5799
+ role: "system",
5800
+ content,
5801
+ cache_control: getCacheControl(providerOptions)
5802
+ });
5803
+ break;
5804
+ }
5805
+ case "user": {
5806
+ if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
5807
+ const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
5808
+ const contentWithCacheControl = cacheControl ? [
5809
+ {
5810
+ type: "text",
5811
+ text: content[0].text,
5812
+ cache_control: cacheControl
5813
+ }
5814
+ ] : content[0].text;
5815
+ messages.push({
5816
+ role: "user",
5817
+ content: contentWithCacheControl
5818
+ });
5819
+ break;
5820
+ }
5821
+ const messageCacheControl = getCacheControl(providerOptions);
5822
+ const contentParts = content.map(
5823
+ (part) => {
5824
+ var _a16, _b2, _c2, _d2, _e2, _f;
5825
+ const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
5826
+ switch (part.type) {
5827
+ case "text":
5828
+ return {
5829
+ type: "text",
5830
+ text: part.text,
5831
+ // For text parts, only use part-specific cache control
5832
+ cache_control: cacheControl
5833
+ };
5834
+ case "file": {
5835
+ if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
5836
+ const url = getFileUrl({
5837
+ part,
5838
+ defaultMediaType: "image/jpeg"
5839
+ });
5840
+ return {
5841
+ type: "image_url",
5842
+ image_url: {
5843
+ url
5844
+ },
5845
+ // For image parts, use part-specific or message-level cache control
5846
+ cache_control: cacheControl
5847
+ };
5848
+ }
5849
+ const fileName = String(
5850
+ (_f = (_e2 = (_d2 = (_c2 = part.providerOptions) == null ? void 0 : _c2.openrouter) == null ? void 0 : _d2.filename) != null ? _e2 : part.filename) != null ? _f : ""
5851
+ );
5852
+ const fileData = getFileUrl({
5853
+ part,
5854
+ defaultMediaType: "application/pdf"
5855
+ });
5856
+ if (isUrl({
5857
+ url: fileData,
5858
+ protocols: /* @__PURE__ */ new Set(["http:", "https:"])
5859
+ })) {
5860
+ return {
5861
+ type: "file",
5862
+ file: {
5863
+ filename: fileName,
5864
+ file_data: fileData
5865
+ }
5866
+ };
5867
+ }
5868
+ return {
5869
+ type: "file",
5870
+ file: {
5871
+ filename: fileName,
5872
+ file_data: fileData
5873
+ },
5874
+ cache_control: cacheControl
5875
+ };
5876
+ }
5877
+ default: {
5878
+ return {
5879
+ type: "text",
5880
+ text: "",
5881
+ cache_control: cacheControl
5882
+ };
5883
+ }
5884
+ }
5885
+ }
5886
+ );
5887
+ messages.push({
5888
+ role: "user",
5889
+ content: contentParts
5890
+ });
5891
+ break;
5892
+ }
5893
+ case "assistant": {
5894
+ let text = "";
5895
+ let reasoning = "";
5896
+ const toolCalls = [];
5897
+ for (const part of content) {
5898
+ switch (part.type) {
5899
+ case "text": {
5900
+ text += part.text;
5901
+ break;
5902
+ }
5903
+ case "tool-call": {
5904
+ toolCalls.push({
5905
+ id: part.toolCallId,
5906
+ type: "function",
5907
+ function: {
5908
+ name: part.toolName,
5909
+ arguments: JSON.stringify(part.input)
5910
+ }
5911
+ });
5912
+ break;
5913
+ }
5914
+ case "reasoning": {
5915
+ reasoning += part.text;
5916
+ break;
5917
+ }
5918
+ }
5919
+ }
5920
+ const parsedProviderOptions = OpenRouterProviderOptionsSchema.safeParse(providerOptions);
5921
+ const preservedReasoningDetails = parsedProviderOptions.success ? (_d = (_c = parsedProviderOptions.data) == null ? void 0 : _c.openrouter) == null ? void 0 : _d.reasoning_details : void 0;
5922
+ messages.push({
5923
+ role: "assistant",
5924
+ content: text,
5925
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
5926
+ reasoning: reasoning || void 0,
5927
+ // Only include reasoning_details if we have the preserved original version
5928
+ reasoning_details: preservedReasoningDetails && Array.isArray(preservedReasoningDetails) && preservedReasoningDetails.length > 0 ? preservedReasoningDetails : void 0,
5929
+ cache_control: getCacheControl(providerOptions)
5930
+ });
5931
+ break;
5932
+ }
5933
+ case "tool": {
5934
+ for (const toolResponse of content) {
5935
+ const content2 = getToolResultContent(toolResponse);
5936
+ messages.push({
5937
+ role: "tool",
5938
+ tool_call_id: toolResponse.toolCallId,
5939
+ content: content2,
5940
+ cache_control: (_e = getCacheControl(providerOptions)) != null ? _e : getCacheControl(toolResponse.providerOptions)
5941
+ });
5942
+ }
5943
+ break;
5944
+ }
5945
+ }
5946
+ }
5947
+ return messages;
5948
+ }
5949
+ function getToolResultContent(input) {
5950
+ return input.output.type === "text" ? input.output.value : JSON.stringify(input.output.value);
5951
+ }
5952
+ z.union([
5953
+ z.literal("auto"),
5954
+ z.literal("none"),
5955
+ z.literal("required"),
5956
+ z.object({
5957
+ type: z.literal("function"),
5958
+ function: z.object({
5959
+ name: z.string()
5960
+ })
5961
+ })
5962
+ ]);
5963
+ function getChatCompletionToolChoice(toolChoice) {
5964
+ switch (toolChoice.type) {
5965
+ case "auto":
5966
+ case "none":
5967
+ case "required":
5968
+ return toolChoice.type;
5969
+ case "tool": {
5970
+ return {
5971
+ type: "function",
5972
+ function: { name: toolChoice.toolName }
5973
+ };
5974
+ }
5975
+ default: {
5976
+ throw new InvalidArgumentError2({
5977
+ argument: "toolChoice",
5978
+ message: `Invalid tool choice type: ${JSON.stringify(toolChoice)}`
5979
+ });
5980
+ }
5981
+ }
5982
+ }
5983
+ var ImageResponseSchema = z.object({
5984
+ type: z.literal("image_url"),
5985
+ image_url: z.object({
5986
+ url: z.string()
5987
+ }).passthrough()
5988
+ }).passthrough();
5989
+ var ImageResponseWithUnknownSchema = z.union([
5990
+ ImageResponseSchema,
5991
+ z.unknown().transform(() => null)
5992
+ ]);
5993
+ var ImageResponseArraySchema = z.array(ImageResponseWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
5994
+ var OpenRouterChatCompletionBaseResponseSchema = z.object({
5995
+ id: z.string().optional(),
5996
+ model: z.string().optional(),
5997
+ provider: z.string().optional(),
5998
+ usage: z.object({
5999
+ prompt_tokens: z.number(),
6000
+ prompt_tokens_details: z.object({
6001
+ cached_tokens: z.number()
6002
+ }).passthrough().nullish(),
6003
+ completion_tokens: z.number(),
6004
+ completion_tokens_details: z.object({
6005
+ reasoning_tokens: z.number()
6006
+ }).passthrough().nullish(),
6007
+ total_tokens: z.number(),
6008
+ cost: z.number().optional(),
6009
+ cost_details: z.object({
6010
+ upstream_inference_cost: z.number().nullish()
6011
+ }).passthrough().nullish()
6012
+ }).passthrough().nullish()
6013
+ }).passthrough();
6014
+ var OpenRouterNonStreamChatCompletionResponseSchema = z.union([
6015
+ // Success response with choices
6016
+ OpenRouterChatCompletionBaseResponseSchema.extend({
6017
+ choices: z.array(
6018
+ z.object({
6019
+ message: z.object({
6020
+ role: z.literal("assistant"),
6021
+ content: z.string().nullable().optional(),
6022
+ reasoning: z.string().nullable().optional(),
6023
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
6024
+ images: ImageResponseArraySchema.nullish(),
6025
+ tool_calls: z.array(
6026
+ z.object({
6027
+ id: z.string().optional().nullable(),
6028
+ type: z.literal("function"),
6029
+ function: z.object({
6030
+ name: z.string(),
6031
+ arguments: z.string()
6032
+ }).passthrough()
6033
+ }).passthrough()
6034
+ ).optional(),
6035
+ annotations: z.array(
6036
+ z.union([
6037
+ // URL citation from web search
6038
+ z.object({
6039
+ type: z.literal("url_citation"),
6040
+ url_citation: z.object({
6041
+ end_index: z.number(),
6042
+ start_index: z.number(),
6043
+ title: z.string(),
6044
+ url: z.string(),
6045
+ content: z.string().optional()
6046
+ }).passthrough()
6047
+ }).passthrough(),
6048
+ // File annotation from FileParserPlugin (old format)
6049
+ z.object({
6050
+ type: z.literal("file_annotation"),
6051
+ file_annotation: z.object({
6052
+ file_id: z.string(),
6053
+ quote: z.string().optional()
6054
+ }).passthrough()
6055
+ }).passthrough(),
6056
+ // File annotation from FileParserPlugin (new format)
6057
+ z.object({
6058
+ type: z.literal("file"),
6059
+ file: z.object({
6060
+ hash: z.string(),
6061
+ name: z.string(),
6062
+ content: z.array(
6063
+ z.object({
6064
+ type: z.string(),
6065
+ text: z.string()
6066
+ }).passthrough()
6067
+ ).optional()
6068
+ }).passthrough()
6069
+ }).passthrough()
6070
+ ])
6071
+ ).nullish()
6072
+ }).passthrough(),
6073
+ index: z.number().nullish(),
6074
+ logprobs: z.object({
6075
+ content: z.array(
6076
+ z.object({
6077
+ token: z.string(),
6078
+ logprob: z.number(),
6079
+ top_logprobs: z.array(
6080
+ z.object({
6081
+ token: z.string(),
6082
+ logprob: z.number()
6083
+ }).passthrough()
6084
+ )
6085
+ }).passthrough()
6086
+ ).nullable()
6087
+ }).passthrough().nullable().optional(),
6088
+ finish_reason: z.string().optional().nullable()
6089
+ }).passthrough()
6090
+ )
6091
+ }),
6092
+ // Error response (HTTP 200 with error payload)
6093
+ OpenRouterErrorResponseSchema.extend({
6094
+ user_id: z.string().optional()
6095
+ })
6096
+ ]);
6097
+ var OpenRouterStreamChatCompletionChunkSchema = z.union([
6098
+ OpenRouterChatCompletionBaseResponseSchema.extend({
6099
+ choices: z.array(
6100
+ z.object({
6101
+ delta: z.object({
6102
+ role: z.enum(["assistant"]).optional(),
6103
+ content: z.string().nullish(),
6104
+ reasoning: z.string().nullish().optional(),
6105
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
6106
+ images: ImageResponseArraySchema.nullish(),
6107
+ tool_calls: z.array(
6108
+ z.object({
6109
+ index: z.number().nullish(),
6110
+ id: z.string().nullish(),
6111
+ type: z.literal("function").optional(),
6112
+ function: z.object({
6113
+ name: z.string().nullish(),
6114
+ arguments: z.string().nullish()
6115
+ }).passthrough()
6116
+ }).passthrough()
6117
+ ).nullish(),
6118
+ annotations: z.array(
6119
+ z.union([
6120
+ // URL citation from web search
6121
+ z.object({
6122
+ type: z.literal("url_citation"),
6123
+ url_citation: z.object({
6124
+ end_index: z.number(),
6125
+ start_index: z.number(),
6126
+ title: z.string(),
6127
+ url: z.string(),
6128
+ content: z.string().optional()
6129
+ }).passthrough()
6130
+ }).passthrough(),
6131
+ // File annotation from FileParserPlugin (old format)
6132
+ z.object({
6133
+ type: z.literal("file_annotation"),
6134
+ file_annotation: z.object({
6135
+ file_id: z.string(),
6136
+ quote: z.string().optional()
6137
+ }).passthrough()
6138
+ }).passthrough(),
6139
+ // File annotation from FileParserPlugin (new format)
6140
+ z.object({
6141
+ type: z.literal("file"),
6142
+ file: z.object({
6143
+ hash: z.string(),
6144
+ name: z.string(),
6145
+ content: z.array(
6146
+ z.object({
6147
+ type: z.string(),
6148
+ text: z.string()
6149
+ }).passthrough()
6150
+ ).optional()
6151
+ }).passthrough()
6152
+ }).passthrough()
6153
+ ])
6154
+ ).nullish()
6155
+ }).passthrough().nullish(),
6156
+ logprobs: z.object({
6157
+ content: z.array(
6158
+ z.object({
6159
+ token: z.string(),
6160
+ logprob: z.number(),
6161
+ top_logprobs: z.array(
6162
+ z.object({
6163
+ token: z.string(),
6164
+ logprob: z.number()
6165
+ }).passthrough()
6166
+ )
6167
+ }).passthrough()
6168
+ ).nullable()
6169
+ }).passthrough().nullish(),
6170
+ finish_reason: z.string().nullable().optional(),
6171
+ index: z.number().nullish()
6172
+ }).passthrough()
6173
+ )
6174
+ }),
6175
+ OpenRouterErrorResponseSchema
6176
+ ]);
6177
+ var OpenRouterChatLanguageModel = class {
6178
+ constructor(modelId, settings, config) {
6179
+ this.specificationVersion = "v2";
6180
+ this.provider = "openrouter";
6181
+ this.defaultObjectGenerationMode = "tool";
6182
+ this.supportedUrls = {
6183
+ "image/*": [
6184
+ /^data:image\/[a-zA-Z]+;base64,/,
6185
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
6186
+ ],
6187
+ // 'text/*': [/^data:text\//, /^https?:\/\/.+$/],
6188
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
6189
+ };
6190
+ this.modelId = modelId;
6191
+ this.settings = settings;
6192
+ this.config = config;
6193
+ }
6194
+ getArgs({
6195
+ prompt,
6196
+ maxOutputTokens,
6197
+ temperature,
6198
+ topP,
6199
+ frequencyPenalty,
6200
+ presencePenalty,
6201
+ seed,
6202
+ stopSequences,
6203
+ responseFormat,
6204
+ topK,
6205
+ tools,
6206
+ toolChoice
6207
+ }) {
6208
+ var _a15;
6209
+ const baseArgs = __spreadValues(__spreadValues({
6210
+ // model id:
6211
+ model: this.modelId,
6212
+ models: this.settings.models,
6213
+ // model specific settings:
6214
+ logit_bias: this.settings.logitBias,
6215
+ logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
6216
+ top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
6217
+ user: this.settings.user,
6218
+ parallel_tool_calls: this.settings.parallelToolCalls,
6219
+ // standardized settings:
6220
+ max_tokens: maxOutputTokens,
6221
+ temperature,
6222
+ top_p: topP,
6223
+ frequency_penalty: frequencyPenalty,
6224
+ presence_penalty: presencePenalty,
6225
+ seed,
6226
+ stop: stopSequences,
6227
+ response_format: responseFormat,
6228
+ top_k: topK,
6229
+ // messages:
6230
+ messages: convertToOpenRouterChatMessages(prompt),
6231
+ // OpenRouter specific settings:
6232
+ include_reasoning: this.settings.includeReasoning,
6233
+ reasoning: this.settings.reasoning,
6234
+ usage: this.settings.usage,
6235
+ // Web search settings:
6236
+ plugins: this.settings.plugins,
6237
+ web_search_options: this.settings.web_search_options,
6238
+ // Provider routing settings:
6239
+ provider: this.settings.provider
6240
+ }, this.config.extraBody), this.settings.extraBody);
6241
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null) {
6242
+ return __spreadProps(__spreadValues({}, baseArgs), {
6243
+ response_format: {
6244
+ type: "json_schema",
6245
+ json_schema: __spreadValues({
6246
+ schema: responseFormat.schema,
6247
+ strict: true,
6248
+ name: (_a15 = responseFormat.name) != null ? _a15 : "response"
6249
+ }, responseFormat.description && {
6250
+ description: responseFormat.description
6251
+ })
6252
+ }
6253
+ });
6254
+ }
6255
+ if (tools && tools.length > 0) {
6256
+ const mappedTools = tools.filter((tool) => tool.type === "function").map((tool) => ({
6257
+ type: "function",
6258
+ function: {
6259
+ name: tool.name,
6260
+ description: tool.description,
6261
+ parameters: tool.inputSchema
6262
+ }
6263
+ }));
6264
+ return __spreadProps(__spreadValues({}, baseArgs), {
6265
+ tools: mappedTools,
6266
+ tool_choice: toolChoice ? getChatCompletionToolChoice(toolChoice) : void 0
6267
+ });
6268
+ }
6269
+ return baseArgs;
6270
+ }
6271
+ async doGenerate(options) {
6272
+ 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;
6273
+ const providerOptions = options.providerOptions || {};
6274
+ const openrouterOptions = providerOptions.openrouter || {};
6275
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
6276
+ const { value: responseValue, responseHeaders } = await postJsonToApi4({
6277
+ url: this.config.url({
6278
+ path: "/chat/completions",
6279
+ modelId: this.modelId
6280
+ }),
6281
+ headers: combineHeaders4(this.config.headers(), options.headers),
6282
+ body: args,
6283
+ failedResponseHandler: openrouterFailedResponseHandler,
6284
+ successfulResponseHandler: createJsonResponseHandler4(
6285
+ OpenRouterNonStreamChatCompletionResponseSchema
6286
+ ),
6287
+ abortSignal: options.abortSignal,
6288
+ fetch: this.config.fetch
6289
+ });
6290
+ if ("error" in responseValue) {
6291
+ const errorData = responseValue.error;
6292
+ throw new APICallError2({
6293
+ message: errorData.message,
6294
+ url: this.config.url({
6295
+ path: "/chat/completions",
6296
+ modelId: this.modelId
6297
+ }),
6298
+ requestBodyValues: args,
6299
+ statusCode: 200,
6300
+ responseHeaders,
6301
+ data: errorData
6302
+ });
6303
+ }
6304
+ const response = responseValue;
6305
+ const choice = response.choices[0];
6306
+ if (!choice) {
6307
+ throw new NoContentGeneratedError({
6308
+ message: "No choice in response"
6309
+ });
6310
+ }
6311
+ const usageInfo = response.usage ? {
6312
+ inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
6313
+ outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
6314
+ totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
6315
+ reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
6316
+ cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
6317
+ } : {
6318
+ inputTokens: 0,
6319
+ outputTokens: 0,
6320
+ totalTokens: 0,
6321
+ reasoningTokens: 0,
6322
+ cachedInputTokens: 0
6323
+ };
6324
+ const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
6325
+ const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
6326
+ switch (detail.type) {
6327
+ case "reasoning.text": {
6328
+ if (detail.text) {
6329
+ return {
6330
+ type: "reasoning",
6331
+ text: detail.text
6332
+ };
6333
+ }
6334
+ break;
6335
+ }
6336
+ case "reasoning.summary": {
6337
+ if (detail.summary) {
6338
+ return {
6339
+ type: "reasoning",
6340
+ text: detail.summary
6341
+ };
6342
+ }
6343
+ break;
6344
+ }
6345
+ case "reasoning.encrypted": {
6346
+ if (detail.data) {
6347
+ return {
6348
+ type: "reasoning",
6349
+ text: "[REDACTED]"
6350
+ };
6351
+ }
6352
+ break;
6353
+ }
6354
+ }
6355
+ return null;
6356
+ }).filter((p) => p !== null) : choice.message.reasoning ? [
6357
+ {
6358
+ type: "reasoning",
6359
+ text: choice.message.reasoning
6360
+ }
6361
+ ] : [];
6362
+ const content = [];
6363
+ content.push(...reasoning);
6364
+ if (choice.message.content) {
6365
+ content.push({
6366
+ type: "text",
6367
+ text: choice.message.content
6368
+ });
6369
+ }
6370
+ if (choice.message.tool_calls) {
6371
+ for (const toolCall of choice.message.tool_calls) {
6372
+ content.push({
6373
+ type: "tool-call",
6374
+ toolCallId: (_j = toolCall.id) != null ? _j : generateId4(),
6375
+ toolName: toolCall.function.name,
6376
+ input: toolCall.function.arguments
6377
+ });
6378
+ }
6379
+ }
6380
+ if (choice.message.images) {
6381
+ for (const image of choice.message.images) {
6382
+ content.push({
6383
+ type: "file",
6384
+ mediaType: getMediaType(image.image_url.url, "image/jpeg"),
6385
+ data: getBase64FromDataUrl(image.image_url.url)
6386
+ });
6387
+ }
6388
+ }
6389
+ if (choice.message.annotations) {
6390
+ for (const annotation of choice.message.annotations) {
6391
+ if (annotation.type === "url_citation") {
6392
+ content.push({
6393
+ type: "source",
6394
+ sourceType: "url",
6395
+ id: annotation.url_citation.url,
6396
+ url: annotation.url_citation.url,
6397
+ title: annotation.url_citation.title,
6398
+ providerMetadata: {
6399
+ openrouter: {
6400
+ content: annotation.url_citation.content || ""
6401
+ }
6402
+ }
6403
+ });
6404
+ }
6405
+ }
6406
+ }
6407
+ return {
6408
+ content,
6409
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
6410
+ usage: usageInfo,
6411
+ warnings: [],
6412
+ providerMetadata: {
6413
+ openrouter: OpenRouterProviderMetadataSchema.parse({
6414
+ provider: (_k = response.provider) != null ? _k : "",
6415
+ reasoning_details: (_l = choice.message.reasoning_details) != null ? _l : [],
6416
+ usage: {
6417
+ promptTokens: (_m = usageInfo.inputTokens) != null ? _m : 0,
6418
+ completionTokens: (_n = usageInfo.outputTokens) != null ? _n : 0,
6419
+ totalTokens: (_o = usageInfo.totalTokens) != null ? _o : 0,
6420
+ cost: (_p = response.usage) == null ? void 0 : _p.cost,
6421
+ promptTokensDetails: {
6422
+ cachedTokens: (_s = (_r = (_q = response.usage) == null ? void 0 : _q.prompt_tokens_details) == null ? void 0 : _r.cached_tokens) != null ? _s : 0
6423
+ },
6424
+ completionTokensDetails: {
6425
+ reasoningTokens: (_v = (_u = (_t = response.usage) == null ? void 0 : _t.completion_tokens_details) == null ? void 0 : _u.reasoning_tokens) != null ? _v : 0
6426
+ },
6427
+ costDetails: {
6428
+ upstreamInferenceCost: (_y = (_x = (_w = response.usage) == null ? void 0 : _w.cost_details) == null ? void 0 : _x.upstream_inference_cost) != null ? _y : 0
6429
+ }
6430
+ }
6431
+ })
6432
+ },
6433
+ request: { body: args },
6434
+ response: {
6435
+ id: response.id,
6436
+ modelId: response.model,
6437
+ headers: responseHeaders
6438
+ }
6439
+ };
6440
+ }
6441
+ async doStream(options) {
6442
+ var _a15;
6443
+ const providerOptions = options.providerOptions || {};
6444
+ const openrouterOptions = providerOptions.openrouter || {};
6445
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
6446
+ const { value: response, responseHeaders } = await postJsonToApi4({
6447
+ url: this.config.url({
6448
+ path: "/chat/completions",
6449
+ modelId: this.modelId
6450
+ }),
6451
+ headers: combineHeaders4(this.config.headers(), options.headers),
6452
+ body: __spreadProps(__spreadValues({}, args), {
6453
+ stream: true,
6454
+ // only include stream_options when in strict compatibility mode:
6455
+ stream_options: this.config.compatibility === "strict" ? __spreadValues({
6456
+ include_usage: true
6457
+ }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
6458
+ }),
6459
+ failedResponseHandler: openrouterFailedResponseHandler,
6460
+ successfulResponseHandler: createEventSourceResponseHandler4(
6461
+ OpenRouterStreamChatCompletionChunkSchema
6462
+ ),
6463
+ abortSignal: options.abortSignal,
6464
+ fetch: this.config.fetch
6465
+ });
6466
+ const toolCalls = [];
6467
+ let finishReason = "other";
6468
+ const usage = {
6469
+ inputTokens: Number.NaN,
6470
+ outputTokens: Number.NaN,
6471
+ totalTokens: Number.NaN,
6472
+ reasoningTokens: Number.NaN,
6473
+ cachedInputTokens: Number.NaN
6474
+ };
6475
+ const openrouterUsage = {};
6476
+ const accumulatedReasoningDetails = [];
6477
+ let textStarted = false;
6478
+ let reasoningStarted = false;
6479
+ let textId;
6480
+ let reasoningId;
6481
+ let openrouterResponseId;
6482
+ let provider;
6483
+ return {
6484
+ stream: response.pipeThrough(
6485
+ new TransformStream({
6486
+ transform(chunk, controller) {
6487
+ var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
6488
+ if (!chunk.success) {
6489
+ finishReason = "error";
6490
+ controller.enqueue({ type: "error", error: chunk.error });
6491
+ return;
6492
+ }
6493
+ const value = chunk.value;
6494
+ if ("error" in value) {
6495
+ finishReason = "error";
6496
+ controller.enqueue({ type: "error", error: value.error });
6497
+ return;
6498
+ }
6499
+ if (value.provider) {
6500
+ provider = value.provider;
6501
+ }
6502
+ if (value.id) {
6503
+ openrouterResponseId = value.id;
6504
+ controller.enqueue({
6505
+ type: "response-metadata",
6506
+ id: value.id
6507
+ });
6508
+ }
6509
+ if (value.model) {
6510
+ controller.enqueue({
6511
+ type: "response-metadata",
6512
+ modelId: value.model
6513
+ });
6514
+ }
6515
+ if (value.usage != null) {
6516
+ usage.inputTokens = value.usage.prompt_tokens;
6517
+ usage.outputTokens = value.usage.completion_tokens;
6518
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
6519
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
6520
+ if (value.usage.prompt_tokens_details) {
6521
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
6522
+ usage.cachedInputTokens = cachedInputTokens;
6523
+ openrouterUsage.promptTokensDetails = {
6524
+ cachedTokens: cachedInputTokens
6525
+ };
6526
+ }
6527
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
6528
+ if (value.usage.completion_tokens_details) {
6529
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
6530
+ usage.reasoningTokens = reasoningTokens;
6531
+ openrouterUsage.completionTokensDetails = {
6532
+ reasoningTokens
6533
+ };
6534
+ }
6535
+ openrouterUsage.cost = value.usage.cost;
6536
+ openrouterUsage.totalTokens = value.usage.total_tokens;
6537
+ }
6538
+ const choice = value.choices[0];
6539
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
6540
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
6541
+ }
6542
+ if ((choice == null ? void 0 : choice.delta) == null) {
6543
+ return;
6544
+ }
6545
+ const delta = choice.delta;
6546
+ const emitReasoningChunk = (chunkText) => {
6547
+ if (!reasoningStarted) {
6548
+ reasoningId = openrouterResponseId || generateId4();
6549
+ controller.enqueue({
6550
+ type: "reasoning-start",
6551
+ id: reasoningId
6552
+ });
6553
+ reasoningStarted = true;
6554
+ }
6555
+ controller.enqueue({
6556
+ type: "reasoning-delta",
6557
+ delta: chunkText,
6558
+ id: reasoningId || generateId4()
6559
+ });
6560
+ };
6561
+ if (delta.reasoning_details && delta.reasoning_details.length > 0) {
6562
+ accumulatedReasoningDetails.push(...delta.reasoning_details);
6563
+ for (const detail of delta.reasoning_details) {
6564
+ switch (detail.type) {
6565
+ case "reasoning.text": {
6566
+ if (detail.text) {
6567
+ emitReasoningChunk(detail.text);
6568
+ }
6569
+ break;
6570
+ }
6571
+ case "reasoning.encrypted": {
6572
+ if (detail.data) {
6573
+ emitReasoningChunk("[REDACTED]");
6574
+ }
6575
+ break;
6576
+ }
6577
+ case "reasoning.summary": {
6578
+ if (detail.summary) {
6579
+ emitReasoningChunk(detail.summary);
6580
+ }
6581
+ break;
6582
+ }
6583
+ }
6584
+ }
6585
+ } else if (delta.reasoning) {
6586
+ emitReasoningChunk(delta.reasoning);
6587
+ }
6588
+ if (delta.content) {
6589
+ if (reasoningStarted && !textStarted) {
6590
+ controller.enqueue({
6591
+ type: "reasoning-end",
6592
+ id: reasoningId || generateId4()
6593
+ });
6594
+ reasoningStarted = false;
6595
+ }
6596
+ if (!textStarted) {
6597
+ textId = openrouterResponseId || generateId4();
6598
+ controller.enqueue({
6599
+ type: "text-start",
6600
+ id: textId
6601
+ });
6602
+ textStarted = true;
6603
+ }
6604
+ controller.enqueue({
6605
+ type: "text-delta",
6606
+ delta: delta.content,
6607
+ id: textId || generateId4()
6608
+ });
6609
+ }
6610
+ if (delta.annotations) {
6611
+ for (const annotation of delta.annotations) {
6612
+ if (annotation.type === "url_citation") {
6613
+ controller.enqueue({
6614
+ type: "source",
6615
+ sourceType: "url",
6616
+ id: annotation.url_citation.url,
6617
+ url: annotation.url_citation.url,
6618
+ title: annotation.url_citation.title,
6619
+ providerMetadata: {
6620
+ openrouter: {
6621
+ content: annotation.url_citation.content || ""
6622
+ }
6623
+ }
6624
+ });
6625
+ }
6626
+ }
6627
+ }
6628
+ if (delta.tool_calls != null) {
6629
+ for (const toolCallDelta of delta.tool_calls) {
6630
+ const index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length - 1;
6631
+ if (toolCalls[index] == null) {
6632
+ if (toolCallDelta.type !== "function") {
6633
+ throw new InvalidResponseDataError2({
6634
+ data: toolCallDelta,
6635
+ message: `Expected 'function' type.`
6636
+ });
6637
+ }
6638
+ if (toolCallDelta.id == null) {
6639
+ throw new InvalidResponseDataError2({
6640
+ data: toolCallDelta,
6641
+ message: `Expected 'id' to be a string.`
6642
+ });
6643
+ }
6644
+ if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) {
6645
+ throw new InvalidResponseDataError2({
6646
+ data: toolCallDelta,
6647
+ message: `Expected 'function.name' to be a string.`
6648
+ });
6649
+ }
6650
+ toolCalls[index] = {
6651
+ id: toolCallDelta.id,
6652
+ type: "function",
6653
+ function: {
6654
+ name: toolCallDelta.function.name,
6655
+ arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
6656
+ },
6657
+ inputStarted: false,
6658
+ sent: false
6659
+ };
6660
+ const toolCall2 = toolCalls[index];
6661
+ if (toolCall2 == null) {
6662
+ throw new InvalidResponseDataError2({
6663
+ data: { index, toolCallsLength: toolCalls.length },
6664
+ message: `Tool call at index ${index} is missing after creation.`
6665
+ });
6666
+ }
6667
+ if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null && isParsableJson2(toolCall2.function.arguments)) {
6668
+ toolCall2.inputStarted = true;
6669
+ controller.enqueue({
6670
+ type: "tool-input-start",
6671
+ id: toolCall2.id,
6672
+ toolName: toolCall2.function.name
6673
+ });
6674
+ controller.enqueue({
6675
+ type: "tool-input-delta",
6676
+ id: toolCall2.id,
6677
+ delta: toolCall2.function.arguments
6678
+ });
6679
+ controller.enqueue({
6680
+ type: "tool-input-end",
6681
+ id: toolCall2.id
6682
+ });
6683
+ controller.enqueue({
6684
+ type: "tool-call",
6685
+ toolCallId: toolCall2.id,
6686
+ toolName: toolCall2.function.name,
6687
+ input: toolCall2.function.arguments
6688
+ });
6689
+ toolCall2.sent = true;
6690
+ }
6691
+ continue;
6692
+ }
6693
+ const toolCall = toolCalls[index];
6694
+ if (toolCall == null) {
6695
+ throw new InvalidResponseDataError2({
6696
+ data: {
6697
+ index,
6698
+ toolCallsLength: toolCalls.length,
6699
+ toolCallDelta
6700
+ },
6701
+ message: `Tool call at index ${index} is missing during merge.`
6702
+ });
6703
+ }
6704
+ if (!toolCall.inputStarted) {
6705
+ toolCall.inputStarted = true;
6706
+ controller.enqueue({
6707
+ type: "tool-input-start",
6708
+ id: toolCall.id,
6709
+ toolName: toolCall.function.name
6710
+ });
6711
+ }
6712
+ if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
6713
+ toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
6714
+ }
6715
+ controller.enqueue({
6716
+ type: "tool-input-delta",
6717
+ id: toolCall.id,
6718
+ delta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
6719
+ });
6720
+ if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson2(toolCall.function.arguments)) {
6721
+ controller.enqueue({
6722
+ type: "tool-call",
6723
+ toolCallId: (_n = toolCall.id) != null ? _n : generateId4(),
6724
+ toolName: toolCall.function.name,
6725
+ input: toolCall.function.arguments
6726
+ });
6727
+ toolCall.sent = true;
6728
+ }
6729
+ }
6730
+ }
6731
+ if (delta.images != null) {
6732
+ for (const image of delta.images) {
6733
+ controller.enqueue({
6734
+ type: "file",
6735
+ mediaType: getMediaType(image.image_url.url, "image/jpeg"),
6736
+ data: getBase64FromDataUrl(image.image_url.url)
6737
+ });
6738
+ }
6739
+ }
6740
+ },
6741
+ flush(controller) {
6742
+ var _a16;
6743
+ if (finishReason === "tool-calls") {
6744
+ for (const toolCall of toolCalls) {
6745
+ if (toolCall && !toolCall.sent) {
6746
+ controller.enqueue({
6747
+ type: "tool-call",
6748
+ toolCallId: (_a16 = toolCall.id) != null ? _a16 : generateId4(),
6749
+ toolName: toolCall.function.name,
6750
+ // Coerce invalid arguments to an empty JSON object
6751
+ input: isParsableJson2(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
6752
+ });
6753
+ toolCall.sent = true;
6754
+ }
6755
+ }
6756
+ }
6757
+ if (reasoningStarted) {
6758
+ controller.enqueue({
6759
+ type: "reasoning-end",
6760
+ id: reasoningId || generateId4()
6761
+ });
6762
+ }
6763
+ if (textStarted) {
6764
+ controller.enqueue({
6765
+ type: "text-end",
6766
+ id: textId || generateId4()
6767
+ });
6768
+ }
6769
+ const openrouterMetadata = {
6770
+ usage: openrouterUsage
6771
+ };
6772
+ if (provider !== void 0) {
6773
+ openrouterMetadata.provider = provider;
6774
+ }
6775
+ if (accumulatedReasoningDetails.length > 0) {
6776
+ openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
6777
+ }
6778
+ controller.enqueue({
6779
+ type: "finish",
6780
+ finishReason,
6781
+ usage,
6782
+ providerMetadata: {
6783
+ openrouter: openrouterMetadata
6784
+ }
6785
+ });
6786
+ }
6787
+ })
6788
+ ),
6789
+ warnings: [],
6790
+ request: { body: args },
6791
+ response: { headers: responseHeaders }
6792
+ };
6793
+ }
6794
+ };
6795
+ function convertToOpenRouterCompletionPrompt({
6796
+ prompt,
6797
+ inputFormat,
6798
+ user = "user",
6799
+ assistant = "assistant"
6800
+ }) {
6801
+ 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") {
6802
+ return { prompt: prompt[0].content[0].text };
6803
+ }
6804
+ let text = "";
6805
+ if (prompt[0] && prompt[0].role === "system") {
6806
+ text += `${prompt[0].content}
6807
+
6808
+ `;
6809
+ prompt = prompt.slice(1);
6810
+ }
6811
+ for (const { role, content } of prompt) {
6812
+ switch (role) {
6813
+ case "system": {
6814
+ throw new InvalidPromptError({
6815
+ message: `Unexpected system message in prompt: ${content}`,
6816
+ prompt
6817
+ });
6818
+ }
6819
+ case "user": {
6820
+ const userMessage = content.map((part) => {
6821
+ switch (part.type) {
6822
+ case "text": {
6823
+ return part.text;
6824
+ }
6825
+ case "file": {
6826
+ throw new UnsupportedFunctionalityError2({
6827
+ functionality: "file attachments"
6828
+ });
6829
+ }
6830
+ default: {
6831
+ return "";
6832
+ }
6833
+ }
6834
+ }).join("");
6835
+ text += `${user}:
6836
+ ${userMessage}
6837
+
6838
+ `;
6839
+ break;
6840
+ }
6841
+ case "assistant": {
6842
+ const assistantMessage = content.map(
6843
+ (part) => {
6844
+ switch (part.type) {
6845
+ case "text": {
6846
+ return part.text;
6847
+ }
6848
+ case "tool-call": {
6849
+ throw new UnsupportedFunctionalityError2({
6850
+ functionality: "tool-call messages"
6851
+ });
6852
+ }
6853
+ case "tool-result": {
6854
+ throw new UnsupportedFunctionalityError2({
6855
+ functionality: "tool-result messages"
6856
+ });
6857
+ }
6858
+ case "reasoning": {
6859
+ throw new UnsupportedFunctionalityError2({
6860
+ functionality: "reasoning messages"
6861
+ });
6862
+ }
6863
+ case "file": {
6864
+ throw new UnsupportedFunctionalityError2({
6865
+ functionality: "file attachments"
6866
+ });
6867
+ }
6868
+ default: {
6869
+ return "";
6870
+ }
6871
+ }
6872
+ }
6873
+ ).join("");
6874
+ text += `${assistant}:
6875
+ ${assistantMessage}
6876
+
6877
+ `;
6878
+ break;
6879
+ }
6880
+ case "tool": {
6881
+ throw new UnsupportedFunctionalityError2({
6882
+ functionality: "tool messages"
6883
+ });
6884
+ }
6885
+ }
6886
+ }
6887
+ text += `${assistant}:
6888
+ `;
6889
+ return {
6890
+ prompt: text
6891
+ };
6892
+ }
6893
+ var OpenRouterCompletionChunkSchema = z.union([
6894
+ z.object({
6895
+ id: z.string().optional(),
6896
+ model: z.string().optional(),
6897
+ choices: z.array(
6898
+ z.object({
6899
+ text: z.string(),
6900
+ reasoning: z.string().nullish().optional(),
6901
+ reasoning_details: ReasoningDetailArraySchema.nullish(),
6902
+ finish_reason: z.string().nullish(),
6903
+ index: z.number().nullish(),
6904
+ logprobs: z.object({
6905
+ tokens: z.array(z.string()),
6906
+ token_logprobs: z.array(z.number()),
6907
+ top_logprobs: z.array(z.record(z.string(), z.number())).nullable()
6908
+ }).passthrough().nullable().optional()
6909
+ }).passthrough()
6910
+ ),
6911
+ usage: z.object({
6912
+ prompt_tokens: z.number(),
6913
+ prompt_tokens_details: z.object({
6914
+ cached_tokens: z.number()
6915
+ }).passthrough().nullish(),
6916
+ completion_tokens: z.number(),
6917
+ completion_tokens_details: z.object({
6918
+ reasoning_tokens: z.number()
6919
+ }).passthrough().nullish(),
6920
+ total_tokens: z.number(),
6921
+ cost: z.number().optional()
6922
+ }).passthrough().nullish()
6923
+ }).passthrough(),
6924
+ OpenRouterErrorResponseSchema
6925
+ ]);
6926
+ var OpenRouterCompletionLanguageModel = class {
6927
+ constructor(modelId, settings, config) {
6928
+ this.specificationVersion = "v2";
6929
+ this.provider = "openrouter";
6930
+ this.supportedUrls = {
6931
+ "image/*": [
6932
+ /^data:image\/[a-zA-Z]+;base64,/,
6933
+ /^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
6934
+ ],
6935
+ "text/*": [/^data:text\//, /^https?:\/\/.+$/],
6936
+ "application/*": [/^data:application\//, /^https?:\/\/.+$/]
6937
+ };
6938
+ this.defaultObjectGenerationMode = void 0;
6939
+ this.modelId = modelId;
6940
+ this.settings = settings;
6941
+ this.config = config;
6942
+ }
6943
+ getArgs({
6944
+ prompt,
6945
+ maxOutputTokens,
6946
+ temperature,
6947
+ topP,
6948
+ frequencyPenalty,
6949
+ presencePenalty,
6950
+ seed,
6951
+ responseFormat,
6952
+ topK,
6953
+ stopSequences,
6954
+ tools,
6955
+ toolChoice
6956
+ }) {
6957
+ const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
6958
+ prompt,
6959
+ inputFormat: "prompt"
6960
+ });
6961
+ if (tools == null ? void 0 : tools.length) {
6962
+ throw new UnsupportedFunctionalityError2({
6963
+ functionality: "tools"
6964
+ });
6965
+ }
6966
+ if (toolChoice) {
6967
+ throw new UnsupportedFunctionalityError2({
6968
+ functionality: "toolChoice"
6969
+ });
6970
+ }
6971
+ return __spreadValues(__spreadValues({
6972
+ // model id:
6973
+ model: this.modelId,
6974
+ models: this.settings.models,
6975
+ // model specific settings:
6976
+ logit_bias: this.settings.logitBias,
6977
+ logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
6978
+ suffix: this.settings.suffix,
6979
+ user: this.settings.user,
6980
+ // standardized settings:
6981
+ max_tokens: maxOutputTokens,
6982
+ temperature,
6983
+ top_p: topP,
6984
+ frequency_penalty: frequencyPenalty,
6985
+ presence_penalty: presencePenalty,
6986
+ seed,
6987
+ stop: stopSequences,
6988
+ response_format: responseFormat,
6989
+ top_k: topK,
6990
+ // prompt:
6991
+ prompt: completionPrompt,
6992
+ // OpenRouter specific settings:
6993
+ include_reasoning: this.settings.includeReasoning,
6994
+ reasoning: this.settings.reasoning
6995
+ }, this.config.extraBody), this.settings.extraBody);
6996
+ }
6997
+ async doGenerate(options) {
6998
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
6999
+ const providerOptions = options.providerOptions || {};
7000
+ const openrouterOptions = providerOptions.openrouter || {};
7001
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
7002
+ const { value: response, responseHeaders } = await postJsonToApi4({
7003
+ url: this.config.url({
7004
+ path: "/completions",
7005
+ modelId: this.modelId
7006
+ }),
7007
+ headers: combineHeaders4(this.config.headers(), options.headers),
7008
+ body: args,
7009
+ failedResponseHandler: openrouterFailedResponseHandler,
7010
+ successfulResponseHandler: createJsonResponseHandler4(
7011
+ OpenRouterCompletionChunkSchema
7012
+ ),
7013
+ abortSignal: options.abortSignal,
7014
+ fetch: this.config.fetch
7015
+ });
7016
+ if ("error" in response) {
7017
+ const errorData = response.error;
7018
+ throw new APICallError2({
7019
+ message: errorData.message,
7020
+ url: this.config.url({
7021
+ path: "/completions",
7022
+ modelId: this.modelId
7023
+ }),
7024
+ requestBodyValues: args,
7025
+ statusCode: 200,
7026
+ responseHeaders,
7027
+ data: errorData
7028
+ });
7029
+ }
7030
+ const choice = response.choices[0];
7031
+ if (!choice) {
7032
+ throw new NoContentGeneratedError({
7033
+ message: "No choice in OpenRouter completion response"
7034
+ });
7035
+ }
7036
+ return {
7037
+ content: [
7038
+ {
7039
+ type: "text",
7040
+ text: (_a15 = choice.text) != null ? _a15 : ""
7041
+ }
7042
+ ],
7043
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
7044
+ usage: {
7045
+ inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
7046
+ outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
7047
+ 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),
7048
+ reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
7049
+ cachedInputTokens: (_o = (_n = (_m = response.usage) == null ? void 0 : _m.prompt_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : 0
7050
+ },
7051
+ warnings: [],
7052
+ response: {
7053
+ headers: responseHeaders
7054
+ }
7055
+ };
7056
+ }
7057
+ async doStream(options) {
7058
+ const providerOptions = options.providerOptions || {};
7059
+ const openrouterOptions = providerOptions.openrouter || {};
7060
+ const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
7061
+ const { value: response, responseHeaders } = await postJsonToApi4({
7062
+ url: this.config.url({
7063
+ path: "/completions",
7064
+ modelId: this.modelId
7065
+ }),
7066
+ headers: combineHeaders4(this.config.headers(), options.headers),
7067
+ body: __spreadProps(__spreadValues({}, args), {
7068
+ stream: true,
7069
+ // only include stream_options when in strict compatibility mode:
7070
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
7071
+ }),
7072
+ failedResponseHandler: openrouterFailedResponseHandler,
7073
+ successfulResponseHandler: createEventSourceResponseHandler4(
7074
+ OpenRouterCompletionChunkSchema
7075
+ ),
7076
+ abortSignal: options.abortSignal,
7077
+ fetch: this.config.fetch
7078
+ });
7079
+ let finishReason = "other";
7080
+ const usage = {
7081
+ inputTokens: Number.NaN,
7082
+ outputTokens: Number.NaN,
7083
+ totalTokens: Number.NaN,
7084
+ reasoningTokens: Number.NaN,
7085
+ cachedInputTokens: Number.NaN
7086
+ };
7087
+ const openrouterUsage = {};
7088
+ return {
7089
+ stream: response.pipeThrough(
7090
+ new TransformStream({
7091
+ transform(chunk, controller) {
7092
+ var _a15, _b;
7093
+ if (!chunk.success) {
7094
+ finishReason = "error";
7095
+ controller.enqueue({ type: "error", error: chunk.error });
7096
+ return;
7097
+ }
7098
+ const value = chunk.value;
7099
+ if ("error" in value) {
7100
+ finishReason = "error";
7101
+ controller.enqueue({ type: "error", error: value.error });
7102
+ return;
7103
+ }
7104
+ if (value.usage != null) {
7105
+ usage.inputTokens = value.usage.prompt_tokens;
7106
+ usage.outputTokens = value.usage.completion_tokens;
7107
+ usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
7108
+ openrouterUsage.promptTokens = value.usage.prompt_tokens;
7109
+ if (value.usage.prompt_tokens_details) {
7110
+ const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
7111
+ usage.cachedInputTokens = cachedInputTokens;
7112
+ openrouterUsage.promptTokensDetails = {
7113
+ cachedTokens: cachedInputTokens
7114
+ };
7115
+ }
7116
+ openrouterUsage.completionTokens = value.usage.completion_tokens;
7117
+ if (value.usage.completion_tokens_details) {
7118
+ const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
7119
+ usage.reasoningTokens = reasoningTokens;
7120
+ openrouterUsage.completionTokensDetails = {
7121
+ reasoningTokens
7122
+ };
7123
+ }
7124
+ openrouterUsage.cost = value.usage.cost;
7125
+ openrouterUsage.totalTokens = value.usage.total_tokens;
7126
+ }
7127
+ const choice = value.choices[0];
7128
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
7129
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
7130
+ }
7131
+ if ((choice == null ? void 0 : choice.text) != null) {
7132
+ controller.enqueue({
7133
+ type: "text-delta",
7134
+ delta: choice.text,
7135
+ id: generateId4()
7136
+ });
7137
+ }
7138
+ },
7139
+ flush(controller) {
7140
+ controller.enqueue({
7141
+ type: "finish",
7142
+ finishReason,
7143
+ usage,
7144
+ providerMetadata: {
7145
+ openrouter: {
7146
+ usage: openrouterUsage
7147
+ }
7148
+ }
7149
+ });
7150
+ }
7151
+ })
7152
+ ),
7153
+ response: {
7154
+ headers: responseHeaders
7155
+ }
7156
+ };
7157
+ }
7158
+ };
7159
+ function removeUndefinedEntries22(record) {
7160
+ return Object.fromEntries(
7161
+ Object.entries(record).filter(([, value]) => value !== null)
7162
+ );
7163
+ }
7164
+ function withUserAgentSuffix3(headers, ...userAgentSuffixParts) {
7165
+ const cleanedHeaders = removeUndefinedEntries22(
7166
+ headers != null ? headers : {}
7167
+ );
7168
+ const currentUserAgentHeader = cleanedHeaders["user-agent"] || "";
7169
+ const newUserAgent = [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ");
7170
+ return __spreadProps(__spreadValues({}, cleanedHeaders), {
7171
+ "user-agent": newUserAgent
7172
+ });
7173
+ }
7174
+ var VERSION5 = "1.2.3";
7175
+ function createOpenRouter(options = {}) {
7176
+ var _a15, _b, _c;
7177
+ const baseURL = (_b = withoutTrailingSlash4((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
7178
+ const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
7179
+ const getHeaders = () => withUserAgentSuffix3(
7180
+ __spreadValues({
7181
+ Authorization: `Bearer ${loadApiKey4({
7182
+ apiKey: options.apiKey,
7183
+ environmentVariableName: "OPENROUTER_API_KEY",
7184
+ description: "OpenRouter"
7185
+ })}`
7186
+ }, options.headers),
7187
+ `ai-sdk/openrouter/${VERSION5}`
7188
+ );
7189
+ const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
7190
+ provider: "openrouter.chat",
7191
+ url: ({ path }) => `${baseURL}${path}`,
7192
+ headers: getHeaders,
7193
+ compatibility,
7194
+ fetch: options.fetch,
7195
+ extraBody: options.extraBody
7196
+ });
7197
+ const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
7198
+ provider: "openrouter.completion",
7199
+ url: ({ path }) => `${baseURL}${path}`,
7200
+ headers: getHeaders,
7201
+ compatibility,
7202
+ fetch: options.fetch,
7203
+ extraBody: options.extraBody
7204
+ });
7205
+ const createLanguageModel = (modelId, settings) => {
7206
+ if (new.target) {
7207
+ throw new Error(
7208
+ "The OpenRouter model function cannot be called with the new keyword."
7209
+ );
7210
+ }
7211
+ if (modelId === "openai/gpt-3.5-turbo-instruct") {
7212
+ return createCompletionModel(
7213
+ modelId,
7214
+ settings
7215
+ );
7216
+ }
7217
+ return createChatModel(modelId, settings);
7218
+ };
7219
+ const provider = (modelId, settings) => createLanguageModel(modelId, settings);
7220
+ provider.languageModel = createLanguageModel;
7221
+ provider.chat = createChatModel;
7222
+ provider.completion = createCompletionModel;
7223
+ return provider;
7224
+ }
7225
+ createOpenRouter({
7226
+ compatibility: "strict"
7227
+ // strict for OpenRouter API
7228
+ });
4776
7229
 
4777
7230
  // src/llm/model/gateway-resolver.ts
4778
7231
  function parseModelRouterId(routerId, gatewayPrefix) {
@@ -4955,5 +7408,5 @@ var ModelsDevGateway = class extends MastraModelGateway {
4955
7408
  };
4956
7409
 
4957
7410
  export { ModelsDevGateway, parseModelRouterId };
4958
- //# sourceMappingURL=chunk-OEIVMCWX.js.map
4959
- //# sourceMappingURL=chunk-OEIVMCWX.js.map
7411
+ //# sourceMappingURL=chunk-MRRFTNF4.js.map
7412
+ //# sourceMappingURL=chunk-MRRFTNF4.js.map