@mastra/core 0.0.0-storage-20250225005900

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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +180 -0
  3. package/dist/agent/index.d.ts +15 -0
  4. package/dist/agent/index.js +1 -0
  5. package/dist/base-CHNzbTDj.d.ts +894 -0
  6. package/dist/base-eWkcLLSb.d.ts +139 -0
  7. package/dist/base.d.ts +6 -0
  8. package/dist/base.js +1 -0
  9. package/dist/bundler/index.d.ts +28 -0
  10. package/dist/bundler/index.js +1 -0
  11. package/dist/chunk-4IIE6KIC.js +10 -0
  12. package/dist/chunk-4ZNSY7J7.js +215 -0
  13. package/dist/chunk-4ZRHVG25.js +402 -0
  14. package/dist/chunk-5275WBGX.js +318 -0
  15. package/dist/chunk-6RDA4JYW.js +49 -0
  16. package/dist/chunk-BB4KXGBU.js +83 -0
  17. package/dist/chunk-C6A6W6XS.js +77 -0
  18. package/dist/chunk-FEBWYMJQ.js +416 -0
  19. package/dist/chunk-KP5SHTKA.js +145 -0
  20. package/dist/chunk-N7KZVQDK.js +61 -0
  21. package/dist/chunk-NDQR6IPC.js +37 -0
  22. package/dist/chunk-NUDAZEOG.js +35 -0
  23. package/dist/chunk-ORM3OCHX.js +1367 -0
  24. package/dist/chunk-PNZK456O.js +88 -0
  25. package/dist/chunk-QXPUH6PK.js +620 -0
  26. package/dist/chunk-RG66XEJT.js +8 -0
  27. package/dist/chunk-SIFBBGY6.js +190 -0
  28. package/dist/chunk-TCMOYQ74.js +1204 -0
  29. package/dist/chunk-WIBGG4X6.js +173 -0
  30. package/dist/chunk-YKDBP67T.js +346 -0
  31. package/dist/chunk-YUOADWSP.js +22 -0
  32. package/dist/chunk-Z735LDV7.js +10 -0
  33. package/dist/chunk-ZDWFBE5L.js +1 -0
  34. package/dist/chunk-ZINPRHAN.js +22 -0
  35. package/dist/deployer/index.d.ts +19 -0
  36. package/dist/deployer/index.js +1 -0
  37. package/dist/eval/index.d.ts +28 -0
  38. package/dist/eval/index.js +1 -0
  39. package/dist/filter/index.d.ts +90 -0
  40. package/dist/filter/index.js +1 -0
  41. package/dist/hooks/index.d.ts +33 -0
  42. package/dist/hooks/index.js +1 -0
  43. package/dist/index-C5uPdbs4.d.ts +90 -0
  44. package/dist/index.d.ts +98 -0
  45. package/dist/index.js +119 -0
  46. package/dist/integration/index.d.ts +53 -0
  47. package/dist/integration/index.js +1 -0
  48. package/dist/llm/index.d.ts +15 -0
  49. package/dist/llm/index.js +1 -0
  50. package/dist/logger/index.d.ts +3 -0
  51. package/dist/logger/index.js +1 -0
  52. package/dist/mastra/index.d.ts +68 -0
  53. package/dist/mastra/index.js +1 -0
  54. package/dist/memory/index.d.ts +15 -0
  55. package/dist/memory/index.js +1 -0
  56. package/dist/relevance/index.d.ts +21 -0
  57. package/dist/relevance/index.js +1 -0
  58. package/dist/storage/index.d.ts +15 -0
  59. package/dist/storage/index.js +2 -0
  60. package/dist/storage/libsql/index.d.ts +81 -0
  61. package/dist/storage/libsql/index.js +1 -0
  62. package/dist/telemetry/index.d.ts +51 -0
  63. package/dist/telemetry/index.js +1 -0
  64. package/dist/telemetry/otel-vendor.d.ts +7 -0
  65. package/dist/telemetry/otel-vendor.js +7 -0
  66. package/dist/tools/index.d.ts +29 -0
  67. package/dist/tools/index.js +1 -0
  68. package/dist/tts/index.d.ts +28 -0
  69. package/dist/tts/index.js +1 -0
  70. package/dist/types-m9RryK9a.d.ts +14 -0
  71. package/dist/utils.d.ts +26 -0
  72. package/dist/utils.js +1 -0
  73. package/dist/vector/index.d.ts +29 -0
  74. package/dist/vector/index.js +1 -0
  75. package/dist/vector/libsql/index.d.ts +29 -0
  76. package/dist/vector/libsql/index.js +1 -0
  77. package/dist/voice/index.d.ts +67 -0
  78. package/dist/voice/index.js +76 -0
  79. package/dist/workflow-CddifUps.d.ts +92 -0
  80. package/dist/workflows/index.d.ts +31 -0
  81. package/dist/workflows/index.js +1 -0
  82. package/package.json +134 -0
