@mastra/core 1.0.0-beta.2 → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/CHANGELOG.md +162 -0
  2. package/dist/agent/agent-legacy.d.ts +2 -2
  3. package/dist/agent/agent-legacy.d.ts.map +1 -1
  4. package/dist/agent/agent.d.ts +1 -1
  5. package/dist/agent/agent.d.ts.map +1 -1
  6. package/dist/agent/agent.types.d.ts +3 -2
  7. package/dist/agent/agent.types.d.ts.map +1 -1
  8. package/dist/agent/index.cjs +9 -9
  9. package/dist/agent/index.js +2 -2
  10. package/dist/agent/message-list/index.cjs +3 -3
  11. package/dist/agent/message-list/index.d.ts.map +1 -1
  12. package/dist/agent/message-list/index.js +1 -1
  13. package/dist/agent/message-list/prompt/convert-file.d.ts +1 -1
  14. package/dist/agent/message-list/prompt/convert-file.d.ts.map +1 -1
  15. package/dist/agent/message-list/prompt/download-assets.d.ts.map +1 -1
  16. package/dist/agent/types.d.ts +1 -0
  17. package/dist/agent/types.d.ts.map +1 -1
  18. package/dist/agent/utils.d.ts.map +1 -1
  19. package/dist/agent/workflows/prepare-stream/index.d.ts +2 -1
  20. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  21. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts +3 -1
  22. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  23. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +2 -1
  24. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts.map +1 -1
  25. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +2 -1
  26. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  27. package/dist/agent/workflows/prepare-stream/stream-step.d.ts +3 -1
  28. package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
  29. package/dist/chunk-3PSWNGBF.js +3 -0
  30. package/dist/{chunk-ZV5CC35D.js.map → chunk-3PSWNGBF.js.map} +1 -1
  31. package/dist/{chunk-IQO7ANVS.cjs → chunk-3VOUB4ZU.cjs} +10 -9
  32. package/dist/chunk-3VOUB4ZU.cjs.map +1 -0
  33. package/dist/{chunk-ZGHTOYHW.js → chunk-4DWZ4Z6H.js} +155 -23
  34. package/dist/chunk-4DWZ4Z6H.js.map +1 -0
  35. package/dist/{chunk-ET6UOTTU.cjs → chunk-4IKJAKCD.cjs} +40 -4
  36. package/dist/chunk-4IKJAKCD.cjs.map +1 -0
  37. package/dist/{chunk-JYYQQEBH.cjs → chunk-4RSHBKDJ.cjs} +241 -4
  38. package/dist/chunk-4RSHBKDJ.cjs.map +1 -0
  39. package/dist/{chunk-MV7KHWUT.js → chunk-5CWWU22H.js} +25 -4
  40. package/dist/chunk-5CWWU22H.js.map +1 -0
  41. package/dist/{chunk-JV2KH24V.js → chunk-BAMR7HKO.js} +18 -13
  42. package/dist/chunk-BAMR7HKO.js.map +1 -0
  43. package/dist/{chunk-7CBEP2ZQ.js → chunk-CKGIPST2.js} +809 -89
  44. package/dist/chunk-CKGIPST2.js.map +1 -0
  45. package/dist/{chunk-4CDL2QJT.js → chunk-D6EDHNGV.js} +53 -16
  46. package/dist/chunk-D6EDHNGV.js.map +1 -0
  47. package/dist/{chunk-ZWNI5IWX.cjs → chunk-EZVRSZMK.cjs} +13 -12
  48. package/dist/chunk-EZVRSZMK.cjs.map +1 -0
  49. package/dist/{chunk-ECFXGXWO.cjs → chunk-G36A2JRR.cjs} +18 -13
  50. package/dist/chunk-G36A2JRR.cjs.map +1 -0
  51. package/dist/{chunk-7PO6SEJF.js → chunk-G3OOCXAI.js} +240 -3
  52. package/dist/chunk-G3OOCXAI.js.map +1 -0
  53. package/dist/{chunk-I4CXL4SR.js → chunk-GRGPQ32U.js} +5 -4
  54. package/dist/chunk-GRGPQ32U.js.map +1 -0
  55. package/dist/{chunk-WM6CK2F3.cjs → chunk-HBJPYQRN.cjs} +57 -19
  56. package/dist/chunk-HBJPYQRN.cjs.map +1 -0
  57. package/dist/{chunk-GGYKYORQ.cjs → chunk-JTXVR2RA.cjs} +27 -6
  58. package/dist/chunk-JTXVR2RA.cjs.map +1 -0
  59. package/dist/{chunk-XEVG546F.js → chunk-JXESKY4A.js} +3 -3
  60. package/dist/{chunk-XEVG546F.js.map → chunk-JXESKY4A.js.map} +1 -1
  61. package/dist/{chunk-7AHYOMHJ.js → chunk-KEURQGCQ.js} +40 -5
  62. package/dist/chunk-KEURQGCQ.js.map +1 -0
  63. package/dist/{chunk-JPGVRWWL.js → chunk-KOSW5PP5.js} +8 -2
  64. package/dist/chunk-KOSW5PP5.js.map +1 -0
  65. package/dist/chunk-MCUX2D5Q.js +420 -0
  66. package/dist/chunk-MCUX2D5Q.js.map +1 -0
  67. package/dist/chunk-N4SJ4YX7.cjs +424 -0
  68. package/dist/chunk-N4SJ4YX7.cjs.map +1 -0
  69. package/dist/{chunk-VOY2RXOC.cjs → chunk-O6NA3Z43.cjs} +6 -6
  70. package/dist/{chunk-VOY2RXOC.cjs.map → chunk-O6NA3Z43.cjs.map} +1 -1
  71. package/dist/{chunk-SNPVZPLB.js → chunk-OQF4H5Y2.js} +6 -5
  72. package/dist/chunk-OQF4H5Y2.js.map +1 -0
  73. package/dist/{chunk-YCVEJ3UN.cjs → chunk-OWX2PUFH.cjs} +846 -123
  74. package/dist/chunk-OWX2PUFH.cjs.map +1 -0
  75. package/dist/chunk-PE3V7GUL.cjs +4 -0
  76. package/dist/{chunk-LJFJTTZQ.cjs.map → chunk-PE3V7GUL.cjs.map} +1 -1
  77. package/dist/{chunk-HDJFSJCK.js → chunk-T3WZCEC4.js} +4 -3
  78. package/dist/chunk-T3WZCEC4.js.map +1 -0
  79. package/dist/{chunk-W7UH2PWL.js → chunk-VU6DVS7J.js} +179 -282
  80. package/dist/chunk-VU6DVS7J.js.map +1 -0
  81. package/dist/{chunk-22443P6A.cjs → chunk-VZGBVYXA.cjs} +173 -41
  82. package/dist/chunk-VZGBVYXA.cjs.map +1 -0
  83. package/dist/{chunk-2ZVKF4HP.cjs → chunk-XRIVPHXV.cjs} +184 -285
  84. package/dist/chunk-XRIVPHXV.cjs.map +1 -0
  85. package/dist/{chunk-LWBQ4P4N.cjs → chunk-YQ7NLZZ3.cjs} +54 -53
  86. package/dist/chunk-YQ7NLZZ3.cjs.map +1 -0
  87. package/dist/{chunk-CB575O6L.cjs → chunk-ZPMFINU2.cjs} +8 -2
  88. package/dist/chunk-ZPMFINU2.cjs.map +1 -0
  89. package/dist/evals/base.d.ts.map +1 -1
  90. package/dist/evals/index.cjs +4 -4
  91. package/dist/evals/index.js +1 -1
  92. package/dist/evals/scoreTraces/index.cjs +5 -4
  93. package/dist/evals/scoreTraces/index.cjs.map +1 -1
  94. package/dist/evals/scoreTraces/index.js +3 -2
  95. package/dist/evals/scoreTraces/index.js.map +1 -1
  96. package/dist/evals/scoreTraces/scoreTracesWorkflow.d.ts.map +1 -1
  97. package/dist/index.cjs +2 -2
  98. package/dist/index.js +1 -1
  99. package/dist/integration/index.cjs +2 -2
  100. package/dist/integration/index.js +1 -1
  101. package/dist/llm/index.cjs +26 -10
  102. package/dist/llm/index.d.ts +1 -0
  103. package/dist/llm/index.d.ts.map +1 -1
  104. package/dist/llm/index.js +5 -1
  105. package/dist/llm/model/aisdk/v5/model.d.ts +47 -0
  106. package/dist/llm/model/aisdk/v5/model.d.ts.map +1 -0
  107. package/dist/llm/model/gateways/base.d.ts +8 -0
  108. package/dist/llm/model/gateways/base.d.ts.map +1 -1
  109. package/dist/llm/model/gateways/models-dev.d.ts +1 -0
  110. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
  111. package/dist/llm/model/gateways/netlify.d.ts +2 -1
  112. package/dist/llm/model/gateways/netlify.d.ts.map +1 -1
  113. package/dist/llm/model/is-v2-model.d.ts +3 -0
  114. package/dist/llm/model/is-v2-model.d.ts.map +1 -0
  115. package/dist/llm/model/model-method-from-agent.d.ts +4 -0
  116. package/dist/llm/model/model-method-from-agent.d.ts.map +1 -0
  117. package/dist/llm/model/model.loop.d.ts +2 -2
  118. package/dist/llm/model/model.loop.d.ts.map +1 -1
  119. package/dist/llm/model/model.loop.types.d.ts +2 -0
  120. package/dist/llm/model/model.loop.types.d.ts.map +1 -1
  121. package/dist/llm/model/provider-registry.d.ts +11 -1
  122. package/dist/llm/model/provider-registry.d.ts.map +1 -1
  123. package/dist/llm/model/provider-types.generated.d.ts +56 -7
  124. package/dist/llm/model/registry-generator.d.ts.map +1 -1
  125. package/dist/llm/model/resolve-model.d.ts +1 -1
  126. package/dist/llm/model/resolve-model.d.ts.map +1 -1
  127. package/dist/llm/model/router.d.ts +12 -5
  128. package/dist/llm/model/router.d.ts.map +1 -1
  129. package/dist/llm/model/shared.types.d.ts +10 -4
  130. package/dist/llm/model/shared.types.d.ts.map +1 -1
  131. package/dist/loop/index.cjs +2 -2
  132. package/dist/loop/index.js +1 -1
  133. package/dist/loop/network/index.d.ts.map +1 -1
  134. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts +37 -0
  135. package/dist/loop/test-utils/MastraLanguageModelV2Mock.d.ts.map +1 -0
  136. package/dist/loop/test-utils/fullStream.d.ts.map +1 -1
  137. package/dist/loop/test-utils/generateText.d.ts.map +1 -1
  138. package/dist/loop/test-utils/options.d.ts.map +1 -1
  139. package/dist/loop/test-utils/resultObject.d.ts.map +1 -1
  140. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  141. package/dist/loop/test-utils/textStream.d.ts.map +1 -1
  142. package/dist/loop/test-utils/toUIMessageStream.d.ts.map +1 -1
  143. package/dist/loop/test-utils/tools.d.ts.map +1 -1
  144. package/dist/loop/test-utils/utils.d.ts +1 -1
  145. package/dist/loop/test-utils/utils.d.ts.map +1 -1
  146. package/dist/loop/types.d.ts +8 -3
  147. package/dist/loop/types.d.ts.map +1 -1
  148. package/dist/loop/workflows/agentic-execution/index.d.ts +12 -12
  149. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  150. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +9 -9
  151. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  152. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +4 -4
  153. package/dist/loop/workflows/agentic-loop/index.d.ts +13 -12
  154. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  155. package/dist/loop/workflows/run-state.d.ts +2 -2
  156. package/dist/loop/workflows/run-state.d.ts.map +1 -1
  157. package/dist/loop/workflows/schema.d.ts +4 -4
  158. package/dist/loop/workflows/stream.d.ts.map +1 -1
  159. package/dist/mastra/index.cjs +2 -2
  160. package/dist/mastra/index.d.ts +127 -3
  161. package/dist/mastra/index.d.ts.map +1 -1
  162. package/dist/mastra/index.js +1 -1
  163. package/dist/memory/index.cjs +8 -8
  164. package/dist/memory/index.js +4 -4
  165. package/dist/models-dev-GCVENVWA.js +3 -0
  166. package/dist/{models-dev-DNBKXHT4.js.map → models-dev-GCVENVWA.js.map} +1 -1
  167. package/dist/models-dev-TIBJR6IG.cjs +12 -0
  168. package/dist/{models-dev-YBEEQIX6.cjs.map → models-dev-TIBJR6IG.cjs.map} +1 -1
  169. package/dist/netlify-NTSNNT6F.cjs +12 -0
  170. package/dist/{netlify-GWNGSIRZ.cjs.map → netlify-NTSNNT6F.cjs.map} +1 -1
  171. package/dist/netlify-O5NJW7CF.js +3 -0
  172. package/dist/{netlify-7G2L5VSH.js.map → netlify-O5NJW7CF.js.map} +1 -1
  173. package/dist/processors/index.cjs +11 -11
  174. package/dist/processors/index.js +1 -1
  175. package/dist/provider-registry-74GMFZKT.js +3 -0
  176. package/dist/provider-registry-74GMFZKT.js.map +1 -0
  177. package/dist/provider-registry-BZP3DIIV.cjs +40 -0
  178. package/dist/provider-registry-BZP3DIIV.cjs.map +1 -0
  179. package/dist/provider-registry.json +140 -18
  180. package/dist/{registry-generator-MK63POJO.cjs → registry-generator-JPCV47SC.cjs} +6 -4
  181. package/dist/registry-generator-JPCV47SC.cjs.map +1 -0
  182. package/dist/{registry-generator-H4YNODDH.js → registry-generator-XD4FPZTU.js} +6 -4
  183. package/dist/registry-generator-XD4FPZTU.js.map +1 -0
  184. package/dist/relevance/index.cjs +2 -2
  185. package/dist/relevance/index.js +1 -1
  186. package/dist/server/index.cjs +2 -1
  187. package/dist/server/index.cjs.map +1 -1
  188. package/dist/server/index.d.ts +4 -0
  189. package/dist/server/index.d.ts.map +1 -1
  190. package/dist/server/index.js +2 -1
  191. package/dist/server/index.js.map +1 -1
  192. package/dist/storage/domains/workflows/inmemory.d.ts +1 -1
  193. package/dist/storage/domains/workflows/inmemory.d.ts.map +1 -1
  194. package/dist/storage/index.cjs +29 -29
  195. package/dist/storage/index.js +1 -1
  196. package/dist/storage/types.d.ts +2 -1
  197. package/dist/storage/types.d.ts.map +1 -1
  198. package/dist/stream/RunOutput.d.ts +1 -1
  199. package/dist/stream/RunOutput.d.ts.map +1 -1
  200. package/dist/stream/aisdk/v5/execute.d.ts +6 -3
  201. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  202. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  203. package/dist/stream/base/input.d.ts +1 -1
  204. package/dist/stream/base/output.d.ts.map +1 -1
  205. package/dist/stream/index.cjs +11 -11
  206. package/dist/stream/index.js +2 -2
  207. package/dist/stream/types.d.ts +4 -3
  208. package/dist/stream/types.d.ts.map +1 -1
  209. package/dist/test-utils/llm-mock.cjs +2 -2
  210. package/dist/test-utils/llm-mock.js +1 -1
  211. package/dist/tools/index.cjs +4 -4
  212. package/dist/tools/index.js +1 -1
  213. package/dist/tools/is-vercel-tool.cjs +2 -2
  214. package/dist/tools/is-vercel-tool.js +1 -1
  215. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  216. package/dist/tools/tool.d.ts.map +1 -1
  217. package/dist/tools/types.d.ts +1 -0
  218. package/dist/tools/types.d.ts.map +1 -1
  219. package/dist/tools/validation.d.ts +12 -0
  220. package/dist/tools/validation.d.ts.map +1 -1
  221. package/dist/utils.cjs +25 -21
  222. package/dist/utils.d.ts +4 -1
  223. package/dist/utils.d.ts.map +1 -1
  224. package/dist/utils.js +1 -1
  225. package/dist/workflows/default.d.ts +24 -8
  226. package/dist/workflows/default.d.ts.map +1 -1
  227. package/dist/workflows/evented/execution-engine.d.ts +3 -1
  228. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  229. package/dist/workflows/evented/index.cjs +10 -10
  230. package/dist/workflows/evented/index.js +1 -1
  231. package/dist/workflows/evented/workflow-event-processor/index.d.ts +5 -4
  232. package/dist/workflows/evented/workflow-event-processor/index.d.ts.map +1 -1
  233. package/dist/workflows/evented/workflow-event-processor/loop.d.ts +1 -1
  234. package/dist/workflows/evented/workflow-event-processor/loop.d.ts.map +1 -1
  235. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts +2 -2
  236. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts.map +1 -1
  237. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts +2 -2
  238. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts.map +1 -1
  239. package/dist/workflows/evented/workflow.d.ts +2 -1
  240. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  241. package/dist/workflows/execution-engine.d.ts +4 -2
  242. package/dist/workflows/execution-engine.d.ts.map +1 -1
  243. package/dist/workflows/index.cjs +28 -16
  244. package/dist/workflows/index.js +1 -1
  245. package/dist/workflows/step.d.ts +1 -0
  246. package/dist/workflows/step.d.ts.map +1 -1
  247. package/dist/workflows/types.d.ts +54 -2
  248. package/dist/workflows/types.d.ts.map +1 -1
  249. package/dist/workflows/utils.d.ts +20 -0
  250. package/dist/workflows/utils.d.ts.map +1 -1
  251. package/dist/workflows/workflow.d.ts +108 -40
  252. package/dist/workflows/workflow.d.ts.map +1 -1
  253. package/package.json +12 -20
  254. package/src/llm/model/provider-types.generated.d.ts +56 -7
  255. package/dist/chunk-22443P6A.cjs.map +0 -1
  256. package/dist/chunk-2ZVKF4HP.cjs.map +0 -1
  257. package/dist/chunk-4CDL2QJT.js.map +0 -1
  258. package/dist/chunk-7AHYOMHJ.js.map +0 -1
  259. package/dist/chunk-7CBEP2ZQ.js.map +0 -1
  260. package/dist/chunk-7PO6SEJF.js.map +0 -1
  261. package/dist/chunk-CB575O6L.cjs.map +0 -1
  262. package/dist/chunk-ECFXGXWO.cjs.map +0 -1
  263. package/dist/chunk-ET6UOTTU.cjs.map +0 -1
  264. package/dist/chunk-GGYKYORQ.cjs.map +0 -1
  265. package/dist/chunk-HDJFSJCK.js.map +0 -1
  266. package/dist/chunk-I4CXL4SR.js.map +0 -1
  267. package/dist/chunk-IQO7ANVS.cjs.map +0 -1
  268. package/dist/chunk-JPGVRWWL.js.map +0 -1
  269. package/dist/chunk-JV2KH24V.js.map +0 -1
  270. package/dist/chunk-JYYQQEBH.cjs.map +0 -1
  271. package/dist/chunk-LJFJTTZQ.cjs +0 -4
  272. package/dist/chunk-LWBQ4P4N.cjs.map +0 -1
  273. package/dist/chunk-MV7KHWUT.js.map +0 -1
  274. package/dist/chunk-SNPVZPLB.js.map +0 -1
  275. package/dist/chunk-W7UH2PWL.js.map +0 -1
  276. package/dist/chunk-WM6CK2F3.cjs.map +0 -1
  277. package/dist/chunk-YCVEJ3UN.cjs.map +0 -1
  278. package/dist/chunk-ZGHTOYHW.js.map +0 -1
  279. package/dist/chunk-ZV5CC35D.js +0 -3
  280. package/dist/chunk-ZWNI5IWX.cjs.map +0 -1
  281. package/dist/models-dev-DNBKXHT4.js +0 -3
  282. package/dist/models-dev-YBEEQIX6.cjs +0 -12
  283. package/dist/netlify-7G2L5VSH.js +0 -3
  284. package/dist/netlify-GWNGSIRZ.cjs +0 -12
  285. package/dist/registry-generator-H4YNODDH.js.map +0 -1
  286. package/dist/registry-generator-MK63POJO.cjs.map +0 -1
