@mastra/core 0.5.0-alpha.8 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/agent/index.cjs +3 -2100
  2. package/dist/agent/index.d.cts +1 -1
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/{base-CTdONy0_.d.cts → base-CIPKleAU.d.cts} +103 -70
  6. package/dist/{base-DIn_km7X.d.ts → base-C_Oq53qk.d.ts} +103 -70
  7. package/dist/base.cjs +5 -140
  8. package/dist/bundler/index.cjs +5 -160
  9. package/dist/chunk-2W2GYEYQ.cjs +25 -0
  10. package/dist/chunk-3ASEZT7U.cjs +1586 -0
  11. package/dist/chunk-43Y7WG5W.cjs +335 -0
  12. package/dist/{chunk-HBHPTMAC.js → chunk-4Y74D74B.js} +46 -6
  13. package/dist/chunk-ENT7U27Y.cjs +37 -0
  14. package/dist/chunk-F5UYWPV4.cjs +14 -0
  15. package/dist/chunk-FL3GQXQ2.cjs +218 -0
  16. package/dist/chunk-FRQFWZDN.cjs +2 -0
  17. package/dist/chunk-GXQRMKSN.cjs +367 -0
  18. package/dist/chunk-HJPMYDWO.cjs +37 -0
  19. package/dist/chunk-IIWRJFLQ.cjs +51 -0
  20. package/dist/chunk-KFQ7Z3PO.cjs +347 -0
  21. package/dist/{chunk-SWDQYPJS.js → chunk-KP5UAFLN.js} +3 -2
  22. package/dist/chunk-KPKFLQFR.cjs +12 -0
  23. package/dist/{chunk-RRJB4TCC.js → chunk-MLFXOST6.js} +1 -1
  24. package/dist/{chunk-KBSR2LLT.js → chunk-OD7ZMKHY.js} +176 -63
  25. package/dist/chunk-OTFLHXHZ.cjs +65 -0
  26. package/dist/chunk-RWTSGWWL.cjs +81 -0
  27. package/dist/chunk-ST5RMVLG.cjs +87 -0
  28. package/dist/chunk-SYQ7NK2E.cjs +24 -0
  29. package/dist/chunk-UZNQG7QO.cjs +1868 -0
  30. package/dist/chunk-V5ORZPFW.cjs +38 -0
  31. package/dist/chunk-VA4P7QJT.cjs +443 -0
  32. package/dist/chunk-WB2HREXE.cjs +166 -0
  33. package/dist/chunk-WOMOGDGR.cjs +691 -0
  34. package/dist/chunk-XB2TJ7LX.cjs +408 -0
  35. package/dist/{chunk-QABMKXI3.js → chunk-XF2FMJYK.js} +1 -1
  36. package/dist/chunk-XLSROQ26.cjs +91 -0
  37. package/dist/chunk-YK3XJ52U.cjs +192 -0
  38. package/dist/{chunk-SF5GHHOQ.js → chunk-YPD6BQIM.js} +121 -93
  39. package/dist/deployer/index.cjs +5 -167
  40. package/dist/eval/index.cjs +9 -105
  41. package/dist/eval/index.d.cts +1 -1
  42. package/dist/eval/index.d.ts +1 -1
  43. package/dist/hooks/index.cjs +14 -83
  44. package/dist/index.cjs +253 -7470
  45. package/dist/index.d.cts +4 -4
  46. package/dist/index.d.ts +4 -4
  47. package/dist/index.js +7 -7
  48. package/dist/integration/index.cjs +9 -108
  49. package/dist/integration/index.d.cts +1 -1
  50. package/dist/integration/index.d.ts +1 -1
  51. package/dist/llm/index.d.cts +1 -1
  52. package/dist/llm/index.d.ts +1 -1
  53. package/dist/logger/index.cjs +33 -161
  54. package/dist/mastra/index.cjs +3 -1755
  55. package/dist/mastra/index.d.cts +1 -1
  56. package/dist/mastra/index.d.ts +1 -1
  57. package/dist/mastra/index.js +1 -1
  58. package/dist/memory/index.cjs +4 -2050
  59. package/dist/memory/index.d.cts +1 -1
  60. package/dist/memory/index.d.ts +1 -1
  61. package/dist/memory/index.js +1 -1
  62. package/dist/relevance/index.cjs +10 -2161
  63. package/dist/relevance/index.d.cts +19 -2
  64. package/dist/relevance/index.d.ts +19 -2
  65. package/dist/relevance/index.js +1 -1
  66. package/dist/storage/index.cjs +29 -367
  67. package/dist/storage/index.d.cts +1 -1
  68. package/dist/storage/index.d.ts +1 -1
  69. package/dist/storage/libsql/index.cjs +9 -798
  70. package/dist/storage/libsql/index.d.cts +1 -1
  71. package/dist/storage/libsql/index.d.ts +1 -1
  72. package/dist/telemetry/index.cjs +21 -408
  73. package/dist/telemetry/index.d.cts +1 -1
  74. package/dist/telemetry/index.d.ts +1 -1
  75. package/dist/tools/index.cjs +11 -22
  76. package/dist/tools/index.d.cts +3 -3
  77. package/dist/tools/index.d.ts +3 -3
  78. package/dist/tts/index.cjs +3 -328
  79. package/dist/utils.cjs +41 -309
  80. package/dist/utils.d.cts +10 -4
  81. package/dist/utils.d.ts +10 -4
  82. package/dist/utils.js +1 -1
  83. package/dist/vector/filter/index.cjs +7 -189
  84. package/dist/vector/index.cjs +5 -172
  85. package/dist/vector/libsql/index.cjs +9 -1047
  86. package/dist/voice/index.cjs +8 -306
  87. package/dist/workflows/index.cjs +65 -1925
  88. package/dist/workflows/index.d.cts +4 -3
  89. package/dist/workflows/index.d.ts +4 -3
  90. package/dist/workflows/index.js +1 -1
  91. package/package.json +27 -27