@@ -0,0 +1,1204 @@
1
+ import { MastraBase } from './chunk-6RDA4JYW.js';
2
+ import { context, trace } from '@opentelemetry/api';
3
+ import { get } from 'radash';
4
+ import sift from 'sift';
5
+ import { setup, createActor, assign, fromPromise } from 'xstate';
6
+
7
+ // src/workflows/utils.ts
8
+ function isErrorEvent(stateEvent) {
9
+ return stateEvent.type.startsWith("xstate.error.actor.");
10
+ }
11
+ function isTransitionEvent(stateEvent) {
12
+ return stateEvent.type.startsWith("xstate.done.actor.");
13
+ }
14
+ function isVariableReference(value) {
15
+ return typeof value === "object" && "step" in value && "path" in value;
16
+ }
17
+ function getStepResult(result) {
18
+ if (result?.status === "success") return result.output;
19
+ return void 0;
20
+ }
21
+
22
+ // src/workflows/workflow.ts
23
+ var Workflow = class extends MastraBase {
24
+ name;
25
+ triggerSchema;
26
+ /** XState machine instance that orchestrates the workflow execution */
27
+ #machine;
28
+ /** XState actor instance that manages the workflow execution */
29
+ #actor = null;
30
+ #runId;
31
+ #retryConfig;
32
+ #mastra;
33
+ // registers stepIds on `after` calls
34
+ #afterStepStack = [];
35
+ #lastStepStack = [];
36
+ #stepGraph = { initial: [] };
37
+ #stepSubscriberGraph = {};
38
+ #steps = {};
39
+ #onStepTransition = /* @__PURE__ */ new Set();
40
+ #executionSpan;
41
+ /**
42
+ * Creates a new Workflow instance
43
+ * @param name - Identifier for the workflow (not necessarily unique)
44
+ * @param logger - Optional logger instance
45
+ */
46
+ constructor({ name, triggerSchema, retryConfig, mastra }) {
47
+ super({ component: "WORKFLOW", name });
48
+ this.name = name;
49
+ this.#retryConfig = retryConfig;
50
+ this.triggerSchema = triggerSchema;
51
+ this.#runId = crypto.randomUUID();
52
+ this.#mastra = mastra;
53
+ if (mastra?.logger) {
54
+ this.logger = mastra?.logger;
55
+ }
56
+ this.initializeMachine();
57
+ }
58
+ /**
59
+ * Initializes the XState machine for the workflow
60
+ *
61
+ * Registers the machine's types, actions, actors, initial context, entry actions, initial state, and states
62
+ * @returns The initialized machine
63
+ */
64
+ initializeMachine() {
65
+ const machine = setup({
66
+ types: {},
67
+ delays: this.#makeDelayMap(),
68
+ actions: this.#getDefaultActions(),
69
+ actors: this.#getDefaultActors()
70
+ }).createMachine({
71
+ id: this.name,
72
+ type: "parallel",
73
+ context: ({ input }) => ({
74
+ ...input
75
+ }),
76
+ states: this.#buildStateHierarchy(this.#stepGraph)
77
+ });
78
+ this.#machine = machine;
79
+ return machine;
80
+ }
81
+ step(step, config) {
82
+ const { variables = {} } = config || {};
83
+ const requiredData = {};
84
+ for (const [key, variable] of Object.entries(variables)) {
85
+ if (variable && isVariableReference(variable)) {
86
+ requiredData[key] = variable;
87
+ }
88
+ }
89
+ const stepKey = this.#makeStepKey(step);
90
+ const graphEntry = {
91
+ step,
92
+ config: {
93
+ ...this.#makeStepDef(stepKey),
94
+ ...config,
95
+ data: requiredData
96
+ }
97
+ };
98
+ this.#steps[stepKey] = step;
99
+ const parentStepKey = this.#afterStepStack[this.#afterStepStack.length - 1];
100
+ const stepGraph = this.#stepSubscriberGraph[parentStepKey || ""];
101
+ if (parentStepKey && stepGraph) {
102
+ if (!stepGraph.initial.some((step2) => step2.step.id === stepKey)) {
103
+ stepGraph.initial.push(graphEntry);
104
+ }
105
+ stepGraph[stepKey] = [];
106
+ } else {
107
+ if (!this.#stepGraph[stepKey]) this.#stepGraph[stepKey] = [];
108
+ this.#stepGraph.initial.push(graphEntry);
109
+ }
110
+ this.#lastStepStack.push(stepKey);
111
+ return this;
112
+ }
113
+ then(step, config) {
114
+ const { variables = {} } = config || {};
115
+ const requiredData = {};
116
+ for (const [key, variable] of Object.entries(variables)) {
117
+ if (variable && isVariableReference(variable)) {
118
+ requiredData[key] = variable;
119
+ }
120
+ }
121
+ const lastStepKey = this.#lastStepStack[this.#lastStepStack.length - 1];
122
+ const stepKey = this.#makeStepKey(step);
123
+ const graphEntry = {
124
+ step,
125
+ config: {
126
+ ...this.#makeStepDef(stepKey),
127
+ ...config,
128
+ data: requiredData
129
+ }
130
+ };
131
+ this.#steps[stepKey] = step;
132
+ if (!lastStepKey) return this;
133
+ const parentStepKey = this.#afterStepStack[this.#afterStepStack.length - 1];
134
+ const stepGraph = this.#stepSubscriberGraph[parentStepKey || ""];
135
+ if (parentStepKey && stepGraph && stepGraph[lastStepKey]) {
136
+ stepGraph[lastStepKey].push(graphEntry);
137
+ } else {
138
+ if (!this.#stepGraph[lastStepKey]) this.#stepGraph[lastStepKey] = [];
139
+ this.#stepGraph[lastStepKey].push(graphEntry);
140
+ }
141
+ return this;
142
+ }
143
+ after(step) {
144
+ const stepKey = this.#makeStepKey(step);
145
+ this.#afterStepStack.push(stepKey);
146
+ if (!this.#stepSubscriberGraph[stepKey]) {
147
+ this.#stepSubscriberGraph[stepKey] = { initial: [] };
148
+ }
149
+ return this;
150
+ }
151
+ /**
152
+ * Executes the workflow with the given trigger data
153
+ * @param triggerData - Initial data to start the workflow with
154
+ * @returns Promise resolving to workflow results or rejecting with error
155
+ * @throws Error if trigger schema validation fails
156
+ */
157
+ createRun() {
158
+ const runId = crypto.randomUUID();
159
+ this.#runId = runId;
160
+ return {
161
+ runId,
162
+ start: async ({ triggerData } = {}) => this.execute({ triggerData })
163
+ };
164
+ }
165
+ async execute({
166
+ triggerData,
167
+ snapshot,
168
+ runId,
169
+ stepId
170
+ } = {}) {
171
+ if (runId) {
172
+ this.#runId = runId;
173
+ this.logger.debug(`Workflow snapshot received`, { runId: this.#runId, snapshot });
174
+ }
175
+ this.#executionSpan = this.#mastra?.telemetry?.tracer.startSpan(`workflow.${this.name}.execute`, {
176
+ attributes: { componentName: this.name, runId: this.#runId }
177
+ });
178
+ const machineInput = snapshot ? snapshot.context : {
179
+ // Maintain the original step results and their output
180
+ steps: {},
181
+ triggerData: triggerData || {},
182
+ attempts: Object.keys(this.#steps).reduce(
183
+ (acc, stepKey) => {
184
+ acc[stepKey] = this.#steps[stepKey]?.retryConfig?.attempts || this.#retryConfig?.attempts || 3;
185
+ return acc;
186
+ },
187
+ {}
188
+ )
189
+ };
190
+ this.logger.debug(`Machine input prepared`, { runId: this.#runId, machineInput });
191
+ const actorSnapshot = snapshot ? {
192
+ ...snapshot,
193
+ context: machineInput
194
+ } : void 0;
195
+ this.logger.debug(`Creating actor with configuration`, {
196
+ machineInput,
197
+ actorSnapshot,
198
+ machineStates: this.#machine.config.states,
199
+ runId: this.#runId
200
+ });
201
+ this.#actor = createActor(this.#machine, {
202
+ inspect: (inspectionEvent) => {
203
+ this.logger.debug("XState inspection event", {
204
+ type: inspectionEvent.type,
205
+ event: inspectionEvent.event,
206
+ runId: this.#runId
207
+ });
208
+ },
209
+ input: machineInput,
210
+ snapshot: actorSnapshot
211
+ });
212
+ this.#actor.start();
213
+ if (stepId) {
214
+ this.#actor.send({ type: "RESET_TO_PENDING", stepId });
215
+ }
216
+ this.logger.debug("Actor started", { runId: this.#runId });
217
+ return new Promise((resolve, reject) => {
218
+ if (!this.#actor) {
219
+ const e = new Error("Actor not initialized");
220
+ this.#executionSpan?.recordException(e);
221
+ this.#executionSpan?.end();
222
+ reject(e);
223
+ return;
224
+ }
225
+ const suspendedPaths = /* @__PURE__ */ new Set();
226
+ this.#actor.subscribe(async (state) => {
227
+ if (this.#onStepTransition) {
228
+ this.#onStepTransition.forEach((onTransition) => {
229
+ onTransition({
230
+ runId: this.#runId,
231
+ value: state.value,
232
+ context: state.context,
233
+ activePaths: this.#getActivePathsAndStatus(state.value),
234
+ timestamp: Date.now()
235
+ })?.catch(() => {
236
+ });
237
+ });
238
+ }
239
+ this.#getSuspendedPaths({
240
+ value: state.value,
241
+ path: "",
242
+ suspendedPaths
243
+ });
244
+ const allStatesValue = state.value;
245
+ const allStatesComplete = this.#recursivelyCheckForFinalState({
246
+ value: allStatesValue,
247
+ suspendedPaths,
248
+ path: ""
249
+ });
250
+ this.logger.debug("State completion check", {
251
+ allStatesComplete,
252
+ suspendedPaths: Array.from(suspendedPaths),
253
+ runId: this.#runId
254
+ });
255
+ if (!allStatesComplete) return;
256
+ try {
257
+ await this.#persistWorkflowSnapshot();
258
+ this.#cleanup();
259
+ this.#executionSpan?.end();
260
+ resolve({
261
+ triggerData,
262
+ results: state.context.steps,
263
+ runId: this.#runId
264
+ });
265
+ } catch (error) {
266
+ this.logger.debug("Failed to persist final snapshot", { error });
267
+ this.#cleanup();
268
+ this.#executionSpan?.end();
269
+ resolve({
270
+ triggerData,
271
+ results: state.context.steps,
272
+ runId: this.#runId
273
+ });
274
+ }
275
+ });
276
+ });
277
+ }
278
+ /**
279
+ * Rebuilds the machine with the current steps configuration and validates the workflow
280
+ *
281
+ * This is the last step of a workflow builder method chain
282
+ * @throws Error if validation fails
283
+ *
284
+ * @returns this instance for method chaining
285
+ */
286
+ commit() {
287
+ this.initializeMachine();
288
+ return this;
289
+ }
290
+ // record all object paths that leads to a suspended state
291
+ #getSuspendedPaths({
292
+ value,
293
+ path,
294
+ suspendedPaths
295
+ }) {
296
+ if (typeof value === "string") {
297
+ if (value === "suspended") {
298
+ suspendedPaths.add(path);
299
+ }
300
+ } else {
301
+ Object.keys(value).forEach(
302
+ (key) => this.#getSuspendedPaths({ value: value[key], path: path ? `${path}.${key}` : key, suspendedPaths })
303
+ );
304
+ }
305
+ }
306
+ #isFinalState(status) {
307
+ return ["completed", "failed"].includes(status);
308
+ }
309
+ #recursivelyCheckForFinalState({
310
+ value,
311
+ suspendedPaths,
312
+ path
313
+ }) {
314
+ if (typeof value === "string") {
315
+ return this.#isFinalState(value) || suspendedPaths.has(path);
316
+ }
317
+ return Object.keys(value).every(
318
+ (key) => this.#recursivelyCheckForFinalState({ value: value[key], suspendedPaths, path: path ? `${path}.${key}` : key })
319
+ );
320
+ }
321
+ #buildBaseState(stepNode, nextSteps = []) {
322
+ const nextStep = nextSteps.shift();
323
+ return {
324
+ initial: "pending",
325
+ on: {
326
+ RESET_TO_PENDING: {
327
+ target: ".pending"
328
+ // Note the dot to target child state
329
+ }
330
+ },
331
+ states: {
332
+ pending: {
333
+ entry: () => {
334
+ this.logger.debug(`Step ${stepNode.step.id} pending`, {
335
+ stepId: stepNode.step.id,
336
+ runId: this.#runId
337
+ });
338
+ },
339
+ exit: () => {
340
+ this.logger.debug(`Step ${stepNode.step.id} finished pending`, {
341
+ stepId: stepNode.step.id,
342
+ runId: this.#runId
343
+ });
344
+ },
345
+ invoke: {
346
+ src: "conditionCheck",
347
+ input: ({ context }) => {
348
+ return {
349
+ context,
350
+ stepNode
351
+ };
352
+ },
353
+ onDone: [
354
+ {
355
+ guard: ({ event }) => {
356
+ return event.output.type === "SUSPENDED";
357
+ },
358
+ target: "suspended",
359
+ actions: [
360
+ assign({
361
+ steps: ({ context, event }) => {
362
+ if (event.output.type !== "SUSPENDED") return context.steps;
363
+ return {
364
+ ...context.steps,
365
+ [stepNode.step.id]: {
366
+ status: "suspended",
367
+ ...context.steps?.[stepNode.step.id] || {}
368
+ }
369
+ };
370
+ },
371
+ attempts: ({ context, event }) => {
372
+ if (event.output.type !== "SUSPENDED") return context.attempts;
373
+ return { ...context.attempts, [stepNode.step.id]: stepNode.step.retryConfig?.attempts || 3 };
374
+ }
375
+ })
376
+ ]
377
+ },
378
+ {
379
+ guard: ({ event }) => {
380
+ return event.output.type === "WAITING";
381
+ },
382
+ target: "waiting",
383
+ actions: [
384
+ { type: "decrementAttemptCount", params: { stepId: stepNode.step.id } },
385
+ assign({
386
+ steps: ({ context, event }) => {
387
+ if (event.output.type !== "WAITING") return context.steps;
388
+ return {
389
+ ...context.steps,
390
+ [stepNode.step.id]: {
391
+ status: "waiting"
392
+ }
393
+ };
394
+ }
395
+ })
396
+ ]
397
+ },
398
+ {
399
+ guard: ({ event }) => {
400
+ return event.output.type === "CONDITIONS_MET";
401
+ },
402
+ target: "executing"
403
+ },
404
+ {
405
+ guard: ({ event }) => {
406
+ return event.output.type === "CONDITION_FAILED";
407
+ },
408
+ target: "failed",
409
+ actions: assign({
410
+ steps: ({ context, event }) => {
411
+ if (event.output.type !== "CONDITION_FAILED") return context.steps;
412
+ this.logger.debug(`Workflow condition check failed`, {
413
+ error: event.output.error,
414
+ stepId: stepNode.step.id
415
+ });
416
+ return {
417
+ ...context.steps,
418
+ [stepNode.step.id]: {
419
+ status: "failed",
420
+ error: event.output.error
421
+ }
422
+ };
423
+ }
424
+ })
425
+ }
426
+ ]
427
+ }
428
+ },
429
+ waiting: {
430
+ entry: () => {
431
+ this.logger.debug(`Step ${stepNode.step.id} waiting`, {
432
+ stepId: stepNode.step.id,
433
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
434
+ runId: this.#runId
435
+ });
436
+ },
437
+ exit: () => {
438
+ this.logger.debug(`Step ${stepNode.step.id} finished waiting`, {
439
+ stepId: stepNode.step.id,
440
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
441
+ runId: this.#runId
442
+ });
443
+ },
444
+ after: {
445
+ [stepNode.step.id]: {
446
+ target: "pending"
447
+ }
448
+ }
449
+ },
450
+ suspended: {
451
+ type: "final",
452
+ entry: [
453
+ () => {
454
+ this.logger.debug(`Step ${stepNode.step.id} suspended`, {
455
+ stepId: stepNode.step.id,
456
+ runId: this.#runId
457
+ });
458
+ },
459
+ assign({
460
+ steps: ({ context }) => ({
461
+ ...context.steps,
462
+ [stepNode.step.id]: {
463
+ ...context?.steps?.[stepNode.step.id] || {},
464
+ status: "suspended"
465
+ }
466
+ })
467
+ })
468
+ ]
469
+ // after: {
470
+ // [stepNode.step.id]: {
471
+ // target: 'pending',
472
+ // actions: [
473
+ // assign({
474
+ // attempts: ({ context }: { context: WorkflowContext }) => ({
475
+ // ...context.attempts,
476
+ // [stepNode.step.id]: this.#steps[stepNode.step.id]?.retryConfig?.attempts || 3,
477
+ // }),
478
+ // }),
479
+ // ],
480
+ // }
481
+ // },
482
+ // entry: () => {
483
+ // this.logger.debug(`Step ${stepNode.step.id} suspended ${new Date().toISOString()}`);
484
+ // },
485
+ // exit: () => {
486
+ // this.logger.debug(`Step ${stepNode.step.id} finished suspended ${new Date().toISOString()}`);
487
+ // },
488
+ // after: {
489
+ // [stepNode.step.id]: {
490
+ // target: 'suspended',
491
+ // },
492
+ // },
493
+ },
494
+ executing: {
495
+ entry: () => {
496
+ this.logger.debug(`Step ${stepNode.step.id} executing`, {
497
+ stepId: stepNode.step.id,
498
+ runId: this.#runId
499
+ });
500
+ },
501
+ on: {
502
+ SUSPENDED: {
503
+ target: "suspended",
504
+ actions: [
505
+ assign({
506
+ steps: ({ context }) => ({
507
+ ...context.steps,
508
+ [stepNode.step.id]: {
509
+ status: "suspended"
510
+ }
511
+ })
512
+ })
513
+ ]
514
+ }
515
+ },
516
+ invoke: {
517
+ src: "resolverFunction",
518
+ input: ({ context }) => ({
519
+ context,
520
+ stepNode
521
+ }),
522
+ onDone: {
523
+ target: "runningSubscribers",
524
+ actions: [
525
+ ({ event }) => this.logger.debug(`Step ${stepNode.step.id} finished executing`, {
526
+ stepId: stepNode.step.id,
527
+ output: event.output,
528
+ runId: this.#runId
529
+ }),
530
+ { type: "updateStepResult", params: { stepId: stepNode.step.id } },
531
+ { type: "spawnSubscribers", params: { stepId: stepNode.step.id } }
532
+ ]
533
+ },
534
+ onError: {
535
+ target: "failed",
536
+ actions: [{ type: "setStepError", params: { stepId: stepNode.step.id } }]
537
+ }
538
+ }
539
+ },
540
+ runningSubscribers: {
541
+ entry: () => {
542
+ this.logger.debug(`Step ${stepNode.step.id} running subscribers`, {
543
+ stepId: stepNode.step.id,
544
+ runId: this.#runId
545
+ });
546
+ },
547
+ exit: () => {
548
+ this.logger.debug(`Step ${stepNode.step.id} finished running subscribers`, {
549
+ stepId: stepNode.step.id,
550
+ runId: this.#runId
551
+ });
552
+ },
553
+ invoke: {
554
+ src: "spawnSubscriberFunction",
555
+ input: ({ context }) => ({
556
+ parentStepId: stepNode.step.id,
557
+ context
558
+ }),
559
+ onDone: {
560
+ target: nextStep ? nextStep.step.id : "completed",
561
+ actions: [
562
+ assign({
563
+ steps: ({ context, event }) => ({
564
+ ...context.steps,
565
+ ...event.output.steps
566
+ })
567
+ }),
568
+ () => this.logger.debug(`Subscriber execution completed`, { stepId: stepNode.step.id })
569
+ ]
570
+ },
571
+ onError: {
572
+ target: nextStep ? nextStep.step.id : "completed",
573
+ actions: ({ event }) => {
574
+ this.logger.debug(`Subscriber execution failed`, {
575
+ error: event.error,
576
+ stepId: stepNode.step.id
577
+ });
578
+ }
579
+ }
580
+ }
581
+ },
582
+ completed: {
583
+ type: "final",
584
+ entry: [
585
+ { type: "notifyStepCompletion", params: { stepId: stepNode.step.id } },
586
+ { type: "snapshotStep", params: { stepId: stepNode.step.id } },
587
+ { type: "persistSnapshot" }
588
+ ]
589
+ },
590
+ failed: {
591
+ type: "final",
592
+ entry: [
593
+ { type: "notifyStepCompletion", params: { stepId: stepNode.step.id } },
594
+ { type: "snapshotStep", params: { stepId: stepNode.step.id } },
595
+ { type: "persistSnapshot" }
596
+ ]
597
+ },
598
+ // build chain of next steps recursively
599
+ ...nextStep ? { [nextStep.step.id]: { ...this.#buildBaseState(nextStep, nextSteps) } } : {}
600
+ }
601
+ };
602
+ }
603
+ #makeStepKey(step) {
604
+ return `${step.id}`;
605
+ }
606
+ /**
607
+ * Builds the state hierarchy for the workflow
608
+ * @returns Object representing the state hierarchy
609
+ */
610
+ #buildStateHierarchy(stepGraph) {
611
+ const states = {};
612
+ stepGraph.initial.forEach((stepNode) => {
613
+ const nextSteps = [...stepGraph[stepNode.step.id] || []];
614
+ states[stepNode.step.id] = {
615
+ ...this.#buildBaseState(stepNode, nextSteps)
616
+ };
617
+ });
618
+ return states;
619
+ }
620
+ #getDefaultActions() {
621
+ return {
622
+ updateStepResult: assign({
623
+ steps: ({ context, event }) => {
624
+ if (!isTransitionEvent(event)) return context.steps;
625
+ const { stepId, result } = event.output;
626
+ return {
627
+ ...context.steps,
628
+ [stepId]: {
629
+ status: "success",
630
+ output: result
631
+ }
632
+ };
633
+ }
634
+ }),
635
+ setStepError: assign({
636
+ steps: ({ context, event }, params) => {
637
+ if (!isErrorEvent(event)) return context.steps;
638
+ const { stepId } = params;
639
+ if (!stepId) return context.steps;
640
+ return {
641
+ ...context.steps,
642
+ [stepId]: {
643
+ status: "failed",
644
+ error: event.error.message
645
+ }
646
+ };
647
+ }
648
+ }),
649
+ notifyStepCompletion: async (_, params) => {
650
+ const { stepId } = params;
651
+ this.logger.debug(`Step ${stepId} completed`);
652
+ },
653
+ snapshotStep: assign({
654
+ _snapshot: ({}, params) => {
655
+ const { stepId } = params;
656
+ return { stepId };
657
+ }
658
+ }),
659
+ persistSnapshot: async ({ context }) => {
660
+ if (context._snapshot) {
661
+ return await this.#persistWorkflowSnapshot();
662
+ }
663
+ return;
664
+ },
665
+ decrementAttemptCount: assign({
666
+ attempts: ({ context, event }, params) => {
667
+ if (!isTransitionEvent(event)) return context.attempts;
668
+ const { stepId } = params;
669
+ const attemptCount = context.attempts[stepId];
670
+ if (attemptCount === void 0) return context.attempts;
671
+ return { ...context.attempts, [stepId]: attemptCount - 1 };
672
+ }
673
+ })
674
+ };
675
+ }
676
+ #getInjectables() {
677
+ return {
678
+ runId: this.#runId,
679
+ mastra: this.#mastra
680
+ };
681
+ }
682
+ #getDefaultActors() {
683
+ return {
684
+ resolverFunction: fromPromise(async ({ input }) => {
685
+ const { stepNode, context } = input;
686
+ const injectables = this.#getInjectables();
687
+ const resolvedData = this.#resolveVariables({
688
+ stepConfig: stepNode.config,
689
+ context,
690
+ stepId: stepNode.step.id
691
+ });
692
+ this.logger.debug(`Resolved variables for ${stepNode.step.id}`, {
693
+ resolvedData,
694
+ runId: this.#runId
695
+ });
696
+ const result = await stepNode.config.handler({
697
+ context: resolvedData,
698
+ suspend: async () => {
699
+ if (this.#actor) {
700
+ context.steps[stepNode.step.id] = {
701
+ status: "suspended"
702
+ };
703
+ await this.#persistWorkflowSnapshot();
704
+ this.logger.debug(`Sending SUSPENDED event for step ${stepNode.step.id}`);
705
+ this.#actor?.send({ type: "SUSPENDED", stepId: stepNode.step.id });
706
+ } else {
707
+ this.logger.debug(`Actor not available for step ${stepNode.step.id}`);
708
+ }
709
+ },
710
+ ...injectables
711
+ });
712
+ this.logger.debug(`Step ${stepNode.step.id} result`, {
713
+ stepId: stepNode.step.id,
714
+ result,
715
+ runId: this.#runId
716
+ });
717
+ return {
718
+ stepId: stepNode.step.id,
719
+ result
720
+ };
721
+ }),
722
+ conditionCheck: fromPromise(async ({ input }) => {
723
+ const { context, stepNode } = input;
724
+ const stepConfig = stepNode.config;
725
+ const attemptCount = context.attempts[stepNode.step.id];
726
+ this.logger.debug(`Checking conditions for step ${stepNode.step.id}`, {
727
+ stepId: stepNode.step.id,
728
+ runId: this.#runId
729
+ });
730
+ this.logger.debug(`Attempt count for step ${stepNode.step.id}`, {
731
+ attemptCount,
732
+ attempts: context.attempts,
733
+ runId: this.#runId,
734
+ stepId: stepNode.step.id
735
+ });
736
+ if (!attemptCount || attemptCount < 0) {
737
+ if (stepConfig?.snapshotOnTimeout) {
738
+ return { type: "SUSPENDED", stepId: stepNode.step.id };
739
+ }
740
+ return { type: "CONDITION_FAILED", error: `Step:${stepNode.step.id} condition check failed` };
741
+ }
742
+ if (!stepConfig?.when) {
743
+ return { type: "CONDITIONS_MET" };
744
+ }
745
+ this.logger.debug(`Checking conditions for step ${stepNode.step.id}`, {
746
+ stepId: stepNode.step.id,
747
+ runId: this.#runId
748
+ });
749
+ if (typeof stepConfig?.when === "function") {
750
+ const conditionMet = await stepConfig.when({ context });
751
+ if (conditionMet) {
752
+ this.logger.debug(`Condition met for step ${stepNode.step.id}`, {
753
+ stepId: stepNode.step.id,
754
+ runId: this.#runId
755
+ });
756
+ return { type: "CONDITIONS_MET" };
757
+ }
758
+ if (!attemptCount || attemptCount < 0) {
759
+ return { type: "CONDITION_FAILED", error: `Step:${stepNode.step.id} condition check failed` };
760
+ }
761
+ return { type: "WAITING", stepId: stepNode.step.id };
762
+ } else {
763
+ const conditionMet = this.#evaluateCondition(stepConfig.when, context);
764
+ if (!conditionMet) {
765
+ return {
766
+ type: "CONDITION_FAILED",
767
+ error: `Step:${stepNode.step.id} condition check failed`
768
+ };
769
+ }
770
+ }
771
+ return { type: "CONDITIONS_MET" };
772
+ }),
773
+ spawnSubscriberFunction: fromPromise(
774
+ async ({
775
+ input
776
+ }) => {
777
+ const { parentStepId, context } = input;
778
+ const stepGraph = this.#stepSubscriberGraph[parentStepId];
779
+ if (!stepGraph) {
780
+ return {
781
+ steps: {}
782
+ };
783
+ }
784
+ const subscriberMachine = setup({
785
+ types: {},
786
+ delays: this.#makeDelayMap(),
787
+ actions: this.#getDefaultActions(),
788
+ actors: this.#getDefaultActors()
789
+ }).createMachine({
790
+ id: `${this.name}-subscriber-${parentStepId}`,
791
+ context,
792
+ type: "parallel",
793
+ states: this.#buildStateHierarchy(stepGraph)
794
+ });
795
+ const actor = createActor(subscriberMachine, { input: context });
796
+ actor.start();
797
+ return new Promise((resolve) => {
798
+ const suspendedPaths = /* @__PURE__ */ new Set();
799
+ actor.subscribe((state) => {
800
+ this.#getSuspendedPaths({
801
+ value: state.value,
802
+ path: "",
803
+ suspendedPaths
804
+ });
805
+ const allStatesValue = state.value;
806
+ const allStatesComplete = this.#recursivelyCheckForFinalState({
807
+ value: allStatesValue,
808
+ suspendedPaths,
809
+ path: ""
810
+ });
811
+ if (allStatesComplete) {
812
+ actor.stop();
813
+ resolve({
814
+ steps: state.context.steps
815
+ });
816
+ }
817
+ });
818
+ });
819
+ }
820
+ )
821
+ };
822
+ }
823
+ /**
824
+ * Persists the workflow state to the database
825
+ */
826
+ async #persistWorkflowSnapshot() {
827
+ const snapshotFromActor = this.#actor?.getPersistedSnapshot();
828
+ if (!this.#mastra?.storage) {
829
+ this.logger.debug("Snapshot cannot be persisted. Mastra engine is not initialized", {
830
+ runId: this.#runId
831
+ });
832
+ return;
833
+ }
834
+ if (!snapshotFromActor) {
835
+ this.logger.debug("Snapshot cannot be persisted. No snapshot received.", { runId: this.#runId });
836
+ return;
837
+ }
838
+ if (this.#mastra?.storage) {
839
+ await this.#mastra.storage.persistWorkflowSnapshot({
840
+ workflowName: this.name,
841
+ runId: this.#runId,
842
+ snapshot: snapshotFromActor
843
+ });
844
+ }
845
+ return this.#runId;
846
+ }
847
+ async #loadWorkflowSnapshot(runId) {
848
+ if (!this.#mastra?.storage) {
849
+ this.logger.debug("Snapshot cannot be loaded. Mastra engine is not initialized", { runId });
850
+ return;
851
+ }
852
+ return this.#mastra.storage.loadWorkflowSnapshot({ runId, workflowName: this.name });
853
+ }
854
+ /**
855
+ * Resolves variables for a step from trigger data or previous step results
856
+ * @param stepConfig - Configuration of the step needing variable resolution
857
+ * @param context - Current workflow context containing results and trigger data
858
+ * @returns Object containing resolved variable values
859
+ */
860
+ #resolveVariables({
861
+ stepConfig,
862
+ context,
863
+ stepId
864
+ }) {
865
+ this.logger.debug(`Resolving variables for step ${stepId}`, {
866
+ stepId,
867
+ runId: this.#runId
868
+ });
869
+ const resolvedData = {
870
+ ...context,
871
+ getStepPayload: (stepId2) => {
872
+ if (stepId2 === "trigger") {
873
+ return context.triggerData;
874
+ }
875
+ const result = context.steps[stepId2];
876
+ if (result && result.status === "success") {
877
+ return result.output;
878
+ }
879
+ return void 0;
880
+ }
881
+ };
882
+ for (const [key, variable] of Object.entries(stepConfig.data)) {
883
+ const sourceData = variable.step === "trigger" ? context.triggerData : getStepResult(context.steps[variable.step.id]);
884
+ this.logger.debug(
885
+ `Got source data for ${key} variable from ${variable.step === "trigger" ? "trigger" : variable.step.id}`,
886
+ {
887
+ sourceData,
888
+ path: variable.path,
889
+ runId: this.#runId
890
+ }
891
+ );
892
+ if (!sourceData && variable.step !== "trigger") {
893
+ resolvedData[key] = void 0;
894
+ continue;
895
+ }
896
+ const value = variable.path === "" || variable.path === "." ? sourceData : get(sourceData, variable.path);
897
+ this.logger.debug(`Resolved variable ${key}`, {
898
+ value,
899
+ runId: this.#runId
900
+ });
901
+ resolvedData[key] = value;
902
+ }
903
+ return resolvedData;
904
+ }
905
+ /**
906
+ * Evaluates a single condition against workflow context
907
+ */
908
+ #evaluateCondition(condition, context) {
909
+ let andBranchResult = true;
910
+ let baseResult = true;
911
+ let orBranchResult = true;
912
+ const simpleCondition = Object.entries(condition).find(([key]) => key.includes("."));
913
+ if (simpleCondition) {
914
+ const [key, queryValue] = simpleCondition;
915
+ const [stepId, ...pathParts] = key.split(".");
916
+ const path = pathParts.join(".");
917
+ const sourceData = stepId === "trigger" ? context.triggerData : getStepResult(context.steps[stepId]);
918
+ this.logger.debug(`Got condition data from step ${stepId}`, {
919
+ stepId,
920
+ sourceData,
921
+ runId: this.#runId
922
+ });
923
+ if (!sourceData) {
924
+ return false;
925
+ }
926
+ let value = get(sourceData, path);
927
+ if (stepId !== "trigger" && path === "status" && !value) {
928
+ value = "success";
929
+ }
930
+ if (typeof queryValue === "object" && queryValue !== null) {
931
+ baseResult = sift(queryValue)(value);
932
+ } else {
933
+ baseResult = value === queryValue;
934
+ }
935
+ }
936
+ if ("ref" in condition) {
937
+ const { ref, query } = condition;
938
+ const sourceData = ref.step === "trigger" ? context.triggerData : getStepResult(context.steps[ref.step.id]);
939
+ this.logger.debug(`Got condition data from ${ref.step === "trigger" ? "trigger" : ref.step.id}`, {
940
+ sourceData,
941
+ runId: this.#runId
942
+ });
943
+ if (!sourceData) {
944
+ return false;
945
+ }
946
+ let value = get(sourceData, ref.path);
947
+ if (ref.step !== "trigger" && ref.path === "status" && !value) {
948
+ value = "success";
949
+ }
950
+ baseResult = sift(query)(value);
951
+ }
952
+ if ("and" in condition) {
953
+ andBranchResult = condition.and.every((cond) => this.#evaluateCondition(cond, context));
954
+ this.logger.debug(`Evaluated AND condition`, {
955
+ andBranchResult,
956
+ runId: this.#runId
957
+ });
958
+ }
959
+ if ("or" in condition) {
960
+ orBranchResult = condition.or.some((cond) => this.#evaluateCondition(cond, context));
961
+ this.logger.debug(`Evaluated OR condition`, {
962
+ orBranchResult,
963
+ runId: this.#runId
964
+ });
965
+ }
966
+ const finalResult = baseResult && andBranchResult && orBranchResult;
967
+ this.logger.debug(`Evaluated condition`, {
968
+ finalResult,
969
+ runId: this.#runId
970
+ });
971
+ return finalResult;
972
+ }
973
+ #makeStepDef(stepId) {
974
+ const executeStep = (handler2, spanName, attributes) => {
975
+ return async (data) => {
976
+ return await context.with(trace.setSpan(context.active(), this.#executionSpan), async () => {
977
+ return this.#mastra.telemetry.traceMethod(handler2, {
978
+ spanName,
979
+ attributes
980
+ })(data);
981
+ });
982
+ };
983
+ };
984
+ const handler = async ({ context, ...rest }) => {
985
+ const targetStep = this.#steps[stepId];
986
+ if (!targetStep) throw new Error(`Step not found`);
987
+ const { payload = {}, execute } = targetStep;
988
+ const mergedData = {
989
+ ...payload,
990
+ ...context
991
+ };
992
+ const finalAction = this.#mastra?.telemetry ? executeStep(execute, `workflow.${this.name}.action.${stepId}`, {
993
+ componentName: this.name,
994
+ runId: context.runId ?? this.#runId
995
+ }) : execute;
996
+ return finalAction ? await finalAction({ context: mergedData, ...rest }) : {};
997
+ };
998
+ const finalHandler = ({ context, ...rest }) => {
999
+ if (this.#executionSpan) {
1000
+ return executeStep(handler, `workflow.${this.name}.step.${stepId}`, {
1001
+ componentName: this.name,
1002
+ runId: context.runId ?? this.#runId
1003
+ })({ context, ...rest });
1004
+ }
1005
+ return handler({ context, ...rest });
1006
+ };
1007
+ return {
1008
+ handler: finalHandler,
1009
+ data: {}
1010
+ };
1011
+ }
1012
+ /**
1013
+ * Creates a map of step IDs to their respective delay values
1014
+ * @returns Object mapping step IDs to delay values
1015
+ */
1016
+ #makeDelayMap() {
1017
+ const delayMap = {};
1018
+ Object.keys(this.#steps).forEach((stepId) => {
1019
+ delayMap[stepId] = this.#steps[stepId]?.retryConfig?.delay || this.#retryConfig?.delay || 1e3;
1020
+ });
1021
+ return delayMap;
1022
+ }
1023
+ /**
1024
+ * Cleans up the actor instance
1025
+ */
1026
+ #cleanup() {
1027
+ if (this.#actor) {
1028
+ this.#actor.stop();
1029
+ this.#actor = null;
1030
+ }
1031
+ }
1032
+ #getActivePathsAndStatus(value) {
1033
+ const paths = [];
1034
+ const traverse = (current, path = []) => {
1035
+ for (const [key, value2] of Object.entries(current)) {
1036
+ const currentPath = [...path, key];
1037
+ if (typeof value2 === "string") {
1038
+ paths.push({
1039
+ stepPath: currentPath,
1040
+ stepId: key,
1041
+ status: value2
1042
+ });
1043
+ } else if (typeof value2 === "object" && value2 !== null) {
1044
+ traverse(value2, currentPath);
1045
+ }
1046
+ }
1047
+ };
1048
+ traverse(value);
1049
+ return paths;
1050
+ }
1051
+ async getState(runId) {
1052
+ if (this.#runId === runId && this.#actor) {
1053
+ const snapshot = this.#actor.getSnapshot();
1054
+ const m = this.#getActivePathsAndStatus(snapshot.value);
1055
+ return {
1056
+ runId,
1057
+ value: snapshot.value,
1058
+ context: snapshot.context,
1059
+ activePaths: m,
1060
+ timestamp: Date.now()
1061
+ };
1062
+ }
1063
+ const storedSnapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
1064
+ runId,
1065
+ workflowName: this.name
1066
+ });
1067
+ if (storedSnapshot) {
1068
+ const parsed = storedSnapshot;
1069
+ const m = this.#getActivePathsAndStatus(parsed.value);
1070
+ return {
1071
+ runId,
1072
+ value: parsed.value,
1073
+ context: parsed.context,
1074
+ activePaths: m,
1075
+ timestamp: Date.now()
1076
+ };
1077
+ }
1078
+ return null;
1079
+ }
1080
+ watch(onTransition) {
1081
+ this.#onStepTransition.add(onTransition);
1082
+ return () => {
1083
+ this.#onStepTransition.delete(onTransition);
1084
+ };
1085
+ }
1086
+ async resume({
1087
+ runId,
1088
+ stepId,
1089
+ context: resumeContext
1090
+ }) {
1091
+ const snapshot = await this.#loadWorkflowSnapshot(runId);
1092
+ if (!snapshot) {
1093
+ throw new Error(`No snapshot found for workflow run ${runId}`);
1094
+ }
1095
+ let parsedSnapshot;
1096
+ try {
1097
+ parsedSnapshot = typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot;
1098
+ } catch (error) {
1099
+ this.logger.debug("Failed to parse workflow snapshot for resume", { error, runId });
1100
+ throw new Error("Failed to parse workflow snapshot");
1101
+ }
1102
+ if (resumeContext) {
1103
+ parsedSnapshot.context.steps[stepId] = {
1104
+ status: "success",
1105
+ output: {
1106
+ ...parsedSnapshot?.context?.steps?.[stepId]?.output || {},
1107
+ ...resumeContext
1108
+ }
1109
+ };
1110
+ }
1111
+ if (parsedSnapshot.children) {
1112
+ Object.entries(parsedSnapshot.children).forEach(([_childId, child]) => {
1113
+ if (child.snapshot?.input?.stepNode) {
1114
+ const stepDef = this.#makeStepDef(child.snapshot.input.stepNode.step.id);
1115
+ child.snapshot.input.stepNode.config = {
1116
+ ...child.snapshot.input.stepNode.config,
1117
+ ...stepDef
1118
+ };
1119
+ child.snapshot.input.context = parsedSnapshot.context;
1120
+ }
1121
+ });
1122
+ }
1123
+ const updateStepInHierarchy = (value, targetStepId) => {
1124
+ const result = {};
1125
+ for (const key of Object.keys(value)) {
1126
+ const currentValue = value[key];
1127
+ if (key === targetStepId) {
1128
+ result[key] = "pending";
1129
+ } else if (typeof currentValue === "object" && currentValue !== null) {
1130
+ result[key] = updateStepInHierarchy(currentValue, targetStepId);
1131
+ } else {
1132
+ result[key] = currentValue;
1133
+ }
1134
+ }
1135
+ return result;
1136
+ };
1137
+ parsedSnapshot.value = updateStepInHierarchy(parsedSnapshot.value, stepId);
1138
+ if (parsedSnapshot.context?.attempts) {
1139
+ parsedSnapshot.context.attempts[stepId] = this.#steps[stepId]?.retryConfig?.attempts || this.#retryConfig?.attempts || 3;
1140
+ }
1141
+ this.logger.debug("Resuming workflow with updated snapshot", {
1142
+ updatedSnapshot: parsedSnapshot,
1143
+ runId,
1144
+ stepId
1145
+ });
1146
+ return this.execute({
1147
+ snapshot: parsedSnapshot,
1148
+ runId,
1149
+ stepId
1150
+ });
1151
+ }
1152
+ __registerPrimitives(p) {
1153
+ if (p.telemetry) {
1154
+ this.__setTelemetry(p.telemetry);
1155
+ }
1156
+ if (p.logger) {
1157
+ this.__setLogger(p.logger);
1158
+ }
1159
+ this.#mastra = p;
1160
+ }
1161
+ get stepGraph() {
1162
+ return this.#stepGraph;
1163
+ }
1164
+ get stepSubscriberGraph() {
1165
+ return this.#stepSubscriberGraph;
1166
+ }
1167
+ get steps() {
1168
+ return this.#steps;
1169
+ }
1170
+ };
1171
+
1172
+ // src/workflows/step.ts
1173
+ var Step = class {
1174
+ id;
1175
+ description;
1176
+ inputSchema;
1177
+ outputSchema;
1178
+ payload;
1179
+ execute;
1180
+ retryConfig;
1181
+ mastra;
1182
+ constructor({
1183
+ id,
1184
+ description,
1185
+ execute,
1186
+ payload,
1187
+ outputSchema,
1188
+ inputSchema,
1189
+ retryConfig
1190
+ }) {
1191
+ this.id = id;
1192
+ this.description = description ?? "";
1193
+ this.inputSchema = inputSchema;
1194
+ this.payload = payload;
1195
+ this.outputSchema = outputSchema;
1196
+ this.execute = execute;
1197
+ this.retryConfig = retryConfig;
1198
+ }
1199
+ };
1200
+ function createStep(opts) {
1201
+ return new Step(opts);
1202
+ }
1203
+
1204
+ export { Step, Workflow, createStep, getStepResult, isErrorEvent, isTransitionEvent, isVariableReference };