@mastra/core 0.18.1-alpha.0 → 0.19.0

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 (281) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/dist/agent/agent.d.ts +19 -9
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/index.cjs +11 -11
  5. package/dist/agent/index.d.ts +1 -1
  6. package/dist/agent/index.d.ts.map +1 -1
  7. package/dist/agent/index.js +2 -2
  8. package/dist/agent/input-processor/index.cjs +6 -6
  9. package/dist/agent/input-processor/index.js +1 -1
  10. package/dist/agent/types.d.ts +13 -8
  11. package/dist/agent/types.d.ts.map +1 -1
  12. package/dist/ai-tracing/exporters/default.d.ts +2 -2
  13. package/dist/ai-tracing/exporters/default.d.ts.map +1 -1
  14. package/dist/ai-tracing/index.cjs +32 -32
  15. package/dist/ai-tracing/index.js +1 -1
  16. package/dist/ai-tracing/types.d.ts +2 -2
  17. package/dist/ai-tracing/types.d.ts.map +1 -1
  18. package/dist/{chunk-ITD7IHN5.js → chunk-2DGWSOVQ.js} +23 -5
  19. package/dist/chunk-2DGWSOVQ.js.map +1 -0
  20. package/dist/{chunk-4PK4GBYZ.cjs → chunk-2GHLV754.cjs} +5 -4
  21. package/dist/chunk-2GHLV754.cjs.map +1 -0
  22. package/dist/{chunk-LL2X7QT7.js → chunk-3WFH6YRI.js} +4 -4
  23. package/dist/{chunk-LL2X7QT7.js.map → chunk-3WFH6YRI.js.map} +1 -1
  24. package/dist/chunk-45CV4JYJ.cjs +4 -0
  25. package/dist/{chunk-VBPPPQO3.cjs.map → chunk-45CV4JYJ.cjs.map} +1 -1
  26. package/dist/{chunk-SEZBEL3U.js → chunk-4BEHJSL6.js} +4 -4
  27. package/dist/{chunk-SEZBEL3U.js.map → chunk-4BEHJSL6.js.map} +1 -1
  28. package/dist/chunk-4LSFAAZW.js +3 -0
  29. package/dist/{chunk-CE73R5W7.js.map → chunk-4LSFAAZW.js.map} +1 -1
  30. package/dist/{chunk-XUAWHRUO.cjs → chunk-4R2TBRS7.cjs} +37 -112
  31. package/dist/chunk-4R2TBRS7.cjs.map +1 -0
  32. package/dist/{chunk-ITBUHG4U.cjs → chunk-4VNAMG7K.cjs} +6 -6
  33. package/dist/{chunk-ITBUHG4U.cjs.map → chunk-4VNAMG7K.cjs.map} +1 -1
  34. package/dist/{chunk-B4REUTZB.js → chunk-5BQOHHCI.js} +5 -5
  35. package/dist/{chunk-B4REUTZB.js.map → chunk-5BQOHHCI.js.map} +1 -1
  36. package/dist/{chunk-FXLZYRV7.js → chunk-5HCVPQTD.js} +3 -3
  37. package/dist/{chunk-FXLZYRV7.js.map → chunk-5HCVPQTD.js.map} +1 -1
  38. package/dist/chunk-5M6ZTQJN.js +1374 -0
  39. package/dist/chunk-5M6ZTQJN.js.map +1 -0
  40. package/dist/{chunk-SW7WPHZ2.cjs → chunk-7E4ESNZS.cjs} +5 -5
  41. package/dist/{chunk-SW7WPHZ2.cjs.map → chunk-7E4ESNZS.cjs.map} +1 -1
  42. package/dist/{chunk-NTS6B2I2.cjs → chunk-A4RAEU6X.cjs} +2 -2
  43. package/dist/{chunk-NTS6B2I2.cjs.map → chunk-A4RAEU6X.cjs.map} +1 -1
  44. package/dist/{chunk-QUB6MWXZ.cjs → chunk-BCWRUNMS.cjs} +38 -37
  45. package/dist/chunk-BCWRUNMS.cjs.map +1 -0
  46. package/dist/{chunk-245ANI3P.js → chunk-BUY5X7DT.js} +4 -4
  47. package/dist/{chunk-245ANI3P.js.map → chunk-BUY5X7DT.js.map} +1 -1
  48. package/dist/{chunk-6ZVNL435.js → chunk-COC64XPP.js} +9 -8
  49. package/dist/chunk-COC64XPP.js.map +1 -0
  50. package/dist/{chunk-6X4FZVGT.cjs → chunk-CQ73JM2N.cjs} +10 -10
  51. package/dist/{chunk-6X4FZVGT.cjs.map → chunk-CQ73JM2N.cjs.map} +1 -1
  52. package/dist/{chunk-7UEBC5KM.cjs → chunk-DRVSEV5Y.cjs} +25 -65
  53. package/dist/chunk-DRVSEV5Y.cjs.map +1 -0
  54. package/dist/{chunk-2TQHRYRK.cjs → chunk-EPMJYNEK.cjs} +4 -4
  55. package/dist/{chunk-2TQHRYRK.cjs.map → chunk-EPMJYNEK.cjs.map} +1 -1
  56. package/dist/{chunk-TKFLL33F.cjs → chunk-F6EJEELE.cjs} +9 -9
  57. package/dist/{chunk-TKFLL33F.cjs.map → chunk-F6EJEELE.cjs.map} +1 -1
  58. package/dist/{chunk-4DNSY645.js → chunk-FV3SA5TI.js} +3 -3
  59. package/dist/{chunk-4DNSY645.js.map → chunk-FV3SA5TI.js.map} +1 -1
  60. package/dist/{chunk-EJ2FU45N.js → chunk-FV4QVXO4.js} +2 -2
  61. package/dist/{chunk-EJ2FU45N.js.map → chunk-FV4QVXO4.js.map} +1 -1
  62. package/dist/{chunk-CKZK2EPZ.cjs → chunk-HNBU4PI7.cjs} +4 -4
  63. package/dist/{chunk-CKZK2EPZ.cjs.map → chunk-HNBU4PI7.cjs.map} +1 -1
  64. package/dist/{chunk-O6PQYYT6.cjs → chunk-HQPFM22N.cjs} +63 -45
  65. package/dist/chunk-HQPFM22N.cjs.map +1 -0
  66. package/dist/{chunk-36DRWGP4.js → chunk-IAXAPVOP.js} +4 -4
  67. package/dist/{chunk-36DRWGP4.js.map → chunk-IAXAPVOP.js.map} +1 -1
  68. package/dist/{chunk-5ZMC3NEO.js → chunk-JKLLXBOY.js} +46 -39
  69. package/dist/chunk-JKLLXBOY.js.map +1 -0
  70. package/dist/{chunk-WVRSMHE5.cjs → chunk-K4AYIXVH.cjs} +4 -4
  71. package/dist/{chunk-WVRSMHE5.cjs.map → chunk-K4AYIXVH.cjs.map} +1 -1
  72. package/dist/{chunk-SALFMUAY.cjs → chunk-LZBVDMVQ.cjs} +19 -19
  73. package/dist/{chunk-SALFMUAY.cjs.map → chunk-LZBVDMVQ.cjs.map} +1 -1
  74. package/dist/{chunk-RPFJBB5X.js → chunk-N4PK4MOG.js} +4 -4
  75. package/dist/{chunk-RPFJBB5X.js.map → chunk-N4PK4MOG.js.map} +1 -1
  76. package/dist/{chunk-QBTRGHUF.cjs → chunk-NHJVMZIL.cjs} +19 -19
  77. package/dist/{chunk-QBTRGHUF.cjs.map → chunk-NHJVMZIL.cjs.map} +1 -1
  78. package/dist/{chunk-BJZWMVNW.js → chunk-OBIF7QD5.js} +3 -3
  79. package/dist/{chunk-BJZWMVNW.js.map → chunk-OBIF7QD5.js.map} +1 -1
  80. package/dist/{chunk-VZLNVGYM.cjs → chunk-PG6ZNDSR.cjs} +21 -21
  81. package/dist/{chunk-VZLNVGYM.cjs.map → chunk-PG6ZNDSR.cjs.map} +1 -1
  82. package/dist/{chunk-XWJWU5OM.js → chunk-PJ6HF3KW.js} +16 -56
  83. package/dist/chunk-PJ6HF3KW.js.map +1 -0
  84. package/dist/{chunk-NG2XDPDY.js → chunk-RAXBZZKS.js} +4 -3
  85. package/dist/chunk-RAXBZZKS.js.map +1 -0
  86. package/dist/chunk-RFGQ3EQV.js +3 -0
  87. package/dist/chunk-RFGQ3EQV.js.map +1 -0
  88. package/dist/{chunk-73S2WYSD.cjs → chunk-RNIY63FP.cjs} +85 -78
  89. package/dist/chunk-RNIY63FP.cjs.map +1 -0
  90. package/dist/{chunk-ROU7YJLG.js → chunk-RYFQKXXS.js} +3 -3
  91. package/dist/{chunk-ROU7YJLG.js.map → chunk-RYFQKXXS.js.map} +1 -1
  92. package/dist/{chunk-C73WLCY3.cjs → chunk-S7UXT3V4.cjs} +21 -3
  93. package/dist/chunk-S7UXT3V4.cjs.map +1 -0
  94. package/dist/{chunk-R5GESRGB.js → chunk-SJMKDSRF.js} +37 -112
  95. package/dist/chunk-SJMKDSRF.js.map +1 -0
  96. package/dist/{chunk-YWXSGDDO.cjs → chunk-SQQMX4VC.cjs} +6 -6
  97. package/dist/{chunk-YWXSGDDO.cjs.map → chunk-SQQMX4VC.cjs.map} +1 -1
  98. package/dist/chunk-TCHOIK53.cjs +4 -0
  99. package/dist/chunk-TCHOIK53.cjs.map +1 -0
  100. package/dist/chunk-TIBULEK6.cjs +1379 -0
  101. package/dist/chunk-TIBULEK6.cjs.map +1 -0
  102. package/dist/{chunk-WECJNCGT.cjs → chunk-UTEH2LCJ.cjs} +19 -19
  103. package/dist/{chunk-WECJNCGT.cjs.map → chunk-UTEH2LCJ.cjs.map} +1 -1
  104. package/dist/{chunk-VGU5ZYYG.js → chunk-VWO3JJXC.js} +4 -4
  105. package/dist/{chunk-VGU5ZYYG.js.map → chunk-VWO3JJXC.js.map} +1 -1
  106. package/dist/{chunk-MCOVMKIS.js → chunk-WHFNGECY.js} +21 -4
  107. package/dist/chunk-WHFNGECY.js.map +1 -0
  108. package/dist/{chunk-NTXNE4YR.js → chunk-XG3SFWOH.js} +3 -3
  109. package/dist/{chunk-NTXNE4YR.js.map → chunk-XG3SFWOH.js.map} +1 -1
  110. package/dist/error/index.cjs +5 -5
  111. package/dist/error/index.d.ts.map +1 -1
  112. package/dist/error/index.js +1 -1
  113. package/dist/error/utils.d.ts +8 -0
  114. package/dist/error/utils.d.ts.map +1 -0
  115. package/dist/eval/index.cjs +3 -3
  116. package/dist/eval/index.js +1 -1
  117. package/dist/index.cjs +84 -67
  118. package/dist/index.cjs.map +1 -1
  119. package/dist/index.js +18 -17
  120. package/dist/index.js.map +1 -1
  121. package/dist/integration/index.cjs +3 -3
  122. package/dist/integration/index.js +1 -1
  123. package/dist/llm/index.cjs +20 -0
  124. package/dist/llm/index.d.ts +3 -1
  125. package/dist/llm/index.d.ts.map +1 -1
  126. package/dist/llm/index.js +1 -1
  127. package/dist/llm/model/gateways/base.d.ts +42 -0
  128. package/dist/llm/model/gateways/base.d.ts.map +1 -0
  129. package/dist/llm/model/gateways/index.d.ts +3 -0
  130. package/dist/llm/model/gateways/index.d.ts.map +1 -0
  131. package/dist/llm/model/gateways/models-dev.d.ts +11 -0
  132. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -0
  133. package/dist/llm/model/index.d.ts +2 -0
  134. package/dist/llm/model/index.d.ts.map +1 -1
  135. package/dist/llm/model/model.loop.d.ts.map +1 -1
  136. package/dist/llm/model/openai-compatible.d.ts +32 -0
  137. package/dist/llm/model/openai-compatible.d.ts.map +1 -0
  138. package/dist/llm/model/provider-registry.generated.d.ts +462 -0
  139. package/dist/llm/model/provider-registry.generated.d.ts.map +1 -0
  140. package/dist/llm/model/shared.types.d.ts +8 -0
  141. package/dist/llm/model/shared.types.d.ts.map +1 -1
  142. package/dist/loop/index.cjs +2 -2
  143. package/dist/loop/index.js +1 -1
  144. package/dist/loop/network/index.d.ts.map +1 -1
  145. package/dist/loop/test-utils/fullStream.d.ts.map +1 -1
  146. package/dist/loop/test-utils/generateText.d.ts.map +1 -1
  147. package/dist/loop/test-utils/options.d.ts.map +1 -1
  148. package/dist/loop/test-utils/resultObject.d.ts.map +1 -1
  149. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  150. package/dist/loop/test-utils/toUIMessageStream.d.ts.map +1 -1
  151. package/dist/loop/test-utils/tools.d.ts.map +1 -1
  152. package/dist/loop/workflows/agentic-execution/index.d.ts +99 -0
  153. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  154. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +66 -0
  155. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  156. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +33 -0
  157. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  158. package/dist/loop/workflows/agentic-loop/index.d.ts +99 -0
  159. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  160. package/dist/loop/workflows/run-state.d.ts +5 -0
  161. package/dist/loop/workflows/run-state.d.ts.map +1 -1
  162. package/dist/loop/workflows/schema.d.ts +38 -0
  163. package/dist/loop/workflows/schema.d.ts.map +1 -1
  164. package/dist/mastra/index.cjs +2 -2
  165. package/dist/mastra/index.d.ts.map +1 -1
  166. package/dist/mastra/index.js +1 -1
  167. package/dist/memory/index.cjs +4 -4
  168. package/dist/memory/index.js +1 -1
  169. package/dist/network/vNext/index.cjs +30 -30
  170. package/dist/network/vNext/index.cjs.map +1 -1
  171. package/dist/network/vNext/index.js +3 -3
  172. package/dist/network/vNext/index.js.map +1 -1
  173. package/dist/processors/index.cjs +10 -10
  174. package/dist/processors/index.js +1 -1
  175. package/dist/processors/processors/language-detector.d.ts.map +1 -1
  176. package/dist/processors/processors/moderation.d.ts.map +1 -1
  177. package/dist/processors/processors/pii-detector.d.ts.map +1 -1
  178. package/dist/processors/processors/prompt-injection-detector.d.ts.map +1 -1
  179. package/dist/processors/processors/structured-output.d.ts.map +1 -1
  180. package/dist/processors/processors/system-prompt-scrubber.d.ts.map +1 -1
  181. package/dist/relevance/index.cjs +4 -4
  182. package/dist/relevance/index.js +1 -1
  183. package/dist/scores/index.cjs +9 -9
  184. package/dist/scores/index.js +2 -2
  185. package/dist/scores/scoreTraces/index.cjs +57 -68
  186. package/dist/scores/scoreTraces/index.cjs.map +1 -1
  187. package/dist/scores/scoreTraces/index.js +48 -59
  188. package/dist/scores/scoreTraces/index.js.map +1 -1
  189. package/dist/scores/scoreTraces/scoreTracesWorkflow.d.ts.map +1 -1
  190. package/dist/scores/scoreTraces/utils.d.ts +4 -8
  191. package/dist/scores/scoreTraces/utils.d.ts.map +1 -1
  192. package/dist/scores/types.d.ts +8 -4
  193. package/dist/scores/types.d.ts.map +1 -1
  194. package/dist/server/index.cjs +7 -7
  195. package/dist/server/index.js +2 -2
  196. package/dist/storage/base.d.ts +14 -5
  197. package/dist/storage/base.d.ts.map +1 -1
  198. package/dist/storage/constants.d.ts.map +1 -1
  199. package/dist/storage/domains/observability/base.d.ts +5 -5
  200. package/dist/storage/domains/observability/base.d.ts.map +1 -1
  201. package/dist/storage/domains/observability/inmemory.d.ts +7 -7
  202. package/dist/storage/domains/observability/inmemory.d.ts.map +1 -1
  203. package/dist/storage/domains/scores/base.d.ts +8 -0
  204. package/dist/storage/domains/scores/base.d.ts.map +1 -1
  205. package/dist/storage/domains/scores/inmemory.d.ts +8 -0
  206. package/dist/storage/domains/scores/inmemory.d.ts.map +1 -1
  207. package/dist/storage/index.cjs +94 -64
  208. package/dist/storage/index.cjs.map +1 -1
  209. package/dist/storage/index.js +59 -29
  210. package/dist/storage/index.js.map +1 -1
  211. package/dist/storage/mock.d.ts +9 -0
  212. package/dist/storage/mock.d.ts.map +1 -1
  213. package/dist/storage/types.d.ts +2 -0
  214. package/dist/storage/types.d.ts.map +1 -1
  215. package/dist/stream/MastraWorkflowStream.d.ts.map +1 -1
  216. package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
  217. package/dist/stream/aisdk/v5/output.d.ts +7 -0
  218. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  219. package/dist/stream/base/output.d.ts.map +1 -1
  220. package/dist/stream/index.cjs +4 -4
  221. package/dist/stream/index.js +1 -1
  222. package/dist/stream/types.d.ts +12 -12
  223. package/dist/stream/types.d.ts.map +1 -1
  224. package/dist/telemetry/index.cjs +7 -7
  225. package/dist/telemetry/index.js +1 -1
  226. package/dist/test-utils/llm-mock.cjs +2 -2
  227. package/dist/test-utils/llm-mock.js +1 -1
  228. package/dist/tools/index.cjs +4 -4
  229. package/dist/tools/index.js +1 -1
  230. package/dist/tools/is-vercel-tool.cjs +2 -2
  231. package/dist/tools/is-vercel-tool.js +1 -1
  232. package/dist/tools/tool.d.ts +2 -4
  233. package/dist/tools/tool.d.ts.map +1 -1
  234. package/dist/tools/types.d.ts +1 -1
  235. package/dist/tools/types.d.ts.map +1 -1
  236. package/dist/tts/index.cjs +2 -2
  237. package/dist/tts/index.js +1 -1
  238. package/dist/{types.d.ts → types/dynamic-argument.d.ts} +3 -3
  239. package/dist/types/dynamic-argument.d.ts.map +1 -0
  240. package/dist/types/index.cjs +4 -0
  241. package/dist/types/index.cjs.map +1 -0
  242. package/dist/types/index.d.ts +2 -0
  243. package/dist/types/index.d.ts.map +1 -0
  244. package/dist/types/index.js +3 -0
  245. package/dist/types/index.js.map +1 -0
  246. package/dist/utils.cjs +17 -17
  247. package/dist/utils.js +1 -1
  248. package/dist/vector/index.cjs +4 -4
  249. package/dist/vector/index.js +1 -1
  250. package/dist/voice/index.cjs +4 -4
  251. package/dist/voice/index.js +1 -1
  252. package/dist/workflows/default.d.ts.map +1 -1
  253. package/dist/workflows/evented/index.cjs +10 -10
  254. package/dist/workflows/evented/index.js +1 -1
  255. package/dist/workflows/index.cjs +12 -12
  256. package/dist/workflows/index.js +1 -1
  257. package/dist/workflows/legacy/index.cjs +22 -22
  258. package/dist/workflows/legacy/index.js +1 -1
  259. package/dist/workflows/types.d.ts +11 -1
  260. package/dist/workflows/types.d.ts.map +1 -1
  261. package/dist/workflows/workflow.d.ts +6 -3
  262. package/dist/workflows/workflow.d.ts.map +1 -1
  263. package/package.json +4 -4
  264. package/types.d.ts +1 -0
  265. package/dist/chunk-4PK4GBYZ.cjs.map +0 -1
  266. package/dist/chunk-5ZMC3NEO.js.map +0 -1
  267. package/dist/chunk-6ZVNL435.js.map +0 -1
  268. package/dist/chunk-73S2WYSD.cjs.map +0 -1
  269. package/dist/chunk-7UEBC5KM.cjs.map +0 -1
  270. package/dist/chunk-C73WLCY3.cjs.map +0 -1
  271. package/dist/chunk-CE73R5W7.js +0 -3
  272. package/dist/chunk-ITD7IHN5.js.map +0 -1
  273. package/dist/chunk-MCOVMKIS.js.map +0 -1
  274. package/dist/chunk-NG2XDPDY.js.map +0 -1
  275. package/dist/chunk-O6PQYYT6.cjs.map +0 -1
  276. package/dist/chunk-QUB6MWXZ.cjs.map +0 -1
  277. package/dist/chunk-R5GESRGB.js.map +0 -1
  278. package/dist/chunk-VBPPPQO3.cjs +0 -4
  279. package/dist/chunk-XUAWHRUO.cjs.map +0 -1
  280. package/dist/chunk-XWJWU5OM.js.map +0 -1
  281. package/dist/types.d.ts.map +0 -1
@@ -1,15 +1,16 @@
1
- import { DefaultVoice } from './chunk-RPFJBB5X.js';
1
+ import { DefaultVoice } from './chunk-N4PK4MOG.js';
2
2
  import { STREAM_FORMAT_SYMBOL, EMITTER_SYMBOL } from './chunk-NLNKQD2T.js';
3
- import { InstrumentClass, Telemetry } from './chunk-SEZBEL3U.js';
4
- import { MastraLLMV1 } from './chunk-LL2X7QT7.js';
5
- import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-245ANI3P.js';
3
+ import { InstrumentClass, Telemetry } from './chunk-4BEHJSL6.js';
4
+ import { MastraLLMV1 } from './chunk-3WFH6YRI.js';
5
+ import { OpenAICompatibleModel } from './chunk-5M6ZTQJN.js';
6
+ import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-BUY5X7DT.js';
6
7
  import { executeHook } from './chunk-TTELJD4F.js';
7
8
  import { zodToJsonSchema } from './chunk-PJKCPRYF.js';
8
- import { wrapMastra, selectFields, getOrCreateSpan, getValidTraceId, ensureToolProperties, makeCoreTool, createMastraProxy, delay } from './chunk-XWJWU5OM.js';
9
+ import { wrapMastra, selectFields, getOrCreateSpan, getValidTraceId, ensureToolProperties, makeCoreTool, createMastraProxy, delay } from './chunk-PJ6HF3KW.js';
9
10
  import { RuntimeContext } from './chunk-HLRWYUFN.js';
10
- import { MastraError } from './chunk-MCOVMKIS.js';
11
+ import { MastraError, safeParseErrorObject } from './chunk-WHFNGECY.js';
11
12
  import { ToolStream } from './chunk-A3QHQYMC.js';
12
- import { Tool, createTool } from './chunk-EJ2FU45N.js';
13
+ import { Tool, createTool } from './chunk-FV4QVXO4.js';
13
14
  import { MastraBase } from './chunk-BMVFEBPE.js';
14
15
  import { RegisteredLogger, ConsoleLogger } from './chunk-BN2M4UK5.js';
15
16
  import { __commonJS, __toESM, __decoratorStart, __decorateElement, __runInitializers } from './chunk-3HXBPDKN.js';
@@ -42,7 +43,7 @@ function getTracer({isEnabled=false,tracer}={}){if(!isEnabled){return noopTracer
42
43
  var TripWire=class extends Error{constructor(reason){super(reason);Object.setPrototypeOf(this,new.target.prototype);}};var getModelOutputForTripwire=async({tripwireReason,runId,tracingContext,options,model,messageList})=>{const tripwireStream=new ReadableStream$1({start(controller){controller.enqueue({type:"tripwire",runId,from:"AGENT"/* AGENT */,payload:{tripwireReason:tripwireReason||""}});controller.close();}});const{rootSpan}=getRootSpan({operationId:`mastra.stream.tripwire`,model:{modelId:model.modelId||"unknown",provider:model.provider||"unknown"},modelSettings:options.modelSettings,headers:options.modelSettings?.headers,telemetry_settings:options.telemetry});const modelOutput=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion||"v2"},stream:tripwireStream,messageList,options:{runId,rootSpan,telemetry_settings:options.telemetry,output:options.output,tracingContext,onFinish:options.onFinish,// Fix these types after the types PR is merged
43
44
  onStepFinish:options.onStepFinish,returnScorerData:options.returnScorerData},messageId:randomUUID()});return modelOutput;};// src/processors/processors/moderation.ts
