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