@mastra/core 0.10.12 → 0.10.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/package.json +1 -1
  2. package/a2a.d.ts +0 -1
  3. package/agent.d.ts +0 -1
  4. package/base.d.ts +0 -1
  5. package/bundler.d.ts +0 -1
  6. package/deployer.d.ts +0 -1
  7. package/di.d.ts +0 -1
  8. package/dist/a2a/index.cjs +0 -79
  9. package/dist/a2a/index.d.cts +0 -780
  10. package/dist/a2a/index.d.ts +0 -780
  11. package/dist/a2a/index.js +0 -68
  12. package/dist/agent/index.cjs +0 -15
  13. package/dist/agent/index.d.cts +0 -29
  14. package/dist/agent/index.d.ts +0 -29
  15. package/dist/agent/index.js +0 -2
  16. package/dist/base-B_y9sMg0.d.cts +0 -162
  17. package/dist/base-CS5eSXbL.d.cts +0 -4117
  18. package/dist/base-ClrXcCRx.d.ts +0 -162
  19. package/dist/base-DBhKcre4.d.ts +0 -4117
  20. package/dist/base.cjs +0 -10
  21. package/dist/base.d.cts +0 -6
  22. package/dist/base.d.ts +0 -6
  23. package/dist/base.js +0 -1
  24. package/dist/bundler/index.cjs +0 -10
  25. package/dist/bundler/index.d.cts +0 -30
  26. package/dist/bundler/index.d.ts +0 -30
  27. package/dist/bundler/index.js +0 -1
  28. package/dist/chunk-2GRYVZ2O.cjs +0 -244
  29. package/dist/chunk-2HDFKWFU.js +0 -2249
  30. package/dist/chunk-32C7JDIZ.js +0 -1
  31. package/dist/chunk-4UBOJFSL.js +0 -989
  32. package/dist/chunk-4UWPFBC6.js +0 -88
  33. package/dist/chunk-4Z3OU5RY.cjs +0 -31
  34. package/dist/chunk-5HTMDAXP.js +0 -359
  35. package/dist/chunk-5IEKR756.js +0 -53
  36. package/dist/chunk-5YDTZN2X.js +0 -114
  37. package/dist/chunk-6UNGH46J.js +0 -75
  38. package/dist/chunk-6Y4UL5Z6.cjs +0 -94
  39. package/dist/chunk-7F6BQXE2.cjs +0 -425
  40. package/dist/chunk-7H2GET5Z.cjs +0 -668
  41. package/dist/chunk-7HZ6NIAF.cjs +0 -2
  42. package/dist/chunk-7MZNOW6W.cjs +0 -2263
  43. package/dist/chunk-7XQIPES3.js +0 -668
  44. package/dist/chunk-AKYTYALY.js +0 -70
  45. package/dist/chunk-ATXBSEFT.js +0 -22
  46. package/dist/chunk-B6TOBUS6.cjs +0 -80
  47. package/dist/chunk-B7SQOKEC.cjs +0 -91
  48. package/dist/chunk-BB4KXGBU.js +0 -83
  49. package/dist/chunk-BB6DPGIV.cjs +0 -6
  50. package/dist/chunk-C4LMN2IR.js +0 -27
  51. package/dist/chunk-DFFVEKIG.js +0 -407
  52. package/dist/chunk-E7AX3U6M.cjs +0 -659
  53. package/dist/chunk-EWCOOO3H.js +0 -5007
  54. package/dist/chunk-F2WMR75C.cjs +0 -183
  55. package/dist/chunk-FBKJ3652.cjs +0 -5034
  56. package/dist/chunk-FEYYOBBG.cjs +0 -24
  57. package/dist/chunk-FL5SZ2XU.js +0 -181
  58. package/dist/chunk-GH2KM66J.js +0 -37
  59. package/dist/chunk-GWFS5DAR.cjs +0 -37
  60. package/dist/chunk-HNEE7IF4.js +0 -60
  61. package/dist/chunk-HSVOEWAM.cjs +0 -2
  62. package/dist/chunk-J52TXHZV.cjs +0 -73
  63. package/dist/chunk-JNMQKJH4.js +0 -10
  64. package/dist/chunk-JQOMTERC.js +0 -89
  65. package/dist/chunk-LABUWBKX.cjs +0 -71
  66. package/dist/chunk-LXFZUKP3.cjs +0 -34
  67. package/dist/chunk-MP2QBLUJ.cjs +0 -70
  68. package/dist/chunk-MUNFCOMB.cjs +0 -62
  69. package/dist/chunk-NH5WJNNS.js +0 -1
  70. package/dist/chunk-P3Q73CAW.cjs +0 -55
  71. package/dist/chunk-PA2YIVIT.js +0 -61
  72. package/dist/chunk-QFTBW7ZZ.cjs +0 -2
  73. package/dist/chunk-QQ5K5TZE.cjs +0 -619
  74. package/dist/chunk-QUSEDVYI.cjs +0 -991
  75. package/dist/chunk-R4V75T7J.js +0 -1
  76. package/dist/chunk-SGGPJWRQ.js +0 -69
  77. package/dist/chunk-ST5RMVLG.cjs +0 -87
  78. package/dist/chunk-TC2SCOTE.js +0 -605
  79. package/dist/chunk-U64IJDC5.cjs +0 -109
  80. package/dist/chunk-UX3B6S2I.cjs +0 -65
  81. package/dist/chunk-V5D2LIF5.js +0 -68
  82. package/dist/chunk-VG4OPO2R.js +0 -240
  83. package/dist/chunk-WQNOATKB.js +0 -103
  84. package/dist/chunk-Y7D2JLKS.js +0 -4
  85. package/dist/chunk-YJEHXYK5.js +0 -657
  86. package/dist/chunk-YOQP5T77.js +0 -32
  87. package/dist/chunk-ZIZ3CVHN.cjs +0 -120
  88. package/dist/chunk-ZPOUMTTH.cjs +0 -362
  89. package/dist/chunk-ZZLBNB3U.cjs +0 -12
  90. package/dist/deployer/index.cjs +0 -10
  91. package/dist/deployer/index.d.cts +0 -19
  92. package/dist/deployer/index.d.ts +0 -19
  93. package/dist/deployer/index.js +0 -1
  94. package/dist/di/index.cjs +0 -10
  95. package/dist/di/index.d.cts +0 -1
  96. package/dist/di/index.d.ts +0 -1
  97. package/dist/di/index.js +0 -1
  98. package/dist/error/index.cjs +0 -22
  99. package/dist/error/index.d.cts +0 -86
  100. package/dist/error/index.d.ts +0 -86
  101. package/dist/error/index.js +0 -1
  102. package/dist/eval/index.cjs +0 -14
  103. package/dist/eval/index.d.cts +0 -43
  104. package/dist/eval/index.d.ts +0 -43
  105. package/dist/eval/index.js +0 -1
  106. package/dist/hooks/index.cjs +0 -18
  107. package/dist/hooks/index.d.cts +0 -33
  108. package/dist/hooks/index.d.ts +0 -33
  109. package/dist/hooks/index.js +0 -1
  110. package/dist/index.cjs +0 -281
  111. package/dist/index.d.cts +0 -92
  112. package/dist/index.d.ts +0 -92
  113. package/dist/index.js +0 -112
  114. package/dist/integration/index.cjs +0 -14
  115. package/dist/integration/index.d.cts +0 -65
  116. package/dist/integration/index.d.ts +0 -65
  117. package/dist/integration/index.js +0 -1
  118. package/dist/llm/index.cjs +0 -10
  119. package/dist/llm/index.d.cts +0 -29
  120. package/dist/llm/index.d.ts +0 -29
  121. package/dist/llm/index.js +0 -1
  122. package/dist/logger/index.cjs +0 -43
  123. package/dist/logger/index.d.cts +0 -96
  124. package/dist/logger/index.d.ts +0 -96
  125. package/dist/logger/index.js +0 -2
  126. package/dist/logger-B8XXh6ya.d.cts +0 -159
  127. package/dist/logger-Bpa2oLL4.d.ts +0 -159
  128. package/dist/mastra/index.cjs +0 -10
  129. package/dist/mastra/index.d.cts +0 -29
  130. package/dist/mastra/index.d.ts +0 -29
  131. package/dist/mastra/index.js +0 -1
  132. package/dist/mcp/index.cjs +0 -106
  133. package/dist/mcp/index.d.cts +0 -29
  134. package/dist/mcp/index.d.ts +0 -29
  135. package/dist/mcp/index.js +0 -100
  136. package/dist/memory/index.cjs +0 -18
  137. package/dist/memory/index.d.cts +0 -29
  138. package/dist/memory/index.d.ts +0 -29
  139. package/dist/memory/index.js +0 -1
  140. package/dist/network/index.cjs +0 -311
  141. package/dist/network/index.d.cts +0 -29
  142. package/dist/network/index.d.ts +0 -29
  143. package/dist/network/index.js +0 -309
  144. package/dist/network/vNext/index.cjs +0 -873
  145. package/dist/network/vNext/index.d.cts +0 -29
  146. package/dist/network/vNext/index.d.ts +0 -29
  147. package/dist/network/vNext/index.js +0 -871
  148. package/dist/relevance/index.cjs +0 -18
  149. package/dist/relevance/index.d.cts +0 -49
  150. package/dist/relevance/index.d.ts +0 -49
  151. package/dist/relevance/index.js +0 -1
  152. package/dist/runtime-context/index.cjs +0 -10
  153. package/dist/runtime-context/index.d.cts +0 -52
  154. package/dist/runtime-context/index.d.ts +0 -52
  155. package/dist/runtime-context/index.js +0 -1
  156. package/dist/server/index.cjs +0 -62
  157. package/dist/server/index.d.cts +0 -52
  158. package/dist/server/index.d.ts +0 -52
  159. package/dist/server/index.js +0 -59
  160. package/dist/storage/index.cjs +0 -336
  161. package/dist/storage/index.d.cts +0 -149
  162. package/dist/storage/index.d.ts +0 -149
  163. package/dist/storage/index.js +0 -303
  164. package/dist/telemetry/index.cjs +0 -30
  165. package/dist/telemetry/index.d.cts +0 -75
  166. package/dist/telemetry/index.d.ts +0 -75
  167. package/dist/telemetry/index.js +0 -1
  168. package/dist/telemetry/otel-vendor.cjs +0 -103
  169. package/dist/telemetry/otel-vendor.d.cts +0 -20
  170. package/dist/telemetry/otel-vendor.d.ts +0 -20
  171. package/dist/telemetry/otel-vendor.js +0 -57
  172. package/dist/tools/index.cjs +0 -18
  173. package/dist/tools/index.d.cts +0 -41
  174. package/dist/tools/index.d.ts +0 -41
  175. package/dist/tools/index.js +0 -1
  176. package/dist/tts/index.cjs +0 -10
  177. package/dist/tts/index.d.cts +0 -28
  178. package/dist/tts/index.d.ts +0 -28
  179. package/dist/tts/index.js +0 -1
  180. package/dist/types-Bo1uigWx.d.cts +0 -17
  181. package/dist/types-Bo1uigWx.d.ts +0 -17
  182. package/dist/utils.cjs +0 -58
  183. package/dist/utils.d.cts +0 -149
  184. package/dist/utils.d.ts +0 -149
  185. package/dist/utils.js +0 -1
  186. package/dist/vector/filter/index.cjs +0 -192
  187. package/dist/vector/filter/index.d.cts +0 -128
  188. package/dist/vector/filter/index.d.ts +0 -128
  189. package/dist/vector/filter/index.js +0 -190
  190. package/dist/vector/index.cjs +0 -10
  191. package/dist/vector/index.d.cts +0 -77
  192. package/dist/vector/index.d.ts +0 -77
  193. package/dist/vector/index.js +0 -1
  194. package/dist/voice/index.cjs +0 -18
  195. package/dist/voice/index.d.cts +0 -29
  196. package/dist/voice/index.d.ts +0 -29
  197. package/dist/voice/index.js +0 -1
  198. package/dist/workflows/constants.cjs +0 -10
  199. package/dist/workflows/constants.d.cts +0 -3
  200. package/dist/workflows/constants.d.ts +0 -3
  201. package/dist/workflows/constants.js +0 -1
  202. package/dist/workflows/index.cjs +0 -42
  203. package/dist/workflows/index.d.cts +0 -282
  204. package/dist/workflows/index.d.ts +0 -282
  205. package/dist/workflows/index.js +0 -1
  206. package/dist/workflows/legacy/index.cjs +0 -90
  207. package/dist/workflows/legacy/index.d.cts +0 -91
  208. package/dist/workflows/legacy/index.d.ts +0 -91
  209. package/dist/workflows/legacy/index.js +0 -1
  210. package/error.d.ts +0 -1
  211. package/eval.d.ts +0 -1
  212. package/hooks.d.ts +0 -1
  213. package/integration.d.ts +0 -1
  214. package/llm.d.ts +0 -1
  215. package/logger.d.ts +0 -1
  216. package/mastra.d.ts +0 -1
  217. package/mcp.d.ts +0 -1
  218. package/memory.d.ts +0 -1
  219. package/network/vNext.d.ts +0 -1
  220. package/network.d.ts +0 -1
  221. package/relevance.d.ts +0 -1
  222. package/runtime-context.d.ts +0 -1
  223. package/server.d.ts +0 -1
  224. package/storage.d.ts +0 -1
  225. package/telemetry/otel-vendor.d.ts +0 -1
  226. package/telemetry.d.ts +0 -1
  227. package/tools.d.ts +0 -1
  228. package/tts.d.ts +0 -1
  229. package/utils.d.ts +0 -1
  230. package/vector/filter.d.ts +0 -1
  231. package/vector.d.ts +0 -1
  232. package/voice.d.ts +0 -1
  233. package/workflows/_constants.d.ts +0 -1
  234. package/workflows/legacy.d.ts +0 -1
  235. package/workflows.d.ts +0 -1