@@ -0,0 +1,1868 @@
1
+ 'use strict';
2
+
3
+ var chunk43Y7WG5W_cjs = require('./chunk-43Y7WG5W.cjs');
4
+ var chunkIIWRJFLQ_cjs = require('./chunk-IIWRJFLQ.cjs');
5
+ var promises = require('timers/promises');
6
+ var api = require('@opentelemetry/api');
7
+ var EventEmitter = require('events');
8
+ var radash = require('radash');
9
+ var sift = require('sift');
10
+ var xstate = require('xstate');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
15
+ var sift__default = /*#__PURE__*/_interopDefault(sift);
16
+
17
+ // src/workflows/types.ts
18
+ var WhenConditionReturnValue = /* @__PURE__ */ ((WhenConditionReturnValue2) => {
19
+ WhenConditionReturnValue2["CONTINUE"] = "continue";
20
+ WhenConditionReturnValue2["CONTINUE_FAILED"] = "continue_failed";
21
+ WhenConditionReturnValue2["ABORT"] = "abort";
22
+ WhenConditionReturnValue2["LIMBO"] = "limbo";
23
+ return WhenConditionReturnValue2;
24
+ })(WhenConditionReturnValue || {});
25
+
26
+ // src/workflows/utils.ts
27
+ function isErrorEvent(stateEvent) {
28
+ return stateEvent.type.startsWith("xstate.error.actor.");
29
+ }
30
+ function isTransitionEvent(stateEvent) {
31
+ return stateEvent.type.startsWith("xstate.done.actor.");
32
+ }
33
+ function isVariableReference(value) {
34
+ return typeof value === "object" && "step" in value && "path" in value;
35
+ }
36
+ function getStepResult(result) {
37
+ if (result?.status === "success") return result.output;
38
+ return void 0;
39
+ }
40
+ function getSuspendedPaths({
41
+ value,
42
+ path,
43
+ suspendedPaths
44
+ }) {
45
+ if (typeof value === "string") {
46
+ if (value === "suspended") {
47
+ suspendedPaths.add(path);
48
+ }
49
+ } else {
50
+ Object.keys(value).forEach(
51
+ (key) => getSuspendedPaths({ value: value[key], path: path ? `${path}.${key}` : key, suspendedPaths })
52
+ );
53
+ }
54
+ }
55
+ function isFinalState(status) {
56
+ return ["completed", "failed"].includes(status);
57
+ }
58
+ function isLimboState(status) {
59
+ return status === "limbo";
60
+ }
61
+ function recursivelyCheckForFinalState({
62
+ value,
63
+ suspendedPaths,
64
+ path
65
+ }) {
66
+ if (typeof value === "string") {
67
+ return isFinalState(value) || isLimboState(value) || suspendedPaths.has(path);
68
+ }
69
+ return Object.keys(value).every(
70
+ (key) => recursivelyCheckForFinalState({ value: value[key], suspendedPaths, path: path ? `${path}.${key}` : key })
71
+ );
72
+ }
73
+ function getActivePathsAndStatus(value) {
74
+ const paths = [];
75
+ const traverse = (current, path = []) => {
76
+ for (const [key, value2] of Object.entries(current)) {
77
+ const currentPath = [...path, key];
78
+ if (typeof value2 === "string") {
79
+ paths.push({
80
+ stepPath: currentPath,
81
+ stepId: key,
82
+ status: value2
83
+ });
84
+ } else if (typeof value2 === "object" && value2 !== null) {
85
+ traverse(value2, currentPath);
86
+ }
87
+ }
88
+ };
89
+ traverse(value);
90
+ return paths;
91
+ }
92
+ function mergeChildValue(startStepId, parent, child) {
93
+ const traverse = (current) => {
94
+ const obj = {};
95
+ for (const [key, value] of Object.entries(current)) {
96
+ if (key === startStepId) {
97
+ obj[key] = { ...child };
98
+ } else if (typeof value === "string") {
99
+ obj[key] = value;
100
+ } else if (typeof value === "object" && value !== null) {
101
+ obj[key] = traverse(value);
102
+ }
103
+ }
104
+ return obj;
105
+ };
106
+ return traverse(parent);
107
+ }
108
+ var updateStepInHierarchy = (value, targetStepId) => {
109
+ const result = {};
110
+ for (const key of Object.keys(value)) {
111
+ const currentValue = value[key];
112
+ if (key === targetStepId) {
113
+ result[key] = "pending";
114
+ } else if (typeof currentValue === "object" && currentValue !== null) {
115
+ result[key] = updateStepInHierarchy(currentValue, targetStepId);
116
+ } else {
117
+ result[key] = currentValue;
118
+ }
119
+ }
120
+ return result;
121
+ };
122
+ function getResultActivePaths(state) {
123
+ return getActivePathsAndStatus(state.value).reduce((acc, curr) => {
124
+ const entry = { status: curr.status };
125
+ if (curr.status === "suspended") {
126
+ entry.suspendPayload = state.context.steps[curr.stepId].suspendPayload;
127
+ }
128
+ acc.set(curr.stepId, entry);
129
+ return acc;
130
+ }, /* @__PURE__ */ new Map());
131
+ }
132
+ var Machine = class extends EventEmitter__default.default {
133
+ logger;
134
+ #mastra;
135
+ #workflowInstance;
136
+ #executionSpan;
137
+ #stepGraph;
138
+ #machine;
139
+ #runId;
140
+ #startStepId;
141
+ name;
142
+ #actor = null;
143
+ #steps = {};
144
+ #retryConfig;
145
+ constructor({
146
+ logger,
147
+ mastra,
148
+ workflowInstance,
149
+ executionSpan,
150
+ name,
151
+ runId,
152
+ steps,
153
+ stepGraph,
154
+ retryConfig,
155
+ startStepId
156
+ }) {
157
+ super();
158
+ this.#mastra = mastra;
159
+ this.#workflowInstance = workflowInstance;
160
+ this.#executionSpan = executionSpan;
161
+ this.logger = logger;
162
+ this.#runId = runId;
163
+ this.#startStepId = startStepId;
164
+ this.name = name;
165
+ this.#stepGraph = stepGraph;
166
+ this.#steps = steps;
167
+ this.#retryConfig = retryConfig;
168
+ this.initializeMachine();
169
+ }
170
+ get startStepId() {
171
+ return this.#startStepId;
172
+ }
173
+ async execute({
174
+ stepId,
175
+ input,
176
+ snapshot
177
+ } = {}) {
178
+ if (snapshot) {
179
+ this.logger.debug(`Workflow snapshot received`, { runId: this.#runId, snapshot });
180
+ }
181
+ this.logger.debug(`Machine input prepared`, { runId: this.#runId, input });
182
+ const actorSnapshot = snapshot ? {
183
+ ...snapshot,
184
+ context: input
185
+ } : void 0;
186
+ this.logger.debug(`Creating actor with configuration`, {
187
+ input,
188
+ actorSnapshot,
189
+ runId: this.#runId,
190
+ machineStates: this.#machine.config.states
191
+ });
192
+ this.#actor = xstate.createActor(this.#machine, {
193
+ inspect: (inspectionEvent) => {
194
+ this.logger.debug("XState inspection event", {
195
+ type: inspectionEvent.type,
196
+ event: inspectionEvent.event,
197
+ runId: this.#runId
198
+ });
199
+ },
200
+ input,
201
+ snapshot: actorSnapshot
202
+ });
203
+ this.#actor.start();
204
+ if (stepId) {
205
+ this.#actor.send({ type: "RESET_TO_PENDING", stepId });
206
+ }
207
+ this.logger.debug("Actor started", { runId: this.#runId });
208
+ return new Promise((resolve, reject) => {
209
+ if (!this.#actor) {
210
+ const e = new Error("Actor not initialized");
211
+ this.#executionSpan?.recordException(e);
212
+ this.#executionSpan?.end();
213
+ reject(e);
214
+ return;
215
+ }
216
+ const suspendedPaths = /* @__PURE__ */ new Set();
217
+ this.#actor.subscribe(async (state) => {
218
+ this.emit("state-update", this.#startStepId, state.value, state.context);
219
+ getSuspendedPaths({
220
+ value: state.value,
221
+ path: "",
222
+ suspendedPaths
223
+ });
224
+ const allStatesValue = state.value;
225
+ const allStatesComplete = recursivelyCheckForFinalState({
226
+ value: allStatesValue,
227
+ suspendedPaths,
228
+ path: ""
229
+ });
230
+ this.logger.debug("State completion check", {
231
+ allStatesComplete,
232
+ suspendedPaths: Array.from(suspendedPaths),
233
+ runId: this.#runId
234
+ });
235
+ if (!allStatesComplete) return;
236
+ try {
237
+ await this.#workflowInstance.persistWorkflowSnapshot();
238
+ this.#cleanup();
239
+ this.#executionSpan?.end();
240
+ resolve({
241
+ results: state.context.steps,
242
+ activePaths: getResultActivePaths(
243
+ state
244
+ )
245
+ });
246
+ } catch (error) {
247
+ this.logger.debug("Failed to persist final snapshot", { error });
248
+ this.#cleanup();
249
+ this.#executionSpan?.end();
250
+ resolve({
251
+ results: state.context.steps,
252
+ activePaths: getResultActivePaths(
253
+ state
254
+ )
255
+ });
256
+ }
257
+ });
258
+ });
259
+ }
260
+ #cleanup() {
261
+ if (this.#actor) {
262
+ this.#actor.stop();
263
+ this.#actor = null;
264
+ }
265
+ this.removeAllListeners();
266
+ }
267
+ #makeDelayMap() {
268
+ const delayMap = {};
269
+ Object.keys(this.#steps).forEach((stepId) => {
270
+ delayMap[stepId] = this.#steps[stepId]?.retryConfig?.delay || this.#retryConfig?.delay || 1e3;
271
+ });
272
+ return delayMap;
273
+ }
274
+ #getDefaultActions() {
275
+ return {
276
+ updateStepResult: xstate.assign({
277
+ steps: ({ context, event }) => {
278
+ if (!isTransitionEvent(event)) return context.steps;
279
+ const { stepId, result } = event.output;
280
+ return {
281
+ ...context.steps,
282
+ [stepId]: {
283
+ status: "success",
284
+ output: result
285
+ }
286
+ };
287
+ }
288
+ }),
289
+ setStepError: xstate.assign({
290
+ steps: ({ context, event }, params) => {
291
+ if (!isErrorEvent(event)) return context.steps;
292
+ const { stepId } = params;
293
+ if (!stepId) return context.steps;
294
+ return {
295
+ ...context.steps,
296
+ [stepId]: {
297
+ status: "failed",
298
+ error: event.error.message
299
+ }
300
+ };
301
+ }
302
+ }),
303
+ notifyStepCompletion: async (_, params) => {
304
+ const { stepId } = params;
305
+ this.logger.debug(`Step ${stepId} completed`);
306
+ },
307
+ snapshotStep: xstate.assign({
308
+ _snapshot: ({}, params) => {
309
+ const { stepId } = params;
310
+ return { stepId };
311
+ }
312
+ }),
313
+ persistSnapshot: async ({ context }) => {
314
+ if (context._snapshot) {
315
+ await this.#workflowInstance.persistWorkflowSnapshot();
316
+ }
317
+ return;
318
+ },
319
+ decrementAttemptCount: xstate.assign({
320
+ attempts: ({ context, event }, params) => {
321
+ if (!isTransitionEvent(event)) return context.attempts;
322
+ const { stepId } = params;
323
+ const attemptCount = context.attempts[stepId];
324
+ if (attemptCount === void 0) return context.attempts;
325
+ return { ...context.attempts, [stepId]: attemptCount - 1 };
326
+ }
327
+ })
328
+ };
329
+ }
330
+ #getDefaultActors() {
331
+ return {
332
+ resolverFunction: xstate.fromPromise(async ({ input }) => {
333
+ const { stepNode, context } = input;
334
+ const attemptCount = context.attempts[stepNode.step.id];
335
+ const resolvedData = this.#resolveVariables({
336
+ stepConfig: stepNode.config,
337
+ context,
338
+ stepId: stepNode.step.id
339
+ });
340
+ this.logger.debug(`Resolved variables for ${stepNode.step.id}`, {
341
+ resolvedData,
342
+ runId: this.#runId
343
+ });
344
+ const logger = this.logger;
345
+ let mastraProxy = void 0;
346
+ if (this.#mastra) {
347
+ mastraProxy = chunk43Y7WG5W_cjs.createMastraProxy({ mastra: this.#mastra, logger });
348
+ }
349
+ let result = void 0;
350
+ try {
351
+ result = await stepNode.config.handler({
352
+ context: resolvedData,
353
+ suspend: async (payload) => {
354
+ await this.#workflowInstance.suspend(stepNode.step.id, this);
355
+ if (this.#actor) {
356
+ context.steps[stepNode.step.id] = {
357
+ status: "suspended",
358
+ suspendPayload: payload
359
+ };
360
+ this.logger.debug(`Sending SUSPENDED event for step ${stepNode.step.id}`);
361
+ this.#actor?.send({ type: "SUSPENDED", suspendPayload: payload, stepId: stepNode.step.id });
362
+ } else {
363
+ this.logger.debug(`Actor not available for step ${stepNode.step.id}`);
364
+ }
365
+ },
366
+ runId: this.#runId,
367
+ mastra: mastraProxy
368
+ });
369
+ } catch (error) {
370
+ this.logger.debug(`Step ${stepNode.step.id} failed`, {
371
+ stepId: stepNode.step.id,
372
+ error,
373
+ runId: this.#runId
374
+ });
375
+ this.logger.debug(`Attempt count for step ${stepNode.step.id}`, {
376
+ attemptCount,
377
+ attempts: context.attempts,
378
+ runId: this.#runId,
379
+ stepId: stepNode.step.id
380
+ });
381
+ if (!attemptCount || attemptCount < 0) {
382
+ return {
383
+ type: "STEP_FAILED",
384
+ error: error instanceof Error ? error.message : `Step:${stepNode.step.id} failed with error: ${error}`,
385
+ stepId: stepNode.step.id
386
+ };
387
+ }
388
+ return { type: "STEP_WAITING", stepId: stepNode.step.id };
389
+ }
390
+ this.logger.debug(`Step ${stepNode.step.id} result`, {
391
+ stepId: stepNode.step.id,
392
+ result,
393
+ runId: this.#runId
394
+ });
395
+ return {
396
+ type: "STEP_SUCCESS",
397
+ result,
398
+ stepId: stepNode.step.id
399
+ };
400
+ }),
401
+ conditionCheck: xstate.fromPromise(async ({ input }) => {
402
+ const { context, stepNode } = input;
403
+ const stepConfig = stepNode.config;
404
+ this.logger.debug(`Checking conditions for step ${stepNode.step.id}`, {
405
+ stepId: stepNode.step.id,
406
+ runId: this.#runId
407
+ });
408
+ if (!stepConfig?.when) {
409
+ return { type: "CONDITIONS_MET" };
410
+ }
411
+ this.logger.debug(`Checking conditions for step ${stepNode.step.id}`, {
412
+ stepId: stepNode.step.id,
413
+ runId: this.#runId
414
+ });
415
+ if (typeof stepConfig?.when === "function") {
416
+ let conditionMet = await stepConfig.when({
417
+ context: {
418
+ ...context,
419
+ getStepResult: (stepId) => {
420
+ const resolvedStepId = typeof stepId === "string" ? stepId : stepId.id;
421
+ if (resolvedStepId === "trigger") {
422
+ return context.triggerData;
423
+ }
424
+ const result = context.steps[resolvedStepId];
425
+ if (result && result.status === "success") {
426
+ return result.output;
427
+ }
428
+ return void 0;
429
+ }
430
+ },
431
+ mastra: this.#mastra
432
+ });
433
+ if (conditionMet === "abort" /* ABORT */) {
434
+ conditionMet = false;
435
+ } else if (conditionMet === "continue_failed" /* CONTINUE_FAILED */) {
436
+ return { type: "CONDITIONS_SKIPPED" };
437
+ } else if (conditionMet === "limbo" /* LIMBO */) {
438
+ return { type: "CONDITIONS_LIMBO" };
439
+ } else if (conditionMet) {
440
+ this.logger.debug(`Condition met for step ${stepNode.step.id}`, {
441
+ stepId: stepNode.step.id,
442
+ runId: this.#runId
443
+ });
444
+ return { type: "CONDITIONS_MET" };
445
+ }
446
+ return { type: "CONDITIONS_LIMBO" };
447
+ } else {
448
+ const conditionMet = this.#evaluateCondition(stepConfig.when, context);
449
+ if (!conditionMet) {
450
+ return {
451
+ type: "CONDITION_FAILED",
452
+ error: `Step:${stepNode.step.id} condition check failed`
453
+ };
454
+ }
455
+ }
456
+ return { type: "CONDITIONS_MET" };
457
+ }),
458
+ spawnSubscriberFunction: xstate.fromPromise(
459
+ async ({
460
+ input
461
+ }) => {
462
+ const { parentStepId, context } = input;
463
+ const result = await this.#workflowInstance.runMachine(parentStepId, context);
464
+ return Promise.resolve({
465
+ steps: result.reduce((acc, r) => {
466
+ return { ...acc, ...r?.results };
467
+ }, {})
468
+ });
469
+ }
470
+ )
471
+ };
472
+ }
473
+ #resolveVariables({
474
+ stepConfig,
475
+ context,
476
+ stepId
477
+ }) {
478
+ this.logger.debug(`Resolving variables for step ${stepId}`, {
479
+ stepId,
480
+ runId: this.#runId
481
+ });
482
+ const resolvedData = {
483
+ ...context,
484
+ getStepResult: (stepId2) => {
485
+ const resolvedStepId = typeof stepId2 === "string" ? stepId2 : stepId2.id;
486
+ if (resolvedStepId === "trigger") {
487
+ return context.triggerData;
488
+ }
489
+ const result = context.steps[resolvedStepId];
490
+ if (result && result.status === "success") {
491
+ return result.output;
492
+ }
493
+ return void 0;
494
+ }
495
+ };
496
+ for (const [key, variable] of Object.entries(stepConfig.data)) {
497
+ const sourceData = variable.step === "trigger" ? context.triggerData : getStepResult(context.steps[variable.step.id]);
498
+ this.logger.debug(
499
+ `Got source data for ${key} variable from ${variable.step === "trigger" ? "trigger" : variable.step.id}`,
500
+ {
501
+ sourceData,
502
+ path: variable.path,
503
+ runId: this.#runId
504
+ }
505
+ );
506
+ if (!sourceData && variable.step !== "trigger") {
507
+ resolvedData[key] = void 0;
508
+ continue;
509
+ }
510
+ const value = variable.path === "" || variable.path === "." ? sourceData : radash.get(sourceData, variable.path);
511
+ this.logger.debug(`Resolved variable ${key}`, {
512
+ value,
513
+ runId: this.#runId
514
+ });
515
+ resolvedData[key] = value;
516
+ }
517
+ return resolvedData;
518
+ }
519
+ initializeMachine() {
520
+ const machine = xstate.setup({
521
+ types: {},
522
+ delays: this.#makeDelayMap(),
523
+ actions: this.#getDefaultActions(),
524
+ actors: this.#getDefaultActors()
525
+ }).createMachine({
526
+ id: this.name,
527
+ type: "parallel",
528
+ context: ({ input }) => ({
529
+ ...input
530
+ }),
531
+ states: this.#buildStateHierarchy(this.#stepGraph)
532
+ });
533
+ this.#machine = machine;
534
+ return machine;
535
+ }
536
+ #buildStateHierarchy(stepGraph) {
537
+ const states = {};
538
+ stepGraph.initial.forEach((stepNode) => {
539
+ const nextSteps = [...stepGraph[stepNode.step.id] || []];
540
+ states[stepNode.step.id] = {
541
+ ...this.#buildBaseState(stepNode, nextSteps)
542
+ };
543
+ });
544
+ return states;
545
+ }
546
+ #buildBaseState(stepNode, nextSteps = []) {
547
+ const nextStep = nextSteps.shift();
548
+ return {
549
+ initial: "pending",
550
+ on: {
551
+ RESET_TO_PENDING: {
552
+ target: ".pending"
553
+ // Note the dot to target child state
554
+ }
555
+ },
556
+ states: {
557
+ pending: {
558
+ entry: () => {
559
+ this.logger.debug(`Step ${stepNode.step.id} pending`, {
560
+ stepId: stepNode.step.id,
561
+ runId: this.#runId
562
+ });
563
+ },
564
+ exit: () => {
565
+ this.logger.debug(`Step ${stepNode.step.id} finished pending`, {
566
+ stepId: stepNode.step.id,
567
+ runId: this.#runId
568
+ });
569
+ },
570
+ invoke: {
571
+ src: "conditionCheck",
572
+ input: ({ context }) => {
573
+ return {
574
+ context,
575
+ stepNode
576
+ };
577
+ },
578
+ onDone: [
579
+ {
580
+ guard: ({ event }) => {
581
+ return event.output.type === "SUSPENDED";
582
+ },
583
+ target: "suspended",
584
+ actions: [
585
+ xstate.assign({
586
+ steps: ({ context, event }) => {
587
+ if (event.output.type !== "SUSPENDED") return context.steps;
588
+ return {
589
+ ...context.steps,
590
+ [stepNode.step.id]: {
591
+ status: "suspended",
592
+ ...context.steps?.[stepNode.step.id] || {}
593
+ }
594
+ };
595
+ },
596
+ attempts: ({ context, event }) => {
597
+ if (event.output.type !== "SUSPENDED") return context.attempts;
598
+ return { ...context.attempts, [stepNode.step.id]: stepNode.step.retryConfig?.attempts || 3 };
599
+ }
600
+ })
601
+ ]
602
+ },
603
+ {
604
+ guard: ({ event }) => {
605
+ return event.output.type === "WAITING";
606
+ },
607
+ target: "waiting",
608
+ actions: [
609
+ { type: "decrementAttemptCount", params: { stepId: stepNode.step.id } },
610
+ xstate.assign({
611
+ steps: ({ context, event }) => {
612
+ if (event.output.type !== "WAITING") return context.steps;
613
+ return {
614
+ ...context.steps,
615
+ [stepNode.step.id]: {
616
+ status: "waiting"
617
+ }
618
+ };
619
+ }
620
+ })
621
+ ]
622
+ },
623
+ {
624
+ guard: ({ event }) => {
625
+ return event.output.type === "CONDITIONS_MET";
626
+ },
627
+ target: "executing"
628
+ },
629
+ {
630
+ guard: ({ event }) => {
631
+ return event.output.type === "CONDITIONS_SKIPPED";
632
+ },
633
+ target: "completed"
634
+ },
635
+ {
636
+ guard: ({ event }) => {
637
+ return event.output.type === "CONDITIONS_LIMBO";
638
+ },
639
+ target: "limbo",
640
+ actions: xstate.assign({
641
+ steps: ({ context }) => {
642
+ const newStep = {
643
+ ...context.steps,
644
+ [stepNode.step.id]: {
645
+ status: "skipped"
646
+ }
647
+ };
648
+ this.logger.debug(`Step ${stepNode.step.id} skipped`, {
649
+ stepId: stepNode.step.id,
650
+ runId: this.#runId
651
+ });
652
+ return newStep;
653
+ }
654
+ })
655
+ },
656
+ {
657
+ guard: ({ event }) => {
658
+ return event.output.type === "CONDITION_FAILED";
659
+ },
660
+ target: "failed",
661
+ actions: xstate.assign({
662
+ steps: ({ context, event }) => {
663
+ if (event.output.type !== "CONDITION_FAILED") return context.steps;
664
+ this.logger.debug(`Workflow condition check failed`, {
665
+ error: event.output.error,
666
+ stepId: stepNode.step.id
667
+ });
668
+ return {
669
+ ...context.steps,
670
+ [stepNode.step.id]: {
671
+ status: "failed",
672
+ error: event.output.error
673
+ }
674
+ };
675
+ }
676
+ })
677
+ }
678
+ ]
679
+ }
680
+ },
681
+ waiting: {
682
+ entry: () => {
683
+ this.logger.debug(`Step ${stepNode.step.id} waiting`, {
684
+ stepId: stepNode.step.id,
685
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
686
+ runId: this.#runId
687
+ });
688
+ },
689
+ exit: () => {
690
+ this.logger.debug(`Step ${stepNode.step.id} finished waiting`, {
691
+ stepId: stepNode.step.id,
692
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
693
+ runId: this.#runId
694
+ });
695
+ },
696
+ after: {
697
+ [stepNode.step.id]: {
698
+ target: "pending"
699
+ }
700
+ }
701
+ },
702
+ limbo: {
703
+ // no target, will stay in limbo indefinitely
704
+ entry: () => {
705
+ this.logger.debug(`Step ${stepNode.step.id} limbo`, {
706
+ stepId: stepNode.step.id,
707
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
708
+ runId: this.#runId
709
+ });
710
+ },
711
+ exit: () => {
712
+ this.logger.debug(`Step ${stepNode.step.id} finished limbo`, {
713
+ stepId: stepNode.step.id,
714
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
715
+ runId: this.#runId
716
+ });
717
+ }
718
+ },
719
+ suspended: {
720
+ type: "final",
721
+ entry: [
722
+ () => {
723
+ this.logger.debug(`Step ${stepNode.step.id} suspended`, {
724
+ stepId: stepNode.step.id,
725
+ runId: this.#runId
726
+ });
727
+ },
728
+ xstate.assign({
729
+ steps: ({ context, event }) => {
730
+ return {
731
+ ...context.steps,
732
+ [stepNode.step.id]: {
733
+ ...context?.steps?.[stepNode.step.id] || {},
734
+ status: "suspended",
735
+ suspendPayload: event.type === "SUSPENDED" ? event.suspendPayload : void 0
736
+ }
737
+ };
738
+ }
739
+ })
740
+ ]
741
+ },
742
+ executing: {
743
+ entry: () => {
744
+ this.logger.debug(`Step ${stepNode.step.id} executing`, {
745
+ stepId: stepNode.step.id,
746
+ runId: this.#runId
747
+ });
748
+ },
749
+ on: {
750
+ SUSPENDED: {
751
+ target: "suspended",
752
+ actions: [
753
+ xstate.assign({
754
+ steps: ({ context, event }) => {
755
+ return {
756
+ ...context.steps,
757
+ [stepNode.step.id]: {
758
+ status: "suspended",
759
+ suspendPayload: event.type === "SUSPENDED" ? event.suspendPayload : void 0
760
+ }
761
+ };
762
+ }
763
+ })
764
+ ]
765
+ }
766
+ },
767
+ invoke: {
768
+ src: "resolverFunction",
769
+ input: ({ context }) => ({
770
+ context,
771
+ stepNode
772
+ }),
773
+ onDone: [
774
+ {
775
+ guard: ({ event }) => {
776
+ return event.output.type === "STEP_FAILED";
777
+ },
778
+ target: "failed",
779
+ actions: xstate.assign({
780
+ steps: ({ context, event }) => {
781
+ if (event.output.type !== "STEP_FAILED") return context.steps;
782
+ const newStep = {
783
+ ...context.steps,
784
+ [stepNode.step.id]: {
785
+ status: "failed",
786
+ error: event.output.error
787
+ }
788
+ };
789
+ this.logger.debug(`Step ${stepNode.step.id} failed`, {
790
+ error: event.output.error,
791
+ stepId: stepNode.step.id
792
+ });
793
+ return newStep;
794
+ }
795
+ })
796
+ },
797
+ {
798
+ guard: ({ event }) => {
799
+ return event.output.type === "STEP_SUCCESS";
800
+ },
801
+ actions: [
802
+ ({ event }) => {
803
+ this.logger.debug(`Step ${stepNode.step.id} finished executing`, {
804
+ stepId: stepNode.step.id,
805
+ output: event.output,
806
+ runId: this.#runId
807
+ });
808
+ },
809
+ { type: "updateStepResult", params: { stepId: stepNode.step.id } },
810
+ { type: "spawnSubscribers", params: { stepId: stepNode.step.id } }
811
+ ],
812
+ target: "runningSubscribers"
813
+ },
814
+ {
815
+ guard: ({ event }) => {
816
+ return event.output.type === "STEP_WAITING";
817
+ },
818
+ target: "waiting",
819
+ actions: [
820
+ { type: "decrementAttemptCount", params: { stepId: stepNode.step.id } },
821
+ xstate.assign({
822
+ steps: ({ context, event }) => {
823
+ if (event.output.type !== "STEP_WAITING") return context.steps;
824
+ return {
825
+ ...context.steps,
826
+ [stepNode.step.id]: {
827
+ status: "waiting"
828
+ }
829
+ };
830
+ }
831
+ })
832
+ ]
833
+ }
834
+ ],
835
+ onError: {
836
+ target: "failed",
837
+ actions: [{ type: "setStepError", params: { stepId: stepNode.step.id } }]
838
+ }
839
+ }
840
+ },
841
+ runningSubscribers: {
842
+ entry: () => {
843
+ this.logger.debug(`Step ${stepNode.step.id} running subscribers`, {
844
+ stepId: stepNode.step.id,
845
+ runId: this.#runId
846
+ });
847
+ },
848
+ exit: () => {
849
+ this.logger.debug(`Step ${stepNode.step.id} finished running subscribers`, {
850
+ stepId: stepNode.step.id,
851
+ runId: this.#runId
852
+ });
853
+ },
854
+ invoke: {
855
+ src: "spawnSubscriberFunction",
856
+ input: ({ context }) => ({
857
+ parentStepId: stepNode.step.id,
858
+ context
859
+ }),
860
+ onDone: {
861
+ target: nextStep ? nextStep.step.id : "completed",
862
+ actions: [
863
+ xstate.assign({
864
+ steps: ({ context, event }) => ({
865
+ ...context.steps,
866
+ ...event.output.steps
867
+ })
868
+ }),
869
+ () => this.logger.debug(`Subscriber execution completed`, { stepId: stepNode.step.id })
870
+ ]
871
+ },
872
+ onError: {
873
+ target: nextStep ? nextStep.step.id : "completed",
874
+ actions: ({ event }) => {
875
+ this.logger.debug(`Subscriber execution failed`, {
876
+ error: event.error,
877
+ stepId: stepNode.step.id
878
+ });
879
+ }
880
+ }
881
+ }
882
+ },
883
+ completed: {
884
+ type: "final",
885
+ entry: [
886
+ { type: "notifyStepCompletion", params: { stepId: stepNode.step.id } },
887
+ { type: "snapshotStep", params: { stepId: stepNode.step.id } },
888
+ { type: "persistSnapshot" }
889
+ ]
890
+ },
891
+ failed: {
892
+ type: "final",
893
+ entry: [
894
+ { type: "notifyStepCompletion", params: { stepId: stepNode.step.id } },
895
+ { type: "snapshotStep", params: { stepId: stepNode.step.id } },
896
+ { type: "persistSnapshot" }
897
+ ]
898
+ },
899
+ // build chain of next steps recursively
900
+ ...nextStep ? { [nextStep.step.id]: { ...this.#buildBaseState(nextStep, nextSteps) } } : {}
901
+ }
902
+ };
903
+ }
904
+ #evaluateCondition(condition, context) {
905
+ let andBranchResult = true;
906
+ let baseResult = true;
907
+ let orBranchResult = true;
908
+ const simpleCondition = Object.entries(condition).find(([key]) => key.includes("."));
909
+ if (simpleCondition) {
910
+ const [key, queryValue] = simpleCondition;
911
+ const [stepId, ...pathParts] = key.split(".");
912
+ const path = pathParts.join(".");
913
+ const sourceData = stepId === "trigger" ? context.triggerData : getStepResult(context.steps[stepId]);
914
+ this.logger.debug(`Got condition data from step ${stepId}`, {
915
+ stepId,
916
+ sourceData,
917
+ runId: this.#runId
918
+ });
919
+ if (!sourceData) {
920
+ return false;
921
+ }
922
+ let value = radash.get(sourceData, path);
923
+ if (stepId !== "trigger" && path === "status" && !value) {
924
+ value = "success";
925
+ }
926
+ if (typeof queryValue === "object" && queryValue !== null) {
927
+ baseResult = sift__default.default(queryValue)(value);
928
+ } else {
929
+ baseResult = value === queryValue;
930
+ }
931
+ }
932
+ if ("ref" in condition) {
933
+ const { ref, query } = condition;
934
+ const sourceData = ref.step === "trigger" ? context.triggerData : getStepResult(context.steps[ref.step.id]);
935
+ this.logger.debug(`Got condition data from ${ref.step === "trigger" ? "trigger" : ref.step.id}`, {
936
+ sourceData,
937
+ runId: this.#runId
938
+ });
939
+ if (!sourceData) {
940
+ return false;
941
+ }
942
+ let value = radash.get(sourceData, ref.path);
943
+ if (ref.step !== "trigger" && ref.path === "status" && !value) {
944
+ value = "success";
945
+ }
946
+ baseResult = sift__default.default(query)(value);
947
+ }
948
+ if ("and" in condition) {
949
+ andBranchResult = condition.and.every((cond) => this.#evaluateCondition(cond, context));
950
+ this.logger.debug(`Evaluated AND condition`, {
951
+ andBranchResult,
952
+ runId: this.#runId
953
+ });
954
+ }
955
+ if ("or" in condition) {
956
+ orBranchResult = condition.or.some((cond) => this.#evaluateCondition(cond, context));
957
+ this.logger.debug(`Evaluated OR condition`, {
958
+ orBranchResult,
959
+ runId: this.#runId
960
+ });
961
+ }
962
+ if ("not" in condition) {
963
+ baseResult = !this.#evaluateCondition(condition.not, context);
964
+ this.logger.debug(`Evaluated NOT condition`, {
965
+ baseResult,
966
+ runId: this.#runId
967
+ });
968
+ }
969
+ const finalResult = baseResult && andBranchResult && orBranchResult;
970
+ this.logger.debug(`Evaluated condition`, {
971
+ finalResult,
972
+ runId: this.#runId
973
+ });
974
+ return finalResult;
975
+ }
976
+ getSnapshot() {
977
+ const snapshot = this.#actor?.getSnapshot();
978
+ return snapshot;
979
+ }
980
+ };
981
+
982
+ // src/workflows/workflow-instance.ts
983
+ var WorkflowInstance = class {
984
+ name;
985
+ #mastra;
986
+ #machines = {};
987
+ logger;
988
+ #steps = {};
989
+ #stepGraph;
990
+ #stepSubscriberGraph = {};
991
+ #retryConfig;
992
+ #runId;
993
+ #state = null;
994
+ #executionSpan;
995
+ #onStepTransition = /* @__PURE__ */ new Set();
996
+ #onFinish;
997
+ // indexed by stepId
998
+ #suspendedMachines = {};
999
+ // {step1&&step2: {step1: true, step2: true}}
1000
+ #compoundDependencies = {};
1001
+ constructor({
1002
+ name,
1003
+ logger,
1004
+ steps,
1005
+ runId,
1006
+ retryConfig,
1007
+ mastra,
1008
+ stepGraph,
1009
+ stepSubscriberGraph,
1010
+ onStepTransition,
1011
+ onFinish
1012
+ }) {
1013
+ this.name = name;
1014
+ this.logger = logger;
1015
+ this.#steps = steps;
1016
+ this.#stepGraph = stepGraph;
1017
+ this.#stepSubscriberGraph = stepSubscriberGraph;
1018
+ this.#retryConfig = retryConfig;
1019
+ this.#mastra = mastra;
1020
+ this.#runId = runId ?? crypto.randomUUID();
1021
+ this.#onStepTransition = onStepTransition;
1022
+ this.#onFinish = onFinish;
1023
+ this.#initializeCompoundDependencies();
1024
+ }
1025
+ setState(state) {
1026
+ this.#state = state;
1027
+ }
1028
+ get runId() {
1029
+ return this.#runId;
1030
+ }
1031
+ get executionSpan() {
1032
+ return this.#executionSpan;
1033
+ }
1034
+ async start({ triggerData } = {}) {
1035
+ const results = await this.execute({ triggerData });
1036
+ if (this.#onFinish) {
1037
+ this.#onFinish();
1038
+ }
1039
+ return {
1040
+ ...results,
1041
+ runId: this.runId
1042
+ };
1043
+ }
1044
+ isCompoundDependencyMet(stepKey) {
1045
+ if (!this.#isCompoundKey(stepKey)) return true;
1046
+ const dependencies = this.#compoundDependencies[stepKey];
1047
+ return dependencies ? Object.values(dependencies).every((status) => status === true) : true;
1048
+ }
1049
+ async execute({
1050
+ triggerData,
1051
+ snapshot,
1052
+ stepId
1053
+ } = {}) {
1054
+ this.#executionSpan = this.#mastra?.getTelemetry()?.tracer.startSpan(`workflow.${this.name}.execute`, {
1055
+ attributes: { componentName: this.name, runId: this.runId }
1056
+ });
1057
+ let machineInput = {
1058
+ // Maintain the original step results and their output
1059
+ steps: {},
1060
+ triggerData: triggerData || {},
1061
+ attempts: Object.keys(this.#steps).reduce(
1062
+ (acc, stepKey) => {
1063
+ acc[stepKey] = this.#steps[stepKey]?.retryConfig?.attempts || this.#retryConfig?.attempts || 3;
1064
+ return acc;
1065
+ },
1066
+ {}
1067
+ )
1068
+ };
1069
+ let stepGraph = this.#stepGraph;
1070
+ let startStepId = "trigger";
1071
+ if (snapshot) {
1072
+ const runState = snapshot;
1073
+ machineInput = runState.context;
1074
+ if (stepId && runState?.suspendedSteps?.[stepId]) {
1075
+ startStepId = runState.suspendedSteps[stepId];
1076
+ stepGraph = this.#stepSubscriberGraph[startStepId] ?? this.#stepGraph;
1077
+ }
1078
+ }
1079
+ const defaultMachine = new Machine({
1080
+ logger: this.logger,
1081
+ mastra: this.#mastra,
1082
+ workflowInstance: this,
1083
+ name: this.name,
1084
+ runId: this.runId,
1085
+ steps: this.#steps,
1086
+ stepGraph,
1087
+ executionSpan: this.#executionSpan,
1088
+ startStepId,
1089
+ retryConfig: this.#retryConfig
1090
+ });
1091
+ this.#machines[startStepId] = defaultMachine;
1092
+ const stateUpdateHandler = (startStepId2, state, context) => {
1093
+ if (startStepId2 === "trigger") {
1094
+ this.#state = state;
1095
+ } else {
1096
+ this.#state = mergeChildValue(startStepId2, this.#state, state);
1097
+ }
1098
+ const now = Date.now();
1099
+ if (this.#onStepTransition) {
1100
+ this.#onStepTransition.forEach((onTransition) => {
1101
+ void onTransition({
1102
+ runId: this.#runId,
1103
+ value: this.#state,
1104
+ context,
1105
+ activePaths: getActivePathsAndStatus(this.#state),
1106
+ timestamp: now
1107
+ });
1108
+ });
1109
+ }
1110
+ };
1111
+ defaultMachine.on("state-update", stateUpdateHandler);
1112
+ const { results, activePaths } = await defaultMachine.execute({ snapshot, stepId, input: machineInput });
1113
+ await this.persistWorkflowSnapshot();
1114
+ return { results, activePaths };
1115
+ }
1116
+ async runMachine(parentStepId, input) {
1117
+ const stepStatus = input.steps[parentStepId]?.status;
1118
+ const subscriberKeys = Object.keys(this.#stepSubscriberGraph).filter((key) => key.split("&&").includes(parentStepId));
1119
+ subscriberKeys.forEach((key) => {
1120
+ if (["success", "failure", "skipped"].includes(stepStatus) && this.#isCompoundKey(key)) {
1121
+ this.#compoundDependencies[key][parentStepId] = true;
1122
+ }
1123
+ });
1124
+ const stateUpdateHandler = (startStepId, state, context) => {
1125
+ if (startStepId === "trigger") {
1126
+ this.#state = state;
1127
+ } else {
1128
+ this.#state = mergeChildValue(startStepId, this.#state, state);
1129
+ }
1130
+ const now = Date.now();
1131
+ if (this.#onStepTransition) {
1132
+ this.#onStepTransition.forEach((onTransition) => {
1133
+ void onTransition({
1134
+ runId: this.#runId,
1135
+ value: this.#state,
1136
+ context,
1137
+ activePaths: getActivePathsAndStatus(this.#state),
1138
+ timestamp: now
1139
+ });
1140
+ });
1141
+ }
1142
+ };
1143
+ const results = await Promise.all(
1144
+ subscriberKeys.map(async (key) => {
1145
+ if (!this.#stepSubscriberGraph[key] || !this.isCompoundDependencyMet(key)) {
1146
+ return;
1147
+ }
1148
+ delete this.#compoundDependencies[key];
1149
+ const machine = new Machine({
1150
+ logger: this.logger,
1151
+ mastra: this.#mastra,
1152
+ workflowInstance: this,
1153
+ name: parentStepId === "trigger" ? this.name : `${this.name}-${parentStepId}`,
1154
+ runId: this.runId,
1155
+ steps: this.#steps,
1156
+ stepGraph: this.#stepSubscriberGraph[key],
1157
+ executionSpan: this.#executionSpan,
1158
+ startStepId: parentStepId
1159
+ });
1160
+ machine.on("state-update", stateUpdateHandler);
1161
+ this.#machines[parentStepId] = machine;
1162
+ return machine.execute({ input });
1163
+ })
1164
+ );
1165
+ return results;
1166
+ }
1167
+ async suspend(stepId, machine) {
1168
+ this.#suspendedMachines[stepId] = machine;
1169
+ }
1170
+ /**
1171
+ * Persists the workflow state to the database
1172
+ */
1173
+ async persistWorkflowSnapshot() {
1174
+ const existingSnapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
1175
+ workflowName: this.name,
1176
+ runId: this.#runId
1177
+ });
1178
+ const machineSnapshots = {};
1179
+ for (const [stepId, machine] of Object.entries(this.#machines)) {
1180
+ const machineSnapshot = machine?.getSnapshot();
1181
+ if (machineSnapshot) {
1182
+ machineSnapshots[stepId] = { ...machineSnapshot };
1183
+ }
1184
+ }
1185
+ let snapshot = machineSnapshots["trigger"];
1186
+ delete machineSnapshots["trigger"];
1187
+ const suspendedSteps = Object.entries(this.#suspendedMachines).reduce(
1188
+ (acc, [stepId, machine]) => {
1189
+ acc[stepId] = machine.startStepId;
1190
+ return acc;
1191
+ },
1192
+ {}
1193
+ );
1194
+ if (!snapshot && existingSnapshot) {
1195
+ existingSnapshot.childStates = { ...existingSnapshot.childStates, ...machineSnapshots };
1196
+ existingSnapshot.suspendedSteps = { ...existingSnapshot.suspendedSteps, ...suspendedSteps };
1197
+ await this.#mastra?.storage?.persistWorkflowSnapshot({
1198
+ workflowName: this.name,
1199
+ runId: this.#runId,
1200
+ snapshot: existingSnapshot
1201
+ });
1202
+ return;
1203
+ } else if (snapshot && !existingSnapshot) {
1204
+ snapshot.suspendedSteps = suspendedSteps;
1205
+ snapshot.childStates = { ...machineSnapshots };
1206
+ await this.#mastra?.storage?.persistWorkflowSnapshot({
1207
+ workflowName: this.name,
1208
+ runId: this.#runId,
1209
+ snapshot
1210
+ });
1211
+ return;
1212
+ } else if (!snapshot) {
1213
+ this.logger.debug("Snapshot cannot be persisted. No snapshot received.", { runId: this.#runId });
1214
+ return;
1215
+ }
1216
+ snapshot.suspendedSteps = { ...existingSnapshot.suspendedSteps, ...suspendedSteps };
1217
+ if (!existingSnapshot || snapshot === existingSnapshot) {
1218
+ await this.#mastra?.storage?.persistWorkflowSnapshot({
1219
+ workflowName: this.name,
1220
+ runId: this.#runId,
1221
+ snapshot
1222
+ });
1223
+ return;
1224
+ }
1225
+ if (existingSnapshot?.childStates) {
1226
+ snapshot.childStates = { ...existingSnapshot.childStates, ...machineSnapshots };
1227
+ } else {
1228
+ snapshot.childStates = machineSnapshots;
1229
+ }
1230
+ await this.#mastra?.storage?.persistWorkflowSnapshot({
1231
+ workflowName: this.name,
1232
+ runId: this.#runId,
1233
+ snapshot
1234
+ });
1235
+ }
1236
+ async getState() {
1237
+ const storedSnapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
1238
+ workflowName: this.name,
1239
+ runId: this.runId
1240
+ });
1241
+ const prevSnapshot = storedSnapshot ? {
1242
+ trigger: storedSnapshot,
1243
+ ...Object.entries(storedSnapshot?.childStates ?? {}).reduce(
1244
+ (acc, [stepId, snapshot2]) => ({ ...acc, [stepId]: snapshot2 }),
1245
+ {}
1246
+ )
1247
+ } : {};
1248
+ const currentSnapshot = Object.entries(this.#machines).reduce(
1249
+ (acc, [stepId, machine]) => {
1250
+ const snapshot2 = machine.getSnapshot();
1251
+ if (!snapshot2) {
1252
+ return acc;
1253
+ }
1254
+ return {
1255
+ ...acc,
1256
+ [stepId]: snapshot2
1257
+ };
1258
+ },
1259
+ {}
1260
+ );
1261
+ Object.assign(prevSnapshot, currentSnapshot);
1262
+ const trigger = prevSnapshot.trigger;
1263
+ delete prevSnapshot.trigger;
1264
+ const snapshot = { ...trigger};
1265
+ const m = getActivePathsAndStatus(prevSnapshot.value);
1266
+ return {
1267
+ runId: this.runId,
1268
+ value: snapshot.value,
1269
+ context: snapshot.context,
1270
+ activePaths: m,
1271
+ timestamp: Date.now()
1272
+ };
1273
+ }
1274
+ #initializeCompoundDependencies() {
1275
+ Object.keys(this.#stepSubscriberGraph).forEach((stepKey) => {
1276
+ if (this.#isCompoundKey(stepKey)) {
1277
+ const requiredSteps = stepKey.split("&&");
1278
+ this.#compoundDependencies[stepKey] = requiredSteps.reduce(
1279
+ (acc, step) => {
1280
+ acc[step] = false;
1281
+ return acc;
1282
+ },
1283
+ {}
1284
+ );
1285
+ }
1286
+ });
1287
+ }
1288
+ #isCompoundKey(key) {
1289
+ return key.includes("&&");
1290
+ }
1291
+ };
1292
+
1293
+ // src/workflows/workflow.ts
1294
+ var Workflow = class extends chunkIIWRJFLQ_cjs.MastraBase {
1295
+ name;
1296
+ triggerSchema;
1297
+ #retryConfig;
1298
+ #mastra;
1299
+ #runs = /* @__PURE__ */ new Map();
1300
+ // registers stepIds on `after` calls
1301
+ #afterStepStack = [];
1302
+ #lastStepStack = [];
1303
+ #ifStack = [];
1304
+ #stepGraph = { initial: [] };
1305
+ #stepSubscriberGraph = {};
1306
+ #steps = {};
1307
+ #onStepTransition = /* @__PURE__ */ new Set();
1308
+ /**
1309
+ * Creates a new Workflow instance
1310
+ * @param name - Identifier for the workflow (not necessarily unique)
1311
+ * @param logger - Optional logger instance
1312
+ */
1313
+ constructor({ name, triggerSchema, retryConfig, mastra }) {
1314
+ super({ component: "WORKFLOW", name });
1315
+ this.name = name;
1316
+ this.#retryConfig = retryConfig;
1317
+ this.triggerSchema = triggerSchema;
1318
+ if (mastra) {
1319
+ this.__registerPrimitives({
1320
+ telemetry: mastra.getTelemetry(),
1321
+ logger: mastra.getLogger()
1322
+ });
1323
+ this.#mastra = mastra;
1324
+ }
1325
+ }
1326
+ step(step, config) {
1327
+ const { variables = {} } = config || {};
1328
+ const requiredData = {};
1329
+ for (const [key, variable] of Object.entries(variables)) {
1330
+ if (variable && isVariableReference(variable)) {
1331
+ requiredData[key] = variable;
1332
+ }
1333
+ }
1334
+ const stepKey = this.#makeStepKey(step);
1335
+ const graphEntry = {
1336
+ step,
1337
+ config: {
1338
+ ...this.#makeStepDef(stepKey),
1339
+ ...config,
1340
+ serializedWhen: typeof config?.when === "function" ? config.when.toString() : config?.when,
1341
+ data: requiredData
1342
+ }
1343
+ };
1344
+ this.#steps[stepKey] = step;
1345
+ const parentStepKey = this.#afterStepStack[this.#afterStepStack.length - 1];
1346
+ const stepGraph = this.#stepSubscriberGraph[parentStepKey || ""];
1347
+ if (parentStepKey && stepGraph) {
1348
+ if (!stepGraph.initial.some((step2) => step2.step.id === stepKey)) {
1349
+ stepGraph.initial.push(graphEntry);
1350
+ }
1351
+ stepGraph[stepKey] = [];
1352
+ } else {
1353
+ if (!this.#stepGraph[stepKey]) this.#stepGraph[stepKey] = [];
1354
+ this.#stepGraph.initial.push(graphEntry);
1355
+ }
1356
+ this.#lastStepStack.push(stepKey);
1357
+ return this;
1358
+ }
1359
+ #makeStepKey(step) {
1360
+ return `${step.id}`;
1361
+ }
1362
+ then(step, config) {
1363
+ const { variables = {} } = config || {};
1364
+ const requiredData = {};
1365
+ for (const [key, variable] of Object.entries(variables)) {
1366
+ if (variable && isVariableReference(variable)) {
1367
+ requiredData[key] = variable;
1368
+ }
1369
+ }
1370
+ const lastStepKey = this.#lastStepStack[this.#lastStepStack.length - 1];
1371
+ const stepKey = this.#makeStepKey(step);
1372
+ const graphEntry = {
1373
+ step,
1374
+ config: {
1375
+ ...this.#makeStepDef(stepKey),
1376
+ ...config,
1377
+ serializedWhen: typeof config?.when === "function" ? config.when.toString() : config?.when,
1378
+ data: requiredData
1379
+ }
1380
+ };
1381
+ this.#steps[stepKey] = step;
1382
+ if (!lastStepKey) return this;
1383
+ const parentStepKey = this.#afterStepStack[this.#afterStepStack.length - 1];
1384
+ const stepGraph = this.#stepSubscriberGraph[parentStepKey || ""];
1385
+ if (parentStepKey && stepGraph && stepGraph[lastStepKey]) {
1386
+ stepGraph[lastStepKey].push(graphEntry);
1387
+ } else {
1388
+ if (!this.#stepGraph[lastStepKey]) this.#stepGraph[lastStepKey] = [];
1389
+ this.#stepGraph[lastStepKey].push(graphEntry);
1390
+ }
1391
+ return this;
1392
+ }
1393
+ loop(applyOperator, condition, fallbackStep, loopType) {
1394
+ const lastStepKey = this.#lastStepStack[this.#lastStepStack.length - 1];
1395
+ if (!lastStepKey) return this;
1396
+ const fallbackStepKey = this.#makeStepKey(fallbackStep);
1397
+ this.#steps[fallbackStepKey] = fallbackStep;
1398
+ const checkStepKey = `__${fallbackStepKey}_check`;
1399
+ const checkStep = {
1400
+ id: checkStepKey,
1401
+ execute: async ({ context }) => {
1402
+ if (typeof condition === "function") {
1403
+ const result = await condition({ context });
1404
+ if (loopType === "while") {
1405
+ return { status: result ? "continue" : "complete" };
1406
+ } else {
1407
+ return { status: result ? "complete" : "continue" };
1408
+ }
1409
+ }
1410
+ if (condition && "ref" in condition) {
1411
+ const { ref, query } = condition;
1412
+ const stepId = typeof ref.step === "string" ? ref.step : "id" in ref.step ? ref.step.id : null;
1413
+ if (!stepId) {
1414
+ return { status: "continue" };
1415
+ }
1416
+ const stepOutput = context.steps?.[stepId]?.output;
1417
+ if (!stepOutput) {
1418
+ return { status: "continue" };
1419
+ }
1420
+ const value = ref.path.split(".").reduce((obj, key) => obj?.[key], stepOutput);
1421
+ const operator = Object.keys(query)[0];
1422
+ const target = query[operator];
1423
+ return applyOperator(operator, value, target);
1424
+ }
1425
+ return { status: "continue" };
1426
+ }
1427
+ };
1428
+ this.#steps[checkStepKey] = checkStep;
1429
+ const loopFinishedStepKey = `__${fallbackStepKey}_loop_finished`;
1430
+ const loopFinishedStep = {
1431
+ id: loopFinishedStepKey,
1432
+ execute: async ({ context }) => {
1433
+ return { success: true };
1434
+ }
1435
+ };
1436
+ this.#steps[checkStepKey] = checkStep;
1437
+ this.then(checkStep);
1438
+ this.after(checkStep).step(fallbackStep, {
1439
+ when: async ({ context }) => {
1440
+ const checkStepResult = context.steps?.[checkStepKey];
1441
+ if (checkStepResult?.status !== "success") {
1442
+ return "abort" /* ABORT */;
1443
+ }
1444
+ const status = checkStepResult?.output?.status;
1445
+ return status === "continue" ? "continue" /* CONTINUE */ : "continue_failed" /* CONTINUE_FAILED */;
1446
+ }
1447
+ }).then(checkStep).step(loopFinishedStep, {
1448
+ when: async ({ context }) => {
1449
+ const checkStepResult = context.steps?.[checkStepKey];
1450
+ if (checkStepResult?.status !== "success") {
1451
+ return "continue_failed" /* CONTINUE_FAILED */;
1452
+ }
1453
+ const status = checkStepResult?.output?.status;
1454
+ return status === "complete" ? "continue" /* CONTINUE */ : "continue_failed" /* CONTINUE_FAILED */;
1455
+ }
1456
+ });
1457
+ return this;
1458
+ }
1459
+ while(condition, fallbackStep) {
1460
+ const applyOperator = (operator, value, target) => {
1461
+ switch (operator) {
1462
+ case "$eq":
1463
+ return { status: value !== target ? "complete" : "continue" };
1464
+ case "$ne":
1465
+ return { status: value === target ? "complete" : "continue" };
1466
+ case "$gt":
1467
+ return { status: value <= target ? "complete" : "continue" };
1468
+ case "$gte":
1469
+ return { status: value < target ? "complete" : "continue" };
1470
+ case "$lt":
1471
+ return { status: value >= target ? "complete" : "continue" };
1472
+ case "$lte":
1473
+ return { status: value > target ? "complete" : "continue" };
1474
+ default:
1475
+ return { status: "continue" };
1476
+ }
1477
+ };
1478
+ return this.loop(applyOperator, condition, fallbackStep, "while");
1479
+ }
1480
+ until(condition, fallbackStep) {
1481
+ const applyOperator = (operator, value, target) => {
1482
+ switch (operator) {
1483
+ case "$eq":
1484
+ return { status: value === target ? "complete" : "continue" };
1485
+ case "$ne":
1486
+ return { status: value !== target ? "complete" : "continue" };
1487
+ case "$gt":
1488
+ return { status: value > target ? "complete" : "continue" };
1489
+ case "$gte":
1490
+ return { status: value >= target ? "complete" : "continue" };
1491
+ case "$lt":
1492
+ return { status: value < target ? "complete" : "continue" };
1493
+ case "$lte":
1494
+ return { status: value <= target ? "complete" : "continue" };
1495
+ default:
1496
+ return { status: "continue" };
1497
+ }
1498
+ };
1499
+ return this.loop(applyOperator, condition, fallbackStep, "until");
1500
+ }
1501
+ if(condition) {
1502
+ const lastStep = this.#steps[this.#lastStepStack[this.#lastStepStack.length - 1] ?? ""];
1503
+ if (!lastStep) {
1504
+ throw new Error("Condition requires a step to be executed after");
1505
+ }
1506
+ this.after(lastStep);
1507
+ const ifStepKey = `__${lastStep.id}_if`;
1508
+ this.step(
1509
+ {
1510
+ id: ifStepKey,
1511
+ execute: async ({ context }) => {
1512
+ return { executed: true };
1513
+ }
1514
+ },
1515
+ {
1516
+ when: condition
1517
+ }
1518
+ );
1519
+ const elseStepKey = `__${lastStep.id}_else`;
1520
+ this.#ifStack.push({ condition, elseStepKey });
1521
+ return this;
1522
+ }
1523
+ else() {
1524
+ const activeCondition = this.#ifStack.pop();
1525
+ if (!activeCondition) {
1526
+ throw new Error("No active condition found");
1527
+ }
1528
+ this.step(
1529
+ {
1530
+ id: activeCondition.elseStepKey,
1531
+ execute: async ({ context }) => {
1532
+ return { executed: true };
1533
+ }
1534
+ },
1535
+ {
1536
+ when: typeof activeCondition.condition === "function" ? async (payload) => {
1537
+ const result = await activeCondition.condition(payload);
1538
+ return !result;
1539
+ } : { not: activeCondition.condition }
1540
+ }
1541
+ );
1542
+ return this;
1543
+ }
1544
+ after(steps) {
1545
+ const stepsArray = Array.isArray(steps) ? steps : [steps];
1546
+ const stepKeys = stepsArray.map((step) => this.#makeStepKey(step));
1547
+ const compoundKey = stepKeys.join("&&");
1548
+ this.#afterStepStack.push(compoundKey);
1549
+ if (!this.#stepSubscriberGraph[compoundKey]) {
1550
+ this.#stepSubscriberGraph[compoundKey] = { initial: [] };
1551
+ }
1552
+ return this;
1553
+ }
1554
+ /**
1555
+ * Executes the workflow with the given trigger data
1556
+ * @param triggerData - Initial data to start the workflow with
1557
+ * @returns Promise resolving to workflow results or rejecting with error
1558
+ * @throws Error if trigger schema validation fails
1559
+ */
1560
+ createRun() {
1561
+ const run = new WorkflowInstance({
1562
+ logger: this.logger,
1563
+ name: this.name,
1564
+ mastra: this.#mastra,
1565
+ retryConfig: this.#retryConfig,
1566
+ steps: this.#steps,
1567
+ stepGraph: this.#stepGraph,
1568
+ stepSubscriberGraph: this.#stepSubscriberGraph,
1569
+ onStepTransition: this.#onStepTransition,
1570
+ onFinish: () => {
1571
+ this.#runs.delete(run.runId);
1572
+ }
1573
+ });
1574
+ this.#runs.set(run.runId, run);
1575
+ return {
1576
+ start: run.start.bind(run),
1577
+ runId: run.runId
1578
+ };
1579
+ }
1580
+ /**
1581
+ * Rebuilds the machine with the current steps configuration and validates the workflow
1582
+ *
1583
+ * This is the last step of a workflow builder method chain
1584
+ * @throws Error if validation fails
1585
+ *
1586
+ * @returns this instance for method chaining
1587
+ */
1588
+ commit() {
1589
+ return this;
1590
+ }
1591
+ // record all object paths that leads to a suspended state
1592
+ #getSuspendedPaths({
1593
+ value,
1594
+ path,
1595
+ suspendedPaths
1596
+ }) {
1597
+ if (typeof value === "string") {
1598
+ if (value === "suspended") {
1599
+ suspendedPaths.add(path);
1600
+ }
1601
+ } else {
1602
+ Object.keys(value).forEach(
1603
+ (key) => this.#getSuspendedPaths({ value: value[key], path: path ? `${path}.${key}` : key, suspendedPaths })
1604
+ );
1605
+ }
1606
+ }
1607
+ async #loadWorkflowSnapshot(runId) {
1608
+ if (!this.#mastra?.storage) {
1609
+ this.logger.debug("Snapshot cannot be loaded. Mastra engine is not initialized", { runId });
1610
+ return;
1611
+ }
1612
+ const activeRun = this.#runs.get(runId);
1613
+ if (activeRun) {
1614
+ await activeRun.persistWorkflowSnapshot();
1615
+ }
1616
+ return this.#mastra.storage.loadWorkflowSnapshot({ runId, workflowName: this.name });
1617
+ }
1618
+ getExecutionSpan(runId) {
1619
+ return this.#runs.get(runId)?.executionSpan;
1620
+ }
1621
+ #makeStepDef(stepId) {
1622
+ const executeStep = (handler2, spanName, attributes) => {
1623
+ return async (data) => {
1624
+ return await api.context.with(
1625
+ api.trace.setSpan(api.context.active(), this.getExecutionSpan(attributes?.runId ?? data?.runId)),
1626
+ async () => {
1627
+ if (this?.telemetry) {
1628
+ return this.telemetry.traceMethod(handler2, {
1629
+ spanName,
1630
+ attributes
1631
+ })(data);
1632
+ } else {
1633
+ return handler2(data);
1634
+ }
1635
+ }
1636
+ );
1637
+ };
1638
+ };
1639
+ const handler = async ({ context, ...rest }) => {
1640
+ const targetStep = this.#steps[stepId];
1641
+ if (!targetStep) throw new Error(`Step not found`);
1642
+ const { payload = {}, execute = async () => {
1643
+ } } = targetStep;
1644
+ const mergedData = {
1645
+ ...payload,
1646
+ ...context
1647
+ };
1648
+ const finalAction = this.telemetry ? executeStep(execute, `workflow.${this.name}.action.${stepId}`, {
1649
+ componentName: this.name,
1650
+ runId: rest.runId
1651
+ }) : execute;
1652
+ return finalAction ? await finalAction({ context: mergedData, ...rest }) : {};
1653
+ };
1654
+ const finalHandler = ({ context, ...rest }) => {
1655
+ if (this.getExecutionSpan(rest?.runId)) {
1656
+ return executeStep(handler, `workflow.${this.name}.step.${stepId}`, {
1657
+ componentName: this.name,
1658
+ runId: rest?.runId
1659
+ })({ context, ...rest });
1660
+ }
1661
+ return handler({ context, ...rest });
1662
+ };
1663
+ return {
1664
+ handler: finalHandler,
1665
+ data: {}
1666
+ };
1667
+ }
1668
+ #getActivePathsAndStatus(value) {
1669
+ const paths = [];
1670
+ const traverse = (current, path = []) => {
1671
+ for (const [key, value2] of Object.entries(current)) {
1672
+ const currentPath = [...path, key];
1673
+ if (typeof value2 === "string") {
1674
+ paths.push({
1675
+ stepPath: currentPath,
1676
+ stepId: key,
1677
+ status: value2
1678
+ });
1679
+ } else if (typeof value2 === "object" && value2 !== null) {
1680
+ traverse(value2, currentPath);
1681
+ }
1682
+ }
1683
+ };
1684
+ traverse(value);
1685
+ return paths;
1686
+ }
1687
+ async getState(runId) {
1688
+ const run = this.#runs.get(runId);
1689
+ if (run) {
1690
+ return run.getState();
1691
+ }
1692
+ const storedSnapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
1693
+ runId,
1694
+ workflowName: this.name
1695
+ });
1696
+ if (storedSnapshot) {
1697
+ const parsed = storedSnapshot;
1698
+ const m = this.#getActivePathsAndStatus(parsed.value);
1699
+ return {
1700
+ runId,
1701
+ value: parsed.value,
1702
+ context: parsed.context,
1703
+ activePaths: m,
1704
+ timestamp: Date.now()
1705
+ };
1706
+ }
1707
+ return null;
1708
+ }
1709
+ watch(onTransition) {
1710
+ this.#onStepTransition.add(onTransition);
1711
+ return () => {
1712
+ this.#onStepTransition.delete(onTransition);
1713
+ };
1714
+ }
1715
+ async resume({
1716
+ runId,
1717
+ stepId,
1718
+ context: resumeContext
1719
+ }) {
1720
+ await promises.setTimeout(0);
1721
+ return this._resume({ runId, stepId, context: resumeContext });
1722
+ }
1723
+ async _resume({
1724
+ runId,
1725
+ stepId,
1726
+ context: resumeContext
1727
+ }) {
1728
+ const snapshot = await this.#loadWorkflowSnapshot(runId);
1729
+ if (!snapshot) {
1730
+ throw new Error(`No snapshot found for workflow run ${runId}`);
1731
+ }
1732
+ let parsedSnapshot;
1733
+ try {
1734
+ parsedSnapshot = typeof snapshot === "string" ? JSON.parse(snapshot) : snapshot;
1735
+ } catch (error) {
1736
+ this.logger.debug("Failed to parse workflow snapshot for resume", { error, runId });
1737
+ throw new Error("Failed to parse workflow snapshot");
1738
+ }
1739
+ const origSnapshot = parsedSnapshot;
1740
+ const startStepId = parsedSnapshot.suspendedSteps?.[stepId];
1741
+ if (!startStepId) {
1742
+ return;
1743
+ }
1744
+ parsedSnapshot = startStepId === "trigger" ? parsedSnapshot : { ...parsedSnapshot?.childStates?.[startStepId], ...{ suspendedSteps: parsedSnapshot.suspendedSteps } };
1745
+ if (!parsedSnapshot) {
1746
+ throw new Error(`No snapshot found for step: ${stepId} starting at ${startStepId}`);
1747
+ }
1748
+ if (resumeContext) {
1749
+ parsedSnapshot.context.steps[stepId] = {
1750
+ status: "success",
1751
+ output: {
1752
+ ...parsedSnapshot?.context?.steps?.[stepId]?.output || {},
1753
+ ...resumeContext
1754
+ }
1755
+ };
1756
+ }
1757
+ if (parsedSnapshot.children) {
1758
+ Object.entries(parsedSnapshot.children).forEach(([_childId, child]) => {
1759
+ if (child.snapshot?.input?.stepNode) {
1760
+ const stepDef = this.#makeStepDef(child.snapshot.input.stepNode.step.id);
1761
+ child.snapshot.input.stepNode.config = {
1762
+ ...child.snapshot.input.stepNode.config,
1763
+ ...stepDef
1764
+ };
1765
+ child.snapshot.input.context = parsedSnapshot.context;
1766
+ }
1767
+ });
1768
+ }
1769
+ parsedSnapshot.value = updateStepInHierarchy(parsedSnapshot.value, stepId);
1770
+ if (parsedSnapshot.context?.attempts) {
1771
+ parsedSnapshot.context.attempts[stepId] = this.#steps[stepId]?.retryConfig?.attempts || this.#retryConfig?.attempts || 3;
1772
+ }
1773
+ this.logger.debug("Resuming workflow with updated snapshot", {
1774
+ updatedSnapshot: parsedSnapshot,
1775
+ runId,
1776
+ stepId
1777
+ });
1778
+ const run = this.#runs.get(runId) ?? new WorkflowInstance({
1779
+ logger: this.logger,
1780
+ name: this.name,
1781
+ mastra: this.#mastra,
1782
+ retryConfig: this.#retryConfig,
1783
+ steps: this.#steps,
1784
+ stepGraph: this.#stepGraph,
1785
+ stepSubscriberGraph: this.#stepSubscriberGraph,
1786
+ onStepTransition: this.#onStepTransition,
1787
+ runId,
1788
+ onFinish: () => {
1789
+ this.#runs.delete(run.runId);
1790
+ }
1791
+ });
1792
+ run.setState(origSnapshot?.value);
1793
+ this.#runs.set(run.runId, run);
1794
+ return run?.execute({
1795
+ snapshot: parsedSnapshot,
1796
+ stepId
1797
+ });
1798
+ }
1799
+ __registerMastra(mastra) {
1800
+ this.#mastra = mastra;
1801
+ }
1802
+ __registerPrimitives(p) {
1803
+ if (p.telemetry) {
1804
+ this.__setTelemetry(p.telemetry);
1805
+ }
1806
+ if (p.logger) {
1807
+ this.__setLogger(p.logger);
1808
+ }
1809
+ }
1810
+ get stepGraph() {
1811
+ return this.#stepGraph;
1812
+ }
1813
+ get stepSubscriberGraph() {
1814
+ return this.#stepSubscriberGraph;
1815
+ }
1816
+ get steps() {
1817
+ return this.#steps;
1818
+ }
1819
+ };
1820
+
1821
+ // src/workflows/step.ts
1822
+ var Step = class {
1823
+ id;
1824
+ description;
1825
+ inputSchema;
1826
+ outputSchema;
1827
+ payload;
1828
+ execute;
1829
+ retryConfig;
1830
+ mastra;
1831
+ constructor({
1832
+ id,
1833
+ description,
1834
+ execute,
1835
+ payload,
1836
+ outputSchema,
1837
+ inputSchema,
1838
+ retryConfig
1839
+ }) {
1840
+ this.id = id;
1841
+ this.description = description ?? "";
1842
+ this.inputSchema = inputSchema;
1843
+ this.payload = payload;
1844
+ this.outputSchema = outputSchema;
1845
+ this.execute = execute;
1846
+ this.retryConfig = retryConfig;
1847
+ }
1848
+ };
1849
+ function createStep(opts) {
1850
+ return new Step(opts);
1851
+ }
1852
+
1853
+ exports.Step = Step;
1854
+ exports.WhenConditionReturnValue = WhenConditionReturnValue;
1855
+ exports.Workflow = Workflow;
1856
+ exports.createStep = createStep;
1857
+ exports.getActivePathsAndStatus = getActivePathsAndStatus;
1858
+ exports.getResultActivePaths = getResultActivePaths;
1859
+ exports.getStepResult = getStepResult;
1860
+ exports.getSuspendedPaths = getSuspendedPaths;
1861
+ exports.isErrorEvent = isErrorEvent;
1862
+ exports.isFinalState = isFinalState;
1863
+ exports.isLimboState = isLimboState;
1864
+ exports.isTransitionEvent = isTransitionEvent;
1865
+ exports.isVariableReference = isVariableReference;
1866
+ exports.mergeChildValue = mergeChildValue;
1867
+ exports.recursivelyCheckForFinalState = recursivelyCheckForFinalState;
1868
+ exports.updateStepInHierarchy = updateStepInHierarchy;