@mastra/core 0.9.0 → 0.9.1-alpha.1

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 (94) hide show
  1. package/dist/agent/index.cjs +2 -2
  2. package/dist/agent/index.d.cts +4 -2
  3. package/dist/agent/index.d.ts +4 -2
  4. package/dist/agent/index.js +1 -1
  5. package/dist/{base-oP3DoUrm.d.cts → base-CZmT-p10.d.cts} +524 -53
  6. package/dist/{base-Bk5V1doj.d.ts → base-DDoWFpFc.d.ts} +524 -53
  7. package/dist/{chunk-NTHHPNOW.js → chunk-34622N67.js} +1 -1
  8. package/dist/{chunk-ATXF6TIO.cjs → chunk-422BXQRT.cjs} +24 -677
  9. package/dist/{chunk-HARYMLZH.js → chunk-4K4DHXRF.js} +6 -658
  10. package/dist/{chunk-N2ONCUUS.js → chunk-6AHC67YY.js} +132 -12
  11. package/dist/chunk-7AGAXO6B.cjs +588 -0
  12. package/dist/{chunk-GEIPVIW4.js → chunk-BFF2O6RO.js} +1 -1
  13. package/dist/{chunk-RASVJ3TR.js → chunk-BU45BMXY.js} +55 -1
  14. package/dist/{chunk-DIZZQ3E5.cjs → chunk-CEXM6WP5.cjs} +2 -2
  15. package/dist/chunk-HNEE7IF4.js +60 -0
  16. package/dist/{chunk-NZDXKMDP.cjs → chunk-LABUWBKX.cjs} +1 -1
  17. package/dist/chunk-MUNFCOMB.cjs +62 -0
  18. package/dist/{chunk-GJWCFDFN.js → chunk-PS2ZF6MA.js} +1 -1
  19. package/dist/{chunk-M472GIT6.js → chunk-SGGPJWRQ.js} +1 -1
  20. package/dist/{chunk-7CSNWYGJ.cjs → chunk-U5DGGGS2.cjs} +2 -2
  21. package/dist/{chunk-W5IA5OGL.cjs → chunk-V7IE36YV.cjs} +58 -4
  22. package/dist/chunk-VMVXIPGW.js +586 -0
  23. package/dist/{chunk-53P5ZBJE.cjs → chunk-YTTBFAQJ.cjs} +2 -2
  24. package/dist/{chunk-KZWBYRXW.cjs → chunk-YZFNMXY4.cjs} +135 -14
  25. package/dist/di/index.cjs +2 -2
  26. package/dist/di/index.d.cts +1 -52
  27. package/dist/di/index.d.ts +1 -52
  28. package/dist/di/index.js +1 -1
  29. package/dist/eval/index.d.cts +4 -2
  30. package/dist/eval/index.d.ts +4 -2
  31. package/dist/index.cjs +60 -55
  32. package/dist/index.d.cts +5 -3
  33. package/dist/index.d.ts +5 -3
  34. package/dist/index.js +10 -9
  35. package/dist/integration/index.cjs +3 -3
  36. package/dist/integration/index.d.cts +4 -2
  37. package/dist/integration/index.d.ts +4 -2
  38. package/dist/integration/index.js +1 -1
  39. package/dist/llm/index.cjs +8 -0
  40. package/dist/llm/index.d.cts +4 -2
  41. package/dist/llm/index.d.ts +4 -2
  42. package/dist/llm/index.js +1 -1
  43. package/dist/mastra/index.cjs +2 -2
  44. package/dist/mastra/index.d.cts +4 -2
  45. package/dist/mastra/index.d.ts +4 -2
  46. package/dist/mastra/index.js +1 -1
  47. package/dist/memory/index.cjs +7 -3
  48. package/dist/memory/index.d.cts +4 -2
  49. package/dist/memory/index.d.ts +4 -2
  50. package/dist/memory/index.js +1 -1
  51. package/dist/network/index.cjs +4 -4
  52. package/dist/network/index.d.cts +4 -2
  53. package/dist/network/index.d.ts +4 -2
  54. package/dist/network/index.js +2 -2
  55. package/dist/relevance/index.cjs +4 -4
  56. package/dist/relevance/index.d.cts +4 -2
  57. package/dist/relevance/index.d.ts +4 -2
  58. package/dist/relevance/index.js +1 -1
  59. package/dist/runtime-context/index.cjs +7 -68
  60. package/dist/runtime-context/index.js +1 -69
  61. package/dist/server/index.d.cts +4 -2
  62. package/dist/server/index.d.ts +4 -2
  63. package/dist/storage/index.d.cts +4 -2
  64. package/dist/storage/index.d.ts +4 -2
  65. package/dist/storage/libsql/index.cjs +19 -0
  66. package/dist/storage/libsql/index.d.cts +7 -8
  67. package/dist/storage/libsql/index.d.ts +7 -8
  68. package/dist/storage/libsql/index.js +19 -0
  69. package/dist/telemetry/index.d.cts +4 -2
  70. package/dist/telemetry/index.d.ts +4 -2
  71. package/dist/tools/index.cjs +4 -4
  72. package/dist/tools/index.d.cts +4 -2
  73. package/dist/tools/index.d.ts +4 -2
  74. package/dist/tools/index.js +1 -1
  75. package/dist/utils.cjs +14 -14
  76. package/dist/utils.d.cts +6 -4
  77. package/dist/utils.d.ts +6 -4
  78. package/dist/utils.js +1 -1
  79. package/dist/voice/index.d.cts +5 -3
  80. package/dist/voice/index.d.ts +5 -3
  81. package/dist/workflows/index.cjs +22 -26
  82. package/dist/workflows/index.d.cts +5 -3
  83. package/dist/workflows/index.d.ts +5 -3
  84. package/dist/workflows/index.js +1 -1
  85. package/dist/workflows/vNext/index.cjs +1058 -0
  86. package/dist/workflows/vNext/index.d.cts +180 -0
  87. package/dist/workflows/vNext/index.d.ts +180 -0
  88. package/dist/workflows/vNext/index.js +1046 -0
  89. package/package.json +11 -1
  90. package/workflows/vNext.d.ts +1 -0
  91. /package/dist/{chunk-WEYWYKLG.cjs → chunk-27PAET7X.cjs} +0 -0
  92. /package/dist/{chunk-FRQFWZDN.cjs → chunk-HSVOEWAM.cjs} +0 -0
  93. /package/dist/{chunk-ZDWFBE5L.js → chunk-NH5WJNNS.js} +0 -0
  94. /package/dist/{chunk-LANFNMEE.js → chunk-SGTFVHOZ.js} +0 -0