@@ -1,2263 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkBB6DPGIV_cjs = require('./chunk-BB6DPGIV.cjs');
4
- var chunkFBKJ3652_cjs = require('./chunk-FBKJ3652.cjs');
5
- var chunk4Z3OU5RY_cjs = require('./chunk-4Z3OU5RY.cjs');
6
- var chunkB6TOBUS6_cjs = require('./chunk-B6TOBUS6.cjs');
7
- var chunkP3Q73CAW_cjs = require('./chunk-P3Q73CAW.cjs');
8
- var chunkZIZ3CVHN_cjs = require('./chunk-ZIZ3CVHN.cjs');
9
- var chunkLABUWBKX_cjs = require('./chunk-LABUWBKX.cjs');
10
- var api = require('@opentelemetry/api');
11
- var crypto = require('crypto');
12
- var EventEmitter = require('events');
13
- var web = require('stream/web');
14
- var zod = require('zod');
15
-
16
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
17
-
18
- var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
19
-
20
- // src/workflows/execution-engine.ts
21
- var ExecutionEngine = class extends chunkP3Q73CAW_cjs.MastraBase {
22
- mastra;
23
- constructor({ mastra }) {
24
- super({ name: "ExecutionEngine", component: chunkZIZ3CVHN_cjs.RegisteredLogger.WORKFLOW });
25
- this.mastra = mastra;
26
- }
27
- __registerMastra(mastra) {
28
- this.mastra = mastra;
29
- }
30
- };
31
- var DefaultExecutionEngine = class extends ExecutionEngine {
32
- /**
33
- * The runCounts map is used to keep track of the run count for each step.
34
- * The step id is used as the key and the run count is the value.
35
- */
36
- runCounts = /* @__PURE__ */ new Map();
37
- /**
38
- * Get or generate the run count for a step.
39
- * If the step id is not in the map, it will be added and the run count will be 0.
40
- * If the step id is in the map, it will return the run count.
41
- *
42
- * @param stepId - The id of the step.
43
- * @returns The run count for the step.
44
- */
45
- getOrGenerateRunCount(stepId) {
46
- if (this.runCounts.has(stepId)) {
47
- const currentRunCount = this.runCounts.get(stepId);
48
- const nextRunCount = currentRunCount + 1;
49
- this.runCounts.set(stepId, nextRunCount);
50
- return nextRunCount;
51
- }
52
- const runCount = 0;
53
- this.runCounts.set(stepId, runCount);
54
- return runCount;
55
- }
56
- async fmtReturnValue(executionSpan, emitter, stepResults, lastOutput, error) {
57
- const base = {
58
- status: lastOutput.status,
59
- steps: stepResults
60
- };
61
- if (lastOutput.status === "success") {
62
- await emitter.emit("watch", {
63
- type: "watch",
64
- payload: {
65
- workflowState: {
66
- status: lastOutput.status,
67
- steps: stepResults,
68
- result: lastOutput.output
69
- }
70
- },
71
- eventTimestamp: Date.now()
72
- });
73
- base.result = lastOutput.output;
74
- } else if (lastOutput.status === "failed") {
75
- await emitter.emit("watch", {
76
- type: "watch",
77
- payload: {
78
- workflowState: {
79
- status: lastOutput.status,
80
- steps: stepResults,
81
- result: null,
82
- error: lastOutput.error
83
- }
84
- },
85
- eventTimestamp: Date.now()
86
- });
87
- 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));
88
- } else if (lastOutput.status === "suspended") {
89
- const suspendedStepIds = Object.entries(stepResults).flatMap(([stepId, stepResult]) => {
90
- if (stepResult?.status === "suspended") {
91
- const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
92
- return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
93
- }
94
- return [];
95
- });
96
- base.suspended = suspendedStepIds;
97
- await emitter.emit("watch", {
98
- type: "watch",
99
- payload: {
100
- workflowState: {
101
- status: lastOutput.status,
102
- steps: stepResults,
103
- result: null,
104
- error: null
105
- }
106
- },
107
- eventTimestamp: Date.now()
108
- });
109
- }
110
- executionSpan?.end();
111
- return base;
112
- }
113
- /**
114
- * Executes a workflow run with the provided execution graph and input
115
- * @param graph The execution graph to execute
116
- * @param input The input data for the workflow
117
- * @returns A promise that resolves to the workflow output
118
- */
119
- async execute(params) {
120
- const { workflowId, runId, graph, input, resume, retryConfig } = params;
121
- const { attempts = 0, delay = 0 } = retryConfig ?? {};
122
- const steps = graph.steps;
123
- if (steps.length === 0) {
124
- throw new chunkB6TOBUS6_cjs.MastraError({
125
- id: "WORKFLOW_EXECUTE_EMPTY_GRAPH",
126
- text: "Workflow must have at least one step",
127
- domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
128
- category: "USER" /* USER */
129
- });
130
- }
131
- const executionSpan = this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`, {
132
- attributes: { componentName: workflowId, runId }
133
- });
134
- let startIdx = 0;
135
- if (resume?.resumePath) {
136
- startIdx = resume.resumePath[0];
137
- resume.resumePath.shift();
138
- }
139
- const stepResults = resume?.stepResults || { input };
140
- let lastOutput;
141
- for (let i = startIdx; i < steps.length; i++) {
142
- const entry = steps[i];
143
- try {
144
- lastOutput = await this.executeEntry({
145
- workflowId,
146
- runId,
147
- entry,
148
- serializedStepGraph: params.serializedStepGraph,
149
- prevStep: steps[i - 1],
150
- stepResults,
151
- resume,
152
- executionContext: {
153
- workflowId,
154
- runId,
155
- executionPath: [i],
156
- suspendedPaths: {},
157
- retryConfig: { attempts, delay },
158
- executionSpan
159
- },
160
- abortController: params.abortController,
161
- emitter: params.emitter,
162
- runtimeContext: params.runtimeContext
163
- });
164
- if (lastOutput.result.status !== "success") {
165
- if (lastOutput.result.status === "bailed") {
166
- lastOutput.result.status = "success";
167
- }
168
- const result2 = await this.fmtReturnValue(
169
- executionSpan,
170
- params.emitter,
171
- stepResults,
172
- lastOutput.result
173
- );
174
- await this.persistStepUpdate({
175
- workflowId,
176
- runId,
177
- stepResults: lastOutput.stepResults,
178
- serializedStepGraph: params.serializedStepGraph,
179
- executionContext: lastOutput.executionContext,
180
- workflowStatus: result2.status,
181
- result: result2.result,
182
- error: result2.error
183
- });
184
- return result2;
185
- }
186
- } catch (e) {
187
- const error = e instanceof chunkB6TOBUS6_cjs.MastraError ? e : new chunkB6TOBUS6_cjs.MastraError(
188
- {
189
- id: "WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",
190
- domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
191
- category: "USER" /* USER */,
192
- details: { workflowId, runId }
193
- },
194
- e
195
- );
196
- this.logger?.trackException(error);
197
- this.logger?.error(`Error executing step: ${error?.stack}`);
198
- const result2 = await this.fmtReturnValue(
199
- executionSpan,
200
- params.emitter,
201
- stepResults,
202
- lastOutput.result,
203
- e
204
- );
205
- await this.persistStepUpdate({
206
- workflowId,
207
- runId,
208
- stepResults: lastOutput.stepResults,
209
- serializedStepGraph: params.serializedStepGraph,
210
- executionContext: lastOutput.executionContext,
211
- workflowStatus: result2.status,
212
- result: result2.result,
213
- error: result2.error
214
- });
215
- return result2;
216
- }
217
- }
218
- const result = await this.fmtReturnValue(executionSpan, params.emitter, stepResults, lastOutput.result);
219
- await this.persistStepUpdate({
220
- workflowId,
221
- runId,
222
- stepResults: lastOutput.stepResults,
223
- serializedStepGraph: params.serializedStepGraph,
224
- executionContext: lastOutput.executionContext,
225
- workflowStatus: result.status,
226
- result: result.result,
227
- error: result.error
228
- });
229
- return result;
230
- }
231
- getStepOutput(stepResults, step) {
232
- if (!step) {
233
- return stepResults.input;
234
- } else if (step.type === "step" || step.type === "waitForEvent") {
235
- return stepResults[step.step.id]?.output;
236
- } else if (step.type === "sleep" || step.type === "sleepUntil") {
237
- return stepResults[step.id]?.output;
238
- } else if (step.type === "parallel" || step.type === "conditional") {
239
- return step.steps.reduce(
240
- (acc, entry) => {
241
- if (entry.type === "step" || entry.type === "waitForEvent") {
242
- acc[entry.step.id] = stepResults[entry.step.id]?.output;
243
- } else if (entry.type === "parallel" || entry.type === "conditional") {
244
- const parallelResult = this.getStepOutput(stepResults, entry)?.output;
245
- acc = { ...acc, ...parallelResult };
246
- } else if (entry.type === "loop") {
247
- acc[entry.step.id] = stepResults[entry.step.id]?.output;
248
- } else if (entry.type === "foreach") {
249
- acc[entry.step.id] = stepResults[entry.step.id]?.output;
250
- } else if (entry.type === "sleep" || entry.type === "sleepUntil") {
251
- acc[entry.id] = stepResults[entry.id]?.output;
252
- }
253
- return acc;
254
- },
255
- {}
256
- );
257
- } else if (step.type === "loop") {
258
- return stepResults[step.step.id]?.output;
259
- } else if (step.type === "foreach") {
260
- return stepResults[step.step.id]?.output;
261
- }
262
- }
263
- async executeSleep({
264
- runId,
265
- entry,
266
- prevOutput,
267
- stepResults,
268
- emitter,
269
- abortController,
270
- runtimeContext
271
- }) {
272
- let { duration, fn } = entry;
273
- if (fn) {
274
- duration = await fn({
275
- runId,
276
- mastra: this.mastra,
277
- runtimeContext,
278
- inputData: prevOutput,
279
- runCount: -1,
280
- getInitData: () => stepResults?.input,
281
- getStepResult: (step) => {
282
- if (!step?.id) {
283
- return null;
284
- }
285
- const result = stepResults[step.id];
286
- if (result?.status === "success") {
287
- return result.output;
288
- }
289
- return null;
290
- },
291
- // TODO: this function shouldn't have suspend probably?
292
- suspend: async (_suspendPayload) => {
293
- },
294
- bail: () => {
295
- },
296
- abort: () => {
297
- abortController?.abort();
298
- },
299
- [chunkBB6DPGIV_cjs.EMITTER_SYMBOL]: emitter,
300
- engine: {},
301
- abortSignal: abortController?.signal
302
- });
303
- }
304
- await new Promise((resolve) => setTimeout(resolve, !duration || duration < 0 ? 0 : duration));
305
- }
306
- async executeSleepUntil({
307
- runId,
308
- entry,
309
- prevOutput,
310
- stepResults,
311
- emitter,
312
- abortController,
313
- runtimeContext
314
- }) {
315
- let { date, fn } = entry;
316
- if (fn) {
317
- date = await fn({
318
- runId,
319
- mastra: this.mastra,
320
- runtimeContext,
321
- inputData: prevOutput,
322
- runCount: -1,
323
- getInitData: () => stepResults?.input,
324
- getStepResult: (step) => {
325
- if (!step?.id) {
326
- return null;
327
- }
328
- const result = stepResults[step.id];
329
- if (result?.status === "success") {
330
- return result.output;
331
- }
332
- return null;
333
- },
334
- // TODO: this function shouldn't have suspend probably?
335
- suspend: async (_suspendPayload) => {
336
- },
337
- bail: () => {
338
- },
339
- abort: () => {
340
- abortController?.abort();
341
- },
342
- [chunkBB6DPGIV_cjs.EMITTER_SYMBOL]: emitter,
343
- engine: {},
344
- abortSignal: abortController?.signal
345
- });
346
- }
347
- const time = !date ? 0 : date?.getTime() - Date.now();
348
- await new Promise((resolve) => setTimeout(resolve, time < 0 ? 0 : time));
349
- }
350
- async executeWaitForEvent({
351
- event,
352
- emitter,
353
- timeout
354
- }) {
355
- return new Promise((resolve, reject) => {
356
- const cb = (eventData) => {
357
- resolve(eventData);
358
- };
359
- if (timeout) {
360
- setTimeout(() => {
361
- emitter.off(`user-event-${event}`, cb);
362
- reject(new Error("Timeout waiting for event"));
363
- }, timeout);
364
- }
365
- emitter.once(`user-event-${event}`, cb);
366
- });
367
- }
368
- async executeStep({
369
- workflowId,
370
- runId,
371
- step,
372
- stepResults,
373
- executionContext,
374
- resume,
375
- prevOutput,
376
- emitter,
377
- abortController,
378
- runtimeContext
379
- }) {
380
- const startTime = resume?.steps[0] === step.id ? void 0 : Date.now();
381
- const resumeTime = resume?.steps[0] === step.id ? Date.now() : void 0;
382
- const stepInfo = {
383
- ...stepResults[step.id],
384
- ...resume?.steps[0] === step.id ? { resumePayload: resume?.resumePayload } : { payload: prevOutput },
385
- ...startTime ? { startedAt: startTime } : {},
386
- ...resumeTime ? { resumedAt: resumeTime } : {}
387
- };
388
- await emitter.emit("watch", {
389
- type: "watch",
390
- payload: {
391
- currentStep: {
392
- id: step.id,
393
- status: "running",
394
- ...stepInfo
395
- },
396
- workflowState: {
397
- status: "running",
398
- steps: {
399
- ...stepResults,
400
- [step.id]: {
401
- status: "running",
402
- ...stepInfo
403
- }
404
- },
405
- result: null,
406
- error: null
407
- }
408
- },
409
- eventTimestamp: Date.now()
410
- });
411
- await emitter.emit("watch-v2", {
412
- type: "step-start",
413
- payload: {
414
- id: step.id,
415
- ...stepInfo,
416
- status: "running"
417
- }
418
- });
419
- const _runStep = (step2, spanName, attributes) => {
420
- return async (data) => {
421
- const telemetry = this.mastra?.getTelemetry();
422
- const span = executionContext.executionSpan;
423
- if (!telemetry || !span) {
424
- return step2.execute(data);
425
- }
426
- return api.context.with(api.trace.setSpan(api.context.active(), span), async () => {
427
- return telemetry.traceMethod(step2.execute.bind(step2), {
428
- spanName,
429
- attributes
430
- })(data);
431
- });
432
- };
433
- };
434
- const runStep = _runStep(step, `workflow.${workflowId}.step.${step.id}`, {
435
- componentName: workflowId,
436
- runId
437
- });
438
- let execResults;
439
- const retries = step.retries ?? executionContext.retryConfig.attempts ?? 0;
440
- const delay = executionContext.retryConfig.delay ?? 0;
441
- for (let i = 0; i < retries + 1; i++) {
442
- if (i > 0 && delay) {
443
- await new Promise((resolve) => setTimeout(resolve, delay));
444
- }
445
- try {
446
- let suspended;
447
- let bailed;
448
- const result = await runStep({
449
- runId,
450
- mastra: this.mastra,
451
- runtimeContext,
452
- inputData: prevOutput,
453
- runCount: this.getOrGenerateRunCount(step.id),
454
- resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
455
- getInitData: () => stepResults?.input,
456
- getStepResult: (step2) => {
457
- if (!step2?.id) {
458
- return null;
459
- }
460
- const result2 = stepResults[step2.id];
461
- if (result2?.status === "success") {
462
- return result2.output;
463
- }
464
- return null;
465
- },
466
- suspend: async (suspendPayload) => {
467
- executionContext.suspendedPaths[step.id] = executionContext.executionPath;
468
- suspended = { payload: suspendPayload };
469
- },
470
- bail: (result2) => {
471
- bailed = { payload: result2 };
472
- },
473
- abort: () => {
474
- abortController?.abort();
475
- },
476
- resume: {
477
- steps: resume?.steps?.slice(1) || [],
478
- resumePayload: resume?.resumePayload,
479
- // @ts-ignore
480
- runId: stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId
481
- },
482
- [chunkBB6DPGIV_cjs.EMITTER_SYMBOL]: emitter,
483
- engine: {},
484
- abortSignal: abortController?.signal
485
- });
486
- if (suspended) {
487
- execResults = { status: "suspended", suspendPayload: suspended.payload, suspendedAt: Date.now() };
488
- } else if (bailed) {
489
- execResults = { status: "bailed", output: bailed.payload, endedAt: Date.now() };
490
- } else {
491
- execResults = { status: "success", output: result, endedAt: Date.now() };
492
- }
493
- break;
494
- } catch (e) {
495
- const error = e instanceof chunkB6TOBUS6_cjs.MastraError ? e : new chunkB6TOBUS6_cjs.MastraError(
496
- {
497
- id: "WORKFLOW_STEP_INVOKE_FAILED",
498
- domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
499
- category: "USER" /* USER */,
500
- details: { workflowId, runId, stepId: step.id }
501
- },
502
- e
503
- );
504
- this.logger.trackException(error);
505
- this.logger.error(`Error executing step ${step.id}: ` + error?.stack);
506
- execResults = {
507
- status: "failed",
508
- error: error?.stack,
509
- endedAt: Date.now()
510
- };
511
- }
512
- }
513
- await emitter.emit("watch", {
514
- type: "watch",
515
- payload: {
516
- currentStep: {
517
- id: step.id,
518
- ...stepInfo,
519
- ...execResults
520
- },
521
- workflowState: {
522
- status: "running",
523
- steps: {
524
- ...stepResults,
525
- [step.id]: {
526
- ...stepInfo,
527
- ...execResults
528
- }
529
- },
530
- result: null,
531
- error: null
532
- }
533
- },
534
- eventTimestamp: Date.now()
535
- });
536
- if (execResults.status === "suspended") {
537
- await emitter.emit("watch-v2", {
538
- type: "step-suspended",
539
- payload: {
540
- id: step.id,
541
- ...execResults
542
- }
543
- });
544
- } else {
545
- await emitter.emit("watch-v2", {
546
- type: "step-result",
547
- payload: {
548
- id: step.id,
549
- ...execResults
550
- }
551
- });
552
- await emitter.emit("watch-v2", {
553
- type: "step-finish",
554
- payload: {
555
- id: step.id,
556
- metadata: {}
557
- }
558
- });
559
- }
560
- return { ...stepInfo, ...execResults };
561
- }
562
- async executeParallel({
563
- workflowId,
564
- runId,
565
- entry,
566
- prevStep,
567
- serializedStepGraph,
568
- stepResults,
569
- resume,
570
- executionContext,
571
- emitter,
572
- abortController,
573
- runtimeContext
574
- }) {
575
- let execResults;
576
- const results = await Promise.all(
577
- entry.steps.map(
578
- (step, i) => this.executeEntry({
579
- workflowId,
580
- runId,
581
- entry: step,
582
- prevStep,
583
- stepResults,
584
- serializedStepGraph,
585
- resume,
586
- executionContext: {
587
- workflowId,
588
- runId,
589
- executionPath: [...executionContext.executionPath, i],
590
- suspendedPaths: executionContext.suspendedPaths,
591
- retryConfig: executionContext.retryConfig,
592
- executionSpan: executionContext.executionSpan
593
- },
594
- emitter,
595
- abortController,
596
- runtimeContext
597
- })
598
- )
599
- );
600
- const hasFailed = results.find((result) => result.result.status === "failed");
601
- const hasSuspended = results.find((result) => result.result.status === "suspended");
602
- if (hasFailed) {
603
- execResults = { status: "failed", error: hasFailed.result.error };
604
- } else if (hasSuspended) {
605
- execResults = { status: "suspended", payload: hasSuspended.result.suspendPayload };
606
- } else if (abortController?.signal?.aborted) {
607
- execResults = { status: "canceled" };
608
- } else {
609
- execResults = {
610
- status: "success",
611
- output: results.reduce((acc, result, index) => {
612
- if (result.result.status === "success") {
613
- acc[entry.steps[index].step.id] = result.result.output;
614
- }
615
- return acc;
616
- }, {})
617
- };
618
- }
619
- return execResults;
620
- }
621
- async executeConditional({
622
- workflowId,
623
- runId,
624
- entry,
625
- prevOutput,
626
- prevStep,
627
- serializedStepGraph,
628
- stepResults,
629
- resume,
630
- executionContext,
631
- emitter,
632
- abortController,
633
- runtimeContext
634
- }) {
635
- let execResults;
636
- const truthyIndexes = (await Promise.all(
637
- entry.conditions.map(async (cond, index) => {
638
- try {
639
- const result = await cond({
640
- runId,
641
- mastra: this.mastra,
642
- runtimeContext,
643
- inputData: prevOutput,
644
- runCount: -1,
645
- getInitData: () => stepResults?.input,
646
- getStepResult: (step) => {
647
- if (!step?.id) {
648
- return null;
649
- }
650
- const result2 = stepResults[step.id];
651
- if (result2?.status === "success") {
652
- return result2.output;
653
- }
654
- return null;
655
- },
656
- // TODO: this function shouldn't have suspend probably?
657
- suspend: async (_suspendPayload) => {
658
- },
659
- bail: () => {
660
- },
661
- abort: () => {
662
- abortController?.abort();
663
- },
664
- [chunkBB6DPGIV_cjs.EMITTER_SYMBOL]: emitter,
665
- engine: {},
666
- abortSignal: abortController?.signal
667
- });
668
- return result ? index : null;
669
- } catch (e) {
670
- const error = e instanceof chunkB6TOBUS6_cjs.MastraError ? e : new chunkB6TOBUS6_cjs.MastraError(
671
- {
672
- id: "WORKFLOW_CONDITION_EVALUATION_FAILED",
673
- domain: "MASTRA_WORKFLOW" /* MASTRA_WORKFLOW */,
674
- category: "USER" /* USER */,
675
- details: { workflowId, runId }
676
- },
677
- e
678
- );
679
- this.logger.trackException(error);
680
- this.logger.error("Error evaluating condition: " + error?.stack);
681
- return null;
682
- }
683
- })
684
- )).filter((index) => index !== null);
685
- const stepsToRun = entry.steps.filter((_, index) => truthyIndexes.includes(index));
686
- const results = await Promise.all(
687
- stepsToRun.map(
688
- (step, index) => this.executeEntry({
689
- workflowId,
690
- runId,
691
- entry: step,
692
- prevStep,
693
- stepResults,
694
- serializedStepGraph,
695
- resume,
696
- executionContext: {
697
- workflowId,
698
- runId,
699
- executionPath: [...executionContext.executionPath, index],
700
- suspendedPaths: executionContext.suspendedPaths,
701
- retryConfig: executionContext.retryConfig,
702
- executionSpan: executionContext.executionSpan
703
- },
704
- emitter,
705
- abortController,
706
- runtimeContext
707
- })
708
- )
709
- );
710
- const hasFailed = results.find((result) => result.result.status === "failed");
711
- const hasSuspended = results.find((result) => result.result.status === "suspended");
712
- if (hasFailed) {
713
- execResults = { status: "failed", error: hasFailed.result.error };
714
- } else if (hasSuspended) {
715
- execResults = { status: "suspended", payload: hasSuspended.result.suspendPayload };
716
- } else if (abortController?.signal?.aborted) {
717
- execResults = { status: "canceled" };
718
- } else {
719
- execResults = {
720
- status: "success",
721
- output: results.reduce((acc, result, index) => {
722
- if (result.result.status === "success") {
723
- acc[stepsToRun[index].step.id] = result.result.output;
724
- }
725
- return acc;
726
- }, {})
727
- };
728
- }
729
- return execResults;
730
- }
731
- async executeLoop({
732
- workflowId,
733
- runId,
734
- entry,
735
- prevOutput,
736
- stepResults,
737
- resume,
738
- executionContext,
739
- emitter,
740
- abortController,
741
- runtimeContext
742
- }) {
743
- const { step, condition } = entry;
744
- let isTrue = true;
745
- let result = { status: "success", output: prevOutput };
746
- do {
747
- result = await this.executeStep({
748
- workflowId,
749
- runId,
750
- step,
751
- stepResults,
752
- executionContext,
753
- resume,
754
- prevOutput: result.output,
755
- emitter,
756
- abortController,
757
- runtimeContext
758
- });
759
- if (result.status !== "success") {
760
- return result;
761
- }
762
- isTrue = await condition({
763
- runId,
764
- mastra: this.mastra,
765
- runtimeContext,
766
- inputData: result.output,
767
- runCount: -1,
768
- getInitData: () => stepResults?.input,
769
- getStepResult: (step2) => {
770
- if (!step2?.id) {
771
- return null;
772
- }
773
- const result2 = stepResults[step2.id];
774
- return result2?.status === "success" ? result2.output : null;
775
- },
776
- suspend: async (_suspendPayload) => {
777
- },
778
- bail: () => {
779
- },
780
- abort: () => {
781
- abortController?.abort();
782
- },
783
- [chunkBB6DPGIV_cjs.EMITTER_SYMBOL]: emitter,
784
- engine: {},
785
- abortSignal: abortController?.signal
786
- });
787
- } while (entry.loopType === "dowhile" ? isTrue : !isTrue);
788
- return result;
789
- }
790
- async executeForeach({
791
- workflowId,
792
- runId,
793
- entry,
794
- prevOutput,
795
- stepResults,
796
- resume,
797
- executionContext,
798
- emitter,
799
- abortController,
800
- runtimeContext
801
- }) {
802
- const { step, opts } = entry;
803
- const results = [];
804
- const concurrency = opts.concurrency;
805
- const startTime = resume?.steps[0] === step.id ? void 0 : Date.now();
806
- const resumeTime = resume?.steps[0] === step.id ? Date.now() : void 0;
807
- for (let i = 0; i < prevOutput.length; i += concurrency) {
808
- const items = prevOutput.slice(i, i + concurrency);
809
- const itemsResults = await Promise.all(
810
- items.map((item) => {
811
- return this.executeStep({
812
- workflowId,
813
- runId,
814
- step,
815
- stepResults,
816
- executionContext,
817
- resume,
818
- prevOutput: item,
819
- emitter,
820
- abortController,
821
- runtimeContext
822
- });
823
- })
824
- );
825
- for (const result of itemsResults) {
826
- if (result.status !== "success") {
827
- return result;
828
- }
829
- results.push(result?.output);
830
- }
831
- }
832
- return {
833
- ...stepResults[step.id],
834
- status: "success",
835
- payload: prevOutput,
836
- ...resume?.steps[0] === step.id ? { resumePayload: resume?.resumePayload } : {},
837
- output: results,
838
- //@ts-ignore
839
- endedAt: Date.now(),
840
- ...startTime ? { startedAt: startTime } : {},
841
- ...resumeTime ? { resumedAt: resumeTime } : {}
842
- };
843
- }
844
- async persistStepUpdate({
845
- workflowId,
846
- runId,
847
- stepResults,
848
- serializedStepGraph,
849
- executionContext,
850
- workflowStatus,
851
- result,
852
- error
853
- }) {
854
- await this.mastra?.getStorage()?.persistWorkflowSnapshot({
855
- workflowName: workflowId,
856
- runId,
857
- snapshot: {
858
- runId,
859
- status: workflowStatus,
860
- value: {},
861
- context: stepResults,
862
- activePaths: [],
863
- serializedStepGraph,
864
- suspendedPaths: executionContext.suspendedPaths,
865
- result,
866
- error,
867
- // @ts-ignore
868
- timestamp: Date.now()
869
- }
870
- });
871
- }
872
- async executeEntry({
873
- workflowId,
874
- runId,
875
- entry,
876
- prevStep,
877
- serializedStepGraph,
878
- stepResults,
879
- resume,
880
- executionContext,
881
- emitter,
882
- abortController,
883
- runtimeContext
884
- }) {
885
- const prevOutput = this.getStepOutput(stepResults, prevStep);
886
- let execResults;
887
- if (entry.type === "step") {
888
- const { step } = entry;
889
- execResults = await this.executeStep({
890
- workflowId,
891
- runId,
892
- step,
893
- stepResults,
894
- executionContext,
895
- resume,
896
- prevOutput,
897
- emitter,
898
- abortController,
899
- runtimeContext
900
- });
901
- } else if (resume?.resumePath?.length && (entry.type === "parallel" || entry.type === "conditional")) {
902
- const idx = resume.resumePath.shift();
903
- return this.executeEntry({
904
- workflowId,
905
- runId,
906
- entry: entry.steps[idx],
907
- prevStep,
908
- serializedStepGraph,
909
- stepResults,
910
- resume,
911
- executionContext: {
912
- workflowId,
913
- runId,
914
- executionPath: [...executionContext.executionPath, idx],
915
- suspendedPaths: executionContext.suspendedPaths,
916
- retryConfig: executionContext.retryConfig,
917
- executionSpan: executionContext.executionSpan
918
- },
919
- emitter,
920
- abortController,
921
- runtimeContext
922
- });
923
- } else if (entry.type === "parallel") {
924
- execResults = await this.executeParallel({
925
- workflowId,
926
- runId,
927
- entry,
928
- prevStep,
929
- stepResults,
930
- serializedStepGraph,
931
- resume,
932
- executionContext,
933
- emitter,
934
- abortController,
935
- runtimeContext
936
- });
937
- } else if (entry.type === "conditional") {
938
- execResults = await this.executeConditional({
939
- workflowId,
940
- runId,
941
- entry,
942
- prevStep,
943
- prevOutput,
944
- stepResults,
945
- serializedStepGraph,
946
- resume,
947
- executionContext,
948
- emitter,
949
- abortController,
950
- runtimeContext
951
- });
952
- } else if (entry.type === "loop") {
953
- execResults = await this.executeLoop({
954
- workflowId,
955
- runId,
956
- entry,
957
- prevStep,
958
- prevOutput,
959
- stepResults,
960
- resume,
961
- executionContext,
962
- emitter,
963
- abortController,
964
- runtimeContext
965
- });
966
- } else if (entry.type === "foreach") {
967
- execResults = await this.executeForeach({
968
- workflowId,
969
- runId,
970
- entry,
971
- prevStep,
972
- prevOutput,
973
- stepResults,
974
- resume,
975
- executionContext,
976
- emitter,
977
- abortController,
978
- runtimeContext
979
- });
980
- } else if (entry.type === "sleep") {
981
- const startedAt = Date.now();
982
- await emitter.emit("watch", {
983
- type: "watch",
984
- payload: {
985
- currentStep: {
986
- id: entry.id,
987
- status: "waiting",
988
- payload: prevOutput,
989
- startedAt
990
- },
991
- workflowState: {
992
- status: "waiting",
993
- steps: {
994
- ...stepResults,
995
- [entry.id]: {
996
- status: "waiting",
997
- payload: prevOutput,
998
- startedAt
999
- }
1000
- },
1001
- result: null,
1002
- error: null
1003
- }
1004
- },
1005
- eventTimestamp: Date.now()
1006
- });
1007
- await emitter.emit("watch-v2", {
1008
- type: "step-waiting",
1009
- payload: {
1010
- id: entry.id,
1011
- payload: prevOutput,
1012
- startedAt,
1013
- status: "waiting"
1014
- }
1015
- });
1016
- await this.persistStepUpdate({
1017
- workflowId,
1018
- runId,
1019
- serializedStepGraph,
1020
- stepResults,
1021
- executionContext,
1022
- workflowStatus: "waiting"
1023
- });
1024
- await this.executeSleep({
1025
- workflowId,
1026
- runId,
1027
- entry,
1028
- prevStep,
1029
- prevOutput,
1030
- stepResults,
1031
- serializedStepGraph,
1032
- resume,
1033
- executionContext,
1034
- emitter,
1035
- abortController,
1036
- runtimeContext
1037
- });
1038
- await this.persistStepUpdate({
1039
- workflowId,
1040
- runId,
1041
- serializedStepGraph,
1042
- stepResults,
1043
- executionContext,
1044
- workflowStatus: "running"
1045
- });
1046
- const endedAt = Date.now();
1047
- const stepInfo = {
1048
- payload: prevOutput,
1049
- startedAt,
1050
- endedAt
1051
- };
1052
- execResults = { ...stepInfo, status: "success", output: prevOutput };
1053
- stepResults[entry.id] = { ...stepInfo, status: "success", output: prevOutput };
1054
- await emitter.emit("watch", {
1055
- type: "watch",
1056
- payload: {
1057
- currentStep: {
1058
- id: entry.id,
1059
- ...execResults
1060
- },
1061
- workflowState: {
1062
- status: "running",
1063
- steps: {
1064
- ...stepResults,
1065
- [entry.id]: {
1066
- ...execResults
1067
- }
1068
- },
1069
- result: null,
1070
- error: null
1071
- }
1072
- },
1073
- eventTimestamp: Date.now()
1074
- });
1075
- await emitter.emit("watch-v2", {
1076
- type: "step-result",
1077
- payload: {
1078
- id: entry.id,
1079
- ...execResults
1080
- }
1081
- });
1082
- await emitter.emit("watch-v2", {
1083
- type: "step-finish",
1084
- payload: {
1085
- id: entry.id,
1086
- metadata: {}
1087
- }
1088
- });
1089
- } else if (entry.type === "sleepUntil") {
1090
- const startedAt = Date.now();
1091
- await emitter.emit("watch", {
1092
- type: "watch",
1093
- payload: {
1094
- currentStep: {
1095
- id: entry.id,
1096
- status: "waiting",
1097
- payload: prevOutput,
1098
- startedAt
1099
- },
1100
- workflowState: {
1101
- status: "waiting",
1102
- steps: {
1103
- ...stepResults,
1104
- [entry.id]: {
1105
- status: "waiting",
1106
- payload: prevOutput,
1107
- startedAt
1108
- }
1109
- },
1110
- result: null,
1111
- error: null
1112
- }
1113
- },
1114
- eventTimestamp: Date.now()
1115
- });
1116
- await emitter.emit("watch-v2", {
1117
- type: "step-waiting",
1118
- payload: {
1119
- id: entry.id,
1120
- payload: prevOutput,
1121
- startedAt,
1122
- status: "waiting"
1123
- }
1124
- });
1125
- await this.persistStepUpdate({
1126
- workflowId,
1127
- runId,
1128
- serializedStepGraph,
1129
- stepResults,
1130
- executionContext,
1131
- workflowStatus: "waiting"
1132
- });
1133
- await this.executeSleepUntil({
1134
- workflowId,
1135
- runId,
1136
- entry,
1137
- prevStep,
1138
- prevOutput,
1139
- stepResults,
1140
- serializedStepGraph,
1141
- resume,
1142
- executionContext,
1143
- emitter,
1144
- abortController,
1145
- runtimeContext
1146
- });
1147
- await this.persistStepUpdate({
1148
- workflowId,
1149
- runId,
1150
- serializedStepGraph,
1151
- stepResults,
1152
- executionContext,
1153
- workflowStatus: "running"
1154
- });
1155
- const endedAt = Date.now();
1156
- const stepInfo = {
1157
- payload: prevOutput,
1158
- startedAt,
1159
- endedAt
1160
- };
1161
- execResults = { ...stepInfo, status: "success", output: prevOutput };
1162
- stepResults[entry.id] = { ...stepInfo, status: "success", output: prevOutput };
1163
- await emitter.emit("watch", {
1164
- type: "watch",
1165
- payload: {
1166
- currentStep: {
1167
- id: entry.id,
1168
- ...execResults
1169
- },
1170
- workflowState: {
1171
- status: "running",
1172
- steps: {
1173
- ...stepResults,
1174
- [entry.id]: {
1175
- ...execResults
1176
- }
1177
- },
1178
- result: null,
1179
- error: null
1180
- }
1181
- },
1182
- eventTimestamp: Date.now()
1183
- });
1184
- await emitter.emit("watch-v2", {
1185
- type: "step-result",
1186
- payload: {
1187
- id: entry.id,
1188
- ...execResults
1189
- }
1190
- });
1191
- await emitter.emit("watch-v2", {
1192
- type: "step-finish",
1193
- payload: {
1194
- id: entry.id,
1195
- metadata: {}
1196
- }
1197
- });
1198
- } else if (entry.type === "waitForEvent") {
1199
- const startedAt = Date.now();
1200
- let eventData;
1201
- await emitter.emit("watch", {
1202
- type: "watch",
1203
- payload: {
1204
- currentStep: {
1205
- id: entry.step.id,
1206
- status: "waiting",
1207
- payload: prevOutput,
1208
- startedAt
1209
- },
1210
- workflowState: {
1211
- status: "waiting",
1212
- steps: {
1213
- ...stepResults,
1214
- [entry.step.id]: {
1215
- status: "waiting",
1216
- payload: prevOutput,
1217
- startedAt
1218
- }
1219
- },
1220
- result: null,
1221
- error: null
1222
- }
1223
- },
1224
- eventTimestamp: Date.now()
1225
- });
1226
- await emitter.emit("watch-v2", {
1227
- type: "step-waiting",
1228
- payload: {
1229
- id: entry.step.id,
1230
- payload: prevOutput,
1231
- startedAt,
1232
- status: "waiting"
1233
- }
1234
- });
1235
- await this.persistStepUpdate({
1236
- workflowId,
1237
- runId,
1238
- serializedStepGraph,
1239
- stepResults,
1240
- executionContext,
1241
- workflowStatus: "waiting"
1242
- });
1243
- try {
1244
- eventData = await this.executeWaitForEvent({ event: entry.event, emitter, timeout: entry.timeout });
1245
- await this.persistStepUpdate({
1246
- workflowId,
1247
- runId,
1248
- serializedStepGraph,
1249
- stepResults,
1250
- executionContext,
1251
- workflowStatus: "running"
1252
- });
1253
- const { step } = entry;
1254
- execResults = await this.executeStep({
1255
- workflowId,
1256
- runId,
1257
- step,
1258
- stepResults,
1259
- executionContext,
1260
- resume: {
1261
- resumePayload: eventData,
1262
- steps: [entry.step.id]
1263
- },
1264
- prevOutput,
1265
- emitter,
1266
- abortController,
1267
- runtimeContext
1268
- });
1269
- } catch (error) {
1270
- execResults = {
1271
- status: "failed",
1272
- error
1273
- };
1274
- }
1275
- const endedAt = Date.now();
1276
- const stepInfo = {
1277
- payload: prevOutput,
1278
- startedAt,
1279
- endedAt
1280
- };
1281
- execResults = { ...execResults, ...stepInfo };
1282
- }
1283
- if (entry.type === "step" || entry.type === "waitForEvent" || entry.type === "loop" || entry.type === "foreach") {
1284
- stepResults[entry.step.id] = execResults;
1285
- }
1286
- if (abortController?.signal?.aborted) {
1287
- execResults = { ...execResults, status: "canceled" };
1288
- }
1289
- await this.persistStepUpdate({
1290
- workflowId,
1291
- runId,
1292
- serializedStepGraph,
1293
- stepResults,
1294
- executionContext,
1295
- workflowStatus: execResults.status
1296
- });
1297
- return { result: execResults, stepResults, executionContext };
1298
- }
1299
- };
1300
- function mapVariable(config) {
1301
- return config;
1302
- }
1303
- function createStep(params) {
1304
- if (params instanceof chunkFBKJ3652_cjs.Agent) {
1305
- return {
1306
- id: params.name,
1307
- // @ts-ignore
1308
- inputSchema: zod.z.object({
1309
- prompt: zod.z.string()
1310
- // resourceId: z.string().optional(),
1311
- // threadId: z.string().optional(),
1312
- }),
1313
- // @ts-ignore
1314
- outputSchema: zod.z.object({
1315
- text: zod.z.string()
1316
- }),
1317
- execute: async ({ inputData, [chunkBB6DPGIV_cjs.EMITTER_SYMBOL]: emitter, runtimeContext, abortSignal, abort }) => {
1318
- let streamPromise = {};
1319
- streamPromise.promise = new Promise((resolve, reject) => {
1320
- streamPromise.resolve = resolve;
1321
- streamPromise.reject = reject;
1322
- });
1323
- const toolData = {
1324
- name: params.name,
1325
- args: inputData
1326
- };
1327
- await emitter.emit("watch-v2", {
1328
- type: "tool-call-streaming-start",
1329
- ...toolData
1330
- });
1331
- const { fullStream } = await params.stream(inputData.prompt, {
1332
- // resourceId: inputData.resourceId,
1333
- // threadId: inputData.threadId,
1334
- runtimeContext,
1335
- onFinish: (result) => {
1336
- streamPromise.resolve(result.text);
1337
- },
1338
- abortSignal
1339
- });
1340
- if (abortSignal.aborted) {
1341
- return abort();
1342
- }
1343
- for await (const chunk of fullStream) {
1344
- switch (chunk.type) {
1345
- case "text-delta":
1346
- await emitter.emit("watch-v2", {
1347
- type: "tool-call-delta",
1348
- ...toolData,
1349
- argsTextDelta: chunk.textDelta
1350
- });
1351
- break;
1352
- case "step-start":
1353
- case "step-finish":
1354
- case "finish":
1355
- break;
1356
- case "tool-call":
1357
- case "tool-result":
1358
- case "tool-call-streaming-start":
1359
- case "tool-call-delta":
1360
- case "source":
1361
- case "file":
1362
- default:
1363
- await emitter.emit("watch-v2", chunk);
1364
- break;
1365
- }
1366
- }
1367
- return {
1368
- text: await streamPromise.promise
1369
- };
1370
- }
1371
- };
1372
- }
1373
- if (params instanceof chunk4Z3OU5RY_cjs.Tool) {
1374
- if (!params.inputSchema || !params.outputSchema) {
1375
- throw new Error("Tool must have input and output schemas defined");
1376
- }
1377
- return {
1378
- // TODO: tool probably should have strong id type
1379
- // @ts-ignore
1380
- id: params.id,
1381
- inputSchema: params.inputSchema,
1382
- outputSchema: params.outputSchema,
1383
- execute: async ({ inputData, mastra, runtimeContext }) => {
1384
- return params.execute({
1385
- context: inputData,
1386
- mastra,
1387
- runtimeContext
1388
- });
1389
- }
1390
- };
1391
- }
1392
- return {
1393
- id: params.id,
1394
- description: params.description,
1395
- inputSchema: params.inputSchema,
1396
- outputSchema: params.outputSchema,
1397
- resumeSchema: params.resumeSchema,
1398
- suspendSchema: params.suspendSchema,
1399
- retries: params.retries,
1400
- execute: params.execute
1401
- };
1402
- }
1403
- function cloneStep(step, opts) {
1404
- return {
1405
- id: opts.id,
1406
- description: step.description,
1407
- inputSchema: step.inputSchema,
1408
- outputSchema: step.outputSchema,
1409
- execute: step.execute,
1410
- retries: step.retries
1411
- };
1412
- }
1413
- function createWorkflow(params) {
1414
- return new Workflow(params);
1415
- }
1416
- function cloneWorkflow(workflow, opts) {
1417
- const wf = new Workflow({
1418
- id: opts.id,
1419
- inputSchema: workflow.inputSchema,
1420
- outputSchema: workflow.outputSchema,
1421
- steps: workflow.stepDefs,
1422
- mastra: workflow.mastra
1423
- });
1424
- wf.setStepFlow(workflow.stepGraph);
1425
- wf.commit();
1426
- return wf;
1427
- }
1428
- var Workflow = class extends chunkP3Q73CAW_cjs.MastraBase {
1429
- id;
1430
- description;
1431
- inputSchema;
1432
- outputSchema;
1433
- steps;
1434
- stepDefs;
1435
- stepFlow;
1436
- serializedStepFlow;
1437
- executionEngine;
1438
- executionGraph;
1439
- retryConfig;
1440
- #mastra;
1441
- #runs = /* @__PURE__ */ new Map();
1442
- constructor({
1443
- mastra,
1444
- id,
1445
- inputSchema,
1446
- outputSchema,
1447
- description,
1448
- executionEngine,
1449
- retryConfig,
1450
- steps
1451
- }) {
1452
- super({ name: id, component: chunkZIZ3CVHN_cjs.RegisteredLogger.WORKFLOW });
1453
- this.id = id;
1454
- this.description = description;
1455
- this.inputSchema = inputSchema;
1456
- this.outputSchema = outputSchema;
1457
- this.retryConfig = retryConfig ?? { attempts: 0, delay: 0 };
1458
- this.executionGraph = this.buildExecutionGraph();
1459
- this.stepFlow = [];
1460
- this.serializedStepFlow = [];
1461
- this.#mastra = mastra;
1462
- this.steps = {};
1463
- this.stepDefs = steps;
1464
- if (!executionEngine) {
1465
- this.executionEngine = new DefaultExecutionEngine({ mastra: this.#mastra });
1466
- } else {
1467
- this.executionEngine = executionEngine;
1468
- }
1469
- this.#runs = /* @__PURE__ */ new Map();
1470
- }
1471
- get runs() {
1472
- return this.#runs;
1473
- }
1474
- get mastra() {
1475
- return this.#mastra;
1476
- }
1477
- __registerMastra(mastra) {
1478
- this.#mastra = mastra;
1479
- this.executionEngine.__registerMastra(mastra);
1480
- }
1481
- __registerPrimitives(p) {
1482
- if (p.telemetry) {
1483
- this.__setTelemetry(p.telemetry);
1484
- }
1485
- if (p.logger) {
1486
- this.__setLogger(p.logger);
1487
- }
1488
- }
1489
- setStepFlow(stepFlow) {
1490
- this.stepFlow = stepFlow;
1491
- }
1492
- /**
1493
- * Adds a step to the workflow
1494
- * @param step The step to add to the workflow
1495
- * @returns The workflow instance for chaining
1496
- */
1497
- then(step) {
1498
- this.stepFlow.push({ type: "step", step });
1499
- this.serializedStepFlow.push({
1500
- type: "step",
1501
- step: {
1502
- id: step.id,
1503
- description: step.description,
1504
- component: step.component,
1505
- serializedStepFlow: step.serializedStepFlow
1506
- }
1507
- });
1508
- this.steps[step.id] = step;
1509
- return this;
1510
- }
1511
- /**
1512
- * Adds a sleep step to the workflow
1513
- * @param duration The duration to sleep for
1514
- * @returns The workflow instance for chaining
1515
- */
1516
- sleep(duration) {
1517
- const id = `sleep_${crypto.randomUUID()}`;
1518
- const opts = typeof duration === "function" ? { type: "sleep", id, fn: duration } : { type: "sleep", id, duration };
1519
- const serializedOpts = typeof duration === "function" ? { type: "sleep", id, fn: duration.toString() } : { type: "sleep", id, duration };
1520
- this.stepFlow.push(opts);
1521
- this.serializedStepFlow.push(serializedOpts);
1522
- this.steps[id] = createStep({
1523
- id,
1524
- inputSchema: zod.z.object({}),
1525
- outputSchema: zod.z.object({}),
1526
- execute: async () => {
1527
- return {};
1528
- }
1529
- });
1530
- return this;
1531
- }
1532
- /**
1533
- * Adds a sleep until step to the workflow
1534
- * @param date The date to sleep until
1535
- * @returns The workflow instance for chaining
1536
- */
1537
- sleepUntil(date) {
1538
- const id = `sleep_${crypto.randomUUID()}`;
1539
- const opts = typeof date === "function" ? { type: "sleepUntil", id, fn: date } : { type: "sleepUntil", id, date };
1540
- const serializedOpts = typeof date === "function" ? { type: "sleepUntil", id, fn: date.toString() } : { type: "sleepUntil", id, date };
1541
- this.stepFlow.push(opts);
1542
- this.serializedStepFlow.push(serializedOpts);
1543
- this.steps[id] = createStep({
1544
- id,
1545
- inputSchema: zod.z.object({}),
1546
- outputSchema: zod.z.object({}),
1547
- execute: async () => {
1548
- return {};
1549
- }
1550
- });
1551
- return this;
1552
- }
1553
- waitForEvent(event, step, opts) {
1554
- this.stepFlow.push({ type: "waitForEvent", event, step, timeout: opts?.timeout });
1555
- this.serializedStepFlow.push({
1556
- type: "waitForEvent",
1557
- event,
1558
- step: {
1559
- id: step.id,
1560
- description: step.description,
1561
- component: step.component,
1562
- serializedStepFlow: step.serializedStepFlow
1563
- },
1564
- timeout: opts?.timeout
1565
- });
1566
- this.steps[step.id] = step;
1567
- return this;
1568
- }
1569
- map(mappingConfig) {
1570
- if (typeof mappingConfig === "function") {
1571
- const mappingStep2 = createStep({
1572
- id: `mapping_${crypto.randomUUID()}`,
1573
- inputSchema: zod.z.object({}),
1574
- outputSchema: zod.z.object({}),
1575
- execute: mappingConfig
1576
- });
1577
- this.stepFlow.push({ type: "step", step: mappingStep2 });
1578
- this.serializedStepFlow.push({
1579
- type: "step",
1580
- step: {
1581
- id: mappingStep2.id,
1582
- mapConfig: mappingConfig.toString()
1583
- }
1584
- });
1585
- return this;
1586
- }
1587
- const newMappingConfig = Object.entries(mappingConfig).reduce(
1588
- (a, [key, mapping]) => {
1589
- const m = mapping;
1590
- if (m.value !== void 0) {
1591
- a[key] = m;
1592
- } else if (m.fn !== void 0) {
1593
- a[key] = {
1594
- fn: m.fn.toString(),
1595
- schema: m.schema
1596
- };
1597
- } else if (m.runtimeContextPath) {
1598
- a[key] = {
1599
- runtimeContextPath: m.runtimeContextPath,
1600
- schema: m.schema
1601
- };
1602
- } else {
1603
- a[key] = m;
1604
- }
1605
- return a;
1606
- },
1607
- {}
1608
- );
1609
- const mappingStep = createStep({
1610
- id: `mapping_${crypto.randomUUID()}`,
1611
- inputSchema: zod.z.object({}),
1612
- outputSchema: zod.z.object({}),
1613
- execute: async (ctx) => {
1614
- const { getStepResult, getInitData, runtimeContext } = ctx;
1615
- const result = {};
1616
- for (const [key, mapping] of Object.entries(mappingConfig)) {
1617
- const m = mapping;
1618
- if (m.value !== void 0) {
1619
- result[key] = m.value;
1620
- continue;
1621
- }
1622
- if (m.fn !== void 0) {
1623
- result[key] = await m.fn(ctx);
1624
- continue;
1625
- }
1626
- if (m.runtimeContextPath) {
1627
- result[key] = runtimeContext.get(m.runtimeContextPath);
1628
- continue;
1629
- }
1630
- const stepResult = m.initData ? getInitData() : getStepResult(Array.isArray(m.step) ? m.step.find((s) => getStepResult(s)) : m.step);
1631
- if (m.path === ".") {
1632
- result[key] = stepResult;
1633
- continue;
1634
- }
1635
- const pathParts = m.path.split(".");
1636
- let value = stepResult;
1637
- for (const part of pathParts) {
1638
- if (typeof value === "object" && value !== null) {
1639
- value = value[part];
1640
- } else {
1641
- throw new Error(`Invalid path ${m.path} in step ${m.step.id}`);
1642
- }
1643
- }
1644
- result[key] = value;
1645
- }
1646
- return result;
1647
- }
1648
- });
1649
- this.stepFlow.push({ type: "step", step: mappingStep });
1650
- this.serializedStepFlow.push({
1651
- type: "step",
1652
- step: {
1653
- id: mappingStep.id,
1654
- mapConfig: JSON.stringify(newMappingConfig, null, 2)
1655
- }
1656
- });
1657
- return this;
1658
- }
1659
- // TODO: make typing better here
1660
- parallel(steps) {
1661
- this.stepFlow.push({ type: "parallel", steps: steps.map((step) => ({ type: "step", step })) });
1662
- this.serializedStepFlow.push({
1663
- type: "parallel",
1664
- steps: steps.map((step) => ({
1665
- type: "step",
1666
- step: {
1667
- id: step.id,
1668
- description: step.description,
1669
- component: step.component,
1670
- serializedStepFlow: step.serializedStepFlow
1671
- }
1672
- }))
1673
- });
1674
- steps.forEach((step) => {
1675
- this.steps[step.id] = step;
1676
- });
1677
- return this;
1678
- }
1679
- // TODO: make typing better here
1680
- branch(steps) {
1681
- this.stepFlow.push({
1682
- type: "conditional",
1683
- steps: steps.map(([_cond, step]) => ({ type: "step", step })),
1684
- // @ts-ignore
1685
- conditions: steps.map(([cond]) => cond),
1686
- serializedConditions: steps.map(([cond, _step]) => ({ id: `${_step.id}-condition`, fn: cond.toString() }))
1687
- });
1688
- this.serializedStepFlow.push({
1689
- type: "conditional",
1690
- steps: steps.map(([_cond, step]) => ({
1691
- type: "step",
1692
- step: {
1693
- id: step.id,
1694
- description: step.description,
1695
- component: step.component,
1696
- serializedStepFlow: step.serializedStepFlow
1697
- }
1698
- })),
1699
- serializedConditions: steps.map(([cond, _step]) => ({ id: `${_step.id}-condition`, fn: cond.toString() }))
1700
- });
1701
- steps.forEach(([_, step]) => {
1702
- this.steps[step.id] = step;
1703
- });
1704
- return this;
1705
- }
1706
- dowhile(step, condition) {
1707
- this.stepFlow.push({
1708
- type: "loop",
1709
- step,
1710
- // @ts-ignore
1711
- condition,
1712
- loopType: "dowhile",
1713
- serializedCondition: { id: `${step.id}-condition`, fn: condition.toString() }
1714
- });
1715
- this.serializedStepFlow.push({
1716
- type: "loop",
1717
- step: {
1718
- id: step.id,
1719
- description: step.description,
1720
- component: step.component,
1721
- serializedStepFlow: step.serializedStepFlow
1722
- },
1723
- serializedCondition: { id: `${step.id}-condition`, fn: condition.toString() },
1724
- loopType: "dowhile"
1725
- });
1726
- this.steps[step.id] = step;
1727
- return this;
1728
- }
1729
- dountil(step, condition) {
1730
- this.stepFlow.push({
1731
- type: "loop",
1732
- step,
1733
- // @ts-ignore
1734
- condition,
1735
- loopType: "dountil",
1736
- serializedCondition: { id: `${step.id}-condition`, fn: condition.toString() }
1737
- });
1738
- this.serializedStepFlow.push({
1739
- type: "loop",
1740
- step: {
1741
- id: step.id,
1742
- description: step.description,
1743
- component: step.component,
1744
- serializedStepFlow: step.serializedStepFlow
1745
- },
1746
- serializedCondition: { id: `${step.id}-condition`, fn: condition.toString() },
1747
- loopType: "dountil"
1748
- });
1749
- this.steps[step.id] = step;
1750
- return this;
1751
- }
1752
- foreach(step, opts) {
1753
- this.stepFlow.push({ type: "foreach", step, opts: opts ?? { concurrency: 1 } });
1754
- this.serializedStepFlow.push({
1755
- type: "foreach",
1756
- step: {
1757
- id: step.id,
1758
- description: step.description,
1759
- component: step.component,
1760
- serializedStepFlow: step.serializedStepFlow
1761
- },
1762
- opts: opts ?? { concurrency: 1 }
1763
- });
1764
- this.steps[step.id] = step;
1765
- return this;
1766
- }
1767
- /**
1768
- * Builds the execution graph for this workflow
1769
- * @returns The execution graph that can be used to execute the workflow
1770
- */
1771
- buildExecutionGraph() {
1772
- return {
1773
- id: this.id,
1774
- steps: this.stepFlow
1775
- };
1776
- }
1777
- /**
1778
- * Finalizes the workflow definition and prepares it for execution
1779
- * This method should be called after all steps have been added to the workflow
1780
- * @returns A built workflow instance ready for execution
1781
- */
1782
- commit() {
1783
- this.executionGraph = this.buildExecutionGraph();
1784
- return this;
1785
- }
1786
- get stepGraph() {
1787
- return this.stepFlow;
1788
- }
1789
- get serializedStepGraph() {
1790
- return this.serializedStepFlow;
1791
- }
1792
- /**
1793
- * Creates a new workflow run instance
1794
- * @param options Optional configuration for the run
1795
- * @returns A Run instance that can be used to execute the workflow
1796
- */
1797
- createRun(options) {
1798
- if (this.stepFlow.length === 0) {
1799
- throw new Error(
1800
- "Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc."
1801
- );
1802
- }
1803
- if (!this.executionGraph.steps) {
1804
- throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");
1805
- }
1806
- const runIdToUse = options?.runId || crypto.randomUUID();
1807
- const run = this.#runs.get(runIdToUse) ?? new Run({
1808
- workflowId: this.id,
1809
- runId: runIdToUse,
1810
- executionEngine: this.executionEngine,
1811
- executionGraph: this.executionGraph,
1812
- mastra: this.#mastra,
1813
- retryConfig: this.retryConfig,
1814
- serializedStepGraph: this.serializedStepGraph,
1815
- cleanup: () => this.#runs.delete(runIdToUse)
1816
- });
1817
- this.#runs.set(runIdToUse, run);
1818
- this.mastra?.getLogger().warn("createRun() is deprecated. Use createRunAsync() instead.");
1819
- return run;
1820
- }
1821
- /**
1822
- * Creates a new workflow run instance and stores a snapshot of the workflow in the storage
1823
- * @param options Optional configuration for the run
1824
- * @returns A Run instance that can be used to execute the workflow
1825
- */
1826
- async createRunAsync(options) {
1827
- if (this.stepFlow.length === 0) {
1828
- throw new Error(
1829
- "Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc."
1830
- );
1831
- }
1832
- if (!this.executionGraph.steps) {
1833
- throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");
1834
- }
1835
- const runIdToUse = options?.runId || crypto.randomUUID();
1836
- const run = this.#runs.get(runIdToUse) ?? new Run({
1837
- workflowId: this.id,
1838
- runId: runIdToUse,
1839
- executionEngine: this.executionEngine,
1840
- executionGraph: this.executionGraph,
1841
- mastra: this.#mastra,
1842
- retryConfig: this.retryConfig,
1843
- serializedStepGraph: this.serializedStepGraph,
1844
- cleanup: () => this.#runs.delete(runIdToUse)
1845
- });
1846
- this.#runs.set(runIdToUse, run);
1847
- const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse);
1848
- if (!workflowSnapshotInStorage) {
1849
- await this.mastra?.getStorage()?.persistWorkflowSnapshot({
1850
- workflowName: this.id,
1851
- runId: runIdToUse,
1852
- snapshot: {
1853
- runId: runIdToUse,
1854
- status: "pending",
1855
- value: {},
1856
- context: {},
1857
- activePaths: [],
1858
- serializedStepGraph: this.serializedStepGraph,
1859
- suspendedPaths: {},
1860
- result: void 0,
1861
- error: void 0,
1862
- // @ts-ignore
1863
- timestamp: Date.now()
1864
- }
1865
- });
1866
- }
1867
- return run;
1868
- }
1869
- async execute({
1870
- inputData,
1871
- resumeData,
1872
- suspend,
1873
- resume,
1874
- [chunkBB6DPGIV_cjs.EMITTER_SYMBOL]: emitter,
1875
- mastra,
1876
- runtimeContext,
1877
- abort,
1878
- abortSignal
1879
- }) {
1880
- this.__registerMastra(mastra);
1881
- const run = resume?.steps?.length ? await this.createRunAsync({ runId: resume.runId }) : await this.createRunAsync();
1882
- const nestedAbortCb = () => {
1883
- abort();
1884
- };
1885
- run.abortController?.signal.addEventListener("abort", nestedAbortCb);
1886
- abortSignal.addEventListener("abort", async () => {
1887
- run.abortController.signal.removeEventListener("abort", nestedAbortCb);
1888
- await run.cancel();
1889
- });
1890
- const unwatchV2 = run.watch((event) => {
1891
- emitter.emit("nested-watch-v2", { event, workflowId: this.id });
1892
- }, "watch-v2");
1893
- const unwatch = run.watch((event) => {
1894
- emitter.emit("nested-watch", { event, workflowId: this.id, runId: run.runId, isResume: !!resume?.steps?.length });
1895
- }, "watch");
1896
- const res = resume?.steps?.length ? await run.resume({ resumeData, step: resume.steps, runtimeContext }) : await run.start({ inputData, runtimeContext });
1897
- unwatch();
1898
- unwatchV2();
1899
- const suspendedSteps = Object.entries(res.steps).filter(([_stepName, stepResult]) => {
1900
- const stepRes = stepResult;
1901
- return stepRes?.status === "suspended";
1902
- });
1903
- if (suspendedSteps?.length) {
1904
- for (const [stepName, stepResult] of suspendedSteps) {
1905
- const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
1906
- await suspend({
1907
- ...stepResult?.suspendPayload,
1908
- __workflow_meta: { runId: run.runId, path: suspendPath }
1909
- });
1910
- }
1911
- }
1912
- if (res.status === "failed") {
1913
- throw res.error;
1914
- }
1915
- return res.status === "success" ? res.result : void 0;
1916
- }
1917
- async getWorkflowRuns(args) {
1918
- const storage = this.#mastra?.getStorage();
1919
- if (!storage) {
1920
- this.logger.debug("Cannot get workflow runs. Mastra storage is not initialized");
1921
- return { runs: [], total: 0 };
1922
- }
1923
- return storage.getWorkflowRuns({ workflowName: this.id, ...args ?? {} });
1924
- }
1925
- async getWorkflowRunById(runId) {
1926
- const storage = this.#mastra?.getStorage();
1927
- if (!storage) {
1928
- this.logger.debug("Cannot get workflow runs from storage. Mastra storage is not initialized");
1929
- return this.#runs.get(runId) ? { ...this.#runs.get(runId), workflowName: this.id } : null;
1930
- }
1931
- const run = await storage.getWorkflowRunById({ runId, workflowName: this.id });
1932
- return run ?? (this.#runs.get(runId) ? { ...this.#runs.get(runId), workflowName: this.id } : null);
1933
- }
1934
- async getWorkflowRunExecutionResult(runId) {
1935
- const storage = this.#mastra?.getStorage();
1936
- if (!storage) {
1937
- this.logger.debug("Cannot get workflow run execution result. Mastra storage is not initialized");
1938
- return null;
1939
- }
1940
- const run = await storage.getWorkflowRunById({ runId, workflowName: this.id });
1941
- let snapshot = run?.snapshot;
1942
- if (!snapshot) {
1943
- return null;
1944
- }
1945
- if (typeof snapshot === "string") {
1946
- try {
1947
- snapshot = JSON.parse(snapshot);
1948
- } catch (e) {
1949
- this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string", e);
1950
- return null;
1951
- }
1952
- }
1953
- return {
1954
- status: snapshot.status,
1955
- result: snapshot.result,
1956
- error: snapshot.error,
1957
- payload: snapshot.context?.input,
1958
- steps: snapshot.context
1959
- };
1960
- }
1961
- };
1962
- var Run = class {
1963
- abortController;
1964
- emitter;
1965
- /**
1966
- * Unique identifier for this workflow
1967
- */
1968
- workflowId;
1969
- /**
1970
- * Unique identifier for this run
1971
- */
1972
- runId;
1973
- /**
1974
- * Internal state of the workflow run
1975
- */
1976
- state = {};
1977
- /**
1978
- * The execution engine for this run
1979
- */
1980
- executionEngine;
1981
- /**
1982
- * The execution graph for this run
1983
- */
1984
- executionGraph;
1985
- /**
1986
- * The serialized step graph for this run
1987
- */
1988
- serializedStepGraph;
1989
- /**
1990
- * The storage for this run
1991
- */
1992
- #mastra;
1993
- closeStreamAction;
1994
- executionResults;
1995
- cleanup;
1996
- retryConfig;
1997
- constructor(params) {
1998
- this.workflowId = params.workflowId;
1999
- this.runId = params.runId;
2000
- this.serializedStepGraph = params.serializedStepGraph;
2001
- this.executionEngine = params.executionEngine;
2002
- this.executionGraph = params.executionGraph;
2003
- this.#mastra = params.mastra;
2004
- this.emitter = new EventEmitter__default.default();
2005
- this.retryConfig = params.retryConfig;
2006
- this.cleanup = params.cleanup;
2007
- this.abortController = new AbortController();
2008
- }
2009
- /**
2010
- * Cancels the workflow execution
2011
- */
2012
- async cancel() {
2013
- this.abortController?.abort();
2014
- }
2015
- async sendEvent(event, data) {
2016
- this.emitter.emit(`user-event-${event}`, data);
2017
- }
2018
- /**
2019
- * Starts the workflow execution with the provided input
2020
- * @param input The input data for the workflow
2021
- * @returns A promise that resolves to the workflow output
2022
- */
2023
- async start({
2024
- inputData,
2025
- runtimeContext
2026
- }) {
2027
- const result = await this.executionEngine.execute({
2028
- workflowId: this.workflowId,
2029
- runId: this.runId,
2030
- graph: this.executionGraph,
2031
- serializedStepGraph: this.serializedStepGraph,
2032
- input: inputData,
2033
- emitter: {
2034
- emit: async (event, data) => {
2035
- this.emitter.emit(event, data);
2036
- },
2037
- on: (event, callback) => {
2038
- this.emitter.on(event, callback);
2039
- },
2040
- off: (event, callback) => {
2041
- this.emitter.off(event, callback);
2042
- },
2043
- once: (event, callback) => {
2044
- this.emitter.once(event, callback);
2045
- }
2046
- },
2047
- retryConfig: this.retryConfig,
2048
- runtimeContext: runtimeContext ?? new chunkLABUWBKX_cjs.RuntimeContext(),
2049
- abortController: this.abortController
2050
- });
2051
- if (result.status !== "suspended") {
2052
- this.cleanup?.();
2053
- }
2054
- return result;
2055
- }
2056
- /**
2057
- * Starts the workflow execution with the provided input as a stream
2058
- * @param input The input data for the workflow
2059
- * @returns A promise that resolves to the workflow output
2060
- */
2061
- stream({ inputData, runtimeContext } = {}) {
2062
- const { readable, writable } = new web.TransformStream();
2063
- const writer = writable.getWriter();
2064
- const unwatch = this.watch(async (event) => {
2065
- try {
2066
- await writer.write(event);
2067
- } catch {
2068
- }
2069
- }, "watch-v2");
2070
- this.closeStreamAction = async () => {
2071
- this.emitter.emit("watch-v2", {
2072
- type: "finish",
2073
- payload: { runId: this.runId }
2074
- });
2075
- unwatch();
2076
- try {
2077
- await writer.close();
2078
- } catch (err) {
2079
- console.error("Error closing stream:", err);
2080
- } finally {
2081
- writer.releaseLock();
2082
- }
2083
- };
2084
- this.emitter.emit("watch-v2", {
2085
- type: "start",
2086
- payload: { runId: this.runId }
2087
- });
2088
- this.executionResults = this.start({ inputData, runtimeContext }).then((result) => {
2089
- if (result.status !== "suspended") {
2090
- this.closeStreamAction?.().catch(() => {
2091
- });
2092
- }
2093
- return result;
2094
- });
2095
- return {
2096
- stream: readable,
2097
- getWorkflowState: () => this.executionResults
2098
- };
2099
- }
2100
- watch(cb, type = "watch") {
2101
- const watchCb = (event) => {
2102
- this.updateState(event.payload);
2103
- cb({ type: event.type, payload: this.getState(), eventTimestamp: event.eventTimestamp });
2104
- };
2105
- const nestedWatchCb = ({ event, workflowId }) => {
2106
- try {
2107
- const { type: type2, payload, eventTimestamp } = event;
2108
- const prefixedSteps = Object.fromEntries(
2109
- Object.entries(payload?.workflowState?.steps ?? {}).map(([stepId, step]) => [
2110
- `${workflowId}.${stepId}`,
2111
- step
2112
- ])
2113
- );
2114
- const newPayload = {
2115
- currentStep: {
2116
- ...payload?.currentStep,
2117
- id: `${workflowId}.${payload?.currentStep?.id}`
2118
- },
2119
- workflowState: {
2120
- steps: prefixedSteps
2121
- }
2122
- };
2123
- this.updateState(newPayload);
2124
- cb({ type: type2, payload: this.getState(), eventTimestamp });
2125
- } catch (e) {
2126
- console.error(e);
2127
- }
2128
- };
2129
- const nestedWatchV2Cb = ({
2130
- event,
2131
- workflowId
2132
- }) => {
2133
- this.emitter.emit("watch-v2", {
2134
- ...event,
2135
- ...event.payload?.id ? { payload: { ...event.payload, id: `${workflowId}.${event.payload.id}` } } : {}
2136
- });
2137
- };
2138
- if (type === "watch") {
2139
- this.emitter.on("watch", watchCb);
2140
- this.emitter.on("nested-watch", nestedWatchCb);
2141
- } else if (type === "watch-v2") {
2142
- this.emitter.on("watch-v2", cb);
2143
- this.emitter.on("nested-watch-v2", nestedWatchV2Cb);
2144
- }
2145
- return () => {
2146
- if (type === "watch-v2") {
2147
- this.emitter.off("watch-v2", cb);
2148
- this.emitter.off("nested-watch-v2", nestedWatchV2Cb);
2149
- } else {
2150
- this.emitter.off("watch", watchCb);
2151
- this.emitter.off("nested-watch", nestedWatchCb);
2152
- }
2153
- };
2154
- }
2155
- async resume(params) {
2156
- const steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
2157
- (step) => typeof step === "string" ? step : step?.id
2158
- );
2159
- const snapshot = await this.#mastra?.getStorage()?.loadWorkflowSnapshot({
2160
- workflowName: this.workflowId,
2161
- runId: this.runId
2162
- });
2163
- if (!snapshot) {
2164
- throw new Error("No snapshot found for this workflow run");
2165
- }
2166
- if (snapshot.status !== "suspended") {
2167
- throw new Error("This workflow run was not suspended");
2168
- }
2169
- const suspendedStepIds = Object.keys(snapshot?.suspendedPaths ?? {});
2170
- const isStepSuspended = suspendedStepIds.includes(steps?.[0] ?? "");
2171
- if (!isStepSuspended) {
2172
- throw new Error("This workflow step was not suspended");
2173
- }
2174
- const executionResultPromise = this.executionEngine.execute({
2175
- workflowId: this.workflowId,
2176
- runId: this.runId,
2177
- graph: this.executionGraph,
2178
- serializedStepGraph: this.serializedStepGraph,
2179
- input: params.resumeData,
2180
- resume: {
2181
- steps,
2182
- stepResults: snapshot?.context,
2183
- resumePayload: params.resumeData,
2184
- // @ts-ignore
2185
- resumePath: snapshot?.suspendedPaths?.[steps?.[0]]
2186
- },
2187
- emitter: {
2188
- emit: (event, data) => {
2189
- this.emitter.emit(event, data);
2190
- return Promise.resolve();
2191
- },
2192
- on: (event, callback) => {
2193
- this.emitter.on(event, callback);
2194
- },
2195
- off: (event, callback) => {
2196
- this.emitter.off(event, callback);
2197
- },
2198
- once: (event, callback) => {
2199
- this.emitter.once(event, callback);
2200
- }
2201
- },
2202
- runtimeContext: params.runtimeContext ?? new chunkLABUWBKX_cjs.RuntimeContext(),
2203
- abortController: this.abortController
2204
- }).then((result) => {
2205
- if (result.status !== "suspended") {
2206
- this.closeStreamAction?.().catch(() => {
2207
- });
2208
- }
2209
- return result;
2210
- });
2211
- this.executionResults = executionResultPromise;
2212
- return executionResultPromise;
2213
- }
2214
- /**
2215
- * Returns the current state of the workflow run
2216
- * @returns The current state of the workflow run
2217
- */
2218
- getState() {
2219
- return this.state;
2220
- }
2221
- updateState(state) {
2222
- if (state.currentStep) {
2223
- this.state.currentStep = state.currentStep;
2224
- } else if (state.workflowState?.status !== "running") {
2225
- delete this.state.currentStep;
2226
- }
2227
- if (state.workflowState) {
2228
- this.state.workflowState = deepMergeWorkflowState(this.state.workflowState ?? {}, state.workflowState ?? {});
2229
- }
2230
- }
2231
- };
2232
- function deepMergeWorkflowState(a, b) {
2233
- if (!a || typeof a !== "object") return b;
2234
- if (!b || typeof b !== "object") return a;
2235
- const result = { ...a };
2236
- for (const key in b) {
2237
- if (b[key] === void 0) continue;
2238
- if (b[key] !== null && typeof b[key] === "object") {
2239
- const aVal = result[key];
2240
- const bVal = b[key];
2241
- if (Array.isArray(bVal)) {
2242
- result[key] = bVal.filter((item) => item !== void 0);
2243
- } else if (typeof aVal === "object" && aVal !== null) {
2244
- result[key] = deepMergeWorkflowState(aVal, bVal);
2245
- } else {
2246
- result[key] = bVal;
2247
- }
2248
- } else {
2249
- result[key] = b[key];
2250
- }
2251
- }
2252
- return result;
2253
- }
2254
-
2255
- exports.DefaultExecutionEngine = DefaultExecutionEngine;
2256
- exports.ExecutionEngine = ExecutionEngine;
2257
- exports.Run = Run;
2258
- exports.Workflow = Workflow;
2259
- exports.cloneStep = cloneStep;
2260
- exports.cloneWorkflow = cloneWorkflow;
2261
- exports.createStep = createStep;
2262
- exports.createWorkflow = createWorkflow;
2263
- exports.mapVariable = mapVariable;