@@ -1,21 +1,21 @@
1
1
  import { DefaultVoice } from './chunk-UIZSWUKP.js';
2
2
  import { STREAM_FORMAT_SYMBOL, EMITTER_SYMBOL } from './chunk-NLNKQD2T.js';
3
- import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-JV2KH24V.js';
4
- import { resolveModelConfig } from './chunk-W7UH2PWL.js';
5
- import { MastraLLMV1 } from './chunk-XEVG546F.js';
3
+ import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-BAMR7HKO.js';
4
+ import { resolveModelConfig } from './chunk-MCUX2D5Q.js';
5
+ import { MastraLLMV1 } from './chunk-JXESKY4A.js';
6
6
  import { executeHook } from './chunk-L54GIUCB.js';
7
- import { selectFields, ensureToolProperties, makeCoreTool, createMastraProxy, delay } from './chunk-4CDL2QJT.js';
7
+ import { removeUndefinedValues, selectFields, ensureToolProperties, makeCoreTool, createMastraProxy, delay } from './chunk-D6EDHNGV.js';
8
8
  import { wrapMastra, getOrCreateSpan } from './chunk-KIZIOFZC.js';
9
9
  import { MastraError, getErrorFromUnknown } from './chunk-JJ5O45LH.js';
10
10
  import { ToolStream } from './chunk-HGNRQ3OG.js';
11
- import { Tool, createTool } from './chunk-7AHYOMHJ.js';
11
+ import { Tool, createTool } from './chunk-KEURQGCQ.js';
12
12
  import { RequestContext } from './chunk-GRBGQ2GE.js';
13
13
  import { zodToJsonSchema } from './chunk-PJKCPRYF.js';
14
14
  import { MastraBase } from './chunk-S6URFGCZ.js';
15
15
  import { RegisteredLogger, ConsoleLogger } from './chunk-KJ2SW6VA.js';
16
16
  import { __commonJS, __toESM } from './chunk-5WRI5ZAA.js';
17
17
  import EventEmitter, { EventEmitter as EventEmitter$1 } from 'events';
18
- import { ReadableStream as ReadableStream$1, TransformStream, WritableStream as WritableStream$1 } from 'stream/web';
18
+ import { WritableStream as WritableStream$1, ReadableStream as ReadableStream$1, TransformStream } from 'stream/web';
19
19
  import * as crypto2 from 'crypto';
20
20
  import { randomUUID } from 'crypto';
21
21
  import { getErrorMessage, TypeValidationError } from '@ai-sdk/provider-v5';
