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