44
45
  var ModerationProcessor=class _ModerationProcessor{name="moderation";moderationAgent;categories;threshold;strategy;includeScores;chunkWindow;// Default OpenAI moderation categories
45
- static DEFAULT_CATEGORIES=["hate","hate/threatening","harassment","harassment/threatening","self-harm","self-harm/intent","self-harm/instructions","sexual","sexual/minors","violence","violence/graphic"];constructor(options){this.categories=options.categories||_ModerationProcessor.DEFAULT_CATEGORIES;this.threshold=options.threshold??0.5;this.strategy=options.strategy||"block";this.includeScores=options.includeScores??false;this.chunkWindow=options.chunkWindow??0;this.moderationAgent=new Agent({name:"content-moderator",instructions:options.instructions||this.createDefaultInstructions(),model:options.model});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const passedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){passedMessages.push(message);continue;}const moderationResult=await this.moderateContent(textContent,false,tracingContext);if(this.isModerationFlagged(moderationResult)){this.handleFlaggedContent(moderationResult,this.strategy,abort);if(this.strategy==="filter"){continue;}}passedMessages.push(message);}return passedMessages;}catch(error){if(error instanceof TripWire){throw error;}args.abort(`Moderation failed: ${error instanceof Error?error.message:"Unknown error"}`);}}async processOutputResult(args){return this.processInput(args);}async processOutputStream(args){try{const{part,streamParts,abort,tracingContext}=args;if(part.type!=="text-delta"){return part;}const contentToModerate=this.buildContextFromChunks(streamParts);const moderationResult=await this.moderateContent(contentToModerate,true,tracingContext);if(this.isModerationFlagged(moderationResult)){this.handleFlaggedContent(moderationResult,this.strategy,abort);if(this.strategy==="filter"){return null;}}return part;}catch(error){if(error instanceof TripWire){throw error;}console.warn("[ModerationProcessor] Stream moderation failed:",error);return args.part;}}/**
46
+ static DEFAULT_CATEGORIES=["hate","hate/threatening","harassment","harassment/threatening","self-harm","self-harm/intent","self-harm/instructions","sexual","sexual/minors","violence","violence/graphic"];constructor(options){this.categories=options.categories||_ModerationProcessor.DEFAULT_CATEGORIES;this.threshold=options.threshold??0.5;this.strategy=options.strategy||"block";this.includeScores=options.includeScores??false;this.chunkWindow=options.chunkWindow??0;this.moderationAgent=new Agent({name:"content-moderator",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const passedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){passedMessages.push(message);continue;}const moderationResult=await this.moderateContent(textContent,false,tracingContext);if(this.isModerationFlagged(moderationResult)){this.handleFlaggedContent(moderationResult,this.strategy,abort);if(this.strategy==="filter"){continue;}}passedMessages.push(message);}return passedMessages;}catch(error){if(error instanceof TripWire){throw error;}args.abort(`Moderation failed: ${error instanceof Error?error.message:"Unknown error"}`);}}async processOutputResult(args){return this.processInput(args);}async processOutputStream(args){try{const{part,streamParts,abort,tracingContext}=args;if(part.type!=="text-delta"){return part;}const contentToModerate=this.buildContextFromChunks(streamParts);const moderationResult=await this.moderateContent(contentToModerate,true,tracingContext);if(this.isModerationFlagged(moderationResult)){this.handleFlaggedContent(moderationResult,this.strategy,abort);if(this.strategy==="filter"){return null;}}return part;}catch(error){if(error instanceof TripWire){throw error;}console.warn("[ModerationProcessor] Stream moderation failed:",error);return args.part;}}/**
46
47
  * Moderate content using the internal agent
47
48
  */async moderateContent(content,isStream=false,tracingContext){const prompt=this.createModerationPrompt(content,isStream);try{const model=await this.moderationAgent.getModel();const schema=z9.object({category_scores:z9.object(this.categories.reduce((props,category)=>{props[category]=z9.number().min(0).max(1).optional();return props;},{})).optional(),reason:z9.string().optional()});let response;if(model.specificationVersion==="v2"){response=await this.moderationAgent.generateVNext(prompt,{output:schema,modelSettings:{temperature:0},tracingContext});}else {response=await this.moderationAgent.generate(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;return result;}catch(error){console.warn("[ModerationProcessor] Agent moderation failed, allowing content:",error);return {};}}/**
48
49
  * Determine if content is flagged based on category scores above threshold
@@ -80,7 +81,7 @@ static DEFAULT_DETECTION_TYPES=["injection",// General prompt injection attempts
80
81
  "data-exfiltration",// Attempts to extract sensitive data
81
82
  "system-override",// Attempts to override system instructions
82
83
  "role-manipulation"// Attempts to manipulate the AI's role or persona
83
- ];constructor(options){this.detectionTypes=options.detectionTypes||_PromptInjectionDetector.DEFAULT_DETECTION_TYPES;this.threshold=options.threshold??0.7;this.strategy=options.strategy||"block";this.includeScores=options.includeScores??false;this.detectionAgent=new Agent({name:"prompt-injection-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){processedMessages.push(message);continue;}const detectionResult=await this.detectPromptInjection(textContent,tracingContext);if(this.isInjectionFlagged(detectionResult)){const processedMessage=this.handleDetectedInjection(message,detectionResult,this.strategy,abort);if(this.strategy==="filter"){continue;}else if(this.strategy==="rewrite"){if(processedMessage){processedMessages.push(processedMessage);}continue;}}processedMessages.push(message);}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}throw new Error(`Prompt injection detection failed: ${error instanceof Error?error.stack:"Unknown error"}`);}}/**
84
+ ];constructor(options){this.detectionTypes=options.detectionTypes||_PromptInjectionDetector.DEFAULT_DETECTION_TYPES;this.threshold=options.threshold??0.7;this.strategy=options.strategy||"block";this.includeScores=options.includeScores??false;this.detectionAgent=new Agent({name:"prompt-injection-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){processedMessages.push(message);continue;}const detectionResult=await this.detectPromptInjection(textContent,tracingContext);if(this.isInjectionFlagged(detectionResult)){const processedMessage=this.handleDetectedInjection(message,detectionResult,this.strategy,abort);if(this.strategy==="filter"){continue;}else if(this.strategy==="rewrite"){if(processedMessage){processedMessages.push(processedMessage);}continue;}}processedMessages.push(message);}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}throw new Error(`Prompt injection detection failed: ${error instanceof Error?error.stack:"Unknown error"}`);}}/**
84
85
  * Detect prompt injection using the internal agent
85
86
  */async detectPromptInjection(content,tracingContext){const prompt=this.createDetectionPrompt(content);try{const model=await this.detectionAgent.getModel();let response;const schema=z9.object({categories:z9.object(this.detectionTypes.reduce((props,type)=>{props[type]=z9.number().min(0).max(1).optional();return props;},{})).optional(),reason:z9.string().optional(),rewritten_content:z9.string().optional()});if(model.specificationVersion==="v2"){response=await this.detectionAgent.generateVNext(prompt,{output:schema,modelSettings:{temperature:0},tracingContext});}else {response=await this.detectionAgent.generate(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;return result;}catch(error){console.warn("[PromptInjectionDetector] Detection agent failed, allowing content:",error);return {};}}/**
86
87
  * Determine if prompt injection is flagged based on category scores above threshold
@@ -121,7 +122,7 @@ static DEFAULT_DETECTION_TYPES=["email",// Email addresses
121
122
  "uuid",// Universally Unique Identifiers
122
123
  "crypto-wallet",// Cryptocurrency wallet addresses
123
124
  "iban"// International Bank Account Numbers
124
- ];constructor(options){this.detectionTypes=options.detectionTypes||_PIIDetector.DEFAULT_DETECTION_TYPES;this.threshold=options.threshold??0.6;this.strategy=options.strategy||"redact";this.redactionMethod=options.redactionMethod||"mask";this.includeDetections=options.includeDetections??false;this.preserveFormat=options.preserveFormat??true;this.detectionAgent=new Agent({name:"pii-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){processedMessages.push(message);continue;}const detectionResult=await this.detectPII(textContent,tracingContext);if(this.isPIIFlagged(detectionResult)){const processedMessage=this.handleDetectedPII(message,detectionResult,this.strategy,abort);if(this.strategy==="filter"){continue;}else if(this.strategy==="redact"){if(processedMessage){processedMessages.push(processedMessage);}else {processedMessages.push(message);}continue;}}processedMessages.push(message);}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}throw new Error(`PII detection failed: ${error instanceof Error?error.stack:"Unknown error"}`);}}/**
125
+ ];constructor(options){this.detectionTypes=options.detectionTypes||_PIIDetector.DEFAULT_DETECTION_TYPES;this.threshold=options.threshold??0.6;this.strategy=options.strategy||"redact";this.redactionMethod=options.redactionMethod||"mask";this.includeDetections=options.includeDetections??false;this.preserveFormat=options.preserveFormat??true;this.detectionAgent=new Agent({name:"pii-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){processedMessages.push(message);continue;}const detectionResult=await this.detectPII(textContent,tracingContext);if(this.isPIIFlagged(detectionResult)){const processedMessage=this.handleDetectedPII(message,detectionResult,this.strategy,abort);if(this.strategy==="filter"){continue;}else if(this.strategy==="redact"){if(processedMessage){processedMessages.push(processedMessage);}else {processedMessages.push(message);}continue;}}processedMessages.push(message);}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}throw new Error(`PII detection failed: ${error instanceof Error?error.stack:"Unknown error"}`);}}/**
125
126
  * Detect PII using the internal agent
126
127
  */async detectPII(content,tracingContext){const prompt=this.createDetectionPrompt(content);const schema=z9.object({categories:z9.object(this.detectionTypes.reduce((props,type)=>{props[type]=z9.number().min(0).max(1).optional();return props;},{})).optional(),detections:z9.array(z9.object({type:z9.string(),value:z9.string(),confidence:z9.number().min(0).max(1),start:z9.number(),end:z9.number(),redacted_value:z9.string().optional()})).optional(),redacted_content:z9.string().optional()});try{const model=await this.detectionAgent.getModel();let response;if(model.specificationVersion==="v2"){response=await this.detectionAgent.generateVNext(prompt,{output:schema,modelSettings:{temperature:0},tracingContext});}else {response=await this.detectionAgent.generate(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;if(!result.redacted_content&&result.detections&&result.detections.length>0){result.redacted_content=this.applyRedactionMethod(content,result.detections);result.detections=result.detections.map(detection=>({...detection,redacted_value:detection.redacted_value||this.redactValue(detection.value,detection.type)}));}return result;}catch(error){console.warn("[PIIDetector] Detection agent failed, allowing content:",error);return {};}}/**
127
128
  * Determine if PII is flagged based on detections or category scores above threshold
@@ -163,7 +164,7 @@ Content: "${content}"`;}};// src/agent/input-processor/processors/pii-detector.t
163
164
  var PIIDetectorInputProcessor=class{name="pii-detector";processor;constructor(options){this.processor=new PIIDetector(options);}async process(args){return this.processor.processInput(args);}};// src/processors/processors/language-detector.ts
164
165
  var LanguageDetector=class _LanguageDetector{name="language-detector";detectionAgent;targetLanguages;threshold;strategy;preserveOriginal;minTextLength;includeDetectionDetails;translationQuality;// Default target language
165
166
  static DEFAULT_TARGET_LANGUAGES=["English","en"];// Common language codes and names mapping
166
- static LANGUAGE_MAP={en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",pt:"Portuguese",ru:"Russian",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Chinese (Simplified)","zh-tw":"Chinese (Traditional)",ar:"Arabic",hi:"Hindi",th:"Thai",vi:"Vietnamese",tr:"Turkish",pl:"Polish",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",el:"Greek",he:"Hebrew",cs:"Czech",hu:"Hungarian",ro:"Romanian",bg:"Bulgarian",hr:"Croatian",sk:"Slovak",sl:"Slovenian",et:"Estonian",lv:"Latvian",lt:"Lithuanian",uk:"Ukrainian",be:"Belarusian"};constructor(options){this.targetLanguages=options.targetLanguages||_LanguageDetector.DEFAULT_TARGET_LANGUAGES;this.threshold=options.threshold??0.7;this.strategy=options.strategy||"detect";this.preserveOriginal=options.preserveOriginal??true;this.minTextLength=options.minTextLength??10;this.includeDetectionDetails=options.includeDetectionDetails??false;this.translationQuality=options.translationQuality||"quality";this.detectionAgent=new Agent({name:"language-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model});}async processInput(args){try{const{messages,abort}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(textContent.length<this.minTextLength){processedMessages.push(message);continue;}const detectionResult=await this.detectLanguage(textContent);if(detectionResult.confidence&&detectionResult.confidence<this.threshold){processedMessages.push(message);continue;}if(!this.isNonTargetLanguage(detectionResult)){const targetLanguageCode=this.getLanguageCode(this.targetLanguages[0]);const targetMessage=this.addLanguageMetadata(message,{iso_code:targetLanguageCode,confidence:0.95});if(this.includeDetectionDetails){console.info(`[LanguageDetector] Content in target language: Language detected: ${this.getLanguageName(targetLanguageCode)} (${targetLanguageCode}) with confidence 0.95`);}processedMessages.push(targetMessage);continue;}const processedMessage=await this.handleDetectedLanguage(message,detectionResult,this.strategy,abort);if(processedMessage){processedMessages.push(processedMessage);}else {continue;}}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}args.abort(`Language detection failed: ${error instanceof Error?error.message:"Unknown error"}`);}}/**
167
+ static LANGUAGE_MAP={en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",pt:"Portuguese",ru:"Russian",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Chinese (Simplified)","zh-tw":"Chinese (Traditional)",ar:"Arabic",hi:"Hindi",th:"Thai",vi:"Vietnamese",tr:"Turkish",pl:"Polish",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",el:"Greek",he:"Hebrew",cs:"Czech",hu:"Hungarian",ro:"Romanian",bg:"Bulgarian",hr:"Croatian",sk:"Slovak",sl:"Slovenian",et:"Estonian",lv:"Latvian",lt:"Lithuanian",uk:"Ukrainian",be:"Belarusian"};constructor(options){this.targetLanguages=options.targetLanguages||_LanguageDetector.DEFAULT_TARGET_LANGUAGES;this.threshold=options.threshold??0.7;this.strategy=options.strategy||"detect";this.preserveOriginal=options.preserveOriginal??true;this.minTextLength=options.minTextLength??10;this.includeDetectionDetails=options.includeDetectionDetails??false;this.translationQuality=options.translationQuality||"quality";this.detectionAgent=new Agent({name:"language-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(textContent.length<this.minTextLength){processedMessages.push(message);continue;}const detectionResult=await this.detectLanguage(textContent);if(detectionResult.confidence&&detectionResult.confidence<this.threshold){processedMessages.push(message);continue;}if(!this.isNonTargetLanguage(detectionResult)){const targetLanguageCode=this.getLanguageCode(this.targetLanguages[0]);const targetMessage=this.addLanguageMetadata(message,{iso_code:targetLanguageCode,confidence:0.95});if(this.includeDetectionDetails){console.info(`[LanguageDetector] Content in target language: Language detected: ${this.getLanguageName(targetLanguageCode)} (${targetLanguageCode}) with confidence 0.95`);}processedMessages.push(targetMessage);continue;}const processedMessage=await this.handleDetectedLanguage(message,detectionResult,this.strategy,abort);if(processedMessage){processedMessages.push(processedMessage);}else {continue;}}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}args.abort(`Language detection failed: ${error instanceof Error?error.message:"Unknown error"}`);}}/**
167
168
  * Detect language using the internal agent
168
169
  */async detectLanguage(content){const prompt=this.createDetectionPrompt(content);try{const model=await this.detectionAgent.getModel();let response;const schema=z9.object({iso_code:z9.string().optional(),confidence:z9.number().min(0).max(1).optional(),translated_text:z9.string().optional()});if(model.specificationVersion==="v2"){response=await this.detectionAgent.generateVNext(prompt,{output:schema,modelSettings:{temperature:0}});}else {response=await this.detectionAgent.generate(prompt,{output:schema,temperature:0});}if(response.object.translated_text&&!response.object.confidence){response.object.confidence=0.95;}return response.object;}catch(error){console.warn("[LanguageDetector] Detection agent failed, assuming target language:",error);return {};}}/**
169
170
  * Determine if language detection indicates non-target language
@@ -218,7 +219,7 @@ var DefaultExecutionEngine=class extends ExecutionEngine{/**
218
219
  *
219
220
  * @param stepId - The id of the step.
220
221
  * @returns The run count for the step.
221
- */getOrGenerateRunCount(stepId){if(this.runCounts.has(stepId)){const currentRunCount=this.runCounts.get(stepId);const nextRunCount=currentRunCount+1;this.runCounts.set(stepId,nextRunCount);return nextRunCount;}const runCount=0;this.runCounts.set(stepId,runCount);return runCount;}async fmtReturnValue(executionSpan,emitter,stepResults,lastOutput,error){const base={status:lastOutput.status,steps:stepResults,input:stepResults.input};if(lastOutput.status==="success"){await emitter.emit("watch",{type:"watch",payload:{workflowState:{status:lastOutput.status,steps:stepResults,result:lastOutput.output}},eventTimestamp:Date.now()});base.result=lastOutput.output;}else if(lastOutput.status==="failed"){await emitter.emit("watch",{type:"watch",payload:{workflowState:{status:lastOutput.status,steps:stepResults,result:null,error:lastOutput.error}},eventTimestamp:Date.now()});base.error=error instanceof Error?error?.stack??error:lastOutput.error??(typeof error==="string"?error:new Error("Unknown error: "+error)?.stack??new Error("Unknown error: "+error));}else if(lastOutput.status==="suspended"){const suspendedStepIds=Object.entries(stepResults).flatMap(([stepId,stepResult])=>{if(stepResult?.status==="suspended"){const nestedPath=stepResult?.suspendPayload?.__workflow_meta?.path;return nestedPath?[[stepId,...nestedPath]]:[[stepId]];}return [];});base.suspended=suspendedStepIds;await emitter.emit("watch",{type:"watch",payload:{workflowState:{status:lastOutput.status,steps:stepResults,result:null,error:null}},eventTimestamp:Date.now()});}executionSpan?.end();return base;}/**
222
+ */getOrGenerateRunCount(stepId){if(this.runCounts.has(stepId)){const currentRunCount=this.runCounts.get(stepId);const nextRunCount=currentRunCount+1;this.runCounts.set(stepId,nextRunCount);return nextRunCount;}const runCount=0;this.runCounts.set(stepId,runCount);return runCount;}async fmtReturnValue(executionSpan,emitter,stepResults,lastOutput,error){const base={status:lastOutput.status,steps:stepResults,input:stepResults.input};if(lastOutput.status==="success"){await emitter.emit("watch",{type:"watch",payload:{workflowState:{status:lastOutput.status,steps:stepResults,result:lastOutput.output}},eventTimestamp:Date.now()});base.result=lastOutput.output;}else if(lastOutput.status==="failed"){await emitter.emit("watch",{type:"watch",payload:{workflowState:{status:lastOutput.status,steps:stepResults,result:null,error:lastOutput.error}},eventTimestamp:Date.now()});if(error instanceof Error){base.error=error?.stack??error;}else if(lastOutput.error){base.error=lastOutput.error;}else if(typeof error==="string"){base.error=error;}else {const errorMessage=safeParseErrorObject(error);const errorObj=new Error("Unknown error: "+errorMessage);base.error=errorObj?.stack??errorObj;}}else if(lastOutput.status==="suspended"){const suspendedStepIds=Object.entries(stepResults).flatMap(([stepId,stepResult])=>{if(stepResult?.status==="suspended"){const nestedPath=stepResult?.suspendPayload?.__workflow_meta?.path;return nestedPath?[[stepId,...nestedPath]]:[[stepId]];}return [];});base.suspended=suspendedStepIds;await emitter.emit("watch",{type:"watch",payload:{workflowState:{status:lastOutput.status,steps:stepResults,result:null,error:null}},eventTimestamp:Date.now()});}executionSpan?.end();return base;}/**
222
223
  * Executes a workflow run with the provided execution graph and input
223
224
  * @param graph The execution graph to execute
224
225
  * @param input The input data for the workflow
@@ -313,7 +314,7 @@ async execute({runId,inputData,resumeData,suspend,resume,[EMITTER_SYMBOL]:emitte
313
314
  * Starts the workflow execution with the provided input as a stream
314
315
  * @param input The input data for the workflow
315
316
  * @returns A promise that resolves to the workflow output
316
- */stream({inputData,runtimeContext,onChunk,tracingContext}={}){if(this.closeStreamAction){return {stream:this.observeStream().stream,getWorkflowState:()=>this.executionResults};}const{readable,writable}=new TransformStream();const writer=writable.getWriter();const unwatch=this.watch(async event=>{try{const e={...event,type:event.type.replace("workflow-","")};await writer.write(e);if(onChunk){await onChunk(e);}}catch{}},"watch-v2");this.closeStreamAction=async()=>{this.emitter.emit("watch-v2",{type:"workflow-finish",payload:{runId:this.runId}});unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writer.close();}catch(err){console.error("Error closing stream:",err);}finally{writer.releaseLock();}};this.emitter.emit("watch-v2",{type:"workflow-start",payload:{runId:this.runId}});this.executionResults=this._start({inputData,runtimeContext,format:"aisdk",tracingContext}).then(result=>{if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});return {stream:readable,getWorkflowState:()=>this.executionResults};}/**
317
+ */stream({inputData,runtimeContext,onChunk,tracingContext,tracingOptions}={}){if(this.closeStreamAction){return {stream:this.observeStream().stream,getWorkflowState:()=>this.executionResults};}const{readable,writable}=new TransformStream();const writer=writable.getWriter();const unwatch=this.watch(async event=>{try{const e={...event,type:event.type.replace("workflow-","")};await writer.write(e);if(onChunk){await onChunk(e);}}catch{}},"watch-v2");this.closeStreamAction=async()=>{this.emitter.emit("watch-v2",{type:"workflow-finish",payload:{runId:this.runId}});unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writer.close();}catch(err){console.error("Error closing stream:",err);}finally{writer.releaseLock();}};this.emitter.emit("watch-v2",{type:"workflow-start",payload:{runId:this.runId}});this.executionResults=this._start({inputData,runtimeContext,format:"aisdk",tracingContext,tracingOptions}).then(result=>{if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});return {stream:readable,getWorkflowState:()=>this.executionResults};}/**
317
318
  * Observe the workflow stream
318
319
  * @returns A readable stream of the workflow events
319
320
  */observeStream(){const{readable,writable}=new TransformStream();const writer=writable.getWriter();const unwatch=this.watch(async event=>{try{const e={...event,type:event.type.replace("workflow-","")};await writer.write(e);}catch{}},"watch-v2");this.#observerHandlers.push(async()=>{unwatch();try{await writer.close();}catch(err){console.error("Error closing stream:",err);}finally{writer.releaseLock();}});return {stream:readable};}/**
@@ -323,11 +324,11 @@ async execute({runId,inputData,resumeData,suspend,resume,[EMITTER_SYMBOL]:emitte
323
324
  * Starts the workflow execution with the provided input as a stream
324
325
  * @param input The input data for the workflow
325
326
  * @returns A promise that resolves to the workflow output
326
- */streamVNext({inputData,runtimeContext,tracingContext,format,closeOnSuspend=true}={}){if(this.closeStreamAction&&this.activeStream){return this.activeStream;}this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._start({inputData,runtimeContext,tracingContext,writableStream:writable,format}).then(result=>{if(closeOnSuspend){this.closeStreamAction?.().catch(()=>{});}else if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}/**
327
+ */streamVNext({inputData,runtimeContext,tracingContext,tracingOptions,format,closeOnSuspend=true}={}){if(this.closeStreamAction&&this.activeStream){return this.activeStream;}this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._start({inputData,runtimeContext,tracingContext,tracingOptions,writableStream:writable,format}).then(result=>{if(closeOnSuspend){this.closeStreamAction?.().catch(()=>{});}else if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}/**
327
328
  * Resumes the workflow execution with the provided input as a stream
328
329
  * @param input The input data for the workflow
329
330
  * @returns A promise that resolves to the workflow output
330
- */resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,format}={}){this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._resume({resumeData,step,runtimeContext,tracingContext,writableStream:writable,format,isVNext:true}).then(result=>{this.closeStreamAction?.().catch(()=>{});return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}watch(cb,type="watch"){const watchCb=event=>{this.updateState(event.payload);cb({type:event.type,payload:this.getState(),eventTimestamp:event.eventTimestamp});};const nestedWatchCb=({event,workflowId})=>{try{const{type:type2,payload,eventTimestamp}=event;const prefixedSteps=Object.fromEntries(Object.entries(payload?.workflowState?.steps??{}).map(([stepId,step])=>[`${workflowId}.${stepId}`,step]));const newPayload={currentStep:{...payload?.currentStep,id:`${workflowId}.${payload?.currentStep?.id}`},workflowState:{steps:prefixedSteps}};this.updateState(newPayload);cb({type:type2,payload:this.getState(),eventTimestamp});}catch(e){console.error(e);}};const nestedWatchV2Cb=({event,workflowId})=>{this.emitter.emit("watch-v2",{...event,...(event.payload?.id?{payload:{...event.payload,id:`${workflowId}.${event.payload.id}`}}:{})});};if(type==="watch"){this.emitter.on("watch",watchCb);this.emitter.on("nested-watch",nestedWatchCb);}else if(type==="watch-v2"){this.emitter.on("watch-v2",cb);this.emitter.on("nested-watch-v2",nestedWatchV2Cb);}return ()=>{if(type==="watch-v2"){this.emitter.off("watch-v2",cb);this.emitter.off("nested-watch-v2",nestedWatchV2Cb);}else {this.emitter.off("watch",watchCb);this.emitter.off("nested-watch",nestedWatchCb);}};}async watchAsync(cb,type="watch"){return this.watch(cb,type);}async resume(params){return this._resume(params);}async _resume(params){const snapshot=await this.#mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:this.workflowId,runId:this.runId});if(!snapshot){throw new Error("No snapshot found for this workflow run: "+this.workflowId+" "+this.runId);}let steps;if(params.step){steps=(Array.isArray(params.step)?params.step:[params.step]).map(step=>typeof step==="string"?step:step?.id);}else {const suspendedStepPaths=[];Object.entries(snapshot?.suspendedPaths??{}).forEach(([stepId,_executionPath])=>{const stepResult=snapshot?.context?.[stepId];if(stepResult&&typeof stepResult==="object"&&"status"in stepResult){const stepRes=stepResult;if(stepRes.status==="suspended"){const nestedPath=stepRes.suspendPayload?.__workflow_meta?.path;if(nestedPath&&Array.isArray(nestedPath)){suspendedStepPaths.push([stepId,...nestedPath]);}else {suspendedStepPaths.push([stepId]);}}}});if(suspendedStepPaths.length===0){throw new Error("No suspended steps found in this workflow run");}if(suspendedStepPaths.length===1){steps=suspendedStepPaths[0];}else {const pathStrings=suspendedStepPaths.map(path=>`[${path.join(", ")}]`);throw new Error(`Multiple suspended steps found: ${pathStrings.join(", ")}. Please specify which step to resume using the "step" parameter.`);}}if(!params.runCount){if(snapshot.status!=="suspended"){throw new Error("This workflow run was not suspended");}const suspendedStepIds=Object.keys(snapshot?.suspendedPaths??{});const isStepSuspended=suspendedStepIds.includes(steps?.[0]??"");if(!isStepSuspended){throw new Error(`This workflow step "${steps?.[0]}" was not suspended. Available suspended steps: [${suspendedStepIds.join(", ")}]`);}}const suspendedStep=this.workflowSteps[steps?.[0]??""];const resumeDataToUse=await this._validateResumeData(params.resumeData,suspendedStep);let runtimeContextInput;if(params.runCount&&params.runCount>0&&params.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new RuntimeContext();Object.entries(snapshot?.runtimeContext??{}).forEach(([key,value])=>{if(!runtimeContextToUse.has(key)){runtimeContextToUse.set(key,value);}});const workflowAISpan=getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:resumeDataToUse,attributes:{workflowId:this.workflowId},tracingPolicy:this.tracingPolicy,tracingOptions:params.tracingOptions,tracingContext:params.tracingContext,runtimeContext:runtimeContextToUse});const traceId=getValidTraceId(workflowAISpan);const executionResultPromise=this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:snapshot?.context?.input,resume:{steps,stepResults,resumePayload:resumeDataToUse,// @ts-ignore
331
+ */resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,format}={}){this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._resume({resumeData,step,runtimeContext,tracingContext,tracingOptions,writableStream:writable,format,isVNext:true}).then(result=>{this.closeStreamAction?.().catch(()=>{});return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}watch(cb,type="watch"){const watchCb=event=>{this.updateState(event.payload);cb({type:event.type,payload:this.getState(),eventTimestamp:event.eventTimestamp});};const nestedWatchCb=({event,workflowId})=>{try{const{type:type2,payload,eventTimestamp}=event;const prefixedSteps=Object.fromEntries(Object.entries(payload?.workflowState?.steps??{}).map(([stepId,step])=>[`${workflowId}.${stepId}`,step]));const newPayload={currentStep:{...payload?.currentStep,id:`${workflowId}.${payload?.currentStep?.id}`},workflowState:{steps:prefixedSteps}};this.updateState(newPayload);cb({type:type2,payload:this.getState(),eventTimestamp});}catch(e){console.error(e);}};const nestedWatchV2Cb=({event,workflowId})=>{this.emitter.emit("watch-v2",{...event,...(event.payload?.id?{payload:{...event.payload,id:`${workflowId}.${event.payload.id}`}}:{})});};if(type==="watch"){this.emitter.on("watch",watchCb);this.emitter.on("nested-watch",nestedWatchCb);}else if(type==="watch-v2"){this.emitter.on("watch-v2",cb);this.emitter.on("nested-watch-v2",nestedWatchV2Cb);}return ()=>{if(type==="watch-v2"){this.emitter.off("watch-v2",cb);this.emitter.off("nested-watch-v2",nestedWatchV2Cb);}else {this.emitter.off("watch",watchCb);this.emitter.off("nested-watch",nestedWatchCb);}};}async watchAsync(cb,type="watch"){return this.watch(cb,type);}async resume(params){return this._resume(params);}async _resume(params){const snapshot=await this.#mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:this.workflowId,runId:this.runId});if(!snapshot){throw new Error("No snapshot found for this workflow run: "+this.workflowId+" "+this.runId);}let steps;if(params.step){steps=(Array.isArray(params.step)?params.step:[params.step]).map(step=>typeof step==="string"?step:step?.id);}else {const suspendedStepPaths=[];Object.entries(snapshot?.suspendedPaths??{}).forEach(([stepId,_executionPath])=>{const stepResult=snapshot?.context?.[stepId];if(stepResult&&typeof stepResult==="object"&&"status"in stepResult){const stepRes=stepResult;if(stepRes.status==="suspended"){const nestedPath=stepRes.suspendPayload?.__workflow_meta?.path;if(nestedPath&&Array.isArray(nestedPath)){suspendedStepPaths.push([stepId,...nestedPath]);}else {suspendedStepPaths.push([stepId]);}}}});if(suspendedStepPaths.length===0){throw new Error("No suspended steps found in this workflow run");}if(suspendedStepPaths.length===1){steps=suspendedStepPaths[0];}else {const pathStrings=suspendedStepPaths.map(path=>`[${path.join(", ")}]`);throw new Error(`Multiple suspended steps found: ${pathStrings.join(", ")}. Please specify which step to resume using the "step" parameter.`);}}if(!params.runCount){if(snapshot.status!=="suspended"){throw new Error("This workflow run was not suspended");}const suspendedStepIds=Object.keys(snapshot?.suspendedPaths??{});const isStepSuspended=suspendedStepIds.includes(steps?.[0]??"");if(!isStepSuspended){throw new Error(`This workflow step "${steps?.[0]}" was not suspended. Available suspended steps: [${suspendedStepIds.join(", ")}]`);}}const suspendedStep=this.workflowSteps[steps?.[0]??""];const resumeDataToUse=await this._validateResumeData(params.resumeData,suspendedStep);let runtimeContextInput;if(params.runCount&&params.runCount>0&&params.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new RuntimeContext();Object.entries(snapshot?.runtimeContext??{}).forEach(([key,value])=>{if(!runtimeContextToUse.has(key)){runtimeContextToUse.set(key,value);}});const workflowAISpan=getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:resumeDataToUse,attributes:{workflowId:this.workflowId},tracingPolicy:this.tracingPolicy,tracingOptions:params.tracingOptions,tracingContext:params.tracingContext,runtimeContext:runtimeContextToUse});const traceId=getValidTraceId(workflowAISpan);const executionResultPromise=this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:snapshot?.context?.input,resume:{steps,stepResults,resumePayload:resumeDataToUse,// @ts-ignore
331
332
  resumePath:snapshot?.suspendedPaths?.[steps?.[0]]},format:params.format,emitter:{emit:(event,data)=>{this.emitter.emit(event,data);return Promise.resolve();},on:(event,callback)=>{this.emitter.on(event,callback);},off:(event,callback)=>{this.emitter.off(event,callback);},once:(event,callback)=>{this.emitter.once(event,callback);}},runtimeContext:runtimeContextToUse,abortController:this.abortController,workflowAISpan}).then(result=>{if(!params.isVNext&&result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}result.traceId=traceId;return result;});this.executionResults=executionResultPromise;return executionResultPromise;}/**
332
333
  * Returns the current state of the workflow run
333
334
  * @returns The current state of the workflow run
@@ -341,7 +342,7 @@ toolCalls:z9.array(z9.any()).optional(),// TypedToolCall[]
341
342
  toolResults:z9.array(z9.any()).optional(),// TypedToolResult[]
342
343
  sources:z9.array(z9.any()).optional(),// LanguageModelV2Source[]
343
344
  staticToolCalls:z9.array(z9.any()).optional(),dynamicToolCalls:z9.array(z9.any()).optional(),staticToolResults:z9.array(z9.any()).optional(),dynamicToolResults:z9.array(z9.any()).optional(),usage:languageModelUsageSchema,steps:z9.array(z9.any())// StepResult[]
344
- }),metadata:z9.object({id:z9.string().optional(),model:z9.string().optional(),modelId:z9.string().optional(),timestamp:z9.date().optional(),providerMetadata:z9.record(z9.any()).optional(),headers:z9.record(z9.string()).optional(),request:z9.record(z9.any()).optional()}),stepResult:llmIterationStepResultSchema});var toolCallInputSchema=z9.object({toolCallId:z9.string(),toolName:z9.string(),args:z9.record(z9.any()),providerMetadata:z9.record(z9.any()).optional(),providerExecuted:z9.boolean().optional(),output:z9.any().optional()});var toolCallOutputSchema=toolCallInputSchema.extend({result:z9.any(),error:z9.any().optional()});// src/loop/workflows/agentic-execution/llm-execution-step.ts
345
+ }),metadata:z9.object({id:z9.string().optional(),model:z9.string().optional(),modelId:z9.string().optional(),modelMetadata:z9.object({modelId:z9.string(),modelVersion:z9.string(),modelProvider:z9.string()}).optional(),timestamp:z9.date().optional(),providerMetadata:z9.record(z9.any()).optional(),headers:z9.record(z9.string()).optional(),request:z9.record(z9.any()).optional()}),stepResult:llmIterationStepResultSchema});var toolCallInputSchema=z9.object({toolCallId:z9.string(),toolName:z9.string(),args:z9.record(z9.any()),providerMetadata:z9.record(z9.any()).optional(),providerExecuted:z9.boolean().optional(),output:z9.any().optional()});var toolCallOutputSchema=toolCallInputSchema.extend({result:z9.any(),error:z9.any().optional()});// src/loop/workflows/agentic-execution/llm-execution-step.ts
345
346
  function asJsonSchema(schema){if(!schema){return void 0;}if(schema&&typeof schema==="object"&&!schema.safeParse&&!schema.jsonSchema){return schema;}return asSchema(schema).jsonSchema;}function getTransformedSchema(schema){let jsonSchema2;jsonSchema2=asJsonSchema(schema);if(!jsonSchema2){return void 0;}const{$schema,...itemSchema}=jsonSchema2;if(itemSchema.type==="array"){const innerElement=itemSchema.items;const arrayOutputSchema={$schema,type:"object",properties:{elements:{type:"array",items:innerElement}},required:["elements"],additionalProperties:false};return {jsonSchema:arrayOutputSchema,outputFormat:"array"};}if(itemSchema.enum&&Array.isArray(itemSchema.enum)){const enumOutputSchema={$schema,type:"object",properties:{result:{type:itemSchema.type||"string",enum:itemSchema.enum}},required:["result"],additionalProperties:false};return {jsonSchema:enumOutputSchema,outputFormat:"enum"};}return {jsonSchema:jsonSchema2,outputFormat:jsonSchema2.type// 'object'
346
347
  };}function getResponseFormat(schema){if(schema){const transformedSchema=getTransformedSchema(schema);return {type:"json",schema:transformedSchema?.jsonSchema};}return {type:"text"};}// src/stream/base/input.ts
347
348
  var MastraModelInput=class extends MastraBase{initialize({runId,createStream,onResult}){const self=this;const stream=new ReadableStream({async start(controller){try{const stream2=await createStream();onResult({warnings:stream2.warnings,request:stream2.request,rawResponse:stream2.rawResponse||stream2.response||{}});await self.transform({runId,stream:stream2.stream,controller});controller.close();}catch(error){controller.error(error);}}});return stream;}};// src/stream/aisdk/v5/transform.ts
@@ -362,7 +363,7 @@ var AISDKV5InputStream=class extends MastraModelInput{constructor({component,nam
362
363
  function getModelSupport(modelId,provider){return modelSupports.find(m=>m.modelId===modelId&&m.provider===provider);}var modelSupports=[];// src/stream/aisdk/v5/execute.ts
363
364
  function execute({runId,model,providerOptions,inputMessages,tools,toolChoice,options,onResult,modelStreamSpan,telemetry_settings,includeRawChunks,modelSettings,output,headers,shouldThrowError}){const v5=new AISDKV5InputStream({component:"LLM",name:model.modelId});const toolsAndToolChoice=prepareToolsAndToolChoice({tools,toolChoice,activeTools:options?.activeTools});if(modelStreamSpan&&toolsAndToolChoice?.tools?.length&&telemetry_settings?.recordOutputs!==false){modelStreamSpan.setAttributes({"stream.prompt.tools":toolsAndToolChoice?.tools?.map(tool=>JSON.stringify(tool))});}const modelSupports2=getModelSupport(model.modelId,model.provider);const modelSupportsResponseFormat=modelSupports2?.capabilities.responseFormat?.support==="full";const responseFormat=output?getResponseFormat(output):void 0;let prompt=inputMessages;if(output&&responseFormat?.type==="json"&&!modelSupportsResponseFormat){prompt=injectJsonInstructionIntoMessages({messages:inputMessages,schema:responseFormat.schema});}const stream=v5.initialize({runId,onResult,createStream:async()=>{try{const streamResult=await model.doStream({...toolsAndToolChoice,prompt,providerOptions,abortSignal:options?.abortSignal,includeRawChunks,responseFormat:modelSupportsResponseFormat?responseFormat:void 0,...(modelSettings??{}),headers});return streamResult;}catch(error){console.error("Error creating stream",error);if(isAbortError$1(error)&&options?.abortSignal?.aborted){console.error("Abort error",error);}if(shouldThrowError){throw error;}return {stream:new ReadableStream({start:async controller=>{controller.enqueue({type:"error",error:{message:error instanceof Error?error.message:JSON.stringify(error),stack:error instanceof Error?error.stack:void 0}});controller.close();}}),warnings:[],request:{},rawResponse:{}};}}});return stream;}// src/stream/aisdk/v5/output-helpers.ts
364
365
  var DefaultStepResult=class{content;finishReason;usage;warnings;request;response;providerMetadata;constructor({content,finishReason,usage,warnings,request,response,providerMetadata}){this.content=content;this.finishReason=finishReason;this.usage=usage;this.warnings=warnings;this.request=request;this.response=response;this.providerMetadata=providerMetadata;}get text(){return this.content.filter(part=>part.type==="text").map(part=>part.text).join("");}get reasoning(){return this.content.filter(part=>part.type==="reasoning");}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(part=>part.text).join("");}get files(){return this.content.filter(part=>part.type==="file").map(part=>part.file);}get sources(){return this.content.filter(part=>part.type==="source");}get toolCalls(){return this.content.filter(part=>part.type==="tool-call");}get staticToolCalls(){return this.toolCalls.filter(toolCall=>toolCall.dynamic===false);}get dynamicToolCalls(){return this.toolCalls.filter(toolCall=>toolCall.dynamic===true);}get toolResults(){return this.content.filter(part=>part.type==="tool-result");}get staticToolResults(){return this.toolResults.filter(toolResult=>toolResult.dynamic===false);}get dynamicToolResults(){return this.toolResults.filter(toolResult=>toolResult.dynamic===true);}};// src/loop/workflows/run-state.ts
365
- var AgenticRunState=class{#state;constructor({_internal,model}){this.#state={responseMetadata:{id:_internal?.generateId?.(),timestamp:_internal?.currentDate?.(),modelId:model.modelId,modelVersion:model.specificationVersion,modelProvider:model.provider,headers:void 0},isReasoning:false,isStreaming:false,providerOptions:void 0,hasToolCallStreaming:false,hasErrored:false,reasoningDeltas:[],textDeltas:[],stepResult:void 0};}setState(state){this.#state={...this.#state,...state};}get state(){return this.#state;}};// src/loop/workflows/agentic-execution/llm-execution-step.ts
366
+ var AgenticRunState=class{#state;constructor({_internal,model}){this.#state={responseMetadata:{id:_internal?.generateId?.(),timestamp:_internal?.currentDate?.(),modelId:model.modelId,modelVersion:model.specificationVersion,modelProvider:model.provider,headers:void 0},modelMetadata:{modelId:model.modelId,modelVersion:model.specificationVersion,modelProvider:model.provider},isReasoning:false,isStreaming:false,providerOptions:void 0,hasToolCallStreaming:false,hasErrored:false,reasoningDeltas:[],textDeltas:[],stepResult:void 0};}setState(state){this.#state={...this.#state,...state};}get state(){return this.#state;}};// src/loop/workflows/agentic-execution/llm-execution-step.ts
366
367
  async function processOutputStream({tools,messageId,messageList,outputStream,runState,options,controller,responseFromModel,includeRawChunks}){for await(const chunk of outputStream.fullStream){if(!chunk){continue;}if(chunk.type=="object"){continue;}if(chunk.type!=="reasoning-delta"&&chunk.type!=="reasoning-signature"&&chunk.type!=="redacted-reasoning"&&runState.state.isReasoning){if(runState.state.reasoningDeltas.length){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:runState.state.reasoningDeltas.join(""),signature:chunk.payload.signature,providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");}runState.setState({isReasoning:false,reasoningDeltas:[]});}if(chunk.type!=="text-delta"&&chunk.type!=="tool-call"&&// not 100% sure about this being the right fix.
367
368
  // basically for some llm providers they add response-metadata after each text-delta
368
369
  // we then flush the chunks by calling messageList.add (a few lines down)
@@ -371,7 +372,7 @@ async function processOutputStream({tools,messageId,messageList,outputStream,run
371
372
  // BUT does this cause other issues?
372
373
  // Alternative solution: in message list allow combining text deltas together when the message source is "response" and the text parts are directly next to each other
373
374
  // simple solution for now is to not flush text deltas on response-metadata
374
- chunk.type!=="response-metadata"&&runState.state.isStreaming){if(runState.state.textDeltas.length){const textStartPayload=chunk.payload;const providerMetadata=textStartPayload.providerMetadata??runState.state.providerOptions;messageList.add({id:messageId,role:"assistant",content:[providerMetadata?{type:"text",text:runState.state.textDeltas.join(""),providerOptions:providerMetadata}:{type:"text",text:runState.state.textDeltas.join("")}]},"response");}runState.setState({isStreaming:false,textDeltas:[]});}switch(chunk.type){case "response-metadata":runState.setState({responseMetadata:{id:chunk.payload.id,timestamp:chunk.payload.timestamp,modelId:chunk.payload.modelId,headers:chunk.payload.headers}});break;case "text-delta":{const textDeltasFromState=runState.state.textDeltas;textDeltasFromState.push(chunk.payload.text);runState.setState({textDeltas:textDeltasFromState,isStreaming:true});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-input-streaming-start":{const tool=tools?.[chunk.payload.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputStart"in tool){try{await tool?.onInputStart?.({toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputStart",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-delta":{const tool=tools?.[chunk.payload.toolName||""]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputDelta"in tool){try{await tool?.onInputDelta?.({inputTextDelta:chunk.payload.argsTextDelta,toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputDelta",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-start":{runState.setState({providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(Object.values(chunk.payload.providerMetadata||{}).find(v=>v?.redactedData)){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:"",providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-delta":{const reasoningDeltasFromState=runState.state.reasoningDeltas;reasoningDeltasFromState.push(chunk.payload.text);runState.setState({isReasoning:true,reasoningDeltas:reasoningDeltasFromState,providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "file":messageList.add({id:messageId,role:"assistant",content:[{type:"file",data:chunk.payload.data,mimeType:chunk.payload.mimeType}]},"response");controller.enqueue(chunk);break;case "source":messageList.add({id:messageId,role:"assistant",content:{format:2,parts:[{type:"source",source:{sourceType:"url",id:chunk.payload.id,url:chunk.payload.url||"",title:chunk.payload.title,providerMetadata:chunk.payload.providerMetadata}}]},createdAt:/* @__PURE__ */new Date()},"response");controller.enqueue(chunk);break;case "finish":runState.setState({providerOptions:chunk.payload.metadata.providerMetadata,stepResult:{reason:chunk.payload.reason,logprobs:chunk.payload.logprobs,warnings:responseFromModel.warnings,totalUsage:chunk.payload.totalUsage,headers:responseFromModel.rawResponse?.headers,messageId,isContinued:!["stop","error"].includes(chunk.payload.stepResult.reason),request:responseFromModel.request}});break;case "error":if(isAbortError(chunk.payload.error)&&options?.abortSignal?.aborted){break;}runState.setState({hasErrored:true});runState.setState({stepResult:{isContinued:false,reason:"error"}});let e=chunk.payload.error;if(typeof e==="object"){e=new Error(e?.message||"Unknown error");Object.assign(e,chunk.payload.error);}controller.enqueue({...chunk,payload:{...chunk.payload,error:e}});await options?.onError?.({error:e});break;default:if(isControllerOpen(controller)){controller.enqueue(chunk);}}if(["text-delta","reasoning-delta","source","tool-call","tool-call-input-streaming-start","tool-call-delta","raw"].includes(chunk.type)){const transformedChunk=convertMastraChunkToAISDKv5({chunk});if(chunk.type==="raw"&&!includeRawChunks){return;}await options?.onChunk?.({chunk:transformedChunk});}if(runState.state.hasErrored){break;}}}function executeStreamWithFallbackModels(models){return async callback=>{let index=0;let finalResult;let done=false;for(const modelConfig of models){index++;const maxRetries=modelConfig.maxRetries||0;let attempt=0;if(done){break;}while(attempt<=maxRetries){try{const isLastModel=attempt===maxRetries&&index===models.length;const result=await callback(modelConfig.model,isLastModel);finalResult=result;done=true;break;}catch(err){attempt++;console.error(`Error executing model ${modelConfig.model.modelId}, attempt ${attempt}====`,err);if(attempt>maxRetries){break;}}}}return finalResult;};}function createLLMExecutionStep({models,_internal,messageId,runId,modelStreamSpan,telemetry_settings,tools,toolChoice,messageList,includeRawChunks,modelSettings,providerOptions,options,toolCallStreaming,controller,output,outputProcessors,headers,downloadRetries,downloadConcurrency}){return createStep({id:"llm-execution",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,execute:async({inputData,bail,tracingContext})=>{let modelResult;let warnings;let request;let rawResponse;const{outputStream,callBail,runState}=await executeStreamWithFallbackModels(models)(async(model,isLastModel)=>{const runState2=new AgenticRunState({_internal,model});switch(model.specificationVersion){case "v2":{const messageListPromptArgs={downloadRetries,downloadConcurrency,supportedUrls:model?.supportedUrls};let inputMessages=await messageList.get.all.aiV5.llmPrompt(messageListPromptArgs);let stepModel=model;let stepToolChoice=toolChoice;let stepTools=tools;if(options?.prepareStep){try{const prepareStepResult=await options.prepareStep({stepNumber:inputData.output?.steps?.length||0,steps:inputData.output?.steps||[],model,messages:messageList.get.all.aiV5.model()});if(prepareStepResult){if(prepareStepResult.model){stepModel=prepareStepResult.model;}if(prepareStepResult.toolChoice){stepToolChoice=prepareStepResult.toolChoice;}if(prepareStepResult.activeTools&&stepTools){const activeToolsSet=new Set(prepareStepResult.activeTools);stepTools=Object.fromEntries(Object.entries(stepTools).filter(([toolName])=>activeToolsSet.has(toolName)));}if(prepareStepResult.messages){const newMessages=prepareStepResult.messages;const newMessageList=new MessageList();for(const message of newMessages){if(message.role==="system"){newMessageList.addSystem(message);}else if(message.role==="user"){newMessageList.add(message,"input");}else if(message.role==="assistant"||message.role==="tool"){newMessageList.add(message,"response");}}inputMessages=await newMessageList.get.all.aiV5.llmPrompt(messageListPromptArgs);}}}catch(error){console.error("Error in prepareStep callback:",error);}}modelResult=execute({runId,model:stepModel,providerOptions,inputMessages,tools:stepTools,toolChoice:stepToolChoice,options,modelSettings,telemetry_settings,includeRawChunks,output,headers,onResult:({warnings:warningsFromStream,request:requestFromStream,rawResponse:rawResponseFromStream})=>{warnings=warningsFromStream;request=requestFromStream||{};rawResponse=rawResponseFromStream;if(!isControllerOpen(controller)){return;}controller.enqueue({runId,from:"AGENT"/* AGENT */,type:"step-start",payload:{request:request||{},warnings:warnings||[],messageId}});},modelStreamSpan,shouldThrowError:!isLastModel});break;}default:{throw new Error(`Unsupported model version: ${model.specificationVersion}`);}}const outputStream2=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion},stream:modelResult,messageList,messageId,options:{runId,rootSpan:modelStreamSpan,toolCallStreaming,telemetry_settings,includeRawChunks,output,outputProcessors,outputProcessorRunnerMode:"stream",tracingContext}});try{await processOutputStream({outputStream:outputStream2,includeRawChunks,tools,messageId,messageList,runState:runState2,options,controller,responseFromModel:{warnings,request,rawResponse}});}catch(error){console.error("Error in LLM Execution Step",error);if(isAbortError(error)&&options?.abortSignal?.aborted){await options?.onAbort?.({steps:inputData?.output?.steps??[]});if(isControllerOpen(controller)){controller.enqueue({type:"abort",runId,from:"AGENT"/* AGENT */,payload:{}});}return {callBail:true,outputStream:outputStream2,runState:runState2};}if(isLastModel){if(isControllerOpen(controller)){controller.enqueue({type:"error",runId,from:"AGENT"/* AGENT */,payload:{error}});}runState2.setState({hasErrored:true,stepResult:{isContinued:false,reason:"error"}});}else {throw error;}}return {outputStream:outputStream2,callBail:false,runState:runState2};});if(callBail){const usage2=outputStream._getImmediateUsage();const responseMetadata2=runState.state.responseMetadata;const text2=outputStream._getImmediateText();return bail({messageId,stepResult:{reason:"abort",warnings,isContinued:false},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata2,headers:rawResponse?.headers,request},output:{text:text2,toolCalls:[],usage:usage2??inputData.output?.usage,steps:[]},messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()}});}if(outputStream.tripwire){runState.setState({stepResult:{isContinued:false,reason:"abort"}});}const toolCalls=outputStream._getImmediateToolCalls()?.map(chunk=>{return chunk.payload;});if(toolCalls.length>0){const assistantContent=[...toolCalls.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,args:toolCall.args};})];messageList.add({id:messageId,role:"assistant",content:assistantContent},"response");}const finishReason=runState?.state?.stepResult?.reason??outputStream._getImmediateFinishReason();const hasErrored=runState.state.hasErrored;const usage=outputStream._getImmediateUsage();const responseMetadata=runState.state.responseMetadata;const text=outputStream._getImmediateText();const tripwireTriggered=outputStream.tripwire;const steps=inputData.output?.steps||[];const existingResponseCount=inputData.messages?.nonUser?.length||0;const allResponseContent=messageList.get.response.aiV5.modelContent(steps.length);const currentIterationContent=allResponseContent.slice(existingResponseCount);steps.push(new DefaultStepResult({warnings:outputStream._getImmediateWarnings(),providerMetadata:runState.state.providerOptions,finishReason:runState.state.stepResult?.reason,content:currentIterationContent,response:{...responseMetadata,...rawResponse,messages:messageList.get.response.aiV5.model()},request,usage:outputStream._getImmediateUsage()}));const messages={all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()};return {messageId,stepResult:{reason:tripwireTriggered?"abort":hasErrored?"error":finishReason,warnings,isContinued:tripwireTriggered?false:!["stop","error"].includes(finishReason)},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata,...rawResponse,headers:rawResponse?.headers,request},output:{text,toolCalls,usage:usage??inputData.output?.usage,steps},messages};}});}// src/loop/workflows/agentic-execution/llm-mapping-step.ts
375
+ chunk.type!=="response-metadata"&&runState.state.isStreaming){if(runState.state.textDeltas.length){const textStartPayload=chunk.payload;const providerMetadata=textStartPayload.providerMetadata??runState.state.providerOptions;messageList.add({id:messageId,role:"assistant",content:[providerMetadata?{type:"text",text:runState.state.textDeltas.join(""),providerOptions:providerMetadata}:{type:"text",text:runState.state.textDeltas.join("")}]},"response");}runState.setState({isStreaming:false,textDeltas:[]});}switch(chunk.type){case "response-metadata":runState.setState({responseMetadata:{id:chunk.payload.id,timestamp:chunk.payload.timestamp,modelId:chunk.payload.modelId,headers:chunk.payload.headers}});break;case "text-delta":{const textDeltasFromState=runState.state.textDeltas;textDeltasFromState.push(chunk.payload.text);runState.setState({textDeltas:textDeltasFromState,isStreaming:true});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-input-streaming-start":{const tool=tools?.[chunk.payload.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputStart"in tool){try{await tool?.onInputStart?.({toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputStart",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-delta":{const tool=tools?.[chunk.payload.toolName||""]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputDelta"in tool){try{await tool?.onInputDelta?.({inputTextDelta:chunk.payload.argsTextDelta,toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputDelta",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-start":{runState.setState({providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(Object.values(chunk.payload.providerMetadata||{}).find(v=>v?.redactedData)){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:"",providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-delta":{const reasoningDeltasFromState=runState.state.reasoningDeltas;reasoningDeltasFromState.push(chunk.payload.text);runState.setState({isReasoning:true,reasoningDeltas:reasoningDeltasFromState,providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "file":messageList.add({id:messageId,role:"assistant",content:[{type:"file",data:chunk.payload.data,mimeType:chunk.payload.mimeType}]},"response");controller.enqueue(chunk);break;case "source":messageList.add({id:messageId,role:"assistant",content:{format:2,parts:[{type:"source",source:{sourceType:"url",id:chunk.payload.id,url:chunk.payload.url||"",title:chunk.payload.title,providerMetadata:chunk.payload.providerMetadata}}]},createdAt:/* @__PURE__ */new Date()},"response");controller.enqueue(chunk);break;case "finish":runState.setState({providerOptions:chunk.payload.metadata.providerMetadata,stepResult:{reason:chunk.payload.reason,logprobs:chunk.payload.logprobs,warnings:responseFromModel.warnings,totalUsage:chunk.payload.totalUsage,headers:responseFromModel.rawResponse?.headers,messageId,isContinued:!["stop","error"].includes(chunk.payload.stepResult.reason),request:responseFromModel.request}});break;case "error":if(isAbortError(chunk.payload.error)&&options?.abortSignal?.aborted){break;}runState.setState({hasErrored:true});runState.setState({stepResult:{isContinued:false,reason:"error"}});let e=chunk.payload.error;if(typeof e==="object"){const errorMessage=safeParseErrorObject(e);e=new Error(errorMessage);Object.assign(e,chunk.payload.error);}controller.enqueue({...chunk,payload:{...chunk.payload,error:e}});await options?.onError?.({error:e});break;default:if(isControllerOpen(controller)){controller.enqueue(chunk);}}if(["text-delta","reasoning-delta","source","tool-call","tool-call-input-streaming-start","tool-call-delta","raw"].includes(chunk.type)){const transformedChunk=convertMastraChunkToAISDKv5({chunk});if(chunk.type==="raw"&&!includeRawChunks){return;}await options?.onChunk?.({chunk:transformedChunk});}if(runState.state.hasErrored){break;}}}function executeStreamWithFallbackModels(models){return async callback=>{let index=0;let finalResult;let done=false;for(const modelConfig of models){index++;const maxRetries=modelConfig.maxRetries||0;let attempt=0;if(done){break;}while(attempt<=maxRetries){try{const isLastModel=attempt===maxRetries&&index===models.length;const result=await callback(modelConfig.model,isLastModel);finalResult=result;done=true;break;}catch(err){attempt++;console.error(`Error executing model ${modelConfig.model.modelId}, attempt ${attempt}====`,err);if(attempt>maxRetries){break;}}}}return finalResult;};}function createLLMExecutionStep({models,_internal,messageId,runId,modelStreamSpan,telemetry_settings,tools,toolChoice,messageList,includeRawChunks,modelSettings,providerOptions,options,toolCallStreaming,controller,output,outputProcessors,headers,downloadRetries,downloadConcurrency}){return createStep({id:"llm-execution",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,execute:async({inputData,bail,tracingContext})=>{let modelResult;let warnings;let request;let rawResponse;const{outputStream,callBail,runState}=await executeStreamWithFallbackModels(models)(async(model,isLastModel)=>{const runState2=new AgenticRunState({_internal,model});switch(model.specificationVersion){case "v2":{const messageListPromptArgs={downloadRetries,downloadConcurrency,supportedUrls:model?.supportedUrls};let inputMessages=await messageList.get.all.aiV5.llmPrompt(messageListPromptArgs);let stepModel=model;let stepToolChoice=toolChoice;let stepTools=tools;if(options?.prepareStep){try{const prepareStepResult=await options.prepareStep({stepNumber:inputData.output?.steps?.length||0,steps:inputData.output?.steps||[],model,messages:messageList.get.all.aiV5.model()});if(prepareStepResult){if(prepareStepResult.model){stepModel=prepareStepResult.model;}if(prepareStepResult.toolChoice){stepToolChoice=prepareStepResult.toolChoice;}if(prepareStepResult.activeTools&&stepTools){const activeToolsSet=new Set(prepareStepResult.activeTools);stepTools=Object.fromEntries(Object.entries(stepTools).filter(([toolName])=>activeToolsSet.has(toolName)));}if(prepareStepResult.messages){const newMessages=prepareStepResult.messages;const newMessageList=new MessageList();for(const message of newMessages){if(message.role==="system"){newMessageList.addSystem(message);}else if(message.role==="user"){newMessageList.add(message,"input");}else if(message.role==="assistant"||message.role==="tool"){newMessageList.add(message,"response");}}inputMessages=await newMessageList.get.all.aiV5.llmPrompt(messageListPromptArgs);}}}catch(error){console.error("Error in prepareStep callback:",error);}}modelResult=execute({runId,model:stepModel,providerOptions,inputMessages,tools:stepTools,toolChoice:stepToolChoice,options,modelSettings,telemetry_settings,includeRawChunks,output,headers,onResult:({warnings:warningsFromStream,request:requestFromStream,rawResponse:rawResponseFromStream})=>{warnings=warningsFromStream;request=requestFromStream||{};rawResponse=rawResponseFromStream;if(!isControllerOpen(controller)){return;}controller.enqueue({runId,from:"AGENT"/* AGENT */,type:"step-start",payload:{request:request||{},warnings:warnings||[],messageId}});},modelStreamSpan,shouldThrowError:!isLastModel});break;}default:{throw new Error(`Unsupported model version: ${model.specificationVersion}`);}}const outputStream2=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion},stream:modelResult,messageList,messageId,options:{runId,rootSpan:modelStreamSpan,toolCallStreaming,telemetry_settings,includeRawChunks,output,outputProcessors,outputProcessorRunnerMode:"stream",tracingContext}});try{await processOutputStream({outputStream:outputStream2,includeRawChunks,tools,messageId,messageList,runState:runState2,options,controller,responseFromModel:{warnings,request,rawResponse}});}catch(error){console.error("Error in LLM Execution Step",error);if(isAbortError(error)&&options?.abortSignal?.aborted){await options?.onAbort?.({steps:inputData?.output?.steps??[]});if(isControllerOpen(controller)){controller.enqueue({type:"abort",runId,from:"AGENT"/* AGENT */,payload:{}});}return {callBail:true,outputStream:outputStream2,runState:runState2};}if(isLastModel){if(isControllerOpen(controller)){controller.enqueue({type:"error",runId,from:"AGENT"/* AGENT */,payload:{error}});}runState2.setState({hasErrored:true,stepResult:{isContinued:false,reason:"error"}});}else {throw error;}}return {outputStream:outputStream2,callBail:false,runState:runState2};});if(callBail){const usage2=outputStream._getImmediateUsage();const responseMetadata2=runState.state.responseMetadata;const text2=outputStream._getImmediateText();return bail({messageId,stepResult:{reason:"abort",warnings,isContinued:false},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata2,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text:text2,toolCalls:[],usage:usage2??inputData.output?.usage,steps:[]},messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()}});}if(outputStream.tripwire){runState.setState({stepResult:{isContinued:false,reason:"abort"}});}const toolCalls=outputStream._getImmediateToolCalls()?.map(chunk=>{return chunk.payload;});if(toolCalls.length>0){const assistantContent=[...toolCalls.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,args:toolCall.args};})];messageList.add({id:messageId,role:"assistant",content:assistantContent},"response");}const finishReason=runState?.state?.stepResult?.reason??outputStream._getImmediateFinishReason();const hasErrored=runState.state.hasErrored;const usage=outputStream._getImmediateUsage();const responseMetadata=runState.state.responseMetadata;const text=outputStream._getImmediateText();const tripwireTriggered=outputStream.tripwire;const steps=inputData.output?.steps||[];const existingResponseCount=inputData.messages?.nonUser?.length||0;const allResponseContent=messageList.get.response.aiV5.modelContent(steps.length);const currentIterationContent=allResponseContent.slice(existingResponseCount);steps.push(new DefaultStepResult({warnings:outputStream._getImmediateWarnings(),providerMetadata:runState.state.providerOptions,finishReason:runState.state.stepResult?.reason,content:currentIterationContent,response:{...responseMetadata,...rawResponse,messages:messageList.get.response.aiV5.model()},request,usage:outputStream._getImmediateUsage()}));const messages={all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()};return {messageId,stepResult:{reason:tripwireTriggered?"abort":hasErrored?"error":finishReason,warnings,isContinued:tripwireTriggered?false:!["stop","error"].includes(finishReason)},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata,...rawResponse,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text,toolCalls,usage:usage??inputData.output?.usage,steps},messages};}});}// src/loop/workflows/agentic-execution/llm-mapping-step.ts
375
376
  function createLLMMappingStep({models,telemetry_settings,_internal,modelStreamSpan,...rest},llmExecutionStep){return createStep({id:"llmExecutionMappingStep",inputSchema:z9.array(toolCallOutputSchema),outputSchema:llmIterationOutputSchema,execute:async({inputData,getStepResult:getStepResult3,bail})=>{const initialResult=getStepResult3(llmExecutionStep);if(inputData?.every(toolCall=>toolCall?.result===void 0)){const errorResults=inputData.filter(toolCall=>toolCall?.error);const toolResultMessageId=rest.experimental_generateMessageId?.()||_internal?.generateId?.();if(errorResults?.length){errorResults.forEach(toolCall=>{const chunk={type:"tool-error",runId:rest.runId,from:"AGENT"/* AGENT */,payload:{error:toolCall.error,args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,providerMetadata:toolCall.providerMetadata}};rest.controller.enqueue(chunk);});rest.messageList.add({id:toolResultMessageId,role:"tool",content:errorResults.map(toolCall=>{return {type:"tool-result",args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,result:{tool_execution_error:toolCall.error?.message??toolCall.error}};})},"response");}initialResult.stepResult.isContinued=false;return bail(initialResult);}if(inputData?.length){for(const toolCall of inputData){const chunk={type:"tool-result",runId:rest.runId,from:"AGENT"/* AGENT */,payload:{args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,result:toolCall.result,providerMetadata:toolCall.providerMetadata,providerExecuted:toolCall.providerExecuted}};rest.controller.enqueue(chunk);if(initialResult?.metadata?.modelVersion==="v2"){await rest.options?.onChunk?.({chunk:convertMastraChunkToAISDKv5({chunk})});}const toolResultMessageId=rest.experimental_generateMessageId?.()||_internal?.generateId?.();rest.messageList.add({id:toolResultMessageId,role:"tool",content:inputData.map(toolCall2=>{return {type:"tool-result",args:toolCall2.args,toolCallId:toolCall2.toolCallId,toolName:toolCall2.toolName,result:toolCall2.result};})},"response");}return {...initialResult,messages:{all:rest.messageList.get.all.aiV5.model(),user:rest.messageList.get.input.aiV5.model(),nonUser:rest.messageList.get.response.aiV5.model()}};}}});}// src/loop/workflows/agentic-execution/tool-call-step.ts