@@ -516,6 +516,11 @@ function runScorer({
516
516
  executeHook("onScorerRun" /* ON_SCORER_RUN */, payload);
517
517
  }
518
518
 
519
+ // src/llm/model/is-v2-model.ts
520
+ function isV2Model(model) {
521
+ return model.specificationVersion === "v2";
522
+ }
523
+
519
524
  // src/stream/base/consume-stream.ts
520
525
  async function consumeStream2({
521
526
  stream,
@@ -572,7 +577,7 @@ var WorkflowRunOutput = class {
572
577
  this.workflowId = workflowId;
573
578
  this.#baseStream = stream;
574
579
  stream.pipeTo(
575
- new WritableStream({
580
+ new WritableStream$1({
576
581
  start() {
577
582
  const chunk = {
578
583
  type: "workflow-start",
@@ -700,7 +705,7 @@ var WorkflowRunOutput = class {
700
705
  };
701
706
  const self = this;
702
707
  stream.pipeTo(
703
- new WritableStream({
708
+ new WritableStream$1({
704
709
  start() {
705
710
  const chunk = {
706
711
  type: "workflow-start",
@@ -935,6 +940,24 @@ async function validateStepInput({
935
940
  }
936
941
  return { inputData, validationError };
937
942
  }
943
+ async function validateStepResumeData({ resumeData, step }) {
944
+ if (!resumeData) {
945
+ return { resumeData: void 0, validationError: void 0 };
946
+ }
947
+ let validationError;
948
+ const resumeSchema = step.resumeSchema;
949
+ if (resumeSchema) {
950
+ const validatedResumeData = await resumeSchema.safeParseAsync(resumeData);
951
+ if (!validatedResumeData.success) {
952
+ const errors = getZodErrors(validatedResumeData.error);
953
+ const errorMessages = errors.map((e) => `- ${e.path?.join(".")}: ${e.message}`).join("\n");
954
+ validationError = new Error("Step resume data validation failed: \n" + errorMessages);
955
+ } else {
956
+ resumeData = validatedResumeData.data;
957
+ }
958
+ }
959
+ return { resumeData, validationError };
960
+ }
938
961
  function getResumeLabelsByStepId(resumeLabels, stepId) {
939
962
  return Object.entries(resumeLabels).filter(([_, value]) => value.stepId === stepId).reduce(
940
963
  (acc, [key, value]) => {
@@ -965,6 +988,111 @@ function createDeprecationProxy(params, {
965
988
  }
966
989
  });
967
990
  }
991
+ var getStepIds = (entry) => {
992
+ if (entry.type === "step" || entry.type === "foreach" || entry.type === "loop") {
993
+ return [entry.step.id];
994
+ }
995
+ if (entry.type === "parallel" || entry.type === "conditional") {
996
+ return entry.steps.map((s) => s.step.id);
997
+ }
998
+ if (entry.type === "sleep" || entry.type === "sleepUntil") {
999
+ return [entry.id];
1000
+ }
1001
+ return [];
1002
+ };
1003
+ var createTimeTravelExecutionParams = (params) => {
1004
+ const { steps, inputData, resumeData, context, nestedStepsContext, snapshot, initialState, graph } = params;
1005
+ const firstStepId = steps[0];
1006
+ let executionPath = [];
1007
+ const stepResults = {};
1008
+ const snapshotContext = snapshot.context;
1009
+ for (const [index, entry] of graph.steps.entries()) {
1010
+ const currentExecPathLength = executionPath.length;
1011
+ if (currentExecPathLength > 0 && !resumeData) {
1012
+ break;
1013
+ }
1014
+ const stepIds = getStepIds(entry);
1015
+ if (stepIds.includes(firstStepId)) {
1016
+ const innerExecutionPath = stepIds?.length > 1 ? [stepIds?.findIndex((s) => s === firstStepId)] : [];
1017
+ executionPath = [index, ...innerExecutionPath];
1018
+ }
1019
+ const prevStep = graph.steps[index - 1];
1020
+ let stepPayload = void 0;
1021
+ if (prevStep) {
1022
+ const prevStepIds = getStepIds(prevStep);
1023
+ if (prevStepIds.length > 0) {
1024
+ if (prevStepIds.length === 1) {
1025
+ stepPayload = stepResults?.[prevStepIds[0]]?.output ?? {};
1026
+ } else {
1027
+ stepPayload = prevStepIds.reduce(
1028
+ (acc, stepId) => {
1029
+ acc[stepId] = stepResults?.[stepId]?.output ?? {};
1030
+ return acc;
1031
+ },
1032
+ {}
1033
+ );
1034
+ }
1035
+ }
1036
+ }
1037
+ if (index === 0 && stepIds.includes(firstStepId)) {
1038
+ stepResults.input = context?.[firstStepId]?.payload ?? inputData ?? snapshotContext?.input;
1039
+ } else if (index === 0) {
1040
+ stepResults.input = stepIds?.reduce((acc, stepId) => {
1041
+ if (acc) return acc;
1042
+ return context?.[stepId]?.payload ?? snapshotContext?.[stepId]?.payload;
1043
+ }, null) ?? snapshotContext?.input ?? {};
1044
+ }
1045
+ let stepOutput = void 0;
1046
+ const nextStep = graph.steps[index + 1];
1047
+ if (nextStep) {
1048
+ const nextStepIds = getStepIds(nextStep);
1049
+ if (nextStepIds.length > 0 && inputData && nextStepIds.includes(firstStepId) && steps.length === 1) {
1050
+ stepOutput = inputData;
1051
+ }
1052
+ }
1053
+ stepIds.forEach((stepId) => {
1054
+ let result;
1055
+ const stepContext = context?.[stepId] ?? snapshotContext[stepId];
1056
+ const defaultStepStatus = steps?.includes(stepId) ? "running" : "success";
1057
+ const status = ["failed", "canceled"].includes(stepContext?.status) ? defaultStepStatus : stepContext?.status ?? defaultStepStatus;
1058
+ const isCompleteStatus = ["success", "failed", "canceled"].includes(status);
1059
+ result = {
1060
+ status,
1061
+ payload: context?.[stepId]?.payload ?? stepPayload ?? snapshotContext[stepId]?.payload ?? {},
1062
+ output: isCompleteStatus ? context?.[stepId]?.output ?? stepOutput ?? snapshotContext[stepId]?.output ?? {} : void 0,
1063
+ resumePayload: stepContext?.resumePayload,
1064
+ suspendPayload: stepContext?.suspendPayload,
1065
+ suspendOutput: stepContext?.suspendOutput,
1066
+ startedAt: stepContext?.startedAt ?? Date.now(),
1067
+ endedAt: isCompleteStatus ? stepContext?.endedAt ?? Date.now() : void 0,
1068
+ suspendedAt: stepContext?.suspendedAt,
1069
+ resumedAt: stepContext?.resumedAt
1070
+ };
1071
+ if (currentExecPathLength > 0 && (!snapshotContext[stepId] || snapshotContext[stepId] && snapshotContext[stepId].status !== "suspended")) {
1072
+ result = void 0;
1073
+ }
1074
+ if (result) {
1075
+ const formattedResult = removeUndefinedValues(result);
1076
+ stepResults[stepId] = formattedResult;
1077
+ }
1078
+ });
1079
+ }
1080
+ if (!executionPath.length) {
1081
+ throw new Error(
1082
+ `Time travel target step not found in execution graph: '${steps?.join(".")}'. Verify the step id/path.`
1083
+ );
1084
+ }
1085
+ const timeTravelData = {
1086
+ inputData,
1087
+ executionPath,
1088
+ steps,
1089
+ stepResults,
1090
+ nestedStepResults: nestedStepsContext,
1091
+ state: initialState ?? snapshot.value ?? {},
1092
+ resumeData
1093
+ };
1094
+ return timeTravelData;
1095
+ };
968
1096
 
969
1097
  // src/workflows/default.ts
970
1098
  var DefaultExecutionEngine = class extends ExecutionEngine {
@@ -1051,7 +1179,9 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1051
1179
  resume,
1052
1180
  retryConfig,
1053
1181
  workflowSpan,
1054
- disableScorers
1182
+ disableScorers,
1183
+ restart,
1184
+ timeTravel
1055
1185
  } = params;
1056
1186
  const { attempts = 0, delay: delay2 = 0 } = retryConfig ?? {};
1057
1187
  const steps = graph.steps;
@@ -1067,19 +1197,26 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1067
1197
  throw empty_graph_error;
1068
1198
  }
1069
1199
  let startIdx = 0;
1070
- if (resume?.resumePath) {
1200
+ if (timeTravel) {
1201
+ startIdx = timeTravel.executionPath[0];
1202
+ timeTravel.executionPath.shift();
1203
+ } else if (restart) {
1204
+ startIdx = restart.activePaths[0];
1205
+ restart.activePaths.shift();
1206
+ } else if (resume?.resumePath) {
1071
1207
  startIdx = resume.resumePath[0];
1072
1208
  resume.resumePath.shift();
1073
1209
  }
1074
- const stepResults = resume?.stepResults || { input };
1210
+ const stepResults = timeTravel?.stepResults || restart?.stepResults || resume?.stepResults || { input };
1075
1211
  let lastOutput;
1076
- let lastState = initialState ?? {};
1212
+ let lastState = timeTravel?.state ?? restart?.state ?? initialState ?? {};
1077
1213
  for (let i = startIdx; i < steps.length; i++) {
1078
1214
  const entry = steps[i];
1079
1215
  const executionContext = {
1080
1216
  workflowId,
1081
1217
  runId,
1082
1218
  executionPath: [i],
1219
+ activeStepsPath: {},
1083
1220
  suspendedPaths: {},
1084
1221
  resumeLabels: {},
1085
1222
  retryConfig: { attempts, delay: delay2 },
@@ -1097,6 +1234,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1097
1234
  prevStep: steps[i - 1],
1098
1235
  stepResults,
1099
1236
  resume,
1237
+ timeTravel,
1238
+ restart,
1100
1239
  tracingContext: {
1101
1240
  currentSpan: workflowSpan
1102
1241
  },
@@ -1386,7 +1525,9 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1386
1525
  step,
1387
1526
  stepResults,
1388
1527
  executionContext,
1528
+ restart,
1389
1529
  resume,
1530
+ timeTravel,
1390
1531
  prevOutput,
1391
1532
  emitter,
1392
1533
  abortController,
@@ -1398,22 +1539,38 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1398
1539
  tracingContext,
1399
1540
  iterationCount
1400
1541
  }) {
1401
- const startTime = resume?.steps[0] === step.id ? void 0 : Date.now();
1402
- const resumeTime = resume?.steps[0] === step.id ? Date.now() : void 0;
1403
1542
  const stepCallId = randomUUID();
1404
1543
  const { inputData, validationError } = await validateStepInput({
1405
1544
  prevOutput,
1406
1545
  step,
1407
- validateInputs: this.options?.validateInputs ?? false
1546
+ validateInputs: this.options?.validateInputs ?? true
1408
1547
  });
1548
+ const { resumeData: timeTravelResumeData, validationError: timeTravelResumeValidationError } = await validateStepResumeData({
1549
+ resumeData: timeTravel?.stepResults[step.id]?.status === "suspended" ? timeTravel?.resumeData : void 0,
1550
+ step
1551
+ });
1552
+ let resumeDataToUse;
1553
+ if (timeTravelResumeData && !timeTravelResumeValidationError) {
1554
+ resumeDataToUse = timeTravelResumeData;
1555
+ } else if (timeTravelResumeData && timeTravelResumeValidationError) {
1556
+ this.logger.warn("Time travel resume data validation failed", {
1557
+ stepId: step.id,
1558
+ error: timeTravelResumeValidationError.message
1559
+ });
1560
+ } else if (resume?.steps[0] === step.id) {
1561
+ resumeDataToUse = resume?.resumePayload;
1562
+ }
1563
+ const startTime = resumeDataToUse ? void 0 : Date.now();
1564
+ const resumeTime = resumeDataToUse ? Date.now() : void 0;
1409
1565
  const stepInfo = {
1410
1566
  ...stepResults[step.id],
1411
- ...resume?.steps[0] === step.id ? { resumePayload: resume?.resumePayload } : { payload: inputData },
1567
+ ...resumeDataToUse ? { resumePayload: resumeDataToUse } : { payload: inputData },
1412
1568
  ...startTime ? { startedAt: startTime } : {},
1413
1569
  ...resumeTime ? { resumedAt: resumeTime } : {},
1414
1570
  status: "running",
1415
1571
  ...iterationCount ? { metadata: { iterationCount } } : {}
1416
1572
  };
1573
+ executionContext.activeStepsPath[step.id] = executionContext.executionPath;
1417
1574
  const stepSpan = tracingContext.currentSpan?.createChildSpan({
1418
1575
  name: `workflow step: '${step.id}'`,
1419
1576
  type: "workflow_step" /* WORKFLOW_STEP */,
@@ -1468,6 +1625,10 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1468
1625
  throw validationError;
1469
1626
  }
1470
1627
  const retryCount = this.getOrGenerateRetryCount(step.id);
1628
+ let timeTravelSteps = [];
1629
+ if (timeTravel && timeTravel.steps.length > 0) {
1630
+ timeTravelSteps = timeTravel.steps[0] === step.id ? timeTravel.steps.slice(1) : [];
1631
+ }
1471
1632
  const result = await runStep({
1472
1633
  runId,
1473
1634
  resourceId,
@@ -1480,7 +1641,7 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1480
1641
  executionContext.state = state;
1481
1642
  },
1482
1643
  retryCount,
1483
- resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
1644
+ resumeData: resumeDataToUse,
1484
1645
  tracingContext: { currentSpan: stepSpan },
1485
1646
  getInitData: () => stepResults?.input,
1486
1647
  getStepResult: getStepResult.bind(this, stepResults),
@@ -1513,6 +1674,15 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1513
1674
  label: resume?.label,
1514
1675
  forEachIndex: resume?.forEachIndex
1515
1676
  } : void 0,
1677
+ // Only pass restart data if this step is part of activeStepsPath
1678
+ // This prevents pending nested workflows from trying to restart instead of start
1679
+ restart: !!restart?.activeStepsPath?.[step.id],
1680
+ timeTravel: timeTravelSteps.length > 0 ? {
1681
+ inputData: timeTravel?.inputData,
1682
+ steps: timeTravelSteps,
1683
+ nestedStepResults: timeTravel?.nestedStepResults,
1684
+ resumeData: timeTravel?.resumeData
1685
+ } : void 0,
1516
1686
  [EMITTER_SYMBOL]: emitter,
1517
1687
  [STREAM_FORMAT_SYMBOL]: executionContext.format,
1518
1688
  engine: {},
@@ -1584,6 +1754,7 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1584
1754
  };
1585
1755
  }
1586
1756
  }
1757
+ delete executionContext.activeStepsPath[step.id];
1587
1758
  if (!skipEmits) {
1588
1759
  if (execResults.status === "suspended") {
1589
1760
  await emitter.emit("watch", {
@@ -1687,6 +1858,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1687
1858
  serializedStepGraph,
1688
1859
  stepResults,
1689
1860
  resume,
1861
+ restart,
1862
+ timeTravel,
1690
1863
  executionContext,
1691
1864
  tracingContext,
1692
1865
  emitter,
@@ -1706,22 +1879,38 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1706
1879
  tracingPolicy: this.options?.tracingPolicy
1707
1880
  });
1708
1881
  const prevOutput = this.getStepOutput(stepResults, prevStep);
1709
- for (const step of entry.steps) {
1710
- if (step.type === "step") {
1711
- const startTime = resume?.steps[0] === step.step.id ? void 0 : Date.now();
1712
- const resumeTime = resume?.steps[0] === step.step.id ? Date.now() : void 0;
1713
- stepResults[step.step.id] = {
1714
- ...stepResults[step.step.id],
1715
- status: "running",
1716
- ...resumeTime ? { resumePayload: resume?.resumePayload } : { payload: prevOutput },
1717
- ...startTime ? { startedAt: startTime } : {},
1718
- ...resumeTime ? { resumedAt: resumeTime } : {}
1719
- };
1882
+ for (const [stepIndex, step] of entry.steps.entries()) {
1883
+ let makeStepRunning = true;
1884
+ if (restart) {
1885
+ makeStepRunning = !!restart.activeStepsPath[step.step.id];
1886
+ }
1887
+ if (timeTravel && timeTravel.executionPath.length > 0) {
1888
+ makeStepRunning = timeTravel.steps[0] === step.step.id;
1720
1889
  }
1890
+ if (!makeStepRunning) {
1891
+ continue;
1892
+ }
1893
+ const startTime = resume?.steps[0] === step.step.id ? void 0 : Date.now();
1894
+ const resumeTime = resume?.steps[0] === step.step.id ? Date.now() : void 0;
1895
+ stepResults[step.step.id] = {
1896
+ ...stepResults[step.step.id],
1897
+ status: "running",
1898
+ ...resumeTime ? { resumePayload: resume?.resumePayload } : { payload: prevOutput },
1899
+ ...startTime ? { startedAt: startTime } : {},
1900
+ ...resumeTime ? { resumedAt: resumeTime } : {}
1901
+ };
1902
+ executionContext.activeStepsPath[step.step.id] = [...executionContext.executionPath, stepIndex];
1903
+ }
1904
+ if (timeTravel && timeTravel.executionPath.length > 0) {
1905
+ timeTravel.executionPath.shift();
1721
1906
  }
1722
1907
  let execResults;
1723
1908
  const results = await Promise.all(
1724
1909
  entry.steps.map(async (step, i) => {
1910
+ const currStepResult = stepResults[step.step.id];
1911
+ if (currStepResult && currStepResult.status !== "running") {
1912
+ return currStepResult;
1913
+ }
1725
1914
  const result = await this.executeStep({
1726
1915
  workflowId,
1727
1916
  runId,
@@ -1730,8 +1919,11 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1730
1919
  prevOutput,
1731
1920
  stepResults,
1732
1921
  serializedStepGraph,
1922
+ restart,
1923
+ timeTravel,
1733
1924
  resume,
1734
1925
  executionContext: {
1926
+ activeStepsPath: executionContext.activeStepsPath,
1735
1927
  workflowId,
1736
1928
  runId,
1737
1929
  executionPath: [...executionContext.executionPath, i],
@@ -1796,6 +1988,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1796
1988
  serializedStepGraph,
1797
1989
  stepResults,
1798
1990
  resume,
1991
+ restart,
1992
+ timeTravel,
1799
1993
  executionContext,
1800
1994
  tracingContext,
1801
1995
  emitter,
@@ -1911,7 +2105,13 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1911
2105
  const results = await Promise.all(
1912
2106
  stepsToRun.map(async (step, index) => {
1913
2107
  const currStepResult = stepResults[step.step.id];
1914
- if (currStepResult && currStepResult.status === "success") {
2108
+ const isRestartStep = restart ? !!restart.activeStepsPath[step.step.id] : void 0;
2109
+ if (currStepResult && timeTravel && timeTravel.executionPath.length > 0) {
2110
+ if (timeTravel.steps[0] !== step.step.id) {
2111
+ return currStepResult;
2112
+ }
2113
+ }
2114
+ if (currStepResult && ["success", "failed"].includes(currStepResult.status) && isRestartStep === void 0) {
1915
2115
  return currStepResult;
1916
2116
  }
1917
2117
  const result = await this.executeStep({
@@ -1923,10 +2123,13 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1923
2123
  stepResults,
1924
2124
  serializedStepGraph,
1925
2125
  resume,
2126
+ restart,
2127
+ timeTravel,
1926
2128
  executionContext: {
1927
2129
  workflowId,
1928
2130
  runId,
1929
2131
  executionPath: [...executionContext.executionPath, index],
2132
+ activeStepsPath: executionContext.activeStepsPath,
1930
2133
  suspendedPaths: executionContext.suspendedPaths,
1931
2134
  resumeLabels: executionContext.resumeLabels,
1932
2135
  retryConfig: executionContext.retryConfig,
@@ -1988,6 +2191,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
1988
2191
  prevOutput,
1989
2192
  stepResults,
1990
2193
  resume,
2194
+ restart,
2195
+ timeTravel,
1991
2196
  executionContext,
1992
2197
  tracingContext,
1993
2198
  emitter,
@@ -2013,6 +2218,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2013
2218
  const prevPayload = stepResults[step.id]?.payload;
2014
2219
  let result = { status: "success", output: prevPayload ?? prevOutput };
2015
2220
  let currentResume = resume;
2221
+ let currentRestart = restart;
2222
+ let currentTimeTravel = timeTravel;
2016
2223
  do {
2017
2224
  result = await this.executeStep({
2018
2225
  workflowId,
@@ -2021,7 +2228,9 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2021
2228
  step,
2022
2229
  stepResults,
2023
2230
  executionContext,
2231
+ restart: currentRestart,
2024
2232
  resume: currentResume,
2233
+ timeTravel: currentTimeTravel,
2025
2234
  prevOutput: result.output,
2026
2235
  tracingContext: {
2027
2236
  currentSpan: loopSpan
@@ -2034,6 +2243,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2034
2243
  serializedStepGraph,
2035
2244
  iterationCount: iteration + 1
2036
2245
  });
2246
+ currentRestart = void 0;
2247
+ currentTimeTravel = void 0;
2037
2248
  if (currentResume && result.status !== "suspended") {
2038
2249
  currentResume = void 0;
2039
2250
  }
@@ -2121,7 +2332,9 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2121
2332
  entry,
2122
2333
  prevOutput,
2123
2334
  stepResults,
2335
+ restart,
2124
2336
  resume,
2337
+ timeTravel,
2125
2338
  executionContext,
2126
2339
  tracingContext,
2127
2340
  emitter,
@@ -2190,6 +2403,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2190
2403
  resourceId,
2191
2404
  step,
2192
2405
  stepResults,
2406
+ restart,
2407
+ timeTravel,
2193
2408
  executionContext: { ...executionContext, foreachIndex: k },
2194
2409
  resume: resumeToUse,
2195
2410
  prevOutput: item,
@@ -2323,7 +2538,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2323
2538
  status: workflowStatus,
2324
2539
  value: executionContext.state,
2325
2540
  context: stepResults,
2326
- activePaths: [],
2541
+ activePaths: executionContext.executionPath,
2542
+ activeStepsPath: executionContext.activeStepsPath,
2327
2543
  serializedStepGraph,
2328
2544
  suspendedPaths: executionContext.suspendedPaths,
2329
2545
  waitingPaths: {},
@@ -2344,6 +2560,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2344
2560
  prevStep,
2345
2561
  serializedStepGraph,
2346
2562
  stepResults,
2563
+ restart,
2564
+ timeTravel,
2347
2565
  resume,
2348
2566
  executionContext,
2349
2567
  tracingContext,
@@ -2364,6 +2582,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2364
2582
  step,
2365
2583
  stepResults,
2366
2584
  executionContext,
2585
+ timeTravel,
2586
+ restart,
2367
2587
  resume,
2368
2588
  prevOutput,
2369
2589
  tracingContext,
@@ -2392,6 +2612,7 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2392
2612
  suspendedPaths: executionContext.suspendedPaths,
2393
2613
  resumeLabels: executionContext.resumeLabels,
2394
2614
  retryConfig: executionContext.retryConfig,
2615
+ activeStepsPath: executionContext.activeStepsPath,
2395
2616
  state: executionContext.state
2396
2617
  },
2397
2618
  tracingContext,
@@ -2471,6 +2692,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2471
2692
  prevStep,
2472
2693
  stepResults,
2473
2694
  serializedStepGraph,
2695
+ timeTravel,
2696
+ restart,
2474
2697
  resume,
2475
2698
  executionContext,
2476
2699
  tracingContext,
@@ -2488,6 +2711,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2488
2711
  prevOutput,
2489
2712
  stepResults,
2490
2713
  serializedStepGraph,
2714
+ timeTravel,
2715
+ restart,
2491
2716
  resume,
2492
2717
  executionContext,
2493
2718
  tracingContext,
@@ -2505,6 +2730,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2505
2730
  prevStep,
2506
2731
  prevOutput,
2507
2732
  stepResults,
2733
+ timeTravel,
2734
+ restart,
2508
2735
  resume,
2509
2736
  executionContext,
2510
2737
  tracingContext,
@@ -2523,6 +2750,8 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2523
2750
  prevStep,
2524
2751
  prevOutput,
2525
2752
  stepResults,
2753
+ timeTravel,
2754
+ restart,
2526
2755
  resume,
2527
2756
  executionContext,
2528
2757
  tracingContext,
@@ -2544,6 +2773,12 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2544
2773
  status: "waiting"
2545
2774
  }
2546
2775
  });
2776
+ stepResults[entry.id] = {
2777
+ status: "waiting",
2778
+ payload: prevOutput,
2779
+ startedAt
2780
+ };
2781
+ executionContext.activeStepsPath[entry.id] = executionContext.executionPath;
2547
2782
  await this.persistStepUpdate({
2548
2783
  workflowId,
2549
2784
  runId,
@@ -2570,6 +2805,7 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2570
2805
  requestContext,
2571
2806
  writableStream
2572
2807
  });
2808
+ delete executionContext.activeStepsPath[entry.id];
2573
2809
  await this.persistStepUpdate({
2574
2810
  workflowId,
2575
2811
  runId,
@@ -2615,6 +2851,12 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2615
2851
  status: "waiting"
2616
2852
  }
2617
2853
  });
2854
+ stepResults[entry.id] = {
2855
+ status: "waiting",
2856
+ payload: prevOutput,
2857
+ startedAt
2858
+ };
2859
+ executionContext.activeStepsPath[entry.id] = executionContext.executionPath;
2618
2860
  await this.persistStepUpdate({
2619
2861
  workflowId,
2620
2862
  runId,
@@ -2641,6 +2883,7 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
2641
2883
  requestContext,
2642
2884
  writableStream
2643
2885
  });
2886
+ delete executionContext.activeStepsPath[entry.id];
2644
2887
  await this.persistStepUpdate({
2645
2888
  workflowId,
2646
2889
  runId,
@@ -2861,8 +3104,12 @@ function cloneStep(step, opts) {
2861
3104
  description: step.description,
2862
3105
  inputSchema: step.inputSchema,
2863
3106
  outputSchema: step.outputSchema,
3107
+ suspendSchema: step.suspendSchema,
3108
+ resumeSchema: step.resumeSchema,
3109
+ stateSchema: step.stateSchema,
2864
3110
  execute: step.execute,
2865
3111
  retries: step.retries,
3112
+ scorers: step.scorers,
2866
3113
  component: step.component
2867
3114
  };
2868
3115
  }
@@ -2875,7 +3122,8 @@ function cloneWorkflow(workflow, opts) {
2875
3122
  inputSchema: workflow.inputSchema,
2876
3123
  outputSchema: workflow.outputSchema,
2877
3124
  steps: workflow.stepDefs,
2878
- mastra: workflow.mastra
3125
+ mastra: workflow.mastra,
3126
+ options: workflow.options
2879
3127
  });
2880
3128
  wf.setStepFlow(workflow.stepGraph);
2881
3129
  wf.commit();
@@ -2889,6 +3137,8 @@ var Workflow = class extends MastraBase {
2889
3137
  stateSchema;
2890
3138
  steps;
2891
3139
  stepDefs;
3140
+ engineType = "default";
3141
+ #nestedWorkflowInput;
2892
3142
  committed = false;
2893
3143
  stepFlow;
2894
3144
  serializedStepFlow;
@@ -2924,7 +3174,7 @@ var Workflow = class extends MastraBase {
2924
3174
  this.steps = {};
2925
3175
  this.stepDefs = steps;
2926
3176
  this.#options = {
2927
- validateInputs: options.validateInputs ?? false,
3177
+ validateInputs: options.validateInputs ?? true,
2928
3178
  shouldPersistSnapshot: options.shouldPersistSnapshot ?? (() => true),
2929
3179
  tracingPolicy: options.tracingPolicy
2930
3180
  };
@@ -2936,6 +3186,7 @@ var Workflow = class extends MastraBase {
2936
3186
  } else {
2937
3187
  this.executionEngine = executionEngine;
2938
3188
  }
3189
+ this.engineType = "default";
2939
3190
  this.#runs = /* @__PURE__ */ new Map();
2940
3191
  }
2941
3192
  get runs() {
@@ -3295,7 +3546,8 @@ var Workflow = class extends MastraBase {
3295
3546
  cleanup: () => this.#runs.delete(runIdToUse),
3296
3547
  tracingPolicy: this.#options?.tracingPolicy,
3297
3548
  workflowSteps: this.steps,
3298
- validateInputs: this.#options?.validateInputs
3549
+ validateInputs: this.#options?.validateInputs,
3550
+ workflowEngineType: this.engineType
3299
3551
  });
3300
3552
  this.#runs.set(runIdToUse, run);
3301
3553
  const shouldPersistSnapshot = this.#options.shouldPersistSnapshot({
@@ -3312,8 +3564,9 @@ var Workflow = class extends MastraBase {
3312
3564
  runId: runIdToUse,
3313
3565
  status: "pending",
3314
3566
  value: {},
3315
- context: {},
3567
+ context: this.#nestedWorkflowInput ? { input: this.#nestedWorkflowInput } : {},
3316
3568
  activePaths: [],
3569
+ activeStepsPath: {},
3317
3570
  serializedStepGraph: this.serializedStepGraph,
3318
3571
  suspendedPaths: {},
3319
3572
  resumeLabels: {},
@@ -3357,7 +3610,9 @@ var Workflow = class extends MastraBase {
3357
3610
  state,
3358
3611
  setState,
3359
3612
  suspend,
3613
+ restart,
3360
3614
  resume,
3615
+ timeTravel,
3361
3616
  [EMITTER_SYMBOL]: emitter,
3362
3617
  mastra,
3363
3618
  requestContext,
@@ -3369,17 +3624,20 @@ var Workflow = class extends MastraBase {
3369
3624
  validateInputs
3370
3625
  }) {
3371
3626
  this.__registerMastra(mastra);
3372
- if (validateInputs) {
3373
- this.#options = {
3374
- ...this.#options || {},
3375
- validateInputs
3376
- };
3377
- }
3627
+ const effectiveValidateInputs = validateInputs ?? this.#options.validateInputs ?? true;
3628
+ this.#options = {
3629
+ ...this.#options || {},
3630
+ validateInputs: effectiveValidateInputs
3631
+ };
3378
3632
  this.executionEngine.options = {
3379
3633
  ...this.executionEngine.options || {},
3380
- validateInputs: validateInputs ?? false
3634
+ validateInputs: effectiveValidateInputs
3381
3635
  };
3382
3636
  const isResume = !!(resume?.steps && resume.steps.length > 0) || !!resume?.label || !!(resume?.steps && resume.steps.length === 0 && (!retryCount || retryCount === 0));
3637
+ if (!restart && !isResume) {
3638
+ this.#nestedWorkflowInput = inputData;
3639
+ }
3640
+ const isTimeTravel = !!(timeTravel && timeTravel.steps.length > 0);
3383
3641
  const run = isResume ? await this.createRun({ runId: resume.runId }) : await this.createRun({ runId });
3384
3642
  const nestedAbortCb = () => {
3385
3643
  abort();
@@ -3395,21 +3653,41 @@ var Workflow = class extends MastraBase {
3395
3653
  if (retryCount && retryCount > 0 && isResume && requestContext) {
3396
3654
  requestContext.set("__mastraWorflowInputData", inputData);
3397
3655
  }
3398
- const res = isResume ? await run.resume({
3399
- resumeData,
3400
- step: resume.steps?.length > 0 ? resume.steps : void 0,
3401
- requestContext,
3402
- tracingContext,
3403
- outputOptions: { includeState: true, includeResumeLabels: true },
3404
- label: resume.label
3405
- }) : await run.start({
3406
- inputData,
3407
- requestContext,
3408
- tracingContext,
3409
- writableStream: writer,
3410
- initialState: state,
3411
- outputOptions: { includeState: true, includeResumeLabels: true }
3412
- });
3656
+ let res;
3657
+ if (isTimeTravel) {
3658
+ res = await run.timeTravel({
3659
+ inputData: timeTravel?.inputData,
3660
+ resumeData: timeTravel?.resumeData,
3661
+ initialState: state,
3662
+ step: timeTravel?.steps,
3663
+ context: timeTravel?.nestedStepResults?.[this.id] ?? {},
3664
+ nestedStepsContext: timeTravel?.nestedStepResults,
3665
+ requestContext,
3666
+ tracingContext,
3667
+ writableStream: writer,
3668
+ outputOptions: { includeState: true, includeResumeLabels: true }
3669
+ });
3670
+ } else if (restart) {
3671
+ res = await run.restart({ requestContext, tracingContext, writableStream: writer });
3672
+ } else if (isResume) {
3673
+ res = await run.resume({
3674
+ resumeData,
3675
+ step: resume.steps?.length > 0 ? resume.steps : void 0,
3676
+ requestContext,
3677
+ tracingContext,
3678
+ outputOptions: { includeState: true, includeResumeLabels: true },
3679
+ label: resume.label
3680
+ });
3681
+ } else {
3682
+ res = await run.start({
3683
+ inputData,
3684
+ requestContext,
3685
+ tracingContext,
3686
+ writableStream: writer,
3687
+ initialState: state,
3688
+ outputOptions: { includeState: true, includeResumeLabels: true }
3689
+ });
3690
+ }
3413
3691
  unwatch();
3414
3692
  const suspendedSteps = Object.entries(res.steps).filter(([_stepName, stepResult]) => {
3415
3693
  const stepRes = stepResult;
@@ -3445,6 +3723,35 @@ var Workflow = class extends MastraBase {
3445
3723
  }
3446
3724
  return storage.listWorkflowRuns({ workflowName: this.id, ...args ?? {} });
3447
3725
  }
3726
+ async listActiveWorkflowRuns() {
3727
+ const runningRuns = await this.listWorkflowRuns({ status: "running" });
3728
+ const waitingRuns = await this.listWorkflowRuns({ status: "waiting" });
3729
+ return {
3730
+ runs: [...runningRuns.runs, ...waitingRuns.runs],
3731
+ total: runningRuns.total + waitingRuns.total
3732
+ };
3733
+ }
3734
+ async restartAllActiveWorkflowRuns() {
3735
+ if (this.engineType !== "default") {
3736
+ this.logger.debug(`Cannot restart active workflow runs for ${this.engineType} engine`);
3737
+ return;
3738
+ }
3739
+ const activeRuns = await this.listActiveWorkflowRuns();
3740
+ if (activeRuns.runs.length > 0) {
3741
+ this.logger.debug(
3742
+ `Restarting ${activeRuns.runs.length} active workflow run${activeRuns.runs.length > 1 ? "s" : ""}`
3743
+ );
3744
+ }
3745
+ for (const runSnapshot of activeRuns.runs) {
3746
+ try {
3747
+ const run = await this.createRun({ runId: runSnapshot.runId });
3748
+ await run.restart();
3749
+ this.logger.debug(`Restarted ${this.id} workflow run ${runSnapshot.runId}`);
3750
+ } catch (error) {
3751
+ this.logger.error(`Failed to restart ${this.id} workflow run ${runSnapshot.runId}: ${error}`);
3752
+ }
3753
+ }
3754
+ }
3448
3755
  async getWorkflowRunById(runId) {
3449
3756
  const storage = this.#mastra?.getStorage();
3450
3757
  if (!storage) {
@@ -3520,7 +3827,9 @@ var Workflow = class extends MastraBase {
3520
3827
  result: snapshot.result,
3521
3828
  error: snapshot.error,
3522
3829
  payload: snapshot.context?.input,
3523
- steps: fullSteps
3830
+ steps: fullSteps,
3831
+ activeStepsPath: snapshot.activeStepsPath,
3832
+ serializedStepGraph: snapshot.serializedStepGraph
3524
3833
  };
3525
3834
  }
3526
3835
  };
@@ -3572,6 +3881,7 @@ var Run = class {
3572
3881
  */
3573
3882
  workflowSteps;
3574
3883
  workflowRunStatus;
3884
+ workflowEngineType;
3575
3885
  /**
3576
3886
  * The storage for this run
3577
3887
  */
@@ -3603,6 +3913,7 @@ var Run = class {
3603
3913
  this.validateInputs = params.validateInputs;
3604
3914
  this.stateSchema = params.stateSchema;
3605
3915
  this.workflowRunStatus = "pending";
3916
+ this.workflowEngineType = params.workflowEngineType;
3606
3917
  }
3607
3918
  get abortController() {
3608
3919
  if (!this.#abortController) {
@@ -3675,6 +3986,20 @@ var Run = class {
3675
3986
  }
3676
3987
  return resumeDataToUse;
3677
3988
  }
3989
+ async _validateTimetravelInputData(inputData, step) {
3990
+ let inputDataToUse = inputData;
3991
+ if (step && step.inputSchema && this.validateInputs) {
3992
+ const inputSchema = step.inputSchema;
3993
+ const validatedInputData = await inputSchema.safeParseAsync(inputData);
3994
+ if (!validatedInputData.success) {
3995
+ const errors = getZodErrors(validatedInputData.error);
3996
+ const errorMessages = errors.map((e) => `- ${e.path?.join(".")}: ${e.message}`).join("\n");
3997
+ throw new Error("Invalid inputData: \n" + errorMessages);
3998
+ }
3999
+ inputDataToUse = validatedInputData.data;
4000
+ }
4001
+ return inputDataToUse;
4002
+ }
3678
4003
  async _start({
3679
4004
  inputData,
3680
4005
  initialState,
@@ -4100,6 +4425,13 @@ var Run = class {
4100
4425
  async resume(params) {
4101
4426
  return this._resume(params);
4102
4427
  }
4428
+ /**
4429
+ * Restarts the workflow execution that was previously active
4430
+ * @returns A promise that resolves to the workflow output
4431
+ */
4432
+ async restart(args = {}) {
4433
+ return this._restart(args);
4434
+ }
4103
4435
  async _resume(params) {
4104
4436
  const snapshot = await this.#mastra?.getStorage()?.loadWorkflowSnapshot({
4105
4437
  workflowName: this.workflowId,
@@ -4167,7 +4499,7 @@ var Run = class {
4167
4499
  params.requestContext.delete("__mastraWorflowInputData");
4168
4500
  }
4169
4501
  const stepResults = { ...snapshot?.context ?? {}, input: requestContextInput ?? snapshot?.context?.input };
4170
- let requestContextToUse = params.requestContext ?? new RequestContext();
4502
+ const requestContextToUse = params.requestContext ?? new RequestContext();
4171
4503
  Object.entries(snapshot?.requestContext ?? {}).forEach(([key, value]) => {
4172
4504
  if (!requestContextToUse.has(key)) {
4173
4505
  requestContextToUse.set(key, value);
@@ -4243,6 +4575,298 @@ var Run = class {
4243
4575
  return result;
4244
4576
  });
4245
4577
  }
4578
+ async _restart({
4579
+ requestContext,
4580
+ writableStream,
4581
+ tracingContext,
4582
+ tracingOptions
4583
+ }) {
4584
+ if (this.workflowEngineType !== "default") {
4585
+ throw new Error(`restart() is not supported on ${this.workflowEngineType} workflows`);
4586
+ }
4587
+ const snapshot = await this.#mastra?.getStorage()?.loadWorkflowSnapshot({
4588
+ workflowName: this.workflowId,
4589
+ runId: this.runId
4590
+ });
4591
+ let nestedWorkflowPending = false;
4592
+ if (!snapshot) {
4593
+ throw new Error(`Snapshot not found for run ${this.runId}`);
4594
+ }
4595
+ if (snapshot.status !== "running" && snapshot.status !== "waiting") {
4596
+ if (snapshot.status === "pending" && !!snapshot.context.input) {
4597
+ nestedWorkflowPending = true;
4598
+ } else {
4599
+ throw new Error("This workflow run was not active");
4600
+ }
4601
+ }
4602
+ let nestedWorkflowActiveStepsPath = {};
4603
+ const firstEntry = this.executionGraph.steps[0];
4604
+ if (firstEntry.type === "step" || firstEntry.type === "foreach" || firstEntry.type === "loop") {
4605
+ nestedWorkflowActiveStepsPath = {
4606
+ [firstEntry.step.id]: [0]
4607
+ };
4608
+ } else if (firstEntry.type === "sleep" || firstEntry.type === "sleepUntil") {
4609
+ nestedWorkflowActiveStepsPath = {
4610
+ [firstEntry.id]: [0]
4611
+ };
4612
+ } else if (firstEntry.type === "conditional" || firstEntry.type === "parallel") {
4613
+ nestedWorkflowActiveStepsPath = firstEntry.steps.reduce(
4614
+ (acc, step) => {
4615
+ acc[step.step.id] = [0];
4616
+ return acc;
4617
+ },
4618
+ {}
4619
+ );
4620
+ }
4621
+ const restartData = {
4622
+ activePaths: nestedWorkflowPending ? [0] : snapshot.activePaths,
4623
+ activeStepsPath: nestedWorkflowPending ? nestedWorkflowActiveStepsPath : snapshot.activeStepsPath,
4624
+ stepResults: snapshot.context,
4625
+ state: snapshot.value
4626
+ };
4627
+ const requestContextToUse = requestContext ?? new RequestContext();
4628
+ for (const [key, value] of Object.entries(snapshot.requestContext ?? {})) {
4629
+ if (!requestContextToUse.has(key)) {
4630
+ requestContextToUse.set(key, value);
4631
+ }
4632
+ }
4633
+ const workflowSpan = getOrCreateSpan({
4634
+ type: "workflow_run" /* WORKFLOW_RUN */,
4635
+ name: `workflow run: '${this.workflowId}'`,
4636
+ attributes: {
4637
+ workflowId: this.workflowId
4638
+ },
4639
+ metadata: {
4640
+ resourceId: this.resourceId,
4641
+ runId: this.runId
4642
+ },
4643
+ tracingPolicy: this.tracingPolicy,
4644
+ tracingOptions,
4645
+ tracingContext,
4646
+ requestContext: requestContextToUse,
4647
+ mastra: this.#mastra
4648
+ });
4649
+ const traceId = workflowSpan?.externalTraceId;
4650
+ const result = await this.executionEngine.execute({
4651
+ workflowId: this.workflowId,
4652
+ runId: this.runId,
4653
+ resourceId: this.resourceId,
4654
+ disableScorers: this.disableScorers,
4655
+ graph: this.executionGraph,
4656
+ serializedStepGraph: this.serializedStepGraph,
4657
+ restart: restartData,
4658
+ emitter: {
4659
+ emit: async (event, data) => {
4660
+ this.emitter.emit(event, data);
4661
+ },
4662
+ on: (event, callback) => {
4663
+ this.emitter.on(event, callback);
4664
+ },
4665
+ off: (event, callback) => {
4666
+ this.emitter.off(event, callback);
4667
+ },
4668
+ once: (event, callback) => {
4669
+ this.emitter.once(event, callback);
4670
+ }
4671
+ },
4672
+ retryConfig: this.retryConfig,
4673
+ requestContext: requestContextToUse,
4674
+ abortController: this.abortController,
4675
+ writableStream,
4676
+ workflowSpan
4677
+ });
4678
+ if (result.status !== "suspended") {
4679
+ this.cleanup?.();
4680
+ }
4681
+ result.traceId = traceId;
4682
+ return result;
4683
+ }
4684
+ async _timeTravel({
4685
+ inputData,
4686
+ resumeData,
4687
+ initialState,
4688
+ step: stepParam,
4689
+ context,
4690
+ nestedStepsContext,
4691
+ requestContext,
4692
+ writableStream,
4693
+ tracingContext,
4694
+ tracingOptions,
4695
+ outputOptions
4696
+ }) {
4697
+ if (!stepParam || Array.isArray(stepParam) && stepParam.length === 0) {
4698
+ throw new Error("Step is required and must be a valid step or array of steps");
4699
+ }
4700
+ const snapshot = await this.#mastra?.getStorage()?.loadWorkflowSnapshot({
4701
+ workflowName: this.workflowId,
4702
+ runId: this.runId
4703
+ });
4704
+ if (!snapshot) {
4705
+ throw new Error(`Snapshot not found for run ${this.runId}`);
4706
+ }
4707
+ if (snapshot.status === "running") {
4708
+ throw new Error("This workflow run is still running, cannot time travel");
4709
+ }
4710
+ let steps;
4711
+ let newStepParam = stepParam;
4712
+ if (typeof stepParam === "string") {
4713
+ newStepParam = stepParam.split(".");
4714
+ }
4715
+ steps = (Array.isArray(newStepParam) ? newStepParam : [newStepParam]).map(
4716
+ (step) => typeof step === "string" ? step : step?.id
4717
+ );
4718
+ let inputDataToUse = inputData;
4719
+ if (inputDataToUse && steps.length === 1) {
4720
+ inputDataToUse = await this._validateTimetravelInputData(inputData, this.workflowSteps[steps[0]]);
4721
+ }
4722
+ const timeTravelData = createTimeTravelExecutionParams({
4723
+ steps,
4724
+ inputData: inputDataToUse,
4725
+ resumeData,
4726
+ context,
4727
+ nestedStepsContext,
4728
+ snapshot,
4729
+ initialState,
4730
+ graph: this.executionGraph
4731
+ });
4732
+ const requestContextToUse = requestContext ?? new RequestContext();
4733
+ for (const [key, value] of Object.entries(snapshot.requestContext ?? {})) {
4734
+ if (!requestContextToUse.has(key)) {
4735
+ requestContextToUse.set(key, value);
4736
+ }
4737
+ }
4738
+ const workflowSpan = getOrCreateSpan({
4739
+ type: "workflow_run" /* WORKFLOW_RUN */,
4740
+ name: `workflow run: '${this.workflowId}'`,
4741
+ input: inputData,
4742
+ attributes: {
4743
+ workflowId: this.workflowId
4744
+ },
4745
+ metadata: {
4746
+ resourceId: this.resourceId,
4747
+ runId: this.runId
4748
+ },
4749
+ tracingPolicy: this.tracingPolicy,
4750
+ tracingOptions,
4751
+ tracingContext,
4752
+ requestContext: requestContextToUse,
4753
+ mastra: this.#mastra
4754
+ });
4755
+ const traceId = workflowSpan?.externalTraceId;
4756
+ const result = await this.executionEngine.execute({
4757
+ workflowId: this.workflowId,
4758
+ runId: this.runId,
4759
+ resourceId: this.resourceId,
4760
+ disableScorers: this.disableScorers,
4761
+ graph: this.executionGraph,
4762
+ timeTravel: timeTravelData,
4763
+ serializedStepGraph: this.serializedStepGraph,
4764
+ emitter: {
4765
+ emit: async (event, data) => {
4766
+ this.emitter.emit(event, data);
4767
+ },
4768
+ on: (event, callback) => {
4769
+ this.emitter.on(event, callback);
4770
+ },
4771
+ off: (event, callback) => {
4772
+ this.emitter.off(event, callback);
4773
+ },
4774
+ once: (event, callback) => {
4775
+ this.emitter.once(event, callback);
4776
+ }
4777
+ },
4778
+ retryConfig: this.retryConfig,
4779
+ requestContext: requestContextToUse,
4780
+ abortController: this.abortController,
4781
+ writableStream,
4782
+ workflowSpan,
4783
+ outputOptions
4784
+ });
4785
+ if (result.status !== "suspended") {
4786
+ this.cleanup?.();
4787
+ }
4788
+ result.traceId = traceId;
4789
+ return result;
4790
+ }
4791
+ async timeTravel(args) {
4792
+ return this._timeTravel(args);
4793
+ }
4794
+ timeTravelStream({
4795
+ inputData,
4796
+ resumeData,
4797
+ initialState,
4798
+ step,
4799
+ context,
4800
+ nestedStepsContext,
4801
+ requestContext,
4802
+ tracingContext,
4803
+ tracingOptions,
4804
+ outputOptions
4805
+ }) {
4806
+ this.closeStreamAction = async () => {
4807
+ };
4808
+ const self = this;
4809
+ const stream = new ReadableStream$1({
4810
+ async start(controller) {
4811
+ const unwatch = self.watch(async ({ type, from = "WORKFLOW" /* WORKFLOW */, payload }) => {
4812
+ controller.enqueue({
4813
+ type,
4814
+ runId: self.runId,
4815
+ from,
4816
+ payload: {
4817
+ stepName: payload.id,
4818
+ ...payload
4819
+ }
4820
+ });
4821
+ });
4822
+ self.closeStreamAction = async () => {
4823
+ unwatch();
4824
+ try {
4825
+ await controller.close();
4826
+ } catch (err) {
4827
+ console.error("Error closing stream:", err);
4828
+ }
4829
+ };
4830
+ const executionResultsPromise = self._timeTravel({
4831
+ inputData,
4832
+ step,
4833
+ context,
4834
+ nestedStepsContext,
4835
+ resumeData,
4836
+ initialState,
4837
+ requestContext,
4838
+ tracingContext,
4839
+ tracingOptions,
4840
+ writableStream: new WritableStream$1({
4841
+ write(chunk) {
4842
+ controller.enqueue(chunk);
4843
+ }
4844
+ }),
4845
+ outputOptions
4846
+ });
4847
+ self.executionResults = executionResultsPromise;
4848
+ let executionResults;
4849
+ try {
4850
+ executionResults = await executionResultsPromise;
4851
+ self.closeStreamAction?.().catch(() => {
4852
+ });
4853
+ if (self.streamOutput) {
4854
+ self.streamOutput.updateResults(executionResults);
4855
+ }
4856
+ } catch (err) {
4857
+ self.streamOutput?.rejectResults(err);
4858
+ self.closeStreamAction?.().catch(() => {
4859
+ });
4860
+ }
4861
+ }
4862
+ });
4863
+ this.streamOutput = new WorkflowRunOutput({
4864
+ runId: this.runId,
4865
+ workflowId: this.workflowId,
4866
+ stream
4867
+ });
4868
+ return this.streamOutput;
4869
+ }
4246
4870
  /**
4247
4871
  * @access private
4248
4872
  * @returns The execution results of the workflow run
@@ -4868,7 +5492,8 @@ function execute({
4868
5492
  modelSettings,
4869
5493
  structuredOutput,
4870
5494
  headers,
4871
- shouldThrowError
5495
+ shouldThrowError,
5496
+ methodType
4872
5497
  }) {
4873
5498
  const v5 = new AISDKV5InputStream({
4874
5499
  component: "LLM",
@@ -4916,7 +5541,8 @@ You don't need to format your response as JSON unless the user asks you to. Just
4916
5541
  const pRetry = await import('p-retry');
4917
5542
  return await pRetry.default(
4918
5543
  async () => {
4919
- const streamResult = await model.doStream({
5544
+ const fn = (methodType === "stream" ? model.doStream : model.doGenerate).bind(model);
5545
+ const streamResult = await fn({
4920
5546
  ...toolsAndToolChoice,
4921
5547
  prompt,
4922
5548
  providerOptions: providerOptionsToUse,
@@ -4940,10 +5566,6 @@ You don't need to format your response as JSON unless the user asks you to. Just
4940
5566
  }
4941
5567
  );
4942
5568
  } catch (error) {
4943
- const abortSignal = options?.abortSignal;
4944
- if (isAbortError(error) && abortSignal?.aborted) {
4945
- console.error("Abort error", error);
4946
- }
4947
5569
  if (shouldThrowError) {
4948
5570
  throw error;
4949
5571
  }
@@ -5415,7 +6037,8 @@ function createLLMExecutionStep({
5415
6037
  headers,
5416
6038
  downloadRetries,
5417
6039
  downloadConcurrency,
5418
- processorStates
6040
+ processorStates,
6041
+ methodType
5419
6042
  }) {
5420
6043
  return createStep({
5421
6044
  id: "llm-execution",
@@ -5494,6 +6117,7 @@ function createLLMExecutionStep({
5494
6117
  includeRawChunks,
5495
6118
  structuredOutput,
5496
6119
  headers,
6120
+ methodType,
5497
6121
  onResult: ({
5498
6122
  warnings: warningsFromStream,
5499
6123
  request: requestFromStream,
@@ -5954,7 +6578,8 @@ function createAgenticExecutionWorkflow({ models, _internal, ...rest }) {
5954
6578
  // VNext execution as internal
5955
6579
  internal: 1 /* WORKFLOW */
5956
6580
  },
5957
- shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended"
6581
+ shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended",
6582
+ validateInputs: false
5958
6583
  }
5959
6584
  }).then(llmExecutionStep).map(
5960
6585
  async ({ inputData }) => {
@@ -5994,7 +6619,8 @@ function createAgenticLoopWorkflow(params) {
5994
6619
  },
5995
6620
  shouldPersistSnapshot: (params2) => {
5996
6621
  return params2.workflowStatus === "suspended";
5997
- }
6622
+ },
6623
+ validateInputs: false
5998
6624
  }
5999
6625
  }).dowhile(agenticExecutionWorkflow, async ({ inputData }) => {
6000
6626
  const typedInputData = inputData;
@@ -6085,7 +6711,7 @@ function workflowLoopStream({
6085
6711
  }) {
6086
6712
  return new ReadableStream$1({
6087
6713
  start: async (controller) => {
6088
- const writer = new WritableStream({
6714
+ const writer = new WritableStream$1({
6089
6715
  write: (chunk) => {
6090
6716
  controller.enqueue(chunk);
6091
6717
  }
@@ -6404,7 +7030,8 @@ var MastraLLMVNext = class extends MastraBase {
6404
7030
  requireToolApproval,
6405
7031
  _internal,
6406
7032
  agentId,
6407
- toolCallId
7033
+ toolCallId,
7034
+ methodType
6408
7035
  }) {
6409
7036
  let stopWhenToUse;
6410
7037
  if (maxSteps && typeof maxSteps === "number") {
@@ -6461,6 +7088,7 @@ var MastraLLMVNext = class extends MastraBase {
6461
7088
  modelSpanTracker,
6462
7089
  requireToolApproval,
6463
7090
  agentId,
7091
+ methodType,
6464
7092
  options: {
6465
7093
  ...options,
6466
7094
  onStepFinish: async (props) => {
@@ -7569,7 +8197,8 @@ ${completionResult?.object?.finalResult}` : ""}
7569
8197
  isOneOff: z5.boolean()
7570
8198
  }),
7571
8199
  options: {
7572
- shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended"
8200
+ shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended",
8201
+ validateInputs: false
7573
8202
  }
7574
8203
  });
7575
8204
  networkWorkflow.then(routingStep).branch([
@@ -7696,7 +8325,8 @@ async function networkLoop({
7696
8325
  iteration: z5.number()
7697
8326
  }),
7698
8327
  options: {
7699
- shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended"
8328
+ shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended",
8329
+ validateInputs: false
7700
8330
  }
7701
8331
  }).dountil(networkWorkflow, async ({ inputData }) => {
7702
8332
  return inputData.isComplete || inputData.iteration >= maxIterations;
@@ -9124,6 +9754,21 @@ the following messages are from ${ymd}
9124
9754
  }
9125
9755
  };
9126
9756
 
9757
+ // src/llm/model/model-method-from-agent.ts
9758
+ function getModelMethodFromAgentMethod(methodType) {
9759
+ if (methodType === "generate" || methodType === "generateLegacy") {
9760
+ return "generate";
9761
+ } else if (methodType === "stream" || methodType === "streamLegacy") {
9762
+ return "stream";
9763
+ } else {
9764
+ throw new MastraError({
9765
+ id: "INVALID_METHOD_TYPE",
9766
+ domain: "AGENT" /* AGENT */,
9767
+ category: "USER" /* USER */
9768
+ });
9769
+ }
9770
+ }
9771
+
9127
9772
  // src/processors/processors/unicode-normalizer.ts
9128
9773
  var UnicodeNormalizer = class {
9129
9774
  id = "unicode-normalizer";
@@ -11122,7 +11767,8 @@ function createMapResultsStep({
11122
11767
  memoryConfig,
11123
11768
  saveQueueManager,
11124
11769
  agentSpan,
11125
- agentId
11770
+ agentId,
11771
+ methodType
11126
11772
  }) {
11127
11773
  return async ({
11128
11774
  inputData,
@@ -11187,7 +11833,9 @@ function createMapResultsStep({
11187
11833
  effectiveOutputProcessors = effectiveOutputProcessors ? [...effectiveOutputProcessors, structuredProcessor] : [structuredProcessor];
11188
11834
  }
11189
11835
  const messageList = memoryData.messageList;
11836
+ const modelMethodType = getModelMethodFromAgentMethod(methodType);
11190
11837
  const loopOptions = {
11838
+ methodType: modelMethodType,
11191
11839
  agentId,
11192
11840
  requestContext: result.requestContext,
11193
11841
  tracingContext: { currentSpan: agentSpan },
@@ -11553,7 +12201,8 @@ function createStreamStep({
11553
12201
  requireToolApproval,
11554
12202
  resumeContext,
11555
12203
  agentId,
11556
- toolCallId
12204
+ toolCallId,
12205
+ methodType
11557
12206
  }) {
11558
12207
  return createStep({
11559
12208
  id: "stream-text-step",
@@ -11571,6 +12220,7 @@ function createStreamStep({
11571
12220
  const processors = validatedInputData.outputProcessors || (capabilities.outputProcessors ? typeof capabilities.outputProcessors === "function" ? await capabilities.outputProcessors({
11572
12221
  requestContext: validatedInputData.requestContext || new RequestContext()
11573
12222
  }) : capabilities.outputProcessors : []);
12223
+ const modelMethodType = getModelMethodFromAgentMethod(methodType);
11574
12224
  const streamResult = capabilities.llm.stream({
11575
12225
  ...validatedInputData,
11576
12226
  outputProcessors: processors,
@@ -11582,7 +12232,8 @@ function createStreamStep({
11582
12232
  generateId: capabilities.generateMessageId
11583
12233
  },
11584
12234
  agentId,
11585
- toolCallId
12235
+ toolCallId,
12236
+ methodType: modelMethodType
11586
12237
  });
11587
12238
  return streamResult;
11588
12239
  }
@@ -11638,7 +12289,8 @@ function createPrepareStreamWorkflow({
11638
12289
  requireToolApproval,
11639
12290
  resumeContext,
11640
12291
  agentId,
11641
- toolCallId
12292
+ toolCallId,
12293
+ methodType
11642
12294
  });
11643
12295
  const mapResultsStep = createMapResultsStep({
11644
12296
  capabilities,
@@ -11650,7 +12302,8 @@ function createPrepareStreamWorkflow({
11650
12302
  memoryConfig,
11651
12303
  saveQueueManager,
11652
12304
  agentSpan,
11653
- agentId
12305
+ agentId,
12306
+ methodType
11654
12307
  });
11655
12308
  return createWorkflow({
11656
12309
  id: "execution-workflow",
@@ -11663,7 +12316,8 @@ function createPrepareStreamWorkflow({
11663
12316
  options: {
11664
12317
  tracingPolicy: {
11665
12318
  internal: 1 /* WORKFLOW */
11666
- }
12319
+ },
12320
+ validateInputs: false
11667
12321
  }
11668
12322
  }).parallel([prepareToolsStep, prepareMemoryStep2]).map(mapResultsStep).then(streamStep).commit();
11669
12323
  }
@@ -12583,6 +13237,7 @@ var Agent = class extends MastraBase {
12583
13237
  "input"
12584
13238
  );
12585
13239
  const result = llm.stream({
13240
+ methodType: "generate",
12586
13241
  requestContext,
12587
13242
  tracingContext,
12588
13243
  messageList,
@@ -12970,12 +13625,24 @@ var Agent = class extends MastraBase {
12970
13625
  });
12971
13626
  let result;
12972
13627
  if ((methodType === "generate" || methodType === "generateLegacy") && modelVersion === "v2") {
13628
+ if (!agent.hasOwnMemory() && this.#memory) {
13629
+ agent.__setMemory(this.#memory);
13630
+ }
13631
+ const subAgentThreadId = randomUUID();
13632
+ const slugify = await import('@sindresorhus/slugify');
13633
+ const subAgentResourceId = `${slugify.default(this.id)}-${agentName}`;
12973
13634
  const generateResult = await agent.generate(inputData.prompt, {
12974
13635
  requestContext,
12975
- tracingContext: context?.tracingContext
13636
+ tracingContext: context?.tracingContext,
13637
+ ...resourceId && threadId ? {
13638
+ memory: {
13639
+ resource: subAgentResourceId,
13640
+ thread: subAgentThreadId
13641
+ }
13642
+ } : {}
12976
13643
  });
12977
- result = { text: generateResult.text };
12978
- } else if ((methodType === "generate" || methodType === "generateLegacy") && modelVersion === "v1") {
13644
+ result = { text: generateResult.text, subAgentThreadId, subAgentResourceId };
13645
+ } else if (methodType === "generate" && modelVersion === "v1") {
12979
13646
  const generateResult = await agent.generateLegacy(inputData.prompt, {
12980
13647
  requestContext,
12981
13648
  tracingContext: context?.tracingContext
@@ -13087,7 +13754,7 @@ var Agent = class extends MastraBase {
13087
13754
  id: `workflow-${workflowName}`,
13088
13755
  description: workflow.description || `Workflow: ${workflowName}`,
13089
13756
  inputSchema: workflow.inputSchema,
13090
- outputSchema: workflow.outputSchema,
13757
+ outputSchema: z.object({ result: workflow.outputSchema, runId: z.string() }),
13091
13758
  mastra: this.#mastra,
13092
13759
  // BREAKING CHANGE v1.0: New tool signature - first param is inputData, second is context
13093
13760
  // manually wrap workflow tools with tracing, so that we can pass the
@@ -13134,7 +13801,8 @@ var Agent = class extends MastraBase {
13134
13801
  }
13135
13802
  result = await streamResult.result;
13136
13803
  }
13137
- return { result, runId: run.runId };
13804
+ const workflowOutput = result?.result || result;
13805
+ return { result: workflowOutput, runId: run.runId };
13138
13806
  } catch (err) {
13139
13807
  const mastraError = new MastraError(
13140
13808
  {
@@ -13414,7 +14082,7 @@ var Agent = class extends MastraBase {
13414
14082
  if (model || !Array.isArray(this.model)) {
13415
14083
  const modelToUse = model ?? this.model;
13416
14084
  const resolvedModel = typeof modelToUse === "function" ? await modelToUse({ requestContext, mastra: this.#mastra }) : modelToUse;
13417
- if (resolvedModel.specificationVersion !== "v2") {
14085
+ if (resolvedModel?.specificationVersion !== "v2") {
13418
14086
  const mastraError = new MastraError({
13419
14087
  id: "AGENT_PREPARE_MODELS_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",
13420
14088
  domain: "AGENT" /* AGENT */,
@@ -13431,6 +14099,7 @@ var Agent = class extends MastraBase {
13431
14099
  return [
13432
14100
  {
13433
14101
  id: "main",
14102
+ // TODO fix type check
13434
14103
  model: resolvedModel,
13435
14104
  maxRetries: this.maxRetries ?? 0,
13436
14105
  enabled: true
@@ -13440,7 +14109,7 @@ var Agent = class extends MastraBase {
13440
14109
  const models = await Promise.all(
13441
14110
  this.model.map(async (modelConfig) => {
13442
14111
  const model2 = await this.resolveModelConfig(modelConfig.model, requestContext);
13443
- if (model2.specificationVersion !== "v2") {
14112
+ if (!isV2Model(model2)) {
13444
14113
  const mastraError = new MastraError({
13445
14114
  id: "AGENT_PREPARE_MODELS_INCOMPATIBLE_WITH_MODEL_ARRAY_V1",
13446
14115
  domain: "AGENT" /* AGENT */,
@@ -13787,8 +14456,59 @@ var Agent = class extends MastraBase {
13787
14456
  });
13788
14457
  }
13789
14458
  async generate(messages, options) {
13790
- const result = await this.stream(messages, options);
13791
- const fullOutput = await result.getFullOutput();
14459
+ const defaultOptions = await this.getDefaultOptions({
14460
+ requestContext: options?.requestContext
14461
+ });
14462
+ const mergedOptions = {
14463
+ ...defaultOptions,
14464
+ ...options ?? {}
14465
+ };
14466
+ const llm = await this.getLLM({
14467
+ requestContext: mergedOptions.requestContext
14468
+ });
14469
+ const modelInfo = llm.getModel();
14470
+ if (modelInfo.specificationVersion !== "v2") {
14471
+ const modelId = modelInfo.modelId || "unknown";
14472
+ const provider = modelInfo.provider || "unknown";
14473
+ throw new MastraError({
14474
+ id: "AGENT_GENERATE_V1_MODEL_NOT_SUPPORTED",
14475
+ domain: "AGENT" /* AGENT */,
14476
+ category: "USER" /* USER */,
14477
+ text: `Agent "${this.name}" is using AI SDK v4 model (${provider}:${modelId}) which is not compatible with generate(). Please use AI SDK v5 models or call the generateLegacy() method instead. See https://mastra.ai/en/docs/streaming/overview for more information.`,
14478
+ details: {
14479
+ agentName: this.name,
14480
+ modelId,
14481
+ provider,
14482
+ specificationVersion: modelInfo.specificationVersion
14483
+ }
14484
+ });
14485
+ }
14486
+ const executeOptions = {
14487
+ ...mergedOptions,
14488
+ messages,
14489
+ methodType: "generate"
14490
+ };
14491
+ const result = await this.#execute(executeOptions);
14492
+ if (result.status !== "success") {
14493
+ if (result.status === "failed") {
14494
+ throw new MastraError(
14495
+ {
14496
+ id: "AGENT_GENERATE_FAILED",
14497
+ domain: "AGENT" /* AGENT */,
14498
+ category: "USER" /* USER */
14499
+ },
14500
+ // pass original error to preserve stack trace
14501
+ result.error
14502
+ );
14503
+ }
14504
+ throw new MastraError({
14505
+ id: "AGENT_GENERATE_UNKNOWN_ERROR",
14506
+ domain: "AGENT" /* AGENT */,
14507
+ category: "USER" /* USER */,
14508
+ text: "An unknown error occurred while streaming"
14509
+ });
14510
+ }
14511
+ const fullOutput = await result.result.getFullOutput();
13792
14512
  const error = fullOutput.error;
13793
14513
  if (fullOutput.finishReason === "error" && error) {
13794
14514
  throw error;
@@ -15773,6 +16493,6 @@ var MastraModelOutput = class extends MastraBase {
15773
16493
  }
15774
16494
  };
15775
16495
 
15776
- export { AISDKV5OutputStream, Agent, BatchPartsProcessor, ChunkFrom, DefaultExecutionEngine, ExecutionEngine, LanguageDetector, MastraAgentNetworkStream, MastraModelOutput, ModerationProcessor, PIIDetector, ProcessorState, PromptInjectionDetector, Run, StructuredOutputProcessor, SystemPromptScrubber, TokenLimiterProcessor, TripWire, UnicodeNormalizer, Workflow, WorkflowRunOutput, cloneStep, cloneWorkflow, convertFullStreamChunkToUIMessageStream, convertMastraChunkToAISDKv5, createDeprecationProxy, createStep, createWorkflow, getResumeLabelsByStepId, getStepResult, getZodErrors, loop, mapVariable, resolveThreadIdFromArgs, runCountDeprecationMessage, tryGenerateWithJsonFallback, tryStreamWithJsonFallback, validateStepInput };
15777
- //# sourceMappingURL=chunk-7CBEP2ZQ.js.map
15778
- //# sourceMappingURL=chunk-7CBEP2ZQ.js.map
16496
+ export { AISDKV5OutputStream, Agent, BatchPartsProcessor, ChunkFrom, DefaultExecutionEngine, ExecutionEngine, LanguageDetector, MastraAgentNetworkStream, MastraModelOutput, ModerationProcessor, PIIDetector, ProcessorState, PromptInjectionDetector, Run, StructuredOutputProcessor, SystemPromptScrubber, TokenLimiterProcessor, TripWire, UnicodeNormalizer, Workflow, WorkflowRunOutput, cloneStep, cloneWorkflow, convertFullStreamChunkToUIMessageStream, convertMastraChunkToAISDKv5, createDeprecationProxy, createStep, createTimeTravelExecutionParams, createWorkflow, getResumeLabelsByStepId, getStepIds, getStepResult, getZodErrors, loop, mapVariable, resolveThreadIdFromArgs, runCountDeprecationMessage, tryGenerateWithJsonFallback, tryStreamWithJsonFallback, validateStepInput, validateStepResumeData };
16497
+ //# sourceMappingURL=chunk-CKGIPST2.js.map
16498
+ //# sourceMappingURL=chunk-CKGIPST2.js.map