@@ -0,0 +1,1058 @@
1
+ 'use strict';
2
+
3
+ var chunk422BXQRT_cjs = require('../../chunk-422BXQRT.cjs');
4
+ var chunkYTTBFAQJ_cjs = require('../../chunk-YTTBFAQJ.cjs');
5
+ var chunkD63P5O4Q_cjs = require('../../chunk-D63P5O4Q.cjs');
6
+ var chunkO7IW545H_cjs = require('../../chunk-O7IW545H.cjs');
7
+ var chunkLABUWBKX_cjs = require('../../chunk-LABUWBKX.cjs');
8
+ var crypto = require('crypto');
9
+ var EventEmitter = require('events');
10
+ var zod = require('zod');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
15
+
16
+ // src/workflows/vNext/execution-engine.ts
17
+ var ExecutionEngine = class extends chunkD63P5O4Q_cjs.MastraBase {
18
+ mastra;
19
+ constructor({ mastra }) {
20
+ super({ name: "ExecutionEngine", component: chunkO7IW545H_cjs.RegisteredLogger.WORKFLOW });
21
+ this.mastra = mastra;
22
+ }
23
+ __registerMastra(mastra) {
24
+ this.mastra = mastra;
25
+ }
26
+ };
27
+
28
+ // src/workflows/vNext/default.ts
29
+ function fmtReturnValue(stepResults, lastOutput, error) {
30
+ const base = {
31
+ status: lastOutput.status,
32
+ steps: stepResults
33
+ };
34
+ if (lastOutput.status === "success") {
35
+ base.result = lastOutput.output;
36
+ } else if (lastOutput.status === "failed") {
37
+ base.error = error instanceof Error ? error : lastOutput.error ?? new Error("Unknown error: " + error);
38
+ } else if (lastOutput.status === "suspended") {
39
+ const suspendedStepIds = Object.entries(stepResults).flatMap(([stepId, stepResult]) => {
40
+ if (stepResult?.status === "suspended") {
41
+ const nestedPath = stepResult?.payload?.__workflow_meta?.path;
42
+ return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
43
+ }
44
+ return [];
45
+ });
46
+ base.suspended = suspendedStepIds;
47
+ }
48
+ return base;
49
+ }
50
+ var DefaultExecutionEngine = class extends ExecutionEngine {
51
+ /**
52
+ * Executes a workflow run with the provided execution graph and input
53
+ * @param graph The execution graph to execute
54
+ * @param input The input data for the workflow
55
+ * @returns A promise that resolves to the workflow output
56
+ */
57
+ async execute(params) {
58
+ const { workflowId, runId, graph, input, resume, retryConfig } = params;
59
+ const { attempts = 0, delay = 0 } = retryConfig ?? {};
60
+ const steps = graph.steps;
61
+ if (steps.length === 0) {
62
+ throw new Error("Workflow must have at least one step");
63
+ }
64
+ await this.mastra?.getStorage()?.init();
65
+ let startIdx = 0;
66
+ if (resume?.resumePath) {
67
+ startIdx = resume.resumePath[0];
68
+ resume.resumePath.shift();
69
+ }
70
+ const stepResults = resume?.stepResults || { input };
71
+ let lastOutput;
72
+ for (let i = startIdx; i < steps.length; i++) {
73
+ const entry = steps[i];
74
+ try {
75
+ lastOutput = await this.executeEntry({
76
+ workflowId,
77
+ runId,
78
+ entry,
79
+ prevStep: steps[i - 1],
80
+ stepResults,
81
+ resume,
82
+ executionContext: {
83
+ executionPath: [i],
84
+ suspendedPaths: {},
85
+ retryConfig: { attempts, delay }
86
+ },
87
+ emitter: params.emitter,
88
+ runtimeContext: params.runtimeContext
89
+ });
90
+ if (lastOutput.status !== "success") {
91
+ if (entry.type === "step") {
92
+ params.emitter.emit("watch", {
93
+ type: "watch",
94
+ payload: {
95
+ currentStep: {
96
+ id: entry.step.id,
97
+ ...lastOutput
98
+ },
99
+ workflowState: {
100
+ status: lastOutput.status,
101
+ steps: stepResults,
102
+ result: null,
103
+ error: lastOutput.error
104
+ }
105
+ },
106
+ eventTimestamp: Date.now()
107
+ });
108
+ }
109
+ return fmtReturnValue(stepResults, lastOutput);
110
+ }
111
+ } catch (e) {
112
+ this.logger.error("Error executing step: " + (e?.stack ?? e));
113
+ if (entry.type === "step") {
114
+ params.emitter.emit("watch", {
115
+ type: "watch",
116
+ payload: {
117
+ currentStep: {
118
+ id: entry.step.id,
119
+ ...lastOutput
120
+ },
121
+ workflowState: {
122
+ status: "running",
123
+ steps: stepResults,
124
+ result: null,
125
+ error: null
126
+ }
127
+ },
128
+ eventTimestamp: Date.now()
129
+ });
130
+ }
131
+ return fmtReturnValue(stepResults, lastOutput, e);
132
+ }
133
+ }
134
+ params.emitter.emit("watch", {
135
+ type: "watch",
136
+ payload: {
137
+ currentStep: null,
138
+ workflowState: {
139
+ status: lastOutput.status,
140
+ steps: stepResults,
141
+ result: lastOutput.output,
142
+ error: lastOutput.error
143
+ }
144
+ },
145
+ eventTimestamp: Date.now()
146
+ });
147
+ return fmtReturnValue(stepResults, lastOutput);
148
+ }
149
+ getStepOutput(stepResults, step) {
150
+ if (!step) {
151
+ return stepResults.input;
152
+ } else if (step.type === "step") {
153
+ return stepResults[step.step.id]?.output;
154
+ } else if (step.type === "parallel" || step.type === "conditional") {
155
+ return step.steps.reduce(
156
+ (acc, entry) => {
157
+ if (entry.type === "step") {
158
+ acc[entry.step.id] = stepResults[entry.step.id]?.output;
159
+ } else if (entry.type === "parallel" || entry.type === "conditional") {
160
+ const parallelResult = this.getStepOutput(stepResults, entry)?.output;
161
+ acc = { ...acc, ...parallelResult };
162
+ } else if (entry.type === "loop") {
163
+ acc[entry.step.id] = stepResults[entry.step.id]?.output;
164
+ } else if (entry.type === "foreach") {
165
+ acc[entry.step.id] = stepResults[entry.step.id]?.output;
166
+ }
167
+ return acc;
168
+ },
169
+ {}
170
+ );
171
+ } else if (step.type === "loop") {
172
+ return stepResults[step.step.id]?.output;
173
+ } else if (step.type === "foreach") {
174
+ return stepResults[step.step.id]?.output;
175
+ }
176
+ }
177
+ async executeStep({
178
+ step,
179
+ stepResults,
180
+ executionContext,
181
+ resume,
182
+ prevOutput,
183
+ emitter,
184
+ runtimeContext
185
+ }) {
186
+ let execResults;
187
+ const retries = step.retries ?? executionContext.retryConfig.attempts ?? 0;
188
+ for (let i = 0; i < retries + 1; i++) {
189
+ try {
190
+ let suspended;
191
+ const result = await step.execute({
192
+ mastra: this.mastra,
193
+ runtimeContext,
194
+ inputData: prevOutput,
195
+ resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
196
+ getInitData: () => stepResults?.input,
197
+ getStepResult: (step2) => {
198
+ const result2 = stepResults[step2.id];
199
+ if (result2?.status === "success") {
200
+ return result2.output;
201
+ }
202
+ return null;
203
+ },
204
+ suspend: async (suspendPayload) => {
205
+ executionContext.suspendedPaths[step.id] = executionContext.executionPath;
206
+ suspended = { payload: suspendPayload };
207
+ },
208
+ resume: {
209
+ steps: resume?.steps?.slice(1) || [],
210
+ resumePayload: resume?.resumePayload,
211
+ // @ts-ignore
212
+ runId: stepResults[step.id]?.payload?.__workflow_meta?.runId
213
+ },
214
+ emitter
215
+ });
216
+ if (suspended) {
217
+ execResults = { status: "suspended", payload: suspended.payload };
218
+ } else {
219
+ execResults = { status: "success", output: result };
220
+ }
221
+ break;
222
+ } catch (e) {
223
+ this.logger.error("Error executing step: " + (e?.stack ?? e));
224
+ execResults = { status: "failed", error: e instanceof Error ? e : new Error("Unknown error: " + e) };
225
+ }
226
+ }
227
+ return execResults;
228
+ }
229
+ async executeParallel({
230
+ workflowId,
231
+ runId,
232
+ entry,
233
+ prevStep,
234
+ stepResults,
235
+ resume,
236
+ executionContext,
237
+ emitter,
238
+ runtimeContext
239
+ }) {
240
+ let execResults;
241
+ const results = await Promise.all(
242
+ entry.steps.map(
243
+ (step, i) => this.executeEntry({
244
+ workflowId,
245
+ runId,
246
+ entry: step,
247
+ prevStep,
248
+ stepResults,
249
+ resume,
250
+ executionContext: {
251
+ executionPath: [...executionContext.executionPath, i],
252
+ suspendedPaths: executionContext.suspendedPaths,
253
+ retryConfig: executionContext.retryConfig
254
+ },
255
+ emitter,
256
+ runtimeContext
257
+ })
258
+ )
259
+ );
260
+ const hasFailed = results.find((result) => result.status === "failed");
261
+ const hasSuspended = results.find((result) => result.status === "suspended");
262
+ if (hasFailed) {
263
+ execResults = { status: "failed", error: hasFailed.error };
264
+ } else if (hasSuspended) {
265
+ execResults = { status: "suspended", payload: hasSuspended.payload };
266
+ } else {
267
+ execResults = {
268
+ status: "success",
269
+ output: results.reduce((acc, result, index) => {
270
+ if (result.status === "success") {
271
+ acc[entry.steps[index].step.id] = result.output;
272
+ }
273
+ return acc;
274
+ }, {})
275
+ };
276
+ }
277
+ return execResults;
278
+ }
279
+ async executeConditional({
280
+ workflowId,
281
+ runId,
282
+ entry,
283
+ prevOutput,
284
+ prevStep,
285
+ stepResults,
286
+ resume,
287
+ executionContext,
288
+ emitter,
289
+ runtimeContext
290
+ }) {
291
+ let execResults;
292
+ const truthyIndexes = (await Promise.all(
293
+ entry.conditions.map(async (cond, index) => {
294
+ try {
295
+ const result = await cond({
296
+ mastra: this.mastra,
297
+ runtimeContext,
298
+ inputData: prevOutput,
299
+ getInitData: () => stepResults?.input,
300
+ getStepResult: (step) => {
301
+ if (!step?.id) {
302
+ return null;
303
+ }
304
+ const result2 = stepResults[step.id];
305
+ if (result2?.status === "success") {
306
+ return result2.output;
307
+ }
308
+ return null;
309
+ },
310
+ // TODO: this function shouldn't have suspend probably?
311
+ suspend: async (_suspendPayload) => {
312
+ },
313
+ emitter
314
+ });
315
+ return result ? index : null;
316
+ } catch (e) {
317
+ this.logger.error("Error evaluating condition: " + (e?.stack ?? e));
318
+ return null;
319
+ }
320
+ })
321
+ )).filter((index) => index !== null);
322
+ const stepsToRun = entry.steps.filter((_, index) => truthyIndexes.includes(index));
323
+ const results = await Promise.all(
324
+ stepsToRun.map(
325
+ (step, index) => this.executeEntry({
326
+ workflowId,
327
+ runId,
328
+ entry: step,
329
+ prevStep,
330
+ stepResults,
331
+ resume,
332
+ executionContext: {
333
+ executionPath: [...executionContext.executionPath, index],
334
+ suspendedPaths: executionContext.suspendedPaths,
335
+ retryConfig: executionContext.retryConfig
336
+ },
337
+ emitter,
338
+ runtimeContext
339
+ })
340
+ )
341
+ );
342
+ const hasFailed = results.find((result) => result.status === "failed");
343
+ const hasSuspended = results.find((result) => result.status === "suspended");
344
+ if (hasFailed) {
345
+ execResults = { status: "failed", error: hasFailed.error };
346
+ } else if (hasSuspended) {
347
+ execResults = { status: "suspended", payload: hasSuspended.payload };
348
+ } else {
349
+ execResults = {
350
+ status: "success",
351
+ output: results.reduce((acc, result, index) => {
352
+ if (result.status === "success") {
353
+ acc[stepsToRun[index].step.id] = result.output;
354
+ }
355
+ return acc;
356
+ }, {})
357
+ };
358
+ }
359
+ return execResults;
360
+ }
361
+ async executeLoop({
362
+ entry,
363
+ prevOutput,
364
+ stepResults,
365
+ resume,
366
+ executionContext,
367
+ emitter,
368
+ runtimeContext
369
+ }) {
370
+ const { step, condition } = entry;
371
+ let isTrue = true;
372
+ let result = { status: "success", output: prevOutput };
373
+ do {
374
+ result = await this.executeStep({
375
+ step,
376
+ stepResults,
377
+ executionContext,
378
+ resume,
379
+ prevOutput: result.output,
380
+ emitter,
381
+ runtimeContext
382
+ });
383
+ if (result.status !== "success") {
384
+ return result;
385
+ }
386
+ isTrue = await condition({
387
+ mastra: this.mastra,
388
+ runtimeContext,
389
+ inputData: result.output,
390
+ getInitData: () => stepResults?.input,
391
+ getStepResult: (step2) => {
392
+ if (!step2?.id) {
393
+ return null;
394
+ }
395
+ const result2 = stepResults[step2.id];
396
+ return result2?.status === "success" ? result2.output : null;
397
+ },
398
+ suspend: async (_suspendPayload) => {
399
+ },
400
+ emitter
401
+ });
402
+ } while (entry.loopType === "dowhile" ? isTrue : !isTrue);
403
+ return result;
404
+ }
405
+ async executeForeach({
406
+ entry,
407
+ prevOutput,
408
+ stepResults,
409
+ resume,
410
+ executionContext,
411
+ emitter,
412
+ runtimeContext
413
+ }) {
414
+ const { step, opts } = entry;
415
+ const results = [];
416
+ const concurrency = opts.concurrency;
417
+ for (let i = 0; i < prevOutput.length; i += concurrency) {
418
+ const items = prevOutput.slice(i, i + concurrency);
419
+ const itemsResults = await Promise.all(
420
+ items.map((item) => {
421
+ return this.executeStep({
422
+ step,
423
+ stepResults,
424
+ executionContext,
425
+ resume,
426
+ prevOutput: item,
427
+ emitter,
428
+ runtimeContext
429
+ });
430
+ })
431
+ );
432
+ for (const result of itemsResults) {
433
+ if (result.status !== "success") {
434
+ return result;
435
+ }
436
+ results.push(result?.output);
437
+ }
438
+ }
439
+ return { status: "success", output: results };
440
+ }
441
+ async executeEntry({
442
+ workflowId,
443
+ runId,
444
+ entry,
445
+ prevStep,
446
+ stepResults,
447
+ resume,
448
+ executionContext,
449
+ emitter,
450
+ runtimeContext
451
+ }) {
452
+ const prevOutput = this.getStepOutput(stepResults, prevStep);
453
+ let execResults;
454
+ if (entry.type === "step" || entry.type === "loop" || entry.type === "foreach") {
455
+ emitter.emit("watch", {
456
+ type: "watch",
457
+ payload: {
458
+ currentStep: {
459
+ id: entry.step.id,
460
+ status: "running"
461
+ },
462
+ workflowState: {
463
+ status: "running",
464
+ steps: {
465
+ ...stepResults,
466
+ [entry.step.id]: {
467
+ status: "running"
468
+ }
469
+ },
470
+ result: null,
471
+ error: null
472
+ }
473
+ },
474
+ eventTimestamp: Date.now()
475
+ });
476
+ }
477
+ if (entry.type === "step") {
478
+ const { step } = entry;
479
+ execResults = await this.executeStep({
480
+ step,
481
+ stepResults,
482
+ executionContext,
483
+ resume,
484
+ prevOutput,
485
+ emitter,
486
+ runtimeContext
487
+ });
488
+ } else if (resume?.resumePath?.length && (entry.type === "parallel" || entry.type === "conditional")) {
489
+ const idx = resume.resumePath.shift();
490
+ return this.executeEntry({
491
+ workflowId,
492
+ runId,
493
+ entry: entry.steps[idx],
494
+ prevStep,
495
+ stepResults,
496
+ resume,
497
+ executionContext: {
498
+ executionPath: [...executionContext.executionPath, idx],
499
+ suspendedPaths: executionContext.suspendedPaths,
500
+ retryConfig: executionContext.retryConfig
501
+ },
502
+ emitter,
503
+ runtimeContext
504
+ });
505
+ } else if (entry.type === "parallel") {
506
+ execResults = await this.executeParallel({
507
+ workflowId,
508
+ runId,
509
+ entry,
510
+ prevStep,
511
+ stepResults,
512
+ resume,
513
+ executionContext,
514
+ emitter,
515
+ runtimeContext
516
+ });
517
+ } else if (entry.type === "conditional") {
518
+ execResults = await this.executeConditional({
519
+ workflowId,
520
+ runId,
521
+ entry,
522
+ prevStep,
523
+ prevOutput,
524
+ stepResults,
525
+ resume,
526
+ executionContext,
527
+ emitter,
528
+ runtimeContext
529
+ });
530
+ } else if (entry.type === "loop") {
531
+ execResults = await this.executeLoop({
532
+ workflowId,
533
+ runId,
534
+ entry,
535
+ prevStep,
536
+ prevOutput,
537
+ stepResults,
538
+ resume,
539
+ executionContext,
540
+ emitter,
541
+ runtimeContext
542
+ });
543
+ } else if (entry.type === "foreach") {
544
+ execResults = await this.executeForeach({
545
+ workflowId,
546
+ runId,
547
+ entry,
548
+ prevStep,
549
+ prevOutput,
550
+ stepResults,
551
+ resume,
552
+ executionContext,
553
+ emitter,
554
+ runtimeContext
555
+ });
556
+ }
557
+ if (entry.type === "step" || entry.type === "loop" || entry.type === "foreach") {
558
+ stepResults[entry.step.id] = execResults;
559
+ }
560
+ await this.mastra?.getStorage()?.persistWorkflowSnapshot({
561
+ workflowName: workflowId,
562
+ runId,
563
+ snapshot: {
564
+ runId,
565
+ value: {},
566
+ context: stepResults,
567
+ activePaths: [],
568
+ suspendedPaths: executionContext.suspendedPaths,
569
+ // @ts-ignore
570
+ timestamp: Date.now()
571
+ }
572
+ });
573
+ if (entry.type === "step" || entry.type === "loop" || entry.type === "foreach") {
574
+ emitter.emit("watch", {
575
+ type: "watch",
576
+ payload: {
577
+ currentStep: {
578
+ id: entry.step.id,
579
+ status: execResults.status,
580
+ output: execResults.output
581
+ },
582
+ workflowState: {
583
+ status: "running",
584
+ steps: stepResults,
585
+ result: null,
586
+ error: null
587
+ }
588
+ },
589
+ eventTimestamp: Date.now()
590
+ });
591
+ }
592
+ return execResults;
593
+ }
594
+ };
595
+
596
+ // src/workflows/vNext/workflow.ts
597
+ function createStep(params) {
598
+ if (params instanceof chunk422BXQRT_cjs.Agent) {
599
+ return {
600
+ id: params.name,
601
+ // @ts-ignore
602
+ inputSchema: zod.z.object({
603
+ prompt: zod.z.string()
604
+ // resourceId: z.string().optional(),
605
+ // threadId: z.string().optional(),
606
+ }),
607
+ // @ts-ignore
608
+ outputSchema: zod.z.object({
609
+ text: zod.z.string()
610
+ }),
611
+ execute: async ({ inputData }) => {
612
+ const result = await params.generate(inputData.prompt, {
613
+ // resourceId: inputData.resourceId,
614
+ // threadId: inputData.threadId,
615
+ });
616
+ return {
617
+ text: result.text
618
+ };
619
+ }
620
+ };
621
+ }
622
+ if (params instanceof chunkYTTBFAQJ_cjs.Tool) {
623
+ if (!params.inputSchema || !params.outputSchema) {
624
+ throw new Error("Tool must have input and output schemas defined");
625
+ }
626
+ return {
627
+ // TODO: tool probably should have strong id type
628
+ // @ts-ignore
629
+ id: params.id,
630
+ inputSchema: params.inputSchema,
631
+ outputSchema: params.outputSchema,
632
+ execute: async ({ inputData, mastra }) => {
633
+ return await params.execute({
634
+ context: inputData,
635
+ mastra
636
+ });
637
+ }
638
+ };
639
+ }
640
+ return {
641
+ id: params.id,
642
+ description: params.description,
643
+ inputSchema: params.inputSchema,
644
+ outputSchema: params.outputSchema,
645
+ resumeSchema: params.resumeSchema,
646
+ suspendSchema: params.suspendSchema,
647
+ execute: params.execute
648
+ };
649
+ }
650
+ function cloneStep(step, opts) {
651
+ return {
652
+ id: opts.id,
653
+ description: step.description,
654
+ inputSchema: step.inputSchema,
655
+ outputSchema: step.outputSchema,
656
+ execute: step.execute
657
+ };
658
+ }
659
+ function createWorkflow(params) {
660
+ return new NewWorkflow(params);
661
+ }
662
+ var NewWorkflow = class extends chunkD63P5O4Q_cjs.MastraBase {
663
+ id;
664
+ description;
665
+ inputSchema;
666
+ outputSchema;
667
+ steps;
668
+ stepFlow;
669
+ executionEngine;
670
+ executionGraph;
671
+ retryConfig;
672
+ #mastra;
673
+ #runs = /* @__PURE__ */ new Map();
674
+ constructor({
675
+ mastra,
676
+ id,
677
+ inputSchema,
678
+ outputSchema,
679
+ description,
680
+ executionEngine,
681
+ retryConfig
682
+ }) {
683
+ super({ name: id, component: chunkO7IW545H_cjs.RegisteredLogger.WORKFLOW });
684
+ this.id = id;
685
+ this.description = description;
686
+ this.inputSchema = inputSchema;
687
+ this.outputSchema = outputSchema;
688
+ this.retryConfig = retryConfig ?? { attempts: 0, delay: 0 };
689
+ this.executionGraph = this.buildExecutionGraph();
690
+ this.stepFlow = [];
691
+ this.#mastra = mastra;
692
+ this.steps = {};
693
+ if (!executionEngine) {
694
+ this.executionEngine = new DefaultExecutionEngine({ mastra: this.#mastra });
695
+ } else {
696
+ this.executionEngine = executionEngine;
697
+ }
698
+ this.#runs = /* @__PURE__ */ new Map();
699
+ }
700
+ __registerMastra(mastra) {
701
+ this.#mastra = mastra;
702
+ this.executionEngine.__registerMastra(mastra);
703
+ }
704
+ __registerPrimitives(p) {
705
+ if (p.telemetry) {
706
+ this.__setTelemetry(p.telemetry);
707
+ }
708
+ if (p.logger) {
709
+ this.__setLogger(p.logger);
710
+ }
711
+ }
712
+ /**
713
+ * Adds a step to the workflow
714
+ * @param step The step to add to the workflow
715
+ * @returns The workflow instance for chaining
716
+ */
717
+ then(step) {
718
+ this.stepFlow.push({ type: "step", step });
719
+ this.steps[step.id] = step;
720
+ return this;
721
+ }
722
+ map(mappingConfig) {
723
+ const mappingStep = createStep({
724
+ id: `mapping_${crypto.randomUUID()}`,
725
+ inputSchema: zod.z.object({}),
726
+ outputSchema: zod.z.object({}),
727
+ execute: async ({ getStepResult, getInitData, runtimeContext }) => {
728
+ const result = {};
729
+ for (const [key, mapping] of Object.entries(mappingConfig)) {
730
+ const m = mapping;
731
+ if (m.value) {
732
+ result[key] = m.value;
733
+ continue;
734
+ }
735
+ if (m.runtimeContextPath) {
736
+ result[key] = runtimeContext.get(m.runtimeContextPath);
737
+ continue;
738
+ }
739
+ const stepResult = m.initData ? getInitData() : getStepResult(m.step);
740
+ if (m.path === ".") {
741
+ result[key] = stepResult;
742
+ continue;
743
+ }
744
+ const pathParts = m.path.split(".");
745
+ let value = stepResult;
746
+ for (const part of pathParts) {
747
+ if (typeof value === "object" && value !== null) {
748
+ value = value[part];
749
+ } else {
750
+ throw new Error(`Invalid path ${m.path} in step ${m.step.id}`);
751
+ }
752
+ }
753
+ result[key] = value;
754
+ }
755
+ return result;
756
+ }
757
+ });
758
+ this.stepFlow.push({ type: "step", step: mappingStep });
759
+ return this;
760
+ }
761
+ // TODO: make typing better here
762
+ parallel(steps) {
763
+ this.stepFlow.push({ type: "parallel", steps: steps.map((step) => ({ type: "step", step })) });
764
+ steps.forEach((step) => {
765
+ this.steps[step.id] = step;
766
+ });
767
+ return this;
768
+ }
769
+ // TODO: make typing better here
770
+ branch(steps) {
771
+ this.stepFlow.push({
772
+ type: "conditional",
773
+ steps: steps.map(([_cond, step]) => ({ type: "step", step })),
774
+ conditions: steps.map(([cond]) => cond),
775
+ serializedConditions: steps.map(([cond, _step]) => ({ id: `${_step.id}-condition`, fn: cond.toString() }))
776
+ });
777
+ steps.forEach(([_, step]) => {
778
+ this.steps[step.id] = step;
779
+ });
780
+ return this;
781
+ }
782
+ dowhile(step, condition) {
783
+ this.stepFlow.push({
784
+ type: "loop",
785
+ step,
786
+ condition,
787
+ loopType: "dowhile",
788
+ serializedCondition: { id: `${step.id}-condition`, fn: condition.toString() }
789
+ });
790
+ this.steps[step.id] = step;
791
+ return this;
792
+ }
793
+ dountil(step, condition) {
794
+ this.stepFlow.push({
795
+ type: "loop",
796
+ step,
797
+ condition,
798
+ loopType: "dountil",
799
+ serializedCondition: { id: `${step.id}-condition`, fn: condition.toString() }
800
+ });
801
+ this.steps[step.id] = step;
802
+ return this;
803
+ }
804
+ foreach(step, opts) {
805
+ this.stepFlow.push({ type: "foreach", step, opts: opts ?? { concurrency: 1 } });
806
+ this.steps[step.id] = step;
807
+ return this;
808
+ }
809
+ /**
810
+ * Builds the execution graph for this workflow
811
+ * @returns The execution graph that can be used to execute the workflow
812
+ */
813
+ buildExecutionGraph() {
814
+ return {
815
+ id: crypto.randomUUID(),
816
+ steps: this.stepFlow
817
+ };
818
+ }
819
+ /**
820
+ * Finalizes the workflow definition and prepares it for execution
821
+ * This method should be called after all steps have been added to the workflow
822
+ * @returns A built workflow instance ready for execution
823
+ */
824
+ commit() {
825
+ this.executionGraph = this.buildExecutionGraph();
826
+ return this;
827
+ }
828
+ get stepGraph() {
829
+ return this.stepFlow;
830
+ }
831
+ /**
832
+ * Creates a new workflow run instance
833
+ * @param options Optional configuration for the run
834
+ * @returns A Run instance that can be used to execute the workflow
835
+ */
836
+ createRun(options) {
837
+ const runIdToUse = options?.runId || crypto.randomUUID();
838
+ const run = this.#runs.get(runIdToUse) ?? new Run({
839
+ workflowId: this.id,
840
+ runId: runIdToUse,
841
+ executionEngine: this.executionEngine,
842
+ executionGraph: this.executionGraph,
843
+ mastra: this.#mastra,
844
+ retryConfig: this.retryConfig,
845
+ cleanup: () => this.#runs.delete(runIdToUse)
846
+ });
847
+ this.#runs.set(runIdToUse, run);
848
+ return run;
849
+ }
850
+ async execute({
851
+ inputData,
852
+ resumeData,
853
+ suspend,
854
+ resume,
855
+ emitter,
856
+ mastra
857
+ }) {
858
+ this.__registerMastra(mastra);
859
+ const run = resume?.steps?.length ? this.createRun({ runId: resume.runId }) : this.createRun();
860
+ const unwatch = run.watch((event) => {
861
+ emitter.emit("nested-watch", { event, workflowId: this.id, runId: run.runId, isResume: !!resume?.steps?.length });
862
+ });
863
+ const res = resume?.steps?.length ? await run.resume({ resumeData, step: resume.steps }) : await run.start({ inputData });
864
+ unwatch();
865
+ const suspendedSteps = Object.entries(res.steps).filter(([_stepName, stepResult]) => {
866
+ const stepRes = stepResult;
867
+ return stepRes?.status === "suspended";
868
+ });
869
+ if (suspendedSteps?.length) {
870
+ for (const [stepName, stepResult] of suspendedSteps) {
871
+ const suspendPath = [stepName, ...stepResult?.payload?.__workflow_meta?.path ?? []];
872
+ await suspend({
873
+ ...stepResult?.payload,
874
+ __workflow_meta: { runId: run.runId, path: suspendPath }
875
+ });
876
+ }
877
+ }
878
+ if (res.status === "failed") {
879
+ throw res.error;
880
+ }
881
+ return res.status === "success" ? res.result : void 0;
882
+ }
883
+ async getWorkflowRuns() {
884
+ const storage = this.#mastra?.getStorage();
885
+ if (!storage) {
886
+ this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
887
+ return { runs: [], total: 0 };
888
+ }
889
+ return storage.getWorkflowRuns({ workflowName: this.id });
890
+ }
891
+ async getWorkflowRun(runId) {
892
+ const runs = await this.getWorkflowRuns();
893
+ return runs?.runs.find((r) => r.runId === runId) || this.#runs.get(runId);
894
+ }
895
+ };
896
+ var Run = class {
897
+ emitter;
898
+ /**
899
+ * Unique identifier for this workflow
900
+ */
901
+ workflowId;
902
+ /**
903
+ * Unique identifier for this run
904
+ */
905
+ runId;
906
+ /**
907
+ * Internal state of the workflow run
908
+ */
909
+ state = {};
910
+ /**
911
+ * The execution engine for this run
912
+ */
913
+ executionEngine;
914
+ /**
915
+ * The execution graph for this run
916
+ */
917
+ executionGraph;
918
+ /**
919
+ * The storage for this run
920
+ */
921
+ #mastra;
922
+ cleanup;
923
+ retryConfig;
924
+ constructor(params) {
925
+ this.workflowId = params.workflowId;
926
+ this.runId = params.runId;
927
+ this.executionEngine = params.executionEngine;
928
+ this.executionGraph = params.executionGraph;
929
+ this.#mastra = params.mastra;
930
+ this.emitter = new EventEmitter__default.default();
931
+ this.retryConfig = params.retryConfig;
932
+ this.cleanup = params.cleanup;
933
+ }
934
+ /**
935
+ * Starts the workflow execution with the provided input
936
+ * @param input The input data for the workflow
937
+ * @returns A promise that resolves to the workflow output
938
+ */
939
+ async start({
940
+ inputData,
941
+ runtimeContext
942
+ }) {
943
+ const result = await this.executionEngine.execute({
944
+ workflowId: this.workflowId,
945
+ runId: this.runId,
946
+ graph: this.executionGraph,
947
+ input: inputData,
948
+ emitter: this.emitter,
949
+ retryConfig: this.retryConfig,
950
+ runtimeContext: runtimeContext ?? new chunkLABUWBKX_cjs.RuntimeContext()
951
+ });
952
+ this.cleanup?.();
953
+ return result;
954
+ }
955
+ watch(cb) {
956
+ this.emitter.on("watch", ({ type, payload, eventTimestamp }) => {
957
+ this.updateState(payload);
958
+ cb({ type, payload: this.getState(), eventTimestamp });
959
+ });
960
+ this.emitter.on("nested-watch", ({ event, workflowId }) => {
961
+ try {
962
+ const { type, payload, eventTimestamp } = event;
963
+ const prefixedSteps = Object.fromEntries(
964
+ Object.entries(payload?.workflowState?.steps ?? {}).map(([stepId, step]) => [
965
+ `${workflowId}.${stepId}`,
966
+ step
967
+ ])
968
+ );
969
+ const newPayload = {
970
+ currentStep: {
971
+ ...payload?.currentStep,
972
+ id: `${workflowId}.${payload?.currentStep?.id}`
973
+ },
974
+ workflowState: {
975
+ ...payload?.workflowState,
976
+ steps: prefixedSteps
977
+ }
978
+ };
979
+ this.updateState(newPayload);
980
+ cb({ type, payload: this.getState(), eventTimestamp });
981
+ } catch (e) {
982
+ console.error(e);
983
+ }
984
+ });
985
+ return () => {
986
+ this.emitter.off("watch", cb);
987
+ };
988
+ }
989
+ async resume(params) {
990
+ const steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
991
+ (step) => typeof step === "string" ? step : step?.id
992
+ );
993
+ const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
994
+ workflowName: this.workflowId,
995
+ runId: this.runId
996
+ });
997
+ return this.executionEngine.execute({
998
+ workflowId: this.workflowId,
999
+ runId: this.runId,
1000
+ graph: this.executionGraph,
1001
+ input: params.resumeData,
1002
+ resume: {
1003
+ steps,
1004
+ stepResults: snapshot?.context,
1005
+ resumePayload: params.resumeData,
1006
+ // @ts-ignore
1007
+ resumePath: snapshot?.suspendedPaths?.[steps?.[0]]
1008
+ },
1009
+ emitter: this.emitter,
1010
+ runtimeContext: params.runtimeContext ?? new chunkLABUWBKX_cjs.RuntimeContext()
1011
+ });
1012
+ }
1013
+ /**
1014
+ * Returns the current state of the workflow run
1015
+ * @returns The current state of the workflow run
1016
+ */
1017
+ getState() {
1018
+ return this.state;
1019
+ }
1020
+ updateState(state) {
1021
+ if (state.currentStep) {
1022
+ this.state.currentStep = state.currentStep;
1023
+ }
1024
+ if (state.workflowState) {
1025
+ this.state.workflowState = deepMerge(this.state.workflowState ?? {}, state.workflowState ?? {});
1026
+ }
1027
+ }
1028
+ };
1029
+ function deepMerge(a, b) {
1030
+ if (!a || typeof a !== "object") return b;
1031
+ if (!b || typeof b !== "object") return a;
1032
+ const result = { ...a };
1033
+ for (const key in b) {
1034
+ if (b[key] === void 0) continue;
1035
+ if (b[key] !== null && typeof b[key] === "object") {
1036
+ const aVal = result[key];
1037
+ const bVal = b[key];
1038
+ if (Array.isArray(bVal)) {
1039
+ result[key] = Array.isArray(aVal) ? [...aVal, ...bVal].filter((item) => item !== void 0) : bVal.filter((item) => item !== void 0);
1040
+ } else if (typeof aVal === "object" && aVal !== null) {
1041
+ result[key] = deepMerge(aVal, bVal);
1042
+ } else {
1043
+ result[key] = bVal;
1044
+ }
1045
+ } else {
1046
+ result[key] = b[key];
1047
+ }
1048
+ }
1049
+ return result;
1050
+ }
1051
+
1052
+ exports.DefaultExecutionEngine = DefaultExecutionEngine;
1053
+ exports.ExecutionEngine = ExecutionEngine;
1054
+ exports.NewWorkflow = NewWorkflow;
1055
+ exports.Run = Run;
1056
+ exports.cloneStep = cloneStep;
1057
+ exports.createStep = createStep;
1058
+ exports.createWorkflow = createWorkflow;