376
377
  function createToolCallStep({tools,messageList,options,telemetry_settings,writer,requireToolApproval,controller,runId,streamState}){return createStep({id:"toolCallStep",inputSchema:toolCallInputSchema,outputSchema:toolCallOutputSchema,execute:async({inputData,suspend,resumeData})=>{if(inputData.providerExecuted){const tracer2=getTracer({isEnabled:telemetry_settings?.isEnabled,tracer:telemetry_settings?.tracer});const span2=tracer2.startSpan("mastra.stream.toolCall").setAttributes({...assembleOperationName({operationId:"mastra.stream.toolCall",telemetry:telemetry_settings}),"stream.toolCall.toolName":inputData.toolName,"stream.toolCall.toolCallId":inputData.toolCallId,"stream.toolCall.args":JSON.stringify(inputData.args),"stream.toolCall.providerExecuted":true});if(inputData.output){span2.setAttributes({"stream.toolCall.result":JSON.stringify(inputData.output)});}span2.end();return {...inputData,result:inputData.output};}const tool=tools?.[inputData.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===inputData.toolName);if(!tool){throw new Error(`Tool ${inputData.toolName} not found`);}if(tool&&"onInputAvailable"in tool){try{await tool?.onInputAvailable?.({toolCallId:inputData.toolCallId,input:inputData.args,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputAvailable",error);}}if(!tool.execute){return inputData;}const tracer=getTracer({isEnabled:telemetry_settings?.isEnabled,tracer:telemetry_settings?.tracer});const span=tracer.startSpan("mastra.stream.toolCall").setAttributes({...assembleOperationName({operationId:"mastra.stream.toolCall",telemetry:telemetry_settings}),"stream.toolCall.toolName":inputData.toolName,"stream.toolCall.toolCallId":inputData.toolCallId,"stream.toolCall.args":JSON.stringify(inputData.args)});try{if(requireToolApproval||tool.requireApproval){if(!resumeData){controller.enqueue({type:"tool-call-approval",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args}});await suspend({requireToolApproval:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args},__streamState:streamState.serialize()});}else {if(!resumeData.approved){const error=new Error("Tool call was declined: "+JSON.stringify({toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args}));return {error,...inputData};}}}const result=await tool.execute(inputData.args,{abortSignal:options?.abortSignal,toolCallId:inputData.toolCallId,messages:messageList.get.input.aiV5.model(),writableStream:writer,suspend:async suspendPayload=>{controller.enqueue({type:"tool-call-suspended",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,suspendPayload}});return await suspend({toolCallSuspended:suspendPayload,__streamState:streamState.serialize()});},resumeData});span.setAttributes({"stream.toolCall.result":JSON.stringify(result)});span.end();return {result,...inputData};}catch(error){span.setStatus({code:2,message:error?.message??error});span.recordException(error);return {error,...inputData};}}});}// src/loop/workflows/agentic-execution/index.ts
377
378
  function createAgenticExecutionWorkflow({models,telemetry_settings,_internal,modelStreamSpan,...rest}){const llmExecutionStep=createLLMExecutionStep({models,_internal,modelStreamSpan,telemetry_settings,...rest});const toolCallStep=createToolCallStep({telemetry_settings,...rest});const llmMappingStep=createLLMMappingStep({models,telemetry_settings,_internal,modelStreamSpan,...rest},llmExecutionStep);return createWorkflow({id:"executionWorkflow",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,options:{tracingPolicy:{// mark all workflow spans related to the
@@ -387,7 +388,7 @@ function isControllerOpen(controller){return controller.desiredSize!==0&&control
387
388
  reason:executionResult.result.stepResult.reason}}});const msToFinish=(_internal?.now?.()??Date.now())-startTimestamp;modelStreamSpan.addEvent("ai.stream.finish");modelStreamSpan.setAttributes({"stream.response.msToFinish":msToFinish,"stream.response.avgOutputTokensPerSecond":1e3*(executionResult?.result?.output?.usage?.outputTokens??0)/msToFinish});controller.close();}});}// src/loop/loop.ts
388
389
  function loop({resumeContext,models,logger,runId,idGenerator,telemetry_settings,messageList,includeRawChunks,modelSettings,tools,_internal,mode="stream",outputProcessors,returnScorerData,llmAISpan,requireToolApproval,...rest}){let loggerToUse=logger||new ConsoleLogger({level:"debug"});if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});loggerToUse.trackException(mastraError);loggerToUse.error(mastraError.toString());throw mastraError;}const firstModel=models[0];let runIdToUse=runId;if(!runIdToUse){runIdToUse=idGenerator?.()||crypto.randomUUID();}const internalToUse={now:_internal?.now||(()=>Date.now()),generateId:_internal?.generateId||(()=>generateId()),currentDate:_internal?.currentDate||(()=>/* @__PURE__ */new Date())};let startTimestamp=internalToUse.now?.();const{rootSpan}=getRootSpan({operationId:mode==="stream"?`mastra.stream`:`mastra.generate`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});rootSpan.setAttributes({...(telemetry_settings?.recordOutputs!==false?{"stream.prompt.messages":JSON.stringify(messageList.get.input.aiV5.model())}:{})});const{rootSpan:modelStreamSpan}=getRootSpan({operationId:`mastra.${mode}.aisdk.doStream`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});const messageId=rest.experimental_generateMessageId?.()||internalToUse.generateId?.();let modelOutput;const serializeStreamState=()=>{return modelOutput?.serializeState();};const deserializeStreamState=state=>{modelOutput?.deserializeState(state);};const workflowLoopProps={resumeContext,models,runId:runIdToUse,logger:loggerToUse,startTimestamp,messageList,includeRawChunks:!!includeRawChunks,_internal:internalToUse,tools,modelStreamSpan,telemetry_settings,modelSettings,outputProcessors,llmAISpan,messageId,requireToolApproval,streamState:{serialize:serializeStreamState,deserialize:deserializeStreamState},...rest};const stream=workflowLoopStream(workflowLoopProps);modelOutput=new MastraModelOutput({model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider,version:firstModel.model.specificationVersion},stream,messageList,messageId,options:{runId:runIdToUse,telemetry_settings,rootSpan,toolCallStreaming:rest.toolCallStreaming,onFinish:rest.options?.onFinish,onStepFinish:rest.options?.onStepFinish,includeRawChunks:!!includeRawChunks,output:rest.output,outputProcessors,outputProcessorRunnerMode:"result",returnScorerData,tracingContext:{currentSpan:llmAISpan}}});return modelOutput;}// src/llm/model/model.loop.ts
389
390
  var MastraLLMVNext=class extends MastraBase{#models;#mastra;#options;#firstModel;constructor({mastra,models,options}){super({name:"aisdk"});this.#options=options;if(mastra){this.#mastra=mastra;if(mastra.getLogger()){this.__setLogger(this.#mastra.getLogger());}}if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LLM_LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}else {this.#models=models;this.#firstModel=models[0];}}__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}}__registerMastra(p){this.#mastra=p;}getProvider(){return this.#firstModel.model.provider;}getModelId(){return this.#firstModel.model.modelId;}getModel(){return this.#firstModel.model;}_applySchemaCompat(schema){const model=this.#firstModel.model;const schemaCompatLayers=[];if(model){const modelInfo={modelId:model.modelId,supportsStructuredOutputs:true,provider:model.provider};schemaCompatLayers.push(new OpenAIReasoningSchemaCompatLayer(modelInfo),new OpenAISchemaCompatLayer(modelInfo),new GoogleSchemaCompatLayer(modelInfo),new AnthropicSchemaCompatLayer(modelInfo),new DeepSeekSchemaCompatLayer(modelInfo),new MetaSchemaCompatLayer(modelInfo));}return applyCompatLayer({schema,compatLayers:schemaCompatLayers,mode:"aiSdkSchema"});}convertToMessages(messages){if(Array.isArray(messages)){return messages.map(m=>{if(typeof m==="string"){return {role:"user",content:m};}return m;});}return [{role:"user",content:messages}];}stream({resumeContext,runId,stopWhen=stepCountIs(5),maxSteps,tools={},modelSettings,toolChoice="auto",telemetry_settings,threadId,resourceId,output,options,outputProcessors,returnScorerData,providerOptions,tracingContext,messageList,requireToolApproval,_internal// ...rest
390
- }){let stopWhenToUse;if(maxSteps&&typeof maxSteps==="number"){stopWhenToUse=stepCountIs(maxSteps);}else {stopWhenToUse=stopWhen;}const messages=messageList.get.all.aiV5.model();const firstModel=this.#firstModel.model;this.logger.debug(`[LLM] - Streaming text`,{runId,threadId,resourceId,messages,tools:Object.keys(tools||{})});const llmAISpan=tracingContext?.currentSpan?.createChildSpan({name:`llm: '${firstModel.modelId}'`,type:"llm_generation"/* LLM_GENERATION */,input:{messages:[...messageList.getSystemMessages(),...messages]},attributes:{model:firstModel.modelId,provider:firstModel.provider,streaming:true,parameters:modelSettings},metadata:{runId,threadId,resourceId},tracingPolicy:this.#options?.tracingPolicy});try{const loopOptions={mastra:this.#mastra,resumeContext,runId,messageList,models:this.#models,tools,stopWhen:stopWhenToUse,toolChoice,modelSettings,providerOptions,telemetry_settings:{...this.experimental_telemetry,...telemetry_settings},_internal,output,outputProcessors,returnScorerData,llmAISpan,requireToolApproval,options:{...options,onStepFinish:async props=>{try{await options?.onStepFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}this.logger.debug("[LLM] - Stream Step Change:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId});if(props?.response?.headers?.["x-ratelimit-remaining-tokens"]&&parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"],10)<2e3){this.logger.warn("Rate limit approaching, waiting 10 seconds",{runId});await delay(10*1e3);}},onFinish:async props=>{try{await options?.onFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}llmAISpan?.end({output:{text:props?.text,reasoning:props?.reasoning,reasoningText:props?.reasoningText,files:props?.files,sources:props?.sources,warnings:props?.warnings},attributes:{finishReason:props?.finishReason,usage:{inputTokens:props?.totalUsage?.inputTokens,outputTokens:props?.totalUsage?.outputTokens,totalTokens:props?.totalUsage?.totalTokens,reasoningTokens:props?.totalUsage?.reasoningTokens,cachedInputTokens:props?.totalUsage?.cachedInputTokens}}});this.logger.debug("[LLM] - Stream Finished:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId,threadId,resourceId});}}};return loop(loopOptions);}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_TEXT_AI_SDK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"THIRD_PARTY"/* THIRD_PARTY */,details:{modelId:firstModel.modelId,modelProvider:firstModel.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown"}},e);llmAISpan?.error({error:mastraError});throw mastraError;}}};// src/loop/network/index.ts
391
+ }){let stopWhenToUse;if(maxSteps&&typeof maxSteps==="number"){stopWhenToUse=stepCountIs(maxSteps);}else {stopWhenToUse=stopWhen;}const messages=messageList.get.all.aiV5.model();const firstModel=this.#firstModel.model;this.logger.debug(`[LLM] - Streaming text`,{runId,threadId,resourceId,messages,tools:Object.keys(tools||{})});const llmAISpan=tracingContext?.currentSpan?.createChildSpan({name:`llm: '${firstModel.modelId}'`,type:"llm_generation"/* LLM_GENERATION */,input:{messages:[...messageList.getSystemMessages(),...messages]},attributes:{model:firstModel.modelId,provider:firstModel.provider,streaming:true,parameters:modelSettings},metadata:{runId,threadId,resourceId},tracingPolicy:this.#options?.tracingPolicy});try{const loopOptions={mastra:this.#mastra,resumeContext,runId,messageList,models:this.#models,tools,stopWhen:stopWhenToUse,toolChoice,modelSettings,providerOptions,telemetry_settings:{...this.experimental_telemetry,...telemetry_settings},_internal,output,outputProcessors,returnScorerData,llmAISpan,requireToolApproval,options:{...options,onStepFinish:async props=>{try{await options?.onStepFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}this.logger.debug("[LLM] - Stream Step Change:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId});if(props?.response?.headers?.["x-ratelimit-remaining-tokens"]&&parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"],10)<2e3){this.logger.warn("Rate limit approaching, waiting 10 seconds",{runId});await delay(10*1e3);}},onFinish:async props=>{try{await options?.onFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}llmAISpan?.end({output:{files:props?.files,object:props?.object,reasoning:props?.reasoning,reasoningText:props?.reasoningText,sources:props?.sources,text:props?.text,warnings:props?.warnings},attributes:{finishReason:props?.finishReason,usage:{inputTokens:props?.totalUsage?.inputTokens,outputTokens:props?.totalUsage?.outputTokens,totalTokens:props?.totalUsage?.totalTokens,reasoningTokens:props?.totalUsage?.reasoningTokens,cachedInputTokens:props?.totalUsage?.cachedInputTokens}}});this.logger.debug("[LLM] - Stream Finished:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId,threadId,resourceId});}}};return loop(loopOptions);}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_TEXT_AI_SDK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"THIRD_PARTY"/* THIRD_PARTY */,details:{modelId:firstModel.modelId,modelProvider:firstModel.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown"}},e);llmAISpan?.error({error:mastraError});throw mastraError;}}};// src/loop/network/index.ts
391
392
  var MastraAgentNetworkStream=class extends ReadableStream$1{#usageCount={inputTokens:0,outputTokens:0,totalTokens:0};#streamPromise;#run;constructor({createStream,run}){const deferredPromise={promise:null,resolve:null,reject:null};deferredPromise.promise=new Promise((resolve,reject)=>{deferredPromise.resolve=resolve;deferredPromise.reject=reject;});const updateUsageCount=usage=>{this.#usageCount.inputTokens+=parseInt(usage?.inputTokens?.toString()??"0",10);this.#usageCount.outputTokens+=parseInt(usage?.outputTokens?.toString()??"0",10);this.#usageCount.totalTokens+=parseInt(usage?.totalTokens?.toString()??"0",10);};super({start:async controller=>{const writer=new WritableStream({write:chunk=>{if(chunk.type==="step-output"&&chunk.payload?.output?.from==="AGENT"&&chunk.payload?.output?.type==="finish"||chunk.type==="step-output"&&chunk.payload?.output?.from==="WORKFLOW"&&chunk.payload?.output?.type==="finish"){const output=chunk.payload?.output;if(output&&"payload"in output&&output.payload){const finishPayload=output.payload;if("usage"in finishPayload&&finishPayload.usage){updateUsageCount(finishPayload.usage);}}}controller.enqueue(chunk);}});const stream=await createStream(writer);for await(const chunk of stream){if(chunk.type==="workflow-step-output"){const innerChunk=chunk.payload.output;if(innerChunk&&typeof innerChunk==="object"&&"payload"in innerChunk){const nestedOutput=innerChunk.payload;if(nestedOutput&&typeof nestedOutput==="object"&&"output"in nestedOutput&&nestedOutput.output){controller.enqueue(nestedOutput.output);}}}}controller.close();deferredPromise.resolve();}});this.#run=run;this.#streamPromise=deferredPromise;}get status(){return this.#streamPromise.promise.then(()=>this.#run._getExecutionResults()).then(res=>res.status);}get result(){return this.#streamPromise.promise.then(()=>this.#run._getExecutionResults());}get usage(){return this.#streamPromise.promise.then(()=>this.#usageCount);}};// src/loop/types.ts
392
393
  var PRIMITIVE_TYPES=z9.enum(["agent","workflow","none","tool"]);// src/loop/network/index.ts
393
394
  async function getRoutingAgent({runtimeContext,agent}){const instructionsToUse=await agent.getInstructions({runtimeContext});const agentsToUse=await agent.listAgents({runtimeContext});const workflowsToUse=await agent.getWorkflows({runtimeContext});const toolsToUse=await agent.getTools({runtimeContext});const model=await agent.getModel({runtimeContext});const memoryToUse=await agent.getMemory({runtimeContext});const agentList=Object.entries(agentsToUse).map(([name,agent2])=>{return ` - **${name}**: ${agent2.getDescription()}`;}).join("\n");const workflowList=Object.entries(workflowsToUse).map(([name,workflow])=>{return ` - **${name}**: ${workflow.description}, input schema: ${JSON.stringify(zodToJsonSchema(workflow.inputSchema))}`;}).join("\n");const memoryTools=await memoryToUse?.getTools?.();const toolList=Object.entries({...toolsToUse,...memoryTools}).map(([name,tool])=>{return ` - **${name}**: ${tool.description}, input schema: ${JSON.stringify(zodToJsonSchema(tool.inputSchema||z9.object({})))}`;}).join("\n");const instructions=`
@@ -437,21 +438,20 @@ _agentNetworkAppend:true});}function getLastMessage(messages){let message="";if(
437
438
 
438
439
  ${completionResult?.object?.finalResult}`:""}
439
440
 
440
- DO NOT CALL THE PRIMITIVE YOURSELF
441
-
442
- Please select the most appropriate primitive to handle this task and the prompt to be sent to the primitive.
443
-
444
- #Rules:
445
- ##Agent:
441
+ # Rules:
442
+
443
+ ## Agent:
446
444
  - prompt should be a text value, like you would call an LLM in a chat interface.
447
445
  - If you are calling the same agent again, make sure to adjust the prompt to be more specific.
448
446
 
449
- ##Workflow/Tool:
447
+ ## Workflow/Tool:
450
448
  - prompt should be a JSON value that corresponds to the input schema of the workflow or tool. The JSON value is stringified.
451
449
  - Make sure to use inputs corresponding to the input schema when calling a workflow or tool.
452
450
 
453
- Make sure to not call the same primitive twice, unless you call it with different arguments and believe it adds something to the task completion criteria. Take into account previous decision making history and results in your decision making and final result. These are messages whose text is a JSON structure with "isNetwork" true.
451
+ DO NOT CALL THE PRIMITIVE YOURSELF. Make sure to not call the same primitive twice, unless you call it with different arguments and believe it adds something to the task completion criteria. Take into account previous decision making history and results in your decision making and final result. These are messages whose text is a JSON structure with "isNetwork" true.
454
452
 
453
+ Please select the most appropriate primitive to handle this task and the prompt to be sent to the primitive. If no primitive is appropriate, return "none" for the primitiveId and "none" for the primitiveType.
454
+
455
455
  {
456
456
  "primitiveId": string,
457
457
  "primitiveType": "agent" | "workflow" | "tool",
@@ -463,8 +463,8 @@ ${completionResult?.object?.finalResult}`:""}
463
463
  `}];const options={structuredOutput:{schema:z9.object({primitiveId:z9.string().describe("The id of the primitive to be called"),primitiveType:PRIMITIVE_TYPES.describe("The type of the primitive to be called"),prompt:z9.string().describe("The json string or text value to be sent to the primitive"),selectionReason:z9.string().describe("The reason you picked the primitive")})},runtimeContext,maxSteps:1,memory:{thread:initData?.threadId??runId,resource:initData?.threadResourceId??networkName,readOnly:true},...routingAgentOptions};const result=await routingAgent.generateVNext(prompt,options);const object=result.object;const endPayload={task:inputData.task,result:"",primitiveId:object.primitiveId,primitiveType:object.primitiveType,prompt:object.prompt,isComplete:object.primitiveId==="none"&&object.primitiveType==="none",selectionReason:object.selectionReason,iteration:iterationCount};await writer.write({type:"routing-agent-end",payload:endPayload});return endPayload;}});const agentStep=createStep({id:"agent-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,writer,getInitData})=>{const agentsMap=await agent.listAgents({runtimeContext});const agentId=inputData.primitiveId;const agentForStep=agentsMap[agentId];if(!agentForStep){const mastraError=new MastraError({id:"AGENT_NETWORK_AGENT_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Agent ${agentId} not found`});throw mastraError;}const runId2=generateId3();await writer.write({type:"agent-execution-start",payload:{agentId:inputData.primitiveId,args:inputData,runId:runId2}});const result=await agentForStep.streamVNext(inputData.prompt,{// resourceId: inputData.resourceId,
464
464
  // threadId: inputData.threadId,
465
465
  runtimeContext,runId:runId2});for await(const chunk of result.fullStream){await writer.write({type:`agent-execution-event-${chunk.type}`,payload:chunk});}const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();const messages=result.messageList.get.all.v1();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,input:inputData.prompt,finalResult:{text:await result.text,toolCalls:await result.toolCalls,messages}})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId2,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,agentId:inputData.primitiveId,result:await result.text,isComplete:false,iteration:inputData.iteration};await writer.write({type:"agent-execution-end",payload:endPayload});return {task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:await result.text,isComplete:false,iteration:inputData.iteration};}});const workflowStep=createStep({id:"workflow-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,writer,getInitData})=>{const workflowsMap=await agent.getWorkflows({runtimeContext});const workflowId=inputData.primitiveId;const wf=workflowsMap[workflowId];if(!wf){const mastraError=new MastraError({id:"AGENT_NETWORK_WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Workflow ${workflowId} not found`});throw mastraError;}let input;try{input=JSON.parse(inputData.prompt);}catch(e){const mastraError=new MastraError({id:"WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const run=await wf.createRunAsync();const toolData={name:wf.name,args:inputData,runId:run.runId};await writer?.write({type:"workflow-execution-start",payload:toolData});const stream=run.streamVNext({inputData:input,runtimeContext});let chunks=[];for await(const chunk of stream){chunks.push(chunk);await writer?.write({type:`workflow-execution-event-${chunk.type}`,payload:chunk});}let runSuccess=true;const workflowState=await stream.result;if(!workflowState?.status||workflowState?.status==="failed"){runSuccess=false;}const finalResult=JSON.stringify({isNetwork:true,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,selectionReason:inputData.selectionReason,input,finalResult:{runId:run.runId,runResult:workflowState,chunks,runSuccess}});const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:finalResult}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration};await writer?.write({type:"workflow-execution-end",payload:endPayload});return endPayload;}});const toolStep=createStep({id:"tool-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const agentTools=await agent.getTools({runtimeContext});const memory=await agent.getMemory({runtimeContext});const memoryTools=await memory?.getTools?.();const toolsMap={...agentTools,...memoryTools};const toolId=inputData.primitiveId;let tool=toolsMap[toolId];if(!tool){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} not found`});throw mastraError;}if(!tool.execute){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} does not have an execute function`});throw mastraError;}let inputDataToUse;try{inputDataToUse=JSON.parse(inputData.prompt);}catch(e){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const toolCallId=generateId3();await writer?.write({type:"tool-execution-start",payload:{args:{...inputData,args:inputDataToUse,toolName:toolId,toolCallId},runId}});const finalResult=await tool.execute({runtimeContext,mastra:agent.getMastraInstance(),resourceId:initData.threadResourceId||networkName,threadId:initData.threadId,runId,memory,context:inputDataToUse,// TODO: Pass proper tracing context when network supports tracing
466
- tracingContext:{currentSpan:void 0},writer},{toolCallId,messages:[]});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:toolId,finalResult:{result:finalResult,toolCallId},input:inputDataToUse})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData.threadId||runId,resourceId:initData.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:toolId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration,toolCallId,toolName:toolId};await writer?.write({type:"tool-execution-end",payload:endPayload});return endPayload;}});const finishStep=createStep({id:"finish-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),result:z9.string(),isComplete:z9.boolean(),iteration:z9.number()}),execute:async({inputData,writer})=>{const endPayload={task:inputData.task,result:inputData.result,isComplete:!!inputData.isComplete,iteration:inputData.iteration};await writer?.write({type:"network-execution-event-step-finish",payload:endPayload});return endPayload;}});const networkWorkflow=createWorkflow({id:"Agent-Network-Outer-Workflow",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean()})});networkWorkflow.then(routingStep).branch([[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="agent",agentStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="workflow",workflowStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="tool",toolStep],[async({inputData})=>inputData.isComplete,finishStep]]).map({task:{step:[routingStep,agentStep,workflowStep,toolStep],path:"task"},isComplete:{step:[agentStep,workflowStep,toolStep,finishStep],path:"isComplete"},completionReason:{step:[routingStep,agentStep,workflowStep,toolStep,finishStep],path:"completionReason"},result:{step:[agentStep,workflowStep,toolStep,finishStep],path:"result"},primitiveId:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveId"},primitiveType:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveType"},iteration:{step:[routingStep,agentStep,workflowStep,toolStep],path:"iteration"},isOneOff:{initData:networkWorkflow,path:"isOneOff"},threadId:{initData:networkWorkflow,path:"threadId"},threadResourceId:{initData:networkWorkflow,path:"threadResourceId"}}).commit();return {networkWorkflow};}async function networkLoop({networkName,runtimeContext,runId,routingAgent,routingAgentOptions,generateId:generateId3,maxIterations,threadId,resourceId,messages}){const{networkWorkflow}=await createNetworkLoop({networkName,runtimeContext,runId,agent:routingAgent,routingAgentOptions,generateId:generateId3});const finalStep=createStep({id:"final-step",inputSchema:networkWorkflow.outputSchema,outputSchema:networkWorkflow.outputSchema,execute:async({inputData,writer})=>{if(inputData.iteration>=maxIterations){await writer?.write({type:"network-execution-event-finish",payload:{...inputData,completionReason:`Max iterations reached: ${maxIterations}`}});return {...inputData,completionReason:`Max iterations reached: ${maxIterations}`};}return inputData;}});const mainWorkflow=createWorkflow({id:"agent-loop-main-workflow",inputSchema:z9.object({iteration:z9.number(),task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number()})}).dountil(networkWorkflow,async({inputData})=>{return inputData.isComplete||inputData.iteration>=maxIterations;}).then(finalStep).commit();const run=await mainWorkflow.createRunAsync({runId});const{thread}=await prepareMemoryStep({runtimeContext,threadId:threadId||run.runId,resourceId:resourceId||networkName,messages,routingAgent,generateId:generateId3});const task=getLastMessage(messages);return new MastraAgentNetworkStream({run,createStream:()=>{return run.streamVNext({inputData:{task,primitiveId:"",primitiveType:"none",iteration:0,threadResourceId:thread?.resourceId,threadId:thread?.id,isOneOff:false,verboseIntrospection:true}});}});}// src/processors/processors/structured-output.ts
467
- var StructuredOutputProcessor=class{name="structured-output";schema;structuringAgent;errorStrategy;fallbackValue;constructor(options,fallbackModel){this.schema=options.schema;this.errorStrategy=options.errorStrategy??"strict";this.fallbackValue=options.fallbackValue;const modelToUse=options.model||fallbackModel;if(!modelToUse){throw new Error("StructuredOutputProcessor requires a model to be provided either in options or as fallback");}this.structuringAgent=new Agent({name:"structured-output-structurer",instructions:options.instructions||this.generateInstructions(),model:modelToUse});}async processOutputResult(args){const{messages,abort}=args;const processedMessages=await Promise.all(messages.map(async message=>{if(message.role!=="assistant"){return message;}const textContent=this.extractTextContent(message);if(!textContent.trim()){return message;}try{const modelDef=await this.structuringAgent.getModel();let structuredResult;const prompt=`Extract and structure the key information from the following text according to the specified schema. Keep the original meaning and details:
466
+ tracingContext:{currentSpan:void 0},writer},{toolCallId,messages:[]});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:toolId,finalResult:{result:finalResult,toolCallId},input:inputDataToUse})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData.threadId||runId,resourceId:initData.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:toolId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration,toolCallId,toolName:toolId};await writer?.write({type:"tool-execution-end",payload:endPayload});return endPayload;}});const finishStep=createStep({id:"finish-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),result:z9.string(),isComplete:z9.boolean(),iteration:z9.number()}),execute:async({inputData,writer})=>{let endResult=inputData.result;if(inputData.primitiveId==="none"&&inputData.primitiveType==="none"&&!inputData.result){endResult=inputData.selectionReason;}const endPayload={task:inputData.task,result:endResult,isComplete:!!inputData.isComplete,iteration:inputData.iteration};await writer?.write({type:"network-execution-event-step-finish",payload:endPayload});return endPayload;}});const networkWorkflow=createWorkflow({id:"Agent-Network-Outer-Workflow",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean()})});networkWorkflow.then(routingStep).branch([[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="agent",agentStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="workflow",workflowStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="tool",toolStep],[async({inputData})=>inputData.isComplete,finishStep]]).map({task:{step:[routingStep,agentStep,workflowStep,toolStep],path:"task"},isComplete:{step:[agentStep,workflowStep,toolStep,finishStep],path:"isComplete"},completionReason:{step:[routingStep,agentStep,workflowStep,toolStep,finishStep],path:"completionReason"},result:{step:[agentStep,workflowStep,toolStep,finishStep],path:"result"},primitiveId:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveId"},primitiveType:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveType"},iteration:{step:[routingStep,agentStep,workflowStep,toolStep],path:"iteration"},isOneOff:{initData:networkWorkflow,path:"isOneOff"},threadId:{initData:networkWorkflow,path:"threadId"},threadResourceId:{initData:networkWorkflow,path:"threadResourceId"}}).commit();return {networkWorkflow};}async function networkLoop({networkName,runtimeContext,runId,routingAgent,routingAgentOptions,generateId:generateId3,maxIterations,threadId,resourceId,messages}){const memoryToUse=await routingAgent.getMemory({runtimeContext});if(!memoryToUse){throw new MastraError({id:"AGENT_NETWORK_MEMORY_REQUIRED",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:"Memory is required for the agent network to function properly. Please configure memory for the agent.",details:{status:400}});}const{networkWorkflow}=await createNetworkLoop({networkName,runtimeContext,runId,agent:routingAgent,routingAgentOptions,generateId:generateId3});const finalStep=createStep({id:"final-step",inputSchema:networkWorkflow.outputSchema,outputSchema:networkWorkflow.outputSchema,execute:async({inputData,writer})=>{if(inputData.iteration>=maxIterations){await writer?.write({type:"network-execution-event-finish",payload:{...inputData,completionReason:`Max iterations reached: ${maxIterations}`}});return {...inputData,completionReason:`Max iterations reached: ${maxIterations}`};}return inputData;}});const mainWorkflow=createWorkflow({id:"agent-loop-main-workflow",inputSchema:z9.object({iteration:z9.number(),task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number()})}).dountil(networkWorkflow,async({inputData})=>{return inputData.isComplete||inputData.iteration>=maxIterations;}).then(finalStep).commit();const run=await mainWorkflow.createRunAsync({runId});const{thread}=await prepareMemoryStep({runtimeContext,threadId:threadId||run.runId,resourceId:resourceId||networkName,messages,routingAgent,generateId:generateId3});const task=getLastMessage(messages);return new MastraAgentNetworkStream({run,createStream:()=>{return run.streamVNext({inputData:{task,primitiveId:"",primitiveType:"none",iteration:0,threadResourceId:thread?.resourceId,threadId:thread?.id,isOneOff:false,verboseIntrospection:true}});}});}// src/processors/processors/structured-output.ts
467
+ var StructuredOutputProcessor=class{name="structured-output";schema;structuringAgent;errorStrategy;fallbackValue;constructor(options,fallbackModel){this.schema=options.schema;this.errorStrategy=options.errorStrategy??"strict";this.fallbackValue=options.fallbackValue;const modelToUse=options.model||fallbackModel;if(!modelToUse){throw new Error("StructuredOutputProcessor requires a model to be provided either in options or as fallback");}this.structuringAgent=new Agent({name:"structured-output-structurer",instructions:options.instructions||this.generateInstructions(),model:modelToUse,options:{tracingPolicy:{internal:15/* ALL */}}});}async processOutputResult(args){const{messages,abort}=args;const processedMessages=await Promise.all(messages.map(async message=>{if(message.role!=="assistant"){return message;}const textContent=this.extractTextContent(message);if(!textContent.trim()){return message;}try{const modelDef=await this.structuringAgent.getModel();let structuredResult;const prompt=`Extract and structure the key information from the following text according to the specified schema. Keep the original meaning and details:
468
468
 
469
469
  ${textContent}`;const schema=this.schema;if(modelDef.specificationVersion==="v2"){structuredResult=await this.structuringAgent.generateVNext(prompt,{output:schema});}else {structuredResult=await this.structuringAgent.generate(prompt,{output:schema});}if(!structuredResult.object){this.handleError("Structuring failed","Internal agent did not generate structured output",abort);if(this.errorStrategy==="fallback"&&this.fallbackValue!==void 0){return {...message,content:{...message.content,metadata:{...(message.content.metadata||{}),structuredOutput:this.fallbackValue}}};}return message;}return {...message,content:{...message.content,parts:[{type:"text",text:textContent// Keep original text unchanged
470
470
  }],metadata:{...(message.content.metadata||{}),structuredOutput:structuredResult.object}}};}catch(error){this.handleError("Processing failed",error instanceof Error?error.message:"Unknown error",abort);if(this.errorStrategy==="fallback"&&this.fallbackValue!==void 0){return {...message,content:{...message.content,metadata:{...(message.content.metadata||{}),structuredOutput:this.fallbackValue}}};}return message;}}));return processedMessages;}/**
@@ -590,7 +590,7 @@ var TokenLimiterProcessor=class{name="token-limiter";encoder;maxTokens;currentTo
590
590
  */getCurrentTokens(){return this.currentTokens;}/**
591
591
  * Get the maximum token limit
592
592
  */getMaxTokens(){return this.maxTokens;}};// src/processors/processors/system-prompt-scrubber.ts
593
- var SystemPromptScrubber=class{name="system-prompt-scrubber";strategy;customPatterns;includeDetections;instructions;redactionMethod;placeholderText;model;detectionAgent;constructor(options){if(!options.model){throw new Error("SystemPromptScrubber requires a model for detection");}this.strategy=options.strategy||"redact";this.customPatterns=options.customPatterns||[];this.includeDetections=options.includeDetections||false;this.redactionMethod=options.redactionMethod||"mask";this.placeholderText=options.placeholderText||"[SYSTEM_PROMPT]";this.instructions=options.instructions||this.getDefaultInstructions();this.model=options.model;this.detectionAgent=new Agent({name:"system-prompt-detector",model:this.model,instructions:this.instructions});}/**
593
+ var SystemPromptScrubber=class{name="system-prompt-scrubber";strategy;customPatterns;includeDetections;instructions;redactionMethod;placeholderText;model;detectionAgent;constructor(options){if(!options.model){throw new Error("SystemPromptScrubber requires a model for detection");}this.strategy=options.strategy||"redact";this.customPatterns=options.customPatterns||[];this.includeDetections=options.includeDetections||false;this.redactionMethod=options.redactionMethod||"mask";this.placeholderText=options.placeholderText||"[SYSTEM_PROMPT]";this.instructions=options.instructions||this.getDefaultInstructions();this.model=options.model;this.detectionAgent=new Agent({name:"system-prompt-detector",model:this.model,instructions:this.instructions,options:{tracingPolicy:{internal:15/* ALL */}}});}/**
594
594
  * Process streaming chunks to detect and handle system prompts
595
595
  */async processOutputStream(args){const{part,abort}=args;if(part.type!=="text-delta"){return part;}const text=part.payload.text;if(!text||text.trim()===""){return part;}try{const detectionResult=await this.detectSystemPrompts(text);if(detectionResult.detections&&detectionResult.detections.length>0){const detectedTypes=detectionResult.detections.map(detection=>detection.type);switch(this.strategy){case "block":abort(`System prompt detected: ${detectedTypes.join(", ")}`);break;case "filter":return null;// Don't emit this part
596
596
  case "warn":console.warn(`[SystemPromptScrubber] System prompt detected in streaming content: ${detectedTypes.join(", ")}`);if(this.includeDetections&&detectionResult.detections){console.warn(`[SystemPromptScrubber] Detections: ${detectionResult.detections.length} items`);}return part;// Allow content through
@@ -646,11 +646,16 @@ _agentNetworkAppend=false;constructor(config){super({component:RegisteredLogger.
646
646
  * Gets or creates an LLM instance based on the current model
647
647
  * @param options Options for getting the LLM
648
648
  * @returns A promise that resolves to the LLM instance
649
- */getLLM({runtimeContext=new RuntimeContext(),model}={}){const modelToUse=model?typeof model==="function"?model({runtimeContext,mastra:this.#mastra}):model:this.getModel({runtimeContext});return resolveMaybePromise(modelToUse,resolvedModel=>{let llm;if(resolvedModel.specificationVersion==="v2"){llm=this.prepareModels(runtimeContext,model).then(models=>{const enabledModels=models.filter(model2=>model2.enabled);return new MastraLLMVNext({models:enabledModels,mastra:this.#mastra,options:{tracingPolicy:this.#options?.tracingPolicy}});});}else {llm=new MastraLLMV1({model:resolvedModel,mastra:this.#mastra,options:{tracingPolicy:this.#options?.tracingPolicy}});}return resolveMaybePromise(llm,resolvedLLM=>{if(this.#primitives){resolvedLLM.__registerPrimitives(this.#primitives);}if(this.#mastra){resolvedLLM.__registerMastra(this.#mastra);}return resolvedLLM;});});}/**
649
+ */getLLM({runtimeContext=new RuntimeContext(),model}={}){const modelToUse=this.getModel({modelConfig:model,runtimeContext});return resolveMaybePromise(modelToUse,resolvedModel=>{let llm;if(resolvedModel.specificationVersion==="v2"){const modelsPromise=Array.isArray(this.model)&&!model?this.prepareModels(runtimeContext):this.prepareModels(runtimeContext,resolvedModel);llm=modelsPromise.then(models=>{const enabledModels=models.filter(model2=>model2.enabled);return new MastraLLMVNext({models:enabledModels,mastra:this.#mastra,options:{tracingPolicy:this.#options?.tracingPolicy}});});}else {llm=new MastraLLMV1({model:resolvedModel,mastra:this.#mastra,options:{tracingPolicy:this.#options?.tracingPolicy}});}return resolveMaybePromise(llm,resolvedLLM=>{if(this.#primitives){resolvedLLM.__registerPrimitives(this.#primitives);}if(this.#mastra){resolvedLLM.__registerMastra(this.#mastra);}return resolvedLLM;});});}// Returns true for model router config object
650
+ isOpenaiCompatibleObjectConfig(modelConfig){if(typeof modelConfig==="object"&&"specificationVersion"in modelConfig)return false;if(typeof modelConfig==="object"&&"id"in modelConfig&&!("model"in modelConfig))return true;return false;}/**
651
+ * Resolves a model configuration to a LanguageModel instance
652
+ * @param modelConfig The model configuration (magic string, config object, or LanguageModel)
653
+ * @returns A LanguageModel instance
654
+ */async resolveModelConfig(modelConfig,runtimeContext){if(typeof modelConfig==="object"&&"specificationVersion"in modelConfig){return modelConfig;}if(typeof modelConfig==="string"||this.isOpenaiCompatibleObjectConfig(modelConfig)){return new OpenAICompatibleModel(modelConfig);}if(typeof modelConfig===`function`){const fromDynamic=await modelConfig({runtimeContext,mastra:this.#mastra});if(typeof fromDynamic===`string`||this.isOpenaiCompatibleObjectConfig(fromDynamic)){return new OpenAICompatibleModel(fromDynamic);}return fromDynamic;}const mastraError=new MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - No model provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}/**
650
655
  * Gets the model, resolving it if it's a function
651
656
  * @param options Options for getting the model
652
657
  * @returns A promise that resolves to the model
653
- */getModel({runtimeContext=new RuntimeContext()}={}){if(typeof this.model!=="function"){if(!this.model){const mastraError=new MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - No model provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}let modelToUse;if(Array.isArray(this.model)){if(this.model.length===0||!this.model[0]){const mastraError=new MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Empty model list provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}modelToUse=this.model[0].model;if(typeof modelToUse!=="function"&&modelToUse.specificationVersion!=="v2"){const mastraError=new MastraError({id:"AGENT_GET_MODEL_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Only v2 models are allowed when an array of models is provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}}else {modelToUse=this.model;}if(typeof modelToUse==="function"){const result2=modelToUse({runtimeContext,mastra:this.#mastra});return resolveMaybePromise(result2,model=>{if(!model){const mastraError=new MastraError({id:"AGENT_GET_MODEL_FUNCTION_EMPTY_RETURN",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Function-based model returned empty value`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}if(Array.isArray(this.model)&&model.specificationVersion!=="v2"){const mastraError=new MastraError({id:"AGENT_GET_MODEL_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Only v2 models are allowed when an array of models is provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return model;});}return modelToUse;}const result=this.model({runtimeContext,mastra:this.#mastra});return resolveMaybePromise(result,model=>{if(!model){const mastraError=new MastraError({id:"AGENT_GET_MODEL_FUNCTION_EMPTY_RETURN",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Function-based model returned empty value`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return model;});}async getModelList(runtimeContext=new RuntimeContext()){if(!Array.isArray(this.model)){return null;}return this.prepareModels(runtimeContext);}__updateInstructions(newInstructions){this.#instructions=newInstructions;this.logger.debug(`[Agents:${this.name}] Instructions updated.`,{model:this.model,name:this.name});}__updateModel({model}){this.model=model;this.logger.debug(`[Agents:${this.name}] Model updated.`,{model:this.model,name:this.name});}reorderModels(modelIds){if(!Array.isArray(this.model)){this.logger.warn(`[Agents:${this.name}] model is not an array`);return;}this.model=this.model.sort((a,b)=>{const aIndex=modelIds.indexOf(a.id);const bIndex=modelIds.indexOf(b.id);return aIndex-bIndex;});this.logger.debug(`[Agents:${this.name}] Models reordered`);}updateModelInModelList({id,model,enabled,maxRetries}){if(!Array.isArray(this.model)){this.logger.warn(`[Agents:${this.name}] model is not an array`);return;}const modelToUpdate=this.model.find(m=>m.id===id);if(!modelToUpdate){this.logger.warn(`[Agents:${this.name}] model ${id} not found`);return;}this.model=this.model.map(mdl=>{if(mdl.id===id){return {...mdl,model:model??mdl.model,enabled:enabled??mdl.enabled,maxRetries:maxRetries??mdl.maxRetries};}return mdl;});this.logger.debug(`[Agents:${this.name}] model ${id} updated`);}#primitives;__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}this.#primitives=p;this.logger.debug(`[Agents:${this.name}] initialized.`,{model:this.model,name:this.name});}__registerMastra(mastra){this.#mastra=mastra;}/**
658
+ */getModel({runtimeContext=new RuntimeContext(),modelConfig=this.model}={}){if(!Array.isArray(modelConfig))return this.resolveModelConfig(modelConfig,runtimeContext);if(modelConfig.length===0||!modelConfig[0]){const mastraError=new MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Empty model list provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return this.resolveModelConfig(modelConfig[0].model,runtimeContext);}async getModelList(runtimeContext=new RuntimeContext()){if(!Array.isArray(this.model)){return null;}return this.prepareModels(runtimeContext);}__updateInstructions(newInstructions){this.#instructions=newInstructions;this.logger.debug(`[Agents:${this.name}] Instructions updated.`,{model:this.model,name:this.name});}__updateModel({model}){this.model=model;this.logger.debug(`[Agents:${this.name}] Model updated.`,{model:this.model,name:this.name});}reorderModels(modelIds){if(!Array.isArray(this.model)){this.logger.warn(`[Agents:${this.name}] model is not an array`);return;}this.model=this.model.sort((a,b)=>{const aIndex=modelIds.indexOf(a.id);const bIndex=modelIds.indexOf(b.id);return aIndex-bIndex;});this.logger.debug(`[Agents:${this.name}] Models reordered`);}updateModelInModelList({id,model,enabled,maxRetries}){if(!Array.isArray(this.model)){this.logger.warn(`[Agents:${this.name}] model is not an array`);return;}const modelToUpdate=this.model.find(m=>m.id===id);if(!modelToUpdate){this.logger.warn(`[Agents:${this.name}] model ${id} not found`);return;}this.model=this.model.map(mdl=>{if(mdl.id===id){return {...mdl,model:model??mdl.model,enabled:enabled??mdl.enabled,maxRetries:maxRetries??mdl.maxRetries};}return mdl;});this.logger.debug(`[Agents:${this.name}] model ${id} updated`);}#primitives;__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}this.#primitives=p;this.logger.debug(`[Agents:${this.name}] initialized.`,{model:this.model,name:this.name});}__registerMastra(mastra){this.#mastra=mastra;}/**
654
659
  * Set the concrete tools for the agent
655
660
  * @param tools
656
661
  */__setTools(tools){this.#tools=tools;this.logger.debug(`[Agents:${this.name}] Tools set for agent ${this.name}`,{model:this.model,name:this.name});}async generateTitleFromUserMessage({message,runtimeContext=new RuntimeContext(),tracingContext,model,instructions}){const llm=await this.getLLM({runtimeContext,model});const normMessage=new MessageList().add(message,"user").get.all.ui().at(-1);if(!normMessage){throw new Error(`Could not generate title from input ${JSON.stringify(message)}`);}const partsToGen=[];for(const part of normMessage.parts){if(part.type===`text`){partsToGen.push(part);}else if(part.type===`source`){partsToGen.push({type:"text",text:`User added URL: ${part.source.url.substring(0,100)}`});}else if(part.type===`file`){partsToGen.push({type:"text",text:`User added ${part.mimeType} file: ${part.data.substring(0,100)}`});}}const systemInstructions=await this.resolveTitleInstructions(runtimeContext,instructions);let text="";if(llm.getModel().specificationVersion==="v2"){const messageList=new MessageList().add([{role:"system",content:systemInstructions}],"system").add([{role:"user",content:JSON.stringify(partsToGen)}],"input");const result=llm.stream({runtimeContext,tracingContext,messageList});text=await result.text;}else {const result=await llm.__text({runtimeContext,tracingContext,messages:[{role:"system",content:systemInstructions},{role:"user",content:JSON.stringify(partsToGen)}]});text=result.text;}const cleanedText=text.replace(/<think>[\s\S]*?<\/think>/g,"").trim();return cleanedText;}getMostRecentUserMessage(messages){const userMessages=messages.filter(message=>message.role==="user");return userMessages.at(-1);}async genTitle(userMessage,runtimeContext,tracingContext,model,instructions){try{if(userMessage){const normMessage=new MessageList().add(userMessage,"user").get.all.ui().at(-1);if(normMessage){return await this.generateTitleFromUserMessage({message:normMessage,runtimeContext,tracingContext,model,instructions});}}return `New Thread ${(/* @__PURE__ */new Date()).toISOString()}`;}catch(e){this.logger.error("Error generating title:",e);return void 0;}}/* @deprecated use agent.getMemory() and query memory directly */async fetchMemory({threadId,thread:passedThread,memoryConfig,resourceId,runId,userMessages,systemMessage,messageList=new MessageList({threadId,resourceId}),runtimeContext=new RuntimeContext()}){const memory=await this.getMemory({runtimeContext});if(memory){const thread=passedThread??(await memory.getThreadById({threadId}));if(!thread){return {threadId:threadId||"",messages:userMessages||[]};}if(userMessages&&userMessages.length>0){messageList.add(userMessages,"memory");}if(systemMessage?.role==="system"){messageList.addSystem(systemMessage,"memory");}const[memoryMessages,memorySystemMessage]=threadId&&memory?await Promise.all([memory.rememberMessages({threadId,resourceId,config:memoryConfig,vectorMessageSearch:messageList.getLatestUserContent()||""}).then(r=>r.messagesV2),memory.getSystemMessage({threadId,memoryConfig})]):[[],null];this.logger.debug("Fetched messages from memory",{threadId,runId,fetchedCount:memoryMessages.length});if(memorySystemMessage){messageList.addSystem(memorySystemMessage,"memory");}messageList.add(memoryMessages,"memory");const systemMessages=messageList.getSystemMessages()?.map(m=>m.content)?.join(`
@@ -690,12 +695,12 @@ _agentNetworkAppend:this._agentNetworkAppend}).addSystem(instructions||(await th
690
695
  messageObjects:processedList,agentAISpan,...(tripwireTriggered&&{tripwire:true,tripwireReason}),threadExists:!!existingThread};},after:async({result,thread:threadAfter,threadId,memoryConfig:memoryConfig2,outputText,runId:runId2,messageList,threadExists,structuredOutput=false,overrideScorers,agentAISpan})=>{const resToLog={text:result?.text,object:result?.object,toolResults:result?.toolResults,toolCalls:result?.toolCalls,usage:result?.usage,steps:result?.steps?.map(s=>{return {stepType:s?.stepType,text:result?.text,object:result?.object,toolResults:result?.toolResults,toolCalls:result?.toolCalls,usage:result?.usage};})};this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`,{runId:runId2,result:resToLog,threadId});const messageListResponses=new MessageList({threadId,resourceId,generateMessageId:this.#mastra?.generateId?.bind(this.#mastra),// @ts-ignore Flag for agent network messages
691
696
  _agentNetworkAppend:this._agentNetworkAppend}).add(result.response.messages,"response").get.all.core();const usedWorkingMemory=messageListResponses?.some(m=>m.role==="tool"&&m?.content?.some(c=>c?.toolName==="updateWorkingMemory"));const memory=await this.getMemory({runtimeContext});const thread2=usedWorkingMemory?threadId?await memory?.getThreadById({threadId}):void 0:threadAfter;if(memory&&resourceId&&thread2){try{let responseMessages=result.response.messages;if(!responseMessages&&result.object){responseMessages=[{role:"assistant",content:[{type:"text",text:outputText// outputText contains the stringified object
692
697
  }]}];}if(responseMessages){messageList.add(responseMessages,"response");}if(!threadExists){await memory.createThread({threadId:thread2.id,metadata:thread2.metadata,title:thread2.title,memoryConfig:memoryConfig2,resourceId:thread2.resourceId});}const promises=[saveQueueManager.flushMessages(messageList,threadId,memoryConfig2)];if(thread2.title?.startsWith("New Thread")){const config=memory.getMergedThreadConfig(memoryConfig2);const userMessage=this.getMostRecentUserMessage(messageList.get.all.ui());const{shouldGenerate,model:titleModel,instructions:titleInstructions}=this.resolveTitleGenerationConfig(config?.threads?.generateTitle);if(shouldGenerate&&userMessage){promises.push(this.genTitle(userMessage,runtimeContext,{currentSpan:agentAISpan},titleModel,titleInstructions).then(title=>{if(title){return memory.createThread({threadId:thread2.id,resourceId,memoryConfig:memoryConfig2,title,metadata:thread2.metadata});}}));}}await Promise.all(promises);}catch(e){await saveQueueManager.flushMessages(messageList,threadId,memoryConfig2);if(e instanceof MastraError){agentAISpan?.error({error:e});throw e;}const mastraError=new MastraError({id:"AGENT_MEMORY_PERSIST_RESPONSE_MESSAGES_FAILED",domain:"AGENT"/* AGENT */,category:"SYSTEM"/* SYSTEM */,details:{agentName:this.name,runId:runId2||"",threadId:threadId||"",result:JSON.stringify(resToLog)}},e);this.logger.trackException(mastraError);this.logger.error(mastraError.toString());agentAISpan?.error({error:mastraError});throw mastraError;}}else {let responseMessages=result.response.messages;if(!responseMessages&&result.object){responseMessages=[{role:"assistant",content:[{type:"text",text:outputText// outputText contains the stringified object
693
- }]}];}if(responseMessages){messageList.add(responseMessages,"response");}}await this.#runScorers({messageList,runId:runId2,outputText,instructions,runtimeContext,structuredOutput,overrideScorers,threadId,resourceId,tracingContext:{currentSpan:agentAISpan}});const scoringData={input:{inputMessages:messageList.getPersisted.input.ui(),rememberedMessages:messageList.getPersisted.remembered.ui(),systemMessages:messageList.getSystemMessages(),taggedSystemMessages:messageList.getPersisted.taggedSystemMessages},output:messageList.getPersisted.response.ui()};agentAISpan?.end({output:{text:result?.text,object:result?.object,files:result?.files}});return {scoringData};}};}async#runScorers({messageList,runId,outputText,instructions,runtimeContext,structuredOutput,overrideScorers,threadId,resourceId,tracingContext}){const agentName=this.name;const userInputMessages=messageList.get.all.ui().filter(m=>m.role==="user");const input=userInputMessages.map(message=>typeof message.content==="string"?message.content:"").join("\n");const runIdToUse=runId||this.#mastra?.generateId()||randomUUID();if(Object.keys(this.evals||{}).length>0){for(const metric of Object.values(this.evals||{})){executeHook("onGeneration"/* ON_GENERATION */,{input,output:outputText,runId:runIdToUse,metric,agentName,instructions:this.#convertInstructionsToString(instructions)});}}let scorers={};try{scorers=overrideScorers?this.resolveOverrideScorerReferences(overrideScorers):await this.getScorers({runtimeContext});}catch(e){this.logger.warn(`[Agent:${this.name}] - Failed to get scorers: ${e}`);return;}const scorerInput={inputMessages:messageList.getPersisted.input.ui(),rememberedMessages:messageList.getPersisted.remembered.ui(),systemMessages:messageList.getSystemMessages(),taggedSystemMessages:messageList.getPersisted.taggedSystemMessages};const scorerOutput=messageList.getPersisted.response.ui();if(Object.keys(scorers||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorers)){runScorer({scorerId:overrideScorers?scorerObject.scorer.name:scorerObject.scorer.name,scorerObject,runId,input:scorerInput,output:scorerOutput,runtimeContext,entity:{id:this.id,name:this.name},source:"LIVE",entityType:"AGENT",structuredOutput:!!structuredOutput,threadId,resourceId,tracingContext});}}}resolveOverrideScorerReferences(overrideScorers){const result={};for(const[id,scorerObject]of Object.entries(overrideScorers)){if(typeof scorerObject.scorer==="string"){try{if(!this.#mastra){throw new MastraError({id:"AGENT_GENEREATE_SCORER_NOT_FOUND",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`Mastra not found when fetching scorer. Make sure to fetch agent from mastra.getAgent()`});}const scorer=this.#mastra.getScorerByName(scorerObject.scorer);result[id]={scorer,sampling:scorerObject.sampling};}catch(error){this.logger.warn(`[Agent:${this.name}] - Failed to get scorer ${scorerObject.scorer}: ${error}`);}}else {result[id]=scorerObject;}}if(Object.keys(result).length===0){throw new MastraError({id:"AGENT_GENEREATE_SCORER_NOT_FOUND",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`No scorers found in overrideScorers`});}return result;}async prepareLLMOptions(messages,options,methodType){const{context,memoryOptions:memoryConfigFromArgs,resourceId:resourceIdFromArgs,maxSteps,onStepFinish,toolsets,clientTools,temperature,toolChoice="auto",runtimeContext=new RuntimeContext(),tracingContext,tracingOptions,savePerStep,writableStream,...args}=options;const threadFromArgs=resolveThreadIdFromArgs({threadId:args.threadId,memory:args.memory});const resourceId=args.memory?.resource||resourceIdFromArgs;const memoryConfig=args.memory?.options||memoryConfigFromArgs;if(resourceId&&threadFromArgs&&!this.hasOwnMemory()){this.logger.warn(`[Agent:${this.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`);}const runId=args.runId||this.#mastra?.generateId()||randomUUID();const instructions=args.instructions||(await this.getInstructions({runtimeContext}));const llm=await this.getLLM({runtimeContext});const activeSpan=Telemetry.getActiveSpan();const baggageEntries={};if(threadFromArgs?.id){if(activeSpan){activeSpan.setAttribute("threadId",threadFromArgs.id);}baggageEntries.threadId={value:threadFromArgs.id};}if(resourceId){if(activeSpan){activeSpan.setAttribute("resourceId",resourceId);}baggageEntries.resourceId={value:resourceId};}if(Object.keys(baggageEntries).length>0){Telemetry.setBaggage(baggageEntries);}const memory=await this.getMemory({runtimeContext});const saveQueueManager=new SaveQueueManager({logger:this.logger,memory});const{before,after}=this.__primitive({messages,instructions,context,thread:threadFromArgs,memoryConfig,resourceId,runId,toolsets,clientTools,runtimeContext,saveQueueManager,writableStream,methodType,tracingContext,tracingOptions});let messageList;let thread;let threadExists;return {llm,before:async()=>{const beforeResult=await before();const{messageObjects,convertedTools,agentAISpan}=beforeResult;threadExists=beforeResult.threadExists||false;messageList=beforeResult.messageList;thread=beforeResult.thread;const threadId=thread?.id;const result={...options,messages:messageObjects,tools:convertedTools,runId,temperature,toolChoice,threadId,resourceId,runtimeContext,onStepFinish:async props=>{if(savePerStep){if(!threadExists&&memory&&thread){await memory.createThread({threadId,title:thread.title,metadata:thread.metadata,resourceId:thread.resourceId,memoryConfig});threadExists=true;}await this.saveStepMessages({saveQueueManager,result:props,messageList,threadId,memoryConfig,runId});}return onStepFinish?.({...props,runId});},...(beforeResult.tripwire&&{tripwire:beforeResult.tripwire,tripwireReason:beforeResult.tripwireReason}),...args,agentAISpan};return result;},after:async({result,outputText,structuredOutput=false,agentAISpan,overrideScorers})=>{const afterResult=await after({result,outputText,threadId:thread?.id,thread,memoryConfig,runId,messageList,structuredOutput,threadExists,agentAISpan,overrideScorers});return afterResult;}};}async prepareModels(runtimeContext,model){if(model||!Array.isArray(this.model)){const modelToUse=model??this.model;const resolvedModel=typeof modelToUse==="function"?await modelToUse({runtimeContext,mastra:this.#mastra}):modelToUse;if(resolvedModel.specificationVersion!=="v2"){const mastraError=new MastraError({id:"AGENT_PREPARE_MODELS_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Only v2 models are allowed when an array of models is provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return [{id:"main",model:resolvedModel,maxRetries:this.maxRetries??0,enabled:true}];}const models=await Promise.all(this.model.map(async modelConfig=>{const model2=typeof modelConfig.model==="function"?await modelConfig.model({runtimeContext,mastra:this.#mastra}):modelConfig.model;if(model2.specificationVersion!=="v2"){const mastraError=new MastraError({id:"AGENT_PREPARE_MODELS_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Only v2 models are allowed when an array of models is provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return {id:modelConfig.id,model:model2,maxRetries:modelConfig.maxRetries,enabled:modelConfig.enabled};}));return models;}/**
698
+ }]}];}if(responseMessages){messageList.add(responseMessages,"response");}}await this.#runScorers({messageList,runId:runId2,outputText,instructions,runtimeContext,structuredOutput,overrideScorers,threadId,resourceId,tracingContext:{currentSpan:agentAISpan}});const scoringData={input:{inputMessages:messageList.getPersisted.input.ui(),rememberedMessages:messageList.getPersisted.remembered.ui(),systemMessages:messageList.getSystemMessages(),taggedSystemMessages:messageList.getPersisted.taggedSystemMessages},output:messageList.getPersisted.response.ui()};agentAISpan?.end({output:{text:result?.text,object:result?.object,files:result?.files}});return {scoringData};}};}async#runScorers({messageList,runId,outputText,instructions,runtimeContext,structuredOutput,overrideScorers,threadId,resourceId,tracingContext}){const agentName=this.name;const userInputMessages=messageList.get.all.ui().filter(m=>m.role==="user");const input=userInputMessages.map(message=>typeof message.content==="string"?message.content:"").join("\n");const runIdToUse=runId||this.#mastra?.generateId()||randomUUID();if(Object.keys(this.evals||{}).length>0){for(const metric of Object.values(this.evals||{})){executeHook("onGeneration"/* ON_GENERATION */,{input,output:outputText,runId:runIdToUse,metric,agentName,instructions:this.#convertInstructionsToString(instructions)});}}let scorers={};try{scorers=overrideScorers?this.resolveOverrideScorerReferences(overrideScorers):await this.getScorers({runtimeContext});}catch(e){this.logger.warn(`[Agent:${this.name}] - Failed to get scorers: ${e}`);return;}const scorerInput={inputMessages:messageList.getPersisted.input.ui(),rememberedMessages:messageList.getPersisted.remembered.ui(),systemMessages:messageList.getSystemMessages(),taggedSystemMessages:messageList.getPersisted.taggedSystemMessages};const scorerOutput=messageList.getPersisted.response.ui();if(Object.keys(scorers||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorers)){runScorer({scorerId:overrideScorers?scorerObject.scorer.name:scorerObject.scorer.name,scorerObject,runId,input:scorerInput,output:scorerOutput,runtimeContext,entity:{id:this.id,name:this.name},source:"LIVE",entityType:"AGENT",structuredOutput:!!structuredOutput,threadId,resourceId,tracingContext});}}}resolveOverrideScorerReferences(overrideScorers){const result={};for(const[id,scorerObject]of Object.entries(overrideScorers)){if(typeof scorerObject.scorer==="string"){try{if(!this.#mastra){throw new MastraError({id:"AGENT_GENEREATE_SCORER_NOT_FOUND",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`Mastra not found when fetching scorer. Make sure to fetch agent from mastra.getAgent()`});}const scorer=this.#mastra.getScorerByName(scorerObject.scorer);result[id]={scorer,sampling:scorerObject.sampling};}catch(error){this.logger.warn(`[Agent:${this.name}] - Failed to get scorer ${scorerObject.scorer}: ${error}`);}}else {result[id]=scorerObject;}}if(Object.keys(result).length===0){throw new MastraError({id:"AGENT_GENEREATE_SCORER_NOT_FOUND",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`No scorers found in overrideScorers`});}return result;}async prepareLLMOptions(messages,options,methodType){const{context,memoryOptions:memoryConfigFromArgs,resourceId:resourceIdFromArgs,maxSteps,onStepFinish,toolsets,clientTools,temperature,toolChoice="auto",runtimeContext=new RuntimeContext(),tracingContext,tracingOptions,savePerStep,writableStream,...args}=options;const threadFromArgs=resolveThreadIdFromArgs({threadId:args.threadId,memory:args.memory});const resourceId=args.memory?.resource||resourceIdFromArgs;const memoryConfig=args.memory?.options||memoryConfigFromArgs;if(resourceId&&threadFromArgs&&!this.hasOwnMemory()){this.logger.warn(`[Agent:${this.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`);}const runId=args.runId||this.#mastra?.generateId()||randomUUID();const instructions=args.instructions||(await this.getInstructions({runtimeContext}));const llm=await this.getLLM({runtimeContext});const activeSpan=Telemetry.getActiveSpan();const baggageEntries={};if(threadFromArgs?.id){if(activeSpan){activeSpan.setAttribute("threadId",threadFromArgs.id);}baggageEntries.threadId={value:threadFromArgs.id};}if(resourceId){if(activeSpan){activeSpan.setAttribute("resourceId",resourceId);}baggageEntries.resourceId={value:resourceId};}if(Object.keys(baggageEntries).length>0){Telemetry.setBaggage(baggageEntries);}const memory=await this.getMemory({runtimeContext});const saveQueueManager=new SaveQueueManager({logger:this.logger,memory});const{before,after}=this.__primitive({messages,instructions,context,thread:threadFromArgs,memoryConfig,resourceId,runId,toolsets,clientTools,runtimeContext,saveQueueManager,writableStream,methodType,tracingContext,tracingOptions});let messageList;let thread;let threadExists;return {llm,before:async()=>{const beforeResult=await before();const{messageObjects,convertedTools,agentAISpan}=beforeResult;threadExists=beforeResult.threadExists||false;messageList=beforeResult.messageList;thread=beforeResult.thread;const threadId=thread?.id;const result={...options,messages:messageObjects,tools:convertedTools,runId,temperature,toolChoice,threadId,resourceId,runtimeContext,onStepFinish:async props=>{if(savePerStep){if(!threadExists&&memory&&thread){await memory.createThread({threadId,title:thread.title,metadata:thread.metadata,resourceId:thread.resourceId,memoryConfig});threadExists=true;}await this.saveStepMessages({saveQueueManager,result:props,messageList,threadId,memoryConfig,runId});}return onStepFinish?.({...props,runId});},...(beforeResult.tripwire&&{tripwire:beforeResult.tripwire,tripwireReason:beforeResult.tripwireReason}),...args,agentAISpan};return result;},after:async({result,outputText,structuredOutput=false,agentAISpan,overrideScorers})=>{const afterResult=await after({result,outputText,threadId:thread?.id,thread,memoryConfig,runId,messageList,structuredOutput,threadExists,agentAISpan,overrideScorers});return afterResult;}};}async prepareModels(runtimeContext,model){if(model||!Array.isArray(this.model)){const modelToUse=model??this.model;const resolvedModel=typeof modelToUse==="function"?await modelToUse({runtimeContext,mastra:this.#mastra}):modelToUse;if(resolvedModel.specificationVersion!=="v2"){const mastraError=new MastraError({id:"AGENT_PREPARE_MODELS_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Only v2 models are allowed when an array of models is provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return [{id:"main",model:resolvedModel,maxRetries:this.maxRetries??0,enabled:true}];}const models=await Promise.all(this.model.map(async modelConfig=>{const model2=await this.resolveModelConfig(modelConfig.model,runtimeContext);if(model2.specificationVersion!=="v2"){const mastraError=new MastraError({id:"AGENT_PREPARE_MODELS_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Only v2 models are allowed when an array of models is provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}const modelId=modelConfig.id||model2.modelId;if(!modelId){const mastraError=new MastraError({id:"AGENT_PREPARE_MODELS_MISSING_MODEL_ID",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Unable to determine model ID. Please provide an explicit ID in the model configuration.`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return {id:modelId,model:model2,maxRetries:modelConfig.maxRetries??0,enabled:modelConfig.enabled??true};}));return models;}/**
694
699
  * Merges telemetry wrapper with default onFinish callback when needed
695
700
  */#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions){let finalOnFinish=streamOptions?.onFinish||defaultStreamOptions.onFinish;if(streamOptions?.onFinish&&streamOptions.onFinish.__hasOriginalOnFinish===false&&defaultStreamOptions.onFinish){const telemetryWrapper=streamOptions.onFinish;const defaultCallback=defaultStreamOptions.onFinish;finalOnFinish=async data=>{await telemetryWrapper(data);await defaultCallback(data);};}return finalOnFinish;}async#execute({methodType,format="mastra",resumeContext,...options}){const runtimeContext=options.runtimeContext||new RuntimeContext();const threadFromArgs=resolveThreadIdFromArgs({threadId:options.threadId,memory:options.memory});const resourceId=options.memory?.resource||options.resourceId;const memoryConfig=options.memory?.options;if(resourceId&&threadFromArgs&&!this.hasOwnMemory()){this.logger.warn(`[Agent:${this.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`);}const llm=await this.getLLM({runtimeContext,model:options.model});const runId=options.runId||this.#mastra?.generateId()||randomUUID();const instructions=options.instructions||(await this.getInstructions({runtimeContext}));const agentAISpan=getOrCreateSpan({type:"agent_run"/* AGENT_RUN */,name:`agent run: '${this.id}'`,input:options.messages,attributes:{agentId:this.id,instructions:this.#convertInstructionsToString(instructions)},metadata:{runId,resourceId,threadId:threadFromArgs?.id},tracingPolicy:this.#options?.tracingPolicy,tracingOptions:options.tracingOptions,tracingContext:options.tracingContext,runtimeContext});const activeSpan=Telemetry.getActiveSpan();const baggageEntries={};if(threadFromArgs?.id){if(activeSpan){activeSpan.setAttribute("threadId",threadFromArgs.id);}baggageEntries.threadId={value:threadFromArgs.id};}if(resourceId){if(activeSpan){activeSpan.setAttribute("resourceId",resourceId);}baggageEntries.resourceId={value:resourceId};}if(Object.keys(baggageEntries).length>0){Telemetry.setBaggage(baggageEntries);}const memory=await this.getMemory({runtimeContext});const saveQueueManager=new SaveQueueManager({logger:this.logger,memory});if(process.env.NODE_ENV!=="test"){this.logger.debug(`[Agents:${this.name}] - Starting generation`,{runId});}const capabilities={agentName:this.name,logger:this.logger,getMemory:this.getMemory.bind(this),getModel:this.getModel.bind(this),generateMessageId:this.#mastra?.generateId?.bind(this.#mastra)||(()=>randomUUID()),_agentNetworkAppend:"_agentNetworkAppend"in this?Boolean(this._agentNetworkAppend):void 0,saveStepMessages:this.saveStepMessages.bind(this),convertTools:this.convertTools.bind(this),getMemoryMessages:this.getMemoryMessages.bind(this),runInputProcessors:this.__runInputProcessors.bind(this),executeOnFinish:this.#executeOnFinish.bind(this),outputProcessors:this.#outputProcessors,llm,getTelemetry:this.#mastra?.getTelemetry?.bind(this.#mastra)};const executionWorkflow=createPrepareStreamWorkflow({capabilities,options:{...options,methodType},threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData:options.returnScorerData,requireToolApproval:options.requireToolApproval,resumeContext});const run=await executionWorkflow.createRunAsync();const result=await run.start({tracingContext:{currentSpan:agentAISpan}});return result;}async#executeOnFinish({result,instructions,readOnlyMemory,thread:threadAfter,threadId,resourceId,memoryConfig,outputText,runtimeContext,agentAISpan,runId,messageList,threadExists,structuredOutput=false,saveQueueManager,overrideScorers}){const resToLog={text:result.text,object:result.object,toolResults:result.toolResults,toolCalls:result.toolCalls,usage:result.usage,steps:result.steps.map(s=>{return {stepType:s.stepType,text:s.text,toolResults:s.toolResults,toolCalls:s.toolCalls,usage:s.usage};})};this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`,{runId,result:resToLog,threadId,resourceId});const messageListResponses=messageList.get.response.aiV4.core();const usedWorkingMemory=messageListResponses.some(m=>m.role==="tool"&&m.content.some(c=>c.toolName==="updateWorkingMemory"));const memory=await this.getMemory({runtimeContext});const thread=usedWorkingMemory?threadId?await memory?.getThreadById({threadId}):void 0:threadAfter;if(memory&&resourceId&&thread&&!readOnlyMemory){try{let responseMessages=result.response.messages;if(!responseMessages&&result.object){responseMessages=[{id:result.response.id,role:"assistant",content:[{type:"text",text:outputText// outputText contains the stringified object
696
701
  }]}];}if(responseMessages){messageList.add(responseMessages,"response");}if(!threadExists){await memory.createThread({threadId:thread.id,metadata:thread.metadata,title:thread.title,memoryConfig,resourceId:thread.resourceId});}const promises=[saveQueueManager.flushMessages(messageList,threadId,memoryConfig)];if(thread.title?.startsWith("New Thread")){const config=memory.getMergedThreadConfig(memoryConfig);const userMessage=this.getMostRecentUserMessage(messageList.get.all.ui());const{shouldGenerate,model:titleModel,instructions:titleInstructions}=this.resolveTitleGenerationConfig(config.threads?.generateTitle);if(shouldGenerate&&userMessage){promises.push(this.genTitle(userMessage,runtimeContext,{currentSpan:agentAISpan},titleModel,titleInstructions).then(title=>{if(title){return memory.createThread({threadId:thread.id,resourceId,memoryConfig,title,metadata:thread.metadata});}}));}}await Promise.all(promises);}catch(e){await saveQueueManager.flushMessages(messageList,threadId,memoryConfig);if(e instanceof MastraError){throw e;}const mastraError=new MastraError({id:"AGENT_MEMORY_PERSIST_RESPONSE_MESSAGES_FAILED",domain:"AGENT"/* AGENT */,category:"SYSTEM"/* SYSTEM */,details:{agentName:this.name,runId:runId||"",threadId:threadId||"",result:JSON.stringify(resToLog)}},e);this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}}else {let responseMessages=result.response.messages;if(!responseMessages&&result.object){responseMessages=[{id:result.response.id,role:"assistant",content:[{type:"text",text:outputText// outputText contains the stringified object
697
702
  }]}];}if(responseMessages){messageList.add(responseMessages,"response");}}await this.#runScorers({messageList,runId,outputText,instructions,runtimeContext,structuredOutput,overrideScorers,tracingContext:{currentSpan:agentAISpan}});agentAISpan?.end({output:{text:result.text,object:result.object,files:result.files}});}async network(messages,options){const runId=options?.runId||this.#mastra?.generateId()||randomUUID();const runtimeContextToUse=options?.runtimeContext||new RuntimeContext();return await networkLoop({networkName:this.name,runtimeContext:runtimeContextToUse,runId,routingAgent:this,routingAgentOptions:{telemetry:options?.telemetry,modelSettings:options?.modelSettings},generateId:()=>this.#mastra?.generateId()||randomUUID(),maxIterations:options?.maxSteps||1,messages,threadId:typeof options?.memory?.thread==="string"?options?.memory?.thread:options?.memory?.thread?.id,resourceId:options?.memory?.resource});}async generateVNext(messages,options){const result=await this.streamVNext(messages,options);const fullOutput=await result.getFullOutput();const error=fullOutput.error;if(fullOutput.finishReason==="error"&&error){throw error;}return fullOutput;}async streamVNext(messages,streamOptions){const defaultStreamOptions=await this.getDefaultVNextStreamOptions({runtimeContext:streamOptions?.runtimeContext});if(defaultStreamOptions.structuredOutput&&defaultStreamOptions.output||streamOptions?.structuredOutput&&streamOptions.output){throw new MastraError({id:"AGENT_STREAM_VNEXT_STRUCTURED_OUTPUT_AND_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput and output cannot be provided at the same time"});}let adjustedDefaultStreamOptions={...defaultStreamOptions};if(streamOptions?.structuredOutput||streamOptions?.output){const{output,structuredOutput,...restDefaultOptions}=adjustedDefaultStreamOptions;adjustedDefaultStreamOptions=restDefaultOptions;}let mergedStreamOptions={...adjustedDefaultStreamOptions,...(streamOptions??{}),onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions)};let modelOverride;if(mergedStreamOptions.structuredOutput&&mergedStreamOptions.maxSteps===1){if(mergedStreamOptions.structuredOutput.model){modelOverride=mergedStreamOptions.structuredOutput.model;}const{structuredOutput,...optionsWithoutStructuredOutput}=mergedStreamOptions;mergedStreamOptions={...optionsWithoutStructuredOutput,output:structuredOutput.schema};}const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext,model:modelOverride});if(llm.getModel().specificationVersion!=="v2"){const modelInfo=llm.getModel();const modelId=modelInfo.modelId||"unknown";const provider=modelInfo.provider||"unknown";throw new MastraError({id:"AGENT_STREAM_VNEXT_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`Agent "${this.name}" is using AI SDK v4 model (${provider}:${modelId}) which is not compatible with streamVNext. Please use AI SDK v5 models or call the stream() method instead. See https://mastra.ai/en/docs/streaming/overview for more information.`,details:{agentName:this.name,modelId,provider,specificationVersion:modelInfo.specificationVersion}});}const executeOptions={...mergedStreamOptions,messages,methodType:"streamVNext",model:modelOverride};const result=await this.#execute(executeOptions);if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_VNEXT_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:result.error.message,details:{error:result.error.message}});}throw new MastraError({id:"AGENT_STREAM_VNEXT_UNKNOWN_ERROR",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"An unknown error occurred while streaming"});}return result.result;}async resumeStreamVNext(resumeContext,streamOptions){const defaultStreamOptions=await this.getDefaultVNextStreamOptions({runtimeContext:streamOptions?.runtimeContext});let mergedStreamOptions={...defaultStreamOptions,...streamOptions,onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions)};let modelOverride;if(mergedStreamOptions.structuredOutput&&mergedStreamOptions.maxSteps===1){if(mergedStreamOptions.structuredOutput.model){modelOverride=mergedStreamOptions.structuredOutput.model;}mergedStreamOptions={...mergedStreamOptions,output:mergedStreamOptions.structuredOutput.schema,structuredOutput:void 0// Remove structuredOutput to avoid confusion downstream
698
- };}const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext,model:modelOverride});if(llm.getModel().specificationVersion!=="v2"){throw new MastraError({id:"AGENT_STREAM_VNEXT_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"V1 models are not supported for streamVNext. Please use stream instead."});}const result=await this.#execute({...mergedStreamOptions,messages:[],resumeContext,methodType:"streamVNext",model:modelOverride});if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_VNEXT_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:result.error.message,details:{error:result.error.message}});}throw new MastraError({id:"AGENT_STREAM_VNEXT_UNKNOWN_ERROR",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"An unknown error occurred while streaming"});}return result.result;}async approveToolCall(streamOptions){return this.resumeStreamVNext({approved:true},streamOptions);}async declineToolCall(streamOptions){return this.resumeStreamVNext({approved:false},streamOptions);}async generate(messages,generateOptions={}){if(!generateDeprecationWarningShown){this.logger.warn("Deprecation NOTICE:\nGenerate method will switch to use generateVNext implementation September 30th, 2025. Please use generateLegacy if you don't want to upgrade just yet.");generateDeprecationWarningShown=true;}return this.generateLegacy(messages,generateOptions);}async generateLegacy(messages,generateOptions={}){const defaultGenerateOptions=await this.getDefaultGenerateOptions({runtimeContext:generateOptions.runtimeContext});const mergedGenerateOptions={...defaultGenerateOptions,...generateOptions,experimental_generateMessageId:defaultGenerateOptions.experimental_generateMessageId||this.#mastra?.generateId?.bind(this.#mastra)};const{llm,before,after}=await this.prepareLLMOptions(messages,mergedGenerateOptions,"generate");if(llm.getModel().specificationVersion!=="v1"){this.logger.error("V2 models are not supported for the current version of generate. Please use generateVNext instead.",{modelId:llm.getModel().modelId});throw new MastraError({id:"AGENT_GENERATE_V2_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{modelId:llm.getModel().modelId},text:"V2 models are not supported for the current version of generate. Please use generateVNext instead."});}let llmToUse=llm;const beforeResult=await before();const traceId=getValidTraceId(beforeResult.agentAISpan);if(beforeResult.tripwire){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:beforeResult.tripwireReason,traceId};return tripwireResult;}const{experimental_output,output,agentAISpan,...llmOptions}=beforeResult;const tracingContext={currentSpan:agentAISpan};let finalOutputProcessors=mergedGenerateOptions.outputProcessors;if(mergedGenerateOptions.structuredOutput){const agentModel=await this.getModel({runtimeContext:mergedGenerateOptions.runtimeContext});const structuredProcessor=new StructuredOutputProcessor(mergedGenerateOptions.structuredOutput,agentModel);finalOutputProcessors=finalOutputProcessors?[...finalOutputProcessors,structuredProcessor]:[structuredProcessor];}if(!output||experimental_output){const result2=await llmToUse.__text({...llmOptions,tracingContext,experimental_output});const outputProcessorResult2=await this.__runOutputProcessors({runtimeContext:mergedGenerateOptions.runtimeContext||new RuntimeContext(),tracingContext,outputProcessorOverrides:finalOutputProcessors,messageList:new MessageList({threadId:llmOptions.threadId||"",resourceId:llmOptions.resourceId||""}).add({role:"assistant",content:[{type:"text",text:result2.text}]},"response")});if(outputProcessorResult2.tripwireTriggered){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:outputProcessorResult2.tripwireReason,traceId};return tripwireResult;}const newText2=outputProcessorResult2.messageList.get.response.v2().map(msg=>msg.content.parts.map(part=>part.type==="text"?part.text:"").join("")).join("");result2.text=newText2;if(finalOutputProcessors&&finalOutputProcessors.length>0){const messages2=outputProcessorResult2.messageList.get.response.v2();this.logger.debug("Checking messages for experimentalOutput metadata:",messages2.map(m=>({role:m.role,hasContentMetadata:!!m.content.metadata,contentMetadata:m.content.metadata})));const messagesWithStructuredData=messages2.filter(msg=>msg.content.metadata&&msg.content.metadata.structuredOutput);this.logger.debug("Messages with structured data:",messagesWithStructuredData.length);if(messagesWithStructuredData[0]&&messagesWithStructuredData[0].content.metadata?.structuredOutput){result2.object=messagesWithStructuredData[0].content.metadata.structuredOutput;this.logger.debug("Using structured data from processor metadata for result.object");}else {try{const processedOutput=JSON.parse(newText2);result2.object=processedOutput;this.logger.debug("Using fallback JSON parsing for result.object");}catch(error){this.logger.warn("Failed to parse processed output as JSON, updating text only",{error});}}}const overrideScorers=mergedGenerateOptions.scorers;const afterResult2=await after({result:result2,outputText:newText2,agentAISpan,...(overrideScorers?{overrideScorers}:{})});if(generateOptions.returnScorerData){result2.scoringData=afterResult2.scoringData;}result2.traceId=traceId;return result2;}const result=await llmToUse.__textObject({...llmOptions,tracingContext,structuredOutput:output});const outputText=JSON.stringify(result.object);const outputProcessorResult=await this.__runOutputProcessors({runtimeContext:mergedGenerateOptions.runtimeContext||new RuntimeContext(),tracingContext,messageList:new MessageList({threadId:llmOptions.threadId||"",resourceId:llmOptions.resourceId||""}).add({role:"assistant",content:[{type:"text",text:outputText}]},"response")});if(outputProcessorResult.tripwireTriggered){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:outputProcessorResult.tripwireReason,traceId};return tripwireResult;}const newText=outputProcessorResult.messageList.get.response.v2().map(msg=>msg.content.parts.map(part=>part.type==="text"?part.text:"").join("")).join("");try{const processedObject=JSON.parse(newText);result.object=processedObject;}catch(error){this.logger.warn("Failed to parse processed output as JSON, keeping original result",{error});}const afterResult=await after({result,outputText:newText,...(generateOptions.scorers?{overrideScorers:generateOptions.scorers}:{}),structuredOutput:true,agentAISpan});if(generateOptions.returnScorerData){result.scoringData=afterResult.scoringData;}result.traceId=traceId;return result;}async stream(messages,streamOptions={}){if(!streamDeprecationWarningShown){this.logger.warn("Deprecation NOTICE:\nStream method will switch to use streamVNext implementation September 30th, 2025. Please use streamLegacy if you don't want to upgrade just yet.");streamDeprecationWarningShown=true;}return this.streamLegacy(messages,streamOptions);}async streamLegacy(messages,streamOptions={}){const defaultStreamOptions=await this.getDefaultStreamOptions({runtimeContext:streamOptions.runtimeContext});const mergedStreamOptions={...defaultStreamOptions,...streamOptions,onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions),experimental_generateMessageId:defaultStreamOptions.experimental_generateMessageId||this.#mastra?.generateId?.bind(this.#mastra)};const{llm,before,after}=await this.prepareLLMOptions(messages,mergedStreamOptions,"stream");if(llm.getModel().specificationVersion!=="v1"){this.logger.error("V2 models are not supported for stream. Please use streamVNext instead.",{modelId:llm.getModel().modelId});throw new MastraError({id:"AGENT_STREAM_V2_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{modelId:llm.getModel().modelId},text:"V2 models are not supported for stream. Please use streamVNext instead."});}const beforeResult=await before();const traceId=getValidTraceId(beforeResult.agentAISpan);if(beforeResult.tripwire){const emptyResult={textStream:async function*(){}(),fullStream:Promise.resolve("").then(()=>{const emptyStream=new globalThis.ReadableStream({start(controller){controller.close();}});return emptyStream;}),text:Promise.resolve(""),usage:Promise.resolve({totalTokens:0,promptTokens:0,completionTokens:0}),finishReason:Promise.resolve("other"),tripwire:true,tripwireReason:beforeResult.tripwireReason,response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},toolCalls:Promise.resolve([]),toolResults:Promise.resolve([]),warnings:Promise.resolve(void 0),request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,traceId,toAIStream:()=>Promise.resolve("").then(()=>{const emptyStream=new globalThis.ReadableStream({start(controller){controller.close();}});return emptyStream;}),get experimental_partialOutputStream(){return async function*(){}();},pipeDataStreamToResponse:()=>Promise.resolve(),pipeTextStreamToResponse:()=>Promise.resolve(),toDataStreamResponse:()=>new Response("",{status:200,headers:{"Content-Type":"text/plain"}}),toTextStreamResponse:()=>new Response("",{status:200,headers:{"Content-Type":"text/plain"}})};return emptyResult;}const{onFinish,runId,output,experimental_output,agentAISpan,...llmOptions}=beforeResult;const overrideScorers=mergedStreamOptions.scorers;const tracingContext={currentSpan:agentAISpan};if(!output||experimental_output){this.logger.debug(`Starting agent ${this.name} llm stream call`,{runId});const streamResult=llm.__stream({...llmOptions,experimental_output,tracingContext,outputProcessors:await this.getResolvedOutputProcessors(mergedStreamOptions.runtimeContext),onFinish:async result=>{try{const outputText=result.text;await after({result,outputText,agentAISpan,...(overrideScorers?{overrideScorers}:{})});}catch(e){this.logger.error("Error saving memory on finish",{error:e,runId});}await onFinish?.({...result,runId});},runId});streamResult.traceId=traceId;return streamResult;}this.logger.debug(`Starting agent ${this.name} llm streamObject call`,{runId});const streamObjectResult=llm.__streamObject({...llmOptions,tracingContext,onFinish:async result=>{try{const outputText=JSON.stringify(result.object);await after({result,outputText,structuredOutput:true,agentAISpan,...(overrideScorers?{overrideScorers}:{})});}catch(e){this.logger.error("Error saving memory on finish",{error:e,runId});}await onFinish?.({...result,runId});},runId,structuredOutput:output});streamObjectResult.traceId=traceId;return streamObjectResult;}/**
703
+ };}const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext,model:modelOverride});if(llm.getModel().specificationVersion!=="v2"){throw new MastraError({id:"AGENT_STREAM_VNEXT_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"V1 models are not supported for streamVNext. Please use stream instead."});}const result=await this.#execute({...mergedStreamOptions,messages:[],resumeContext,methodType:"streamVNext",model:modelOverride});if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_VNEXT_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:result.error.message,details:{error:result.error.message}});}throw new MastraError({id:"AGENT_STREAM_VNEXT_UNKNOWN_ERROR",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"An unknown error occurred while streaming"});}return result.result;}async approveToolCall(streamOptions){return this.resumeStreamVNext({approved:true},streamOptions);}async declineToolCall(streamOptions){return this.resumeStreamVNext({approved:false},streamOptions);}async generate(messages,generateOptions={}){if(!generateDeprecationWarningShown){this.logger.warn("Deprecation NOTICE:\nGenerate method will switch to use generateVNext implementation the week of September 30th, 2025. Please use generateLegacy if you don't want to upgrade just yet.");generateDeprecationWarningShown=true;}return this.generateLegacy(messages,generateOptions);}async generateLegacy(messages,generateOptions={}){const defaultGenerateOptions=await this.getDefaultGenerateOptions({runtimeContext:generateOptions.runtimeContext});const mergedGenerateOptions={...defaultGenerateOptions,...generateOptions,experimental_generateMessageId:defaultGenerateOptions.experimental_generateMessageId||this.#mastra?.generateId?.bind(this.#mastra)};const{llm,before,after}=await this.prepareLLMOptions(messages,mergedGenerateOptions,"generate");if(llm.getModel().specificationVersion!=="v1"){this.logger.error("V2 models are not supported for the current version of generate. Please use generateVNext instead.",{modelId:llm.getModel().modelId});throw new MastraError({id:"AGENT_GENERATE_V2_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{modelId:llm.getModel().modelId},text:"V2 models are not supported for the current version of generate. Please use generateVNext instead."});}let llmToUse=llm;const beforeResult=await before();const traceId=getValidTraceId(beforeResult.agentAISpan);if(beforeResult.tripwire){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:beforeResult.tripwireReason,traceId};return tripwireResult;}const{experimental_output,output,agentAISpan,...llmOptions}=beforeResult;const tracingContext={currentSpan:agentAISpan};let finalOutputProcessors=mergedGenerateOptions.outputProcessors;if(mergedGenerateOptions.structuredOutput){const agentModel=await this.getModel({runtimeContext:mergedGenerateOptions.runtimeContext});const structuredProcessor=new StructuredOutputProcessor(mergedGenerateOptions.structuredOutput,agentModel);finalOutputProcessors=finalOutputProcessors?[...finalOutputProcessors,structuredProcessor]:[structuredProcessor];}if(!output||experimental_output){const result2=await llmToUse.__text({...llmOptions,tracingContext,experimental_output});const outputProcessorResult2=await this.__runOutputProcessors({runtimeContext:mergedGenerateOptions.runtimeContext||new RuntimeContext(),tracingContext,outputProcessorOverrides:finalOutputProcessors,messageList:new MessageList({threadId:llmOptions.threadId||"",resourceId:llmOptions.resourceId||""}).add({role:"assistant",content:[{type:"text",text:result2.text}]},"response")});if(outputProcessorResult2.tripwireTriggered){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:outputProcessorResult2.tripwireReason,traceId};return tripwireResult;}const newText2=outputProcessorResult2.messageList.get.response.v2().map(msg=>msg.content.parts.map(part=>part.type==="text"?part.text:"").join("")).join("");result2.text=newText2;if(finalOutputProcessors&&finalOutputProcessors.length>0){const messages2=outputProcessorResult2.messageList.get.response.v2();this.logger.debug("Checking messages for experimentalOutput metadata:",messages2.map(m=>({role:m.role,hasContentMetadata:!!m.content.metadata,contentMetadata:m.content.metadata})));const messagesWithStructuredData=messages2.filter(msg=>msg.content.metadata&&msg.content.metadata.structuredOutput);this.logger.debug("Messages with structured data:",messagesWithStructuredData.length);if(messagesWithStructuredData[0]&&messagesWithStructuredData[0].content.metadata?.structuredOutput){result2.object=messagesWithStructuredData[0].content.metadata.structuredOutput;this.logger.debug("Using structured data from processor metadata for result.object");}else {try{const processedOutput=JSON.parse(newText2);result2.object=processedOutput;this.logger.debug("Using fallback JSON parsing for result.object");}catch(error){this.logger.warn("Failed to parse processed output as JSON, updating text only",{error});}}}const overrideScorers=mergedGenerateOptions.scorers;const afterResult2=await after({result:result2,outputText:newText2,agentAISpan,...(overrideScorers?{overrideScorers}:{})});if(generateOptions.returnScorerData){result2.scoringData=afterResult2.scoringData;}result2.traceId=traceId;return result2;}const result=await llmToUse.__textObject({...llmOptions,tracingContext,structuredOutput:output});const outputText=JSON.stringify(result.object);const outputProcessorResult=await this.__runOutputProcessors({runtimeContext:mergedGenerateOptions.runtimeContext||new RuntimeContext(),tracingContext,messageList:new MessageList({threadId:llmOptions.threadId||"",resourceId:llmOptions.resourceId||""}).add({role:"assistant",content:[{type:"text",text:outputText}]},"response")});if(outputProcessorResult.tripwireTriggered){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:outputProcessorResult.tripwireReason,traceId};return tripwireResult;}const newText=outputProcessorResult.messageList.get.response.v2().map(msg=>msg.content.parts.map(part=>part.type==="text"?part.text:"").join("")).join("");try{const processedObject=JSON.parse(newText);result.object=processedObject;}catch(error){this.logger.warn("Failed to parse processed output as JSON, keeping original result",{error});}const afterResult=await after({result,outputText:newText,...(generateOptions.scorers?{overrideScorers:generateOptions.scorers}:{}),structuredOutput:true,agentAISpan});if(generateOptions.returnScorerData){result.scoringData=afterResult.scoringData;}result.traceId=traceId;return result;}async stream(messages,streamOptions={}){if(!streamDeprecationWarningShown){this.logger.warn("Deprecation NOTICE:\nStream method will switch to use streamVNext implementation the week of September 30th, 2025. Please use streamLegacy if you don't want to upgrade just yet.");streamDeprecationWarningShown=true;}return this.streamLegacy(messages,streamOptions);}async streamLegacy(messages,streamOptions={}){const defaultStreamOptions=await this.getDefaultStreamOptions({runtimeContext:streamOptions.runtimeContext});const mergedStreamOptions={...defaultStreamOptions,...streamOptions,onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions),experimental_generateMessageId:defaultStreamOptions.experimental_generateMessageId||this.#mastra?.generateId?.bind(this.#mastra)};const{llm,before,after}=await this.prepareLLMOptions(messages,mergedStreamOptions,"stream");if(llm.getModel().specificationVersion!=="v1"){this.logger.error("V2 models are not supported for stream. Please use streamVNext instead.",{modelId:llm.getModel().modelId});throw new MastraError({id:"AGENT_STREAM_V2_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{modelId:llm.getModel().modelId},text:"V2 models are not supported for stream. Please use streamVNext instead."});}const beforeResult=await before();const traceId=getValidTraceId(beforeResult.agentAISpan);if(beforeResult.tripwire){const emptyResult={textStream:async function*(){}(),fullStream:Promise.resolve("").then(()=>{const emptyStream=new globalThis.ReadableStream({start(controller){controller.close();}});return emptyStream;}),text:Promise.resolve(""),usage:Promise.resolve({totalTokens:0,promptTokens:0,completionTokens:0}),finishReason:Promise.resolve("other"),tripwire:true,tripwireReason:beforeResult.tripwireReason,response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},toolCalls:Promise.resolve([]),toolResults:Promise.resolve([]),warnings:Promise.resolve(void 0),request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,traceId,toAIStream:()=>Promise.resolve("").then(()=>{const emptyStream=new globalThis.ReadableStream({start(controller){controller.close();}});return emptyStream;}),get experimental_partialOutputStream(){return async function*(){}();},pipeDataStreamToResponse:()=>Promise.resolve(),pipeTextStreamToResponse:()=>Promise.resolve(),toDataStreamResponse:()=>new Response("",{status:200,headers:{"Content-Type":"text/plain"}}),toTextStreamResponse:()=>new Response("",{status:200,headers:{"Content-Type":"text/plain"}})};return emptyResult;}const{onFinish,runId,output,experimental_output,agentAISpan,...llmOptions}=beforeResult;const overrideScorers=mergedStreamOptions.scorers;const tracingContext={currentSpan:agentAISpan};if(!output||experimental_output){this.logger.debug(`Starting agent ${this.name} llm stream call`,{runId});const streamResult=llm.__stream({...llmOptions,experimental_output,tracingContext,outputProcessors:await this.getResolvedOutputProcessors(mergedStreamOptions.runtimeContext),onFinish:async result=>{try{const outputText=result.text;await after({result,outputText,agentAISpan,...(overrideScorers?{overrideScorers}:{})});}catch(e){this.logger.error("Error saving memory on finish",{error:e,runId});}await onFinish?.({...result,runId});},runId});streamResult.traceId=traceId;return streamResult;}this.logger.debug(`Starting agent ${this.name} llm streamObject call`,{runId});const streamObjectResult=llm.__streamObject({...llmOptions,tracingContext,onFinish:async result=>{try{const outputText=JSON.stringify(result.object);await after({result,outputText,structuredOutput:true,agentAISpan,...(overrideScorers?{overrideScorers}:{})});}catch(e){this.logger.error("Error saving memory on finish",{error:e,runId});}await onFinish?.({...result,runId});},runId,structuredOutput:output});streamObjectResult.traceId=traceId;return streamObjectResult;}/**
699
704
  * Convert text to speech using the configured voice provider
700
705
  * @param input Text or text stream to convert to speech
701
706
  * @param options Speech options including speaker and provider-specific options
@@ -725,7 +730,9 @@ _agentNetworkAppend:this._agentNetworkAppend}).add(result.response.messages,"res
725
730
  - do not use quotes or colons
726
731
  - the entire text you return will be used as the title`;if(!instructions){return DEFAULT_TITLE_INSTRUCTIONS;}if(typeof instructions==="string"){return instructions;}else {const result=instructions({runtimeContext,mastra:this.#mastra});return resolveMaybePromise(result,resolvedInstructions=>{return resolvedInstructions||DEFAULT_TITLE_INSTRUCTIONS;});}}};Agent=/*@__PURE__*/(_=>{_init=__decoratorStart(_a);Agent=__decorateElement(_init,0,"Agent",_Agent_decorators,Agent);__runInitializers(_init,1,Agent);// src/stream/aisdk/v5/output.ts
727
732
  return Agent;})();// src/stream/aisdk/v5/output.ts
728
- var AISDKV5OutputStream=class{#modelOutput;#options;#messageList;constructor({modelOutput,options,messageList}){this.#modelOutput=modelOutput;this.#options=options;this.#messageList=messageList;}toTextStreamResponse(init){return createTextStreamResponse({// Type assertion needed due to ReadableStream type mismatch between Node.js (stream/web) and DOM types
733
+ var AISDKV5OutputStream=class{#modelOutput;#options;#messageList;/**
734
+ * Trace ID used on the execution (if the execution was traced).
735
+ */traceId;constructor({modelOutput,options,messageList}){this.#modelOutput=modelOutput;this.#options=options;this.#messageList=messageList;this.traceId=getValidTraceId(options.tracingContext?.currentSpan);}toTextStreamResponse(init){return createTextStreamResponse({// Type assertion needed due to ReadableStream type mismatch between Node.js (stream/web) and DOM types
729
736
  // Both have the same interface but TypeScript treats them as incompatible
730
737
  textStream:this.#modelOutput.textStream,...init});}toUIMessageStreamResponse({generateMessageId,originalMessages,sendFinish,sendReasoning,sendSources,onError,sendStart,messageMetadata,onFinish,...init}={}){return createUIMessageStreamResponse({stream:this.toUIMessageStream({generateMessageId,originalMessages,sendFinish,sendReasoning,sendSources,onError,sendStart,messageMetadata,onFinish}),...init});}toUIMessageStream({generateMessageId,originalMessages,sendFinish=true,sendReasoning=true,sendSources=false,onError=getErrorMessage,sendStart=true,messageMetadata,onFinish}={}){let responseMessageId=generateMessageId!=null?getResponseUIMessageId({originalMessages,responseMessageId:generateMessageId}):void 0;return createUIMessageStream({onError,onFinish,generateId:()=>responseMessageId??generateMessageId?.()??generateId(),execute:async({writer})=>{for await(const part of this.fullStream){const messageMetadataValue=messageMetadata?.({part});const partType=part.type;responseMessageId=this.#modelOutput.messageId;const transformedChunk=convertFullStreamChunkToUIMessageStream({part,sendReasoning,messageMetadataValue,sendSources,sendStart,sendFinish,responseMessageId,onError});if(transformedChunk){writer.write(transformedChunk);}if(messageMetadataValue!=null&&partType!=="start"&&partType!=="finish"){writer.write({type:"message-metadata",messageMetadata:messageMetadataValue});}}}});}async consumeStream(options){try{await consumeStream({// Type coercion needed due to ReadableStream type mismatch between Node and DOM types
731
738
  stream:this.fullStream,onError:options?.onError});}catch(error){console.error("consumeStream error",error);options?.onError?.(error);}}get sources(){return this.#modelOutput.sources.then(sources=>sources.map(source=>{return convertMastraChunkToAISDKv5({chunk:source});}));}get files(){return this.#modelOutput.files.then(files=>files.map(file=>{if(file.type==="file"){const result=convertMastraChunkToAISDKv5({chunk:file});return result&&"file"in result?result.file:void 0;}return;}).filter(Boolean));}get text(){return this.#modelOutput.text;}/**
@@ -736,7 +743,7 @@ stream:this.fullStream,onError:options?.onError});}catch(error){console.error("c
736
743
  * Stream of individual array elements when output schema is an array type.
737
744
  */get elementStream(){return this.#modelOutput.elementStream;}/**
738
745
  * Stream of all chunks in AI SDK v5 format.
739
- */get fullStream(){let startEvent;let hasStarted=false;const responseFormat=getResponseFormat(this.#options.output);const fullStream=this.#modelOutput.fullStream;const transformedStream=fullStream.pipeThrough(new TransformStream({transform(chunk,controller){if(responseFormat?.type==="json"&&chunk.type==="object"){controller.enqueue(chunk);return;}if(chunk.type==="step-start"&&!startEvent){startEvent=convertMastraChunkToAISDKv5({chunk});return;}else if(chunk.type!=="error"){hasStarted=true;}if(startEvent&&hasStarted){controller.enqueue(startEvent);startEvent=void 0;}if("payload"in chunk){const transformedChunk=convertMastraChunkToAISDKv5({chunk});if(transformedChunk){controller.enqueue(transformedChunk);}}}}));return transformedStream;}async getFullOutput(){await this.consumeStream();const object=await this.object;const fullOutput={text:await this.#modelOutput.text,usage:await this.#modelOutput.usage,steps:await this.steps,finishReason:await this.#modelOutput.finishReason,warnings:await this.#modelOutput.warnings,providerMetadata:await this.#modelOutput.providerMetadata,request:await this.#modelOutput.request,reasoning:await this.reasoning,reasoningText:await this.reasoningText,toolCalls:await this.toolCalls,toolResults:await this.toolResults,sources:await this.sources,files:await this.files,response:await this.response,content:this.content,totalUsage:await this.#modelOutput.totalUsage,error:this.error,tripwire:this.#modelOutput.tripwire,tripwireReason:this.#modelOutput.tripwireReason,...(object?{object}:{})};fullOutput.response.messages=this.#modelOutput.messageList.get.response.aiV5.model();return fullOutput;}get tripwire(){return this.#modelOutput.tripwire;}get tripwireReason(){return this.#modelOutput.tripwireReason;}get error(){return this.#modelOutput.error;}get object(){return this.#modelOutput.object;}};// src/stream/base/output-format-handlers.ts
746
+ */get fullStream(){let startEvent;let hasStarted=false;const responseFormat=getResponseFormat(this.#options.output);const fullStream=this.#modelOutput.fullStream;const transformedStream=fullStream.pipeThrough(new TransformStream({transform(chunk,controller){if(responseFormat?.type==="json"&&chunk.type==="object"){controller.enqueue(chunk);return;}if(chunk.type==="step-start"&&!startEvent){startEvent=convertMastraChunkToAISDKv5({chunk});return;}else if(chunk.type!=="error"){hasStarted=true;}if(startEvent&&hasStarted){controller.enqueue(startEvent);startEvent=void 0;}if("payload"in chunk){const transformedChunk=convertMastraChunkToAISDKv5({chunk});if(transformedChunk){controller.enqueue(transformedChunk);}}}}));return transformedStream;}async getFullOutput(){await this.consumeStream();const object=await this.object;const fullOutput={text:await this.#modelOutput.text,usage:await this.#modelOutput.usage,steps:await this.steps,finishReason:await this.#modelOutput.finishReason,warnings:await this.#modelOutput.warnings,providerMetadata:await this.#modelOutput.providerMetadata,request:await this.#modelOutput.request,reasoning:await this.reasoning,reasoningText:await this.reasoningText,toolCalls:await this.toolCalls,toolResults:await this.toolResults,sources:await this.sources,files:await this.files,response:await this.response,content:this.content,totalUsage:await this.#modelOutput.totalUsage,error:this.error,tripwire:this.#modelOutput.tripwire,tripwireReason:this.#modelOutput.tripwireReason,traceId:this.traceId,...(object?{object}:{})};fullOutput.response.messages=this.#modelOutput.messageList.get.response.aiV5.model();return fullOutput;}get tripwire(){return this.#modelOutput.tripwire;}get tripwireReason(){return this.#modelOutput.tripwireReason;}get error(){return this.#modelOutput.error;}get object(){return this.#modelOutput.object;}};// src/stream/base/output-format-handlers.ts
740
747
  var BaseFormatHandler=class{/**
741
748
  * The user-provided schema to validate the final result against.
742
749
  */schema;/**
@@ -766,7 +773,7 @@ var MastraModelOutput=class extends MastraBase{#status="running";#aisdkv5;#error
766
773
  */traceId;messageId;constructor({model:_model,stream,messageList,options,messageId}){super({component:"LLM",name:"MastraModelOutput"});this.#options=options;this.#returnScorerData=!!options.returnScorerData;this.runId=options.runId;this.traceId=getValidTraceId(options.tracingContext?.currentSpan);this.#model=_model;this.messageId=messageId;if(options.outputProcessors?.length){this.processorRunner=new ProcessorRunner({inputProcessors:[],outputProcessors:options.outputProcessors,logger:this.logger,agentName:"MastraModelOutput"});}if(options.outputProcessorRunnerMode){this.outputProcessorRunnerMode=options.outputProcessorRunnerMode;}this.messageList=messageList;const self=this;let processedStream=stream;const processorRunner=this.processorRunner;if(processorRunner&&options.outputProcessorRunnerMode===`stream`){const processorStates=/* @__PURE__ */new Map();processedStream=stream.pipeThrough(new TransformStream({async transform(chunk,controller){const{part:processed,blocked,reason}=await processorRunner.processPart(chunk,processorStates);if(blocked){controller.enqueue({type:"tripwire",payload:{tripwireReason:reason||"Output processor blocked content"}});return;}if(processed){controller.enqueue(processed);}}}));}this.#baseStream=processedStream.pipeThrough(new TransformStream({transform:async(chunk,controller)=>{switch(chunk.type){case "tool-call-suspended":case "tool-call-approval":self.#status="suspended";self.#delayedPromises.suspendPayload.resolve(chunk.payload);break;case "source":self.#bufferedSources.push(chunk);self.#bufferedByStep.sources.push(chunk);break;case "text-delta":self.#bufferedText.push(chunk.payload.text);self.#bufferedByStep.text+=chunk.payload.text;if(chunk.payload.id){const ary=self.#bufferedTextChunks[chunk.payload.id]??[];ary.push(chunk.payload.text);self.#bufferedTextChunks[chunk.payload.id]=ary;}break;case "tool-call-input-streaming-start":self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId]=chunk.payload.toolName;break;case "tool-call-delta":if(!self.#toolCallArgsDeltas[chunk.payload.toolCallId]){self.#toolCallArgsDeltas[chunk.payload.toolCallId]=[];}self.#toolCallArgsDeltas?.[chunk.payload.toolCallId]?.push(chunk.payload.argsTextDelta);chunk.payload.toolName||=self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId];break;case "file":self.#bufferedFiles.push(chunk);self.#bufferedByStep.files.push(chunk);break;case "reasoning-start":self.#bufferedReasoningDetails[chunk.payload.id]={type:"reasoning",runId:chunk.runId,from:chunk.from,payload:{id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata,text:""}};break;case "reasoning-delta":{self.#bufferedReasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});self.#bufferedByStep.reasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(bufferedReasoning){bufferedReasoning.payload.text+=chunk.payload.text;if(chunk.payload.providerMetadata){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}}break;}case "reasoning-end":{const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(chunk.payload.providerMetadata&&bufferedReasoning){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}break;}case "tool-call":self.#toolCalls.push(chunk);self.#bufferedByStep.toolCalls.push(chunk);const toolCallPayload=chunk.payload;if(toolCallPayload?.output?.from==="AGENT"&&toolCallPayload?.output?.type==="finish"){const finishPayload=toolCallPayload.output.payload;if(finishPayload?.usage){self.updateUsageCount(finishPayload.usage);}}break;case "tool-result":self.#toolResults.push(chunk);self.#bufferedByStep.toolResults.push(chunk);break;case "step-finish":{self.updateUsageCount(chunk.payload.output.usage);self.#warnings=chunk.payload.stepResult.warnings||[];if(chunk.payload.metadata.request){self.#request=chunk.payload.metadata.request;}const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;const stepResult={stepType:self.#bufferedSteps.length===0?"initial":"tool-result",sources:self.#bufferedByStep.sources,files:self.#bufferedByStep.files,toolCalls:self.#bufferedByStep.toolCalls,toolResults:self.#bufferedByStep.toolResults,content:messageList.get.response.aiV5.modelContent(-1),text:self.#bufferedByStep.text,reasoningText:self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""),reasoning:self.#bufferedByStep.reasoning,get staticToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===false);},get dynamicToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===true);},get staticToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===false);},get dynamicToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===true);},finishReason:chunk.payload.stepResult.reason,usage:chunk.payload.output.usage,warnings:self.#warnings,request:request||{},response:{id:chunk.payload.id||"",timestamp:chunk.payload.metadata?.timestamp||/* @__PURE__ */new Date(),modelId:chunk.payload.metadata?.modelId||chunk.payload.metadata?.model||"",...otherMetadata,messages:chunk.payload.messages?.nonUser||[],uiMessages:messageList.get.response.aiV5.ui()},providerMetadata};await options?.onStepFinish?.({...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),...stepResult});self.#bufferedSteps.push(stepResult);self.#bufferedByStep={text:"",reasoning:[],sources:[],files:[],toolCalls:[],toolResults:[],dynamicToolCalls:[],dynamicToolResults:[],staticToolCalls:[],staticToolResults:[],content:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{},response:{id:"",timestamp:/* @__PURE__ */new Date(),modelId:"",messages:[],uiMessages:[]},reasoningText:"",providerMetadata:void 0,finishReason:void 0};break;}case "tripwire":self.#tripwire=true;self.#tripwireReason=chunk.payload?.tripwireReason||"Content blocked";self.#finishReason="other";self.#delayedPromises.text.resolve(self.#bufferedText.join(""));self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.object.resolve(void 0);self.#delayedPromises.usage.resolve(self.#usageCount);self.#delayedPromises.warnings.resolve(self.#warnings);self.#delayedPromises.providerMetadata.resolve(void 0);self.#delayedPromises.response.resolve({});self.#delayedPromises.request.resolve({});self.#delayedPromises.reasoning.resolve([]);self.#delayedPromises.reasoningText.resolve(void 0);self.#delayedPromises.sources.resolve([]);self.#delayedPromises.files.resolve([]);self.#delayedPromises.toolCalls.resolve([]);self.#delayedPromises.toolResults.resolve([]);self.#delayedPromises.steps.resolve(self.#bufferedSteps);self.#delayedPromises.totalUsage.resolve(self.#usageCount);self.#delayedPromises.content.resolve([]);controller.enqueue(chunk);controller.terminate();return;case "finish":self.#status="success";if(chunk.payload.stepResult.reason){self.#finishReason=chunk.payload.stepResult.reason;}let response={};if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}this.populateUsageCount(chunk.payload.output.usage);chunk.payload.output.usage={inputTokens:self.#usageCount.inputTokens??0,outputTokens:self.#usageCount.outputTokens??0,totalTokens:self.#usageCount.totalTokens??0,...(self.#usageCount.reasoningTokens!==void 0&&{reasoningTokens:self.#usageCount.reasoningTokens}),...(self.#usageCount.cachedInputTokens!==void 0&&{cachedInputTokens:self.#usageCount.cachedInputTokens})};try{if(self.processorRunner&&self.outputProcessorRunnerMode===`result`){self.messageList=await self.processorRunner.runOutputProcessors(self.messageList);const outputText=self.messageList.get.response.aiV4.core().map(m=>MessageList.coreContentToString(m.content)).join("\n");const messages=self.messageList.get.response.v2();const messagesWithStructuredData=messages.filter(msg=>msg.content.metadata&&"structuredOutput"in msg.content.metadata&&msg.content.metadata.structuredOutput);if(messagesWithStructuredData[0]&&messagesWithStructuredData[0].content.metadata?.structuredOutput){const structuredOutput=messagesWithStructuredData[0].content.metadata.structuredOutput;self.#delayedPromises.object.resolve(structuredOutput);}else if(!self.#options.output){self.#delayedPromises.object.resolve(void 0);}self.#delayedPromises.text.resolve(outputText);self.#delayedPromises.finishReason.resolve(self.#finishReason);if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}}else {const textContent=self.#bufferedText.join("");self.#delayedPromises.text.resolve(textContent);self.#delayedPromises.finishReason.resolve(self.#finishReason);const messages=self.messageList.get.response.v2();const messagesWithStructuredData=messages.filter(msg=>msg.content.metadata&&"structuredOutput"in msg.content.metadata&&msg.content.metadata.structuredOutput);if(messagesWithStructuredData[0]&&// this is to make typescript happy
767
774
  messagesWithStructuredData[0].content.metadata?.structuredOutput){const structuredOutput=messagesWithStructuredData[0].content.metadata.structuredOutput;self.#delayedPromises.object.resolve(structuredOutput);}else if(!self.#options.output&&self.#delayedPromises.object.status.type!=="resolved"){self.#delayedPromises.object.resolve(void 0);}}}catch(error2){if(error2 instanceof TripWire){self.#tripwire=true;self.#tripwireReason=error2.message;self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.text.resolve("");}else {self.#error=error2 instanceof Error?error2.message:String(error2);self.#delayedPromises.finishReason.resolve("error");self.#delayedPromises.text.resolve("");}self.#delayedPromises.object.resolve(void 0);}self.#delayedPromises.usage.resolve(self.#usageCount);self.#delayedPromises.warnings.resolve(self.#warnings);self.#delayedPromises.providerMetadata.resolve(chunk.payload.metadata?.providerMetadata);self.#delayedPromises.response.resolve(response);self.#delayedPromises.request.resolve(self.#request||{});self.#delayedPromises.text.resolve(self.#bufferedText.join(""));const reasoningText=self.#bufferedReasoning.length>0?self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""):void 0;self.#delayedPromises.reasoningText.resolve(reasoningText);self.#delayedPromises.reasoning.resolve(Object.values(self.#bufferedReasoningDetails||{}));self.#delayedPromises.sources.resolve(self.#bufferedSources);self.#delayedPromises.files.resolve(self.#bufferedFiles);self.#delayedPromises.toolCalls.resolve(self.#toolCalls);self.#delayedPromises.toolResults.resolve(self.#toolResults);self.#delayedPromises.steps.resolve(self.#bufferedSteps);self.#delayedPromises.totalUsage.resolve(self.#getTotalUsage());self.#delayedPromises.content.resolve(messageList.get.response.aiV5.stepContent());self.#delayedPromises.suspendPayload.resolve(void 0);const baseFinishStep=self.#bufferedSteps[self.#bufferedSteps.length-1];if(baseFinishStep){const onFinishPayload={// StepResult properties from baseFinishStep
768
775
  providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnings:baseFinishStep.warnings??[],finishReason:chunk.payload.stepResult.reason,content:messageList.get.response.aiV5.stepContent(),request:await self.request,error:self.error,reasoning:await self.reasoning,reasoningText:await self.reasoningText,sources:await self.sources,files:await self.files,steps:self.#bufferedSteps,response:{...(await self.response),...baseFinishStep.response,messages:messageList.get.response.aiV5.model()},usage:chunk.payload.output.usage,totalUsage:self.#getTotalUsage(),toolCalls:await self.toolCalls,toolResults:await self.toolResults,staticToolCalls:(await self.toolCalls).filter(toolCall=>toolCall?.payload?.dynamic===false),staticToolResults:(await self.toolResults).filter(toolResult=>toolResult?.payload?.dynamic===false),dynamicToolCalls:(await self.toolCalls).filter(toolCall=>toolCall?.payload?.dynamic===true),dynamicToolResults:(await self.toolResults).filter(toolResult=>toolResult?.payload?.dynamic===true),// Custom properties (not part of standard callback)
769
- ...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),object:self.#delayedPromises.object.status.type==="resolved"?self.#delayedPromises.object.status.value:self.#options.output&&baseFinishStep.text?(()=>{try{return JSON.parse(baseFinishStep.text);}catch{return void 0;}})():void 0};await options?.onFinish?.(onFinishPayload);}if(options?.rootSpan){options.rootSpan.setAttributes({...(self.#model.modelId?{"aisdk.model.id":self.#model.modelId}:{}),...(self.#model.provider?{"aisdk.model.provider":self.#model.provider}:{}),...(baseFinishStep?.usage?.reasoningTokens?{"stream.usage.reasoningTokens":baseFinishStep.usage.reasoningTokens}:{}),...(baseFinishStep?.usage?.totalTokens?{"stream.usage.totalTokens":baseFinishStep.usage.totalTokens}:{}),...(baseFinishStep?.usage?.inputTokens?{"stream.usage.inputTokens":baseFinishStep.usage.inputTokens}:{}),...(baseFinishStep?.usage?.outputTokens?{"stream.usage.outputTokens":baseFinishStep.usage.outputTokens}:{}),...(baseFinishStep?.usage?.cachedInputTokens?{"stream.usage.cachedInputTokens":baseFinishStep.usage.cachedInputTokens}:{}),...(baseFinishStep?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(baseFinishStep?.providerMetadata)}:{}),...(baseFinishStep?.finishReason?{"stream.response.finishReason":baseFinishStep?.finishReason}:{}),...(options?.telemetry_settings?.recordOutputs!==false?{"stream.response.text":baseFinishStep?.text}:{}),...(baseFinishStep?.toolCalls&&options?.telemetry_settings?.recordOutputs!==false?{"stream.response.toolCalls":JSON.stringify(baseFinishStep?.toolCalls?.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.payload?.toolCallId,args:toolCall.payload?.args,toolName:toolCall.payload?.toolName};}).filter(Boolean))}:{})});options.rootSpan.end();}break;case "error":self.#error=chunk.payload.error;self.#status="failed";const error=typeof self.#error==="object"?new Error(self.#error.message):new Error(String(self.#error));Object.values(self.#delayedPromises).forEach(promise=>promise.reject(error));break;}controller.enqueue(chunk);}}));this.#aisdkv5=new AISDKV5OutputStream({modelOutput:this,messageList,options:{toolCallStreaming:options?.toolCallStreaming,output:options?.output}});const methodsToBind=[{name:"consumeStream",fn:this.consumeStream},{name:"getFullOutput",fn:this.getFullOutput},{name:"teeStream",fn:this.teeStream}];methodsToBind.forEach(({name,fn})=>{this[name]=fn.bind(this);});const bindGetter=(name,getter)=>{Object.defineProperty(this,name,{get:getter.bind(this),enumerable:true,configurable:true});};const proto=Object.getPrototypeOf(this);const descriptors=Object.getOwnPropertyDescriptors(proto);for(const[key,descriptor]of Object.entries(descriptors)){if(descriptor.get&&key!=="constructor"){bindGetter(key,descriptor.get);}}}#getDelayedPromise(promise){if(!this.#streamConsumed){void this.consumeStream();}return promise.promise;}/**
776
+ ...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),object:self.#delayedPromises.object.status.type==="resolved"?self.#delayedPromises.object.status.value:self.#options.output&&baseFinishStep.text?(()=>{try{return JSON.parse(baseFinishStep.text);}catch{return void 0;}})():void 0};await options?.onFinish?.(onFinishPayload);}if(options?.rootSpan){options.rootSpan.setAttributes({...(self.#model.modelId?{"aisdk.model.id":self.#model.modelId}:{}),...(self.#model.provider?{"aisdk.model.provider":self.#model.provider}:{}),...(baseFinishStep?.usage?.reasoningTokens?{"stream.usage.reasoningTokens":baseFinishStep.usage.reasoningTokens}:{}),...(baseFinishStep?.usage?.totalTokens?{"stream.usage.totalTokens":baseFinishStep.usage.totalTokens}:{}),...(baseFinishStep?.usage?.inputTokens?{"stream.usage.inputTokens":baseFinishStep.usage.inputTokens}:{}),...(baseFinishStep?.usage?.outputTokens?{"stream.usage.outputTokens":baseFinishStep.usage.outputTokens}:{}),...(baseFinishStep?.usage?.cachedInputTokens?{"stream.usage.cachedInputTokens":baseFinishStep.usage.cachedInputTokens}:{}),...(baseFinishStep?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(baseFinishStep?.providerMetadata)}:{}),...(baseFinishStep?.finishReason?{"stream.response.finishReason":baseFinishStep?.finishReason}:{}),...(options?.telemetry_settings?.recordOutputs!==false?{"stream.response.text":baseFinishStep?.text}:{}),...(baseFinishStep?.toolCalls&&options?.telemetry_settings?.recordOutputs!==false?{"stream.response.toolCalls":JSON.stringify(baseFinishStep?.toolCalls?.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.payload?.toolCallId,args:toolCall.payload?.args,toolName:toolCall.payload?.toolName};}).filter(Boolean))}:{})});options.rootSpan.end();}break;case "error":self.#error=chunk.payload.error;self.#status="failed";const errorMessage=self.#error?.message||safeParseErrorObject(self.#error);const error=new Error(errorMessage);Object.values(self.#delayedPromises).forEach(promise=>promise.reject(error));break;}controller.enqueue(chunk);}}));this.#aisdkv5=new AISDKV5OutputStream({modelOutput:this,messageList,options:{toolCallStreaming:options?.toolCallStreaming,output:options?.output,tracingContext:options?.tracingContext}});const methodsToBind=[{name:"consumeStream",fn:this.consumeStream},{name:"getFullOutput",fn:this.getFullOutput},{name:"teeStream",fn:this.teeStream}];methodsToBind.forEach(({name,fn})=>{this[name]=fn.bind(this);});const bindGetter=(name,getter)=>{Object.defineProperty(this,name,{get:getter.bind(this),enumerable:true,configurable:true});};const proto=Object.getPrototypeOf(this);const descriptors=Object.getOwnPropertyDescriptors(proto);for(const[key,descriptor]of Object.entries(descriptors)){if(descriptor.get&&key!=="constructor"){bindGetter(key,descriptor.get);}}}#getDelayedPromise(promise){if(!this.#streamConsumed){void this.consumeStream();}return promise.promise;}/**
770
777
  * Resolves to the complete text response after streaming completes.
771
778
  */get text(){return this.#getDelayedPromise(this.#delayedPromises.text);}/**
772
779
  * Resolves to reasoning parts array for models that support reasoning.
@@ -837,5 +844,5 @@ providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnin
837
844
  /** @internal */_getImmediateToolCalls(){return this.#toolCalls;}/** @internal */_getImmediateToolResults(){return this.#toolResults;}/** @internal */_getImmediateText(){return this.#bufferedText.join("");}/** @internal */_getImmediateUsage(){return this.#usageCount;}/** @internal */_getImmediateWarnings(){return this.#warnings;}/** @internal */_getImmediateFinishReason(){return this.#finishReason;}#getTotalUsage(){let total=this.#usageCount.totalTokens;if(total===void 0){const input=this.#usageCount.inputTokens??0;const output=this.#usageCount.outputTokens??0;const reasoning=this.#usageCount.reasoningTokens??0;total=input+output+reasoning;}return {inputTokens:this.#usageCount.inputTokens,outputTokens:this.#usageCount.outputTokens,totalTokens:total,reasoningTokens:this.#usageCount.reasoningTokens,cachedInputTokens:this.#usageCount.cachedInputTokens};}get status(){return this.#status;}serializeState(){return {status:this.#status,bufferedSteps:this.#bufferedSteps,bufferedReasoningDetails:this.#bufferedReasoningDetails,bufferedByStep:this.#bufferedByStep,bufferedText:this.#bufferedText,bufferedTextChunks:this.#bufferedTextChunks,bufferedSources:this.#bufferedSources,bufferedReasoning:this.#bufferedReasoning,bufferedFiles:this.#bufferedFiles,toolCallArgsDeltas:this.#toolCallArgsDeltas,toolCallDeltaIdNameMap:this.#toolCallDeltaIdNameMap,toolCalls:this.#toolCalls,toolResults:this.#toolResults,warnings:this.#warnings,finishReason:this.#finishReason,request:this.#request,usageCount:this.#usageCount,tripwire:this.#tripwire,tripwireReason:this.#tripwireReason};}deserializeState(state){this.#status=state.status;this.#bufferedSteps=state.bufferedSteps;this.#bufferedReasoningDetails=state.bufferedReasoningDetails;this.#bufferedByStep=state.bufferedByStep;this.#bufferedText=state.bufferedText;this.#bufferedTextChunks=state.bufferedTextChunks;this.#bufferedSources=state.bufferedSources;this.#bufferedReasoning=state.bufferedReasoning;this.#bufferedFiles=state.bufferedFiles;this.#toolCallArgsDeltas=state.toolCallArgsDeltas;this.#toolCallDeltaIdNameMap=state.toolCallDeltaIdNameMap;this.#toolCalls=state.toolCalls;this.#toolResults=state.toolResults;this.#warnings=state.warnings;this.#finishReason=state.finishReason;this.#request=state.request;this.#usageCount=state.usageCount;this.#tripwire=state.tripwire;this.#tripwireReason=state.tripwireReason;}};
838
845
 
839
846
  export { AISDKV5OutputStream, Agent, BatchPartsProcessor, ChunkFrom, DefaultExecutionEngine, ExecutionEngine, LanguageDetector, LanguageDetectorInputProcessor, LegacyStep, LegacyWorkflow, MastraModelOutput, ModerationInputProcessor, ModerationProcessor, PIIDetector, PIIDetectorInputProcessor, PRIMITIVE_TYPES, PromptInjectionDetector, PromptInjectionDetectorInputProcessor, Run, StructuredOutputProcessor, SystemPromptScrubber, TokenLimiterProcessor, TripWire, UnicodeNormalizer, UnicodeNormalizerInputProcessor, WhenConditionReturnValue, Workflow, agentToStep, cloneStep, cloneWorkflow, createStep, createWorkflow, getActivePathsAndStatus, getResultActivePaths, getStepResult, getStepResult2, getSuspendedPaths, isAgent, isConditionalKey, isErrorEvent, isFinalState, isLimboState, isTransitionEvent, isVariableReference, isWorkflow, loop, mapVariable, mergeChildValue, recursivelyCheckForFinalState, resolveVariables, updateStepInHierarchy, validateStepInput, workflowToStep };
840
- //# sourceMappingURL=chunk-5ZMC3NEO.js.map
841
- //# sourceMappingURL=chunk-5ZMC3NEO.js.map
847
+ //# sourceMappingURL=chunk-JKLLXBOY.js.map
848
+ //# sourceMappingURL=chunk-JKLLXBOY.js.map