@mastra/inngest 0.0.0-ai-sdk-network-text-delta-20251017172601 → 0.0.0-alternative-angelfish-f7665c-20260119184917
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/CHANGELOG.md +1716 -3
- package/dist/__tests__/adapters/_utils.d.ts +18 -0
- package/dist/__tests__/adapters/_utils.d.ts.map +1 -0
- package/dist/execution-engine.d.ts +206 -0
- package/dist/execution-engine.d.ts.map +1 -0
- package/dist/index.cjs +2027 -1317
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +80 -297
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2111 -1404
- package/dist/index.js.map +1 -1
- package/dist/pubsub.d.ts +56 -0
- package/dist/pubsub.d.ts.map +1 -0
- package/dist/run.d.ts +175 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/serve.d.ts +76 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/types.d.ts +16 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/workflow.d.ts +52 -0
- package/dist/workflow.d.ts.map +1 -0
- package/package.json +33 -17
package/dist/index.js
CHANGED
|
@@ -1,434 +1,1502 @@
|
|
|
1
|
+
import { MessageList, Agent, TripWire } from '@mastra/core/agent';
|
|
2
|
+
import { getErrorFromUnknown, MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';
|
|
3
|
+
import { EntityType, SpanType } from '@mastra/core/observability';
|
|
4
|
+
import { ProcessorStepOutputSchema, ProcessorStepSchema, ProcessorRunner } from '@mastra/core/processors';
|
|
5
|
+
import { Tool } from '@mastra/core/tools';
|
|
6
|
+
import { DefaultExecutionEngine, createTimeTravelExecutionParams, Run, hydrateSerializedStepErrors, Workflow } from '@mastra/core/workflows';
|
|
7
|
+
import { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
|
|
8
|
+
import { z } from 'zod';
|
|
1
9
|
import { randomUUID } from 'crypto';
|
|
10
|
+
import { RequestContext } from '@mastra/core/di';
|
|
11
|
+
import { NonRetriableError } from 'inngest';
|
|
2
12
|
import { subscribe } from '@inngest/realtime';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { Run, Workflow, DefaultExecutionEngine, getStepResult, validateStepInput } from '@mastra/core/workflows';
|
|
7
|
-
import { EMITTER_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
|
|
8
|
-
import { NonRetriableError, RetryAfterError } from 'inngest';
|
|
13
|
+
import { PubSub } from '@mastra/core/events';
|
|
14
|
+
import { ReadableStream } from 'stream/web';
|
|
15
|
+
import { ChunkFrom, WorkflowRunOutput } from '@mastra/core/stream';
|
|
9
16
|
import { serve as serve$1 } from 'inngest/hono';
|
|
10
|
-
import { z } from 'zod';
|
|
11
17
|
|
|
12
18
|
// src/index.ts
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const workflowFunctions = Array.from(
|
|
21
|
-
new Set(
|
|
22
|
-
Object.values(wfs).flatMap((wf) => {
|
|
23
|
-
if (wf instanceof InngestWorkflow) {
|
|
24
|
-
wf.__registerMastra(mastra);
|
|
25
|
-
return wf.getFunctions();
|
|
26
|
-
}
|
|
27
|
-
return [];
|
|
28
|
-
})
|
|
29
|
-
)
|
|
30
|
-
);
|
|
31
|
-
return serve$1({
|
|
32
|
-
...registerOptions,
|
|
33
|
-
client: inngest,
|
|
34
|
-
functions: [...workflowFunctions, ...userFunctions]
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
var InngestRun = class extends Run {
|
|
38
|
-
inngest;
|
|
39
|
-
serializedStepGraph;
|
|
40
|
-
#mastra;
|
|
41
|
-
constructor(params, inngest) {
|
|
42
|
-
super(params);
|
|
43
|
-
this.inngest = inngest;
|
|
44
|
-
this.serializedStepGraph = params.serializedStepGraph;
|
|
45
|
-
this.#mastra = params.mastra;
|
|
19
|
+
var InngestExecutionEngine = class extends DefaultExecutionEngine {
|
|
20
|
+
inngestStep;
|
|
21
|
+
inngestAttempts;
|
|
22
|
+
constructor(mastra, inngestStep, inngestAttempts = 0, options) {
|
|
23
|
+
super({ mastra, options });
|
|
24
|
+
this.inngestStep = inngestStep;
|
|
25
|
+
this.inngestAttempts = inngestAttempts;
|
|
46
26
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
27
|
+
// =============================================================================
|
|
28
|
+
// Hook Overrides
|
|
29
|
+
// =============================================================================
|
|
30
|
+
/**
|
|
31
|
+
* Format errors while preserving Error instances and their custom properties.
|
|
32
|
+
* Uses getErrorFromUnknown to ensure all error properties are preserved.
|
|
33
|
+
*/
|
|
34
|
+
formatResultError(error, lastOutput) {
|
|
35
|
+
const outputError = lastOutput?.error;
|
|
36
|
+
const errorSource = error || outputError;
|
|
37
|
+
const errorInstance = getErrorFromUnknown(errorSource, {
|
|
38
|
+
serializeStack: true,
|
|
39
|
+
// Include stack in JSON for better debugging in Inngest
|
|
40
|
+
fallbackMessage: "Unknown workflow error"
|
|
52
41
|
});
|
|
53
|
-
|
|
54
|
-
return json.data;
|
|
42
|
+
return errorInstance.toJSON();
|
|
55
43
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Detect InngestWorkflow instances for special nested workflow handling
|
|
46
|
+
*/
|
|
47
|
+
isNestedWorkflowStep(step) {
|
|
48
|
+
return step instanceof InngestWorkflow;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Inngest requires requestContext serialization for memoization.
|
|
52
|
+
* When steps are replayed, the original function doesn't re-execute,
|
|
53
|
+
* so requestContext modifications must be captured and restored.
|
|
54
|
+
*/
|
|
55
|
+
requiresDurableContextSerialization() {
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Execute a step with retry logic for Inngest.
|
|
60
|
+
* Retries are handled via step-level retry (RetryAfterError thrown INSIDE step.run()).
|
|
61
|
+
* After retries exhausted, error propagates here and we return a failed result.
|
|
62
|
+
*/
|
|
63
|
+
async executeStepWithRetry(stepId, runStep, params) {
|
|
64
|
+
for (let i = 0; i < params.retries + 1; i++) {
|
|
65
|
+
if (i > 0 && params.delay) {
|
|
66
|
+
await new Promise((resolve) => setTimeout(resolve, params.delay));
|
|
69
67
|
}
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
68
|
+
try {
|
|
69
|
+
const result = await this.wrapDurableOperation(stepId, runStep);
|
|
70
|
+
return { ok: true, result };
|
|
71
|
+
} catch (e) {
|
|
72
|
+
if (i === params.retries) {
|
|
73
|
+
const cause = e?.cause;
|
|
74
|
+
if (cause?.status === "failed") {
|
|
75
|
+
params.stepSpan?.error({
|
|
76
|
+
error: e,
|
|
77
|
+
attributes: { status: "failed" }
|
|
78
|
+
});
|
|
79
|
+
if (cause.error && !(cause.error instanceof Error)) {
|
|
80
|
+
cause.error = getErrorFromUnknown(cause.error, { serializeStack: false });
|
|
81
|
+
}
|
|
82
|
+
return { ok: false, error: cause };
|
|
83
|
+
}
|
|
84
|
+
const errorInstance = getErrorFromUnknown(e, {
|
|
85
|
+
serializeStack: false,
|
|
86
|
+
fallbackMessage: "Unknown step execution error"
|
|
87
|
+
});
|
|
88
|
+
params.stepSpan?.error({
|
|
89
|
+
error: errorInstance,
|
|
90
|
+
attributes: { status: "failed" }
|
|
91
|
+
});
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
error: {
|
|
95
|
+
status: "failed",
|
|
96
|
+
error: errorInstance,
|
|
97
|
+
endedAt: Date.now()
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
76
101
|
}
|
|
77
102
|
}
|
|
78
|
-
return
|
|
103
|
+
return { ok: false, error: { status: "failed", error: new Error("Unknown error"), endedAt: Date.now() } };
|
|
79
104
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
});
|
|
105
|
+
/**
|
|
106
|
+
* Use Inngest's sleep primitive for durability
|
|
107
|
+
*/
|
|
108
|
+
async executeSleepDuration(duration, sleepId, workflowId) {
|
|
109
|
+
await this.inngestStep.sleep(`workflow.${workflowId}.sleep.${sleepId}`, duration < 0 ? 0 : duration);
|
|
85
110
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
111
|
+
/**
|
|
112
|
+
* Use Inngest's sleepUntil primitive for durability
|
|
113
|
+
*/
|
|
114
|
+
async executeSleepUntilDate(date, sleepUntilId, workflowId) {
|
|
115
|
+
await this.inngestStep.sleepUntil(`workflow.${workflowId}.sleepUntil.${sleepUntilId}`, date);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Wrap durable operations in Inngest step.run() for durability.
|
|
119
|
+
*
|
|
120
|
+
* IMPORTANT: Errors are wrapped with a cause structure before throwing.
|
|
121
|
+
* This is necessary because Inngest's error serialization (serialize-error-cjs)
|
|
122
|
+
* only captures standard Error properties (message, name, stack, code, cause).
|
|
123
|
+
* Custom properties like statusCode, responseHeaders from AI SDK errors would
|
|
124
|
+
* be lost. By putting our serialized error (via getErrorFromUnknown with toJSON())
|
|
125
|
+
* in the cause property, we ensure custom properties survive serialization.
|
|
126
|
+
* The cause property is in serialize-error-cjs's allowlist, and when the cause
|
|
127
|
+
* object is finally JSON.stringify'd, our error's toJSON() is called.
|
|
128
|
+
*/
|
|
129
|
+
async wrapDurableOperation(operationId, operationFn) {
|
|
130
|
+
return this.inngestStep.run(operationId, async () => {
|
|
131
|
+
try {
|
|
132
|
+
return await operationFn();
|
|
133
|
+
} catch (e) {
|
|
134
|
+
const errorInstance = getErrorFromUnknown(e, {
|
|
135
|
+
serializeStack: false,
|
|
136
|
+
fallbackMessage: "Unknown step execution error"
|
|
137
|
+
});
|
|
138
|
+
throw new Error(errorInstance.message, {
|
|
139
|
+
cause: {
|
|
140
|
+
status: "failed",
|
|
141
|
+
error: errorInstance,
|
|
142
|
+
endedAt: Date.now()
|
|
143
|
+
}
|
|
144
|
+
});
|
|
91
145
|
}
|
|
92
146
|
});
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Provide Inngest step primitive in engine context
|
|
150
|
+
*/
|
|
151
|
+
getEngineContext() {
|
|
152
|
+
return { step: this.inngestStep };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* For Inngest, lifecycle callbacks are invoked in the workflow's finalize step
|
|
156
|
+
* (wrapped in step.run for durability), not in execute(). Override to skip.
|
|
157
|
+
*/
|
|
158
|
+
async invokeLifecycleCallbacks(_result) {
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Actually invoke the lifecycle callbacks. Called from workflow.ts finalize step.
|
|
162
|
+
*/
|
|
163
|
+
async invokeLifecycleCallbacksInternal(result) {
|
|
164
|
+
return super.invokeLifecycleCallbacks(result);
|
|
165
|
+
}
|
|
166
|
+
// =============================================================================
|
|
167
|
+
// Durable Span Lifecycle Hooks
|
|
168
|
+
// =============================================================================
|
|
169
|
+
/**
|
|
170
|
+
* Create a step span durably - on first execution, creates and exports span.
|
|
171
|
+
* On replay, returns cached span data without re-creating.
|
|
172
|
+
*/
|
|
173
|
+
async createStepSpan(params) {
|
|
174
|
+
const { executionContext, operationId, options, parentSpan } = params;
|
|
175
|
+
const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;
|
|
176
|
+
const exportedSpan = await this.wrapDurableOperation(operationId, async () => {
|
|
177
|
+
const observability = this.mastra?.observability?.getSelectedInstance({});
|
|
178
|
+
if (!observability) return void 0;
|
|
179
|
+
const span = observability.startSpan({
|
|
180
|
+
...options,
|
|
181
|
+
entityType: options.entityType,
|
|
182
|
+
traceId: executionContext.tracingIds?.traceId,
|
|
183
|
+
parentSpanId
|
|
106
184
|
});
|
|
185
|
+
return span?.exportSpan();
|
|
186
|
+
});
|
|
187
|
+
if (exportedSpan) {
|
|
188
|
+
const observability = this.mastra?.observability?.getSelectedInstance({});
|
|
189
|
+
return observability?.rebuildSpan(exportedSpan);
|
|
107
190
|
}
|
|
191
|
+
return void 0;
|
|
108
192
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
snapshot: {
|
|
118
|
-
runId: this.runId,
|
|
119
|
-
serializedStepGraph: this.serializedStepGraph,
|
|
120
|
-
value: {},
|
|
121
|
-
context: {},
|
|
122
|
-
activePaths: [],
|
|
123
|
-
suspendedPaths: {},
|
|
124
|
-
resumeLabels: {},
|
|
125
|
-
waitingPaths: {},
|
|
126
|
-
timestamp: Date.now(),
|
|
127
|
-
status: "running"
|
|
128
|
-
}
|
|
193
|
+
/**
|
|
194
|
+
* End a step span durably.
|
|
195
|
+
*/
|
|
196
|
+
async endStepSpan(params) {
|
|
197
|
+
const { span, operationId, endOptions } = params;
|
|
198
|
+
if (!span) return;
|
|
199
|
+
await this.wrapDurableOperation(operationId, async () => {
|
|
200
|
+
span.end(endOptions);
|
|
129
201
|
});
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Record error on step span durably.
|
|
205
|
+
*/
|
|
206
|
+
async errorStepSpan(params) {
|
|
207
|
+
const { span, operationId, errorOptions } = params;
|
|
208
|
+
if (!span) return;
|
|
209
|
+
await this.wrapDurableOperation(operationId, async () => {
|
|
210
|
+
span.error(errorOptions);
|
|
140
211
|
});
|
|
141
|
-
const eventId = eventOutput.ids[0];
|
|
142
|
-
if (!eventId) {
|
|
143
|
-
throw new Error("Event ID is not set");
|
|
144
|
-
}
|
|
145
|
-
const runOutput = await this.getRunOutput(eventId);
|
|
146
|
-
const result = runOutput?.output?.result;
|
|
147
|
-
if (result.status === "failed") {
|
|
148
|
-
result.error = new Error(result.error);
|
|
149
|
-
}
|
|
150
|
-
if (result.status !== "suspended") {
|
|
151
|
-
this.cleanup?.();
|
|
152
|
-
}
|
|
153
|
-
return result;
|
|
154
212
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
213
|
+
/**
|
|
214
|
+
* Create a generic child span durably (for control-flow operations).
|
|
215
|
+
* On first execution, creates and exports span. On replay, returns cached span data.
|
|
216
|
+
*/
|
|
217
|
+
async createChildSpan(params) {
|
|
218
|
+
const { executionContext, operationId, options, parentSpan } = params;
|
|
219
|
+
const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;
|
|
220
|
+
const exportedSpan = await this.wrapDurableOperation(operationId, async () => {
|
|
221
|
+
const observability = this.mastra?.observability?.getSelectedInstance({});
|
|
222
|
+
if (!observability) return void 0;
|
|
223
|
+
const span = observability.startSpan({
|
|
224
|
+
...options,
|
|
225
|
+
traceId: executionContext.tracingIds?.traceId,
|
|
226
|
+
parentSpanId
|
|
227
|
+
});
|
|
228
|
+
return span?.exportSpan();
|
|
162
229
|
});
|
|
163
|
-
|
|
164
|
-
|
|
230
|
+
if (exportedSpan) {
|
|
231
|
+
const observability = this.mastra?.observability?.getSelectedInstance({});
|
|
232
|
+
return observability?.rebuildSpan(exportedSpan);
|
|
233
|
+
}
|
|
234
|
+
return void 0;
|
|
165
235
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
236
|
+
/**
|
|
237
|
+
* End a generic child span durably (for control-flow operations).
|
|
238
|
+
*/
|
|
239
|
+
async endChildSpan(params) {
|
|
240
|
+
const { span, operationId, endOptions } = params;
|
|
241
|
+
if (!span) return;
|
|
242
|
+
await this.wrapDurableOperation(operationId, async () => {
|
|
243
|
+
span.end(endOptions);
|
|
173
244
|
});
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
stepResults: snapshot?.context,
|
|
184
|
-
resume: {
|
|
185
|
-
steps,
|
|
186
|
-
stepResults: snapshot?.context,
|
|
187
|
-
resumePayload: resumeDataToUse,
|
|
188
|
-
// @ts-ignore
|
|
189
|
-
resumePath: snapshot?.suspendedPaths?.[steps?.[0]]
|
|
190
|
-
}
|
|
191
|
-
}
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Record error on a generic child span durably (for control-flow operations).
|
|
248
|
+
*/
|
|
249
|
+
async errorChildSpan(params) {
|
|
250
|
+
const { span, operationId, errorOptions } = params;
|
|
251
|
+
if (!span) return;
|
|
252
|
+
await this.wrapDurableOperation(operationId, async () => {
|
|
253
|
+
span.error(errorOptions);
|
|
192
254
|
});
|
|
193
|
-
const eventId = eventOutput.ids[0];
|
|
194
|
-
if (!eventId) {
|
|
195
|
-
throw new Error("Event ID is not set");
|
|
196
|
-
}
|
|
197
|
-
const runOutput = await this.getRunOutput(eventId);
|
|
198
|
-
const result = runOutput?.output?.result;
|
|
199
|
-
if (result.status === "failed") {
|
|
200
|
-
result.error = new Error(result.error);
|
|
201
|
-
}
|
|
202
|
-
return result;
|
|
203
255
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
256
|
+
/**
|
|
257
|
+
* Execute nested InngestWorkflow using inngestStep.invoke() for durability.
|
|
258
|
+
* This MUST be called directly (not inside step.run()) due to Inngest constraints.
|
|
259
|
+
*/
|
|
260
|
+
async executeWorkflowStep(params) {
|
|
261
|
+
if (!(params.step instanceof InngestWorkflow)) {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
const {
|
|
265
|
+
step,
|
|
266
|
+
stepResults,
|
|
267
|
+
executionContext,
|
|
268
|
+
resume,
|
|
269
|
+
timeTravel,
|
|
270
|
+
prevOutput,
|
|
271
|
+
inputData,
|
|
272
|
+
pubsub,
|
|
273
|
+
startedAt,
|
|
274
|
+
perStep,
|
|
275
|
+
stepSpan
|
|
276
|
+
} = params;
|
|
277
|
+
const nestedTracingContext = executionContext.tracingIds?.traceId ? {
|
|
278
|
+
traceId: executionContext.tracingIds.traceId,
|
|
279
|
+
parentSpanId: stepSpan?.id
|
|
280
|
+
} : void 0;
|
|
281
|
+
const isResume = !!resume?.steps?.length;
|
|
282
|
+
let result;
|
|
283
|
+
let runId;
|
|
284
|
+
const isTimeTravel = !!(timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === step.id);
|
|
285
|
+
try {
|
|
286
|
+
if (isResume) {
|
|
287
|
+
runId = stepResults[resume?.steps?.[0] ?? ""]?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();
|
|
288
|
+
const workflowsStore = await this.mastra?.getStorage()?.getStore("workflows");
|
|
289
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
290
|
+
workflowName: step.id,
|
|
291
|
+
runId
|
|
292
|
+
});
|
|
293
|
+
const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
|
|
294
|
+
function: step.getFunction(),
|
|
295
|
+
data: {
|
|
296
|
+
inputData,
|
|
297
|
+
initialState: executionContext.state ?? snapshot?.value ?? {},
|
|
298
|
+
runId,
|
|
299
|
+
resume: {
|
|
300
|
+
runId,
|
|
301
|
+
steps: resume.steps.slice(1),
|
|
302
|
+
stepResults: snapshot?.context,
|
|
303
|
+
resumePayload: resume.resumePayload,
|
|
304
|
+
resumePath: resume.steps?.[1] ? snapshot?.suspendedPaths?.[resume.steps?.[1]] : void 0
|
|
305
|
+
},
|
|
306
|
+
outputOptions: { includeState: true },
|
|
307
|
+
perStep,
|
|
308
|
+
tracingOptions: nestedTracingContext
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
result = invokeResp.result;
|
|
312
|
+
runId = invokeResp.runId;
|
|
313
|
+
executionContext.state = invokeResp.result.state;
|
|
314
|
+
} else if (isTimeTravel) {
|
|
315
|
+
const workflowsStoreForTimeTravel = await this.mastra?.getStorage()?.getStore("workflows");
|
|
316
|
+
const snapshot = await workflowsStoreForTimeTravel?.loadWorkflowSnapshot({
|
|
317
|
+
workflowName: step.id,
|
|
318
|
+
runId: executionContext.runId
|
|
319
|
+
}) ?? { context: {} };
|
|
320
|
+
const timeTravelParams = createTimeTravelExecutionParams({
|
|
321
|
+
steps: timeTravel.steps.slice(1),
|
|
322
|
+
inputData: timeTravel.inputData,
|
|
323
|
+
resumeData: timeTravel.resumeData,
|
|
324
|
+
context: timeTravel.nestedStepResults?.[step.id] ?? {},
|
|
325
|
+
nestedStepsContext: timeTravel.nestedStepResults ?? {},
|
|
326
|
+
snapshot,
|
|
327
|
+
graph: step.buildExecutionGraph()
|
|
328
|
+
});
|
|
329
|
+
const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
|
|
330
|
+
function: step.getFunction(),
|
|
331
|
+
data: {
|
|
332
|
+
timeTravel: timeTravelParams,
|
|
333
|
+
initialState: executionContext.state ?? {},
|
|
334
|
+
runId: executionContext.runId,
|
|
335
|
+
outputOptions: { includeState: true },
|
|
336
|
+
perStep,
|
|
337
|
+
tracingOptions: nestedTracingContext
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
result = invokeResp.result;
|
|
341
|
+
runId = invokeResp.runId;
|
|
342
|
+
executionContext.state = invokeResp.result.state;
|
|
343
|
+
} else {
|
|
344
|
+
const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
|
|
345
|
+
function: step.getFunction(),
|
|
346
|
+
data: {
|
|
347
|
+
inputData,
|
|
348
|
+
initialState: executionContext.state ?? {},
|
|
349
|
+
outputOptions: { includeState: true },
|
|
350
|
+
perStep,
|
|
351
|
+
tracingOptions: nestedTracingContext
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
result = invokeResp.result;
|
|
355
|
+
runId = invokeResp.runId;
|
|
356
|
+
executionContext.state = invokeResp.result.state;
|
|
216
357
|
}
|
|
217
|
-
)
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const writer = writable.getWriter();
|
|
230
|
-
const unwatch = this.watch(async (event) => {
|
|
231
|
-
try {
|
|
232
|
-
const e = {
|
|
233
|
-
...event,
|
|
234
|
-
type: event.type.replace("workflow-", "")
|
|
358
|
+
} catch (e) {
|
|
359
|
+
const errorCause = e?.cause;
|
|
360
|
+
if (errorCause && typeof errorCause === "object") {
|
|
361
|
+
result = errorCause;
|
|
362
|
+
runId = errorCause.runId || randomUUID();
|
|
363
|
+
} else {
|
|
364
|
+
runId = randomUUID();
|
|
365
|
+
result = {
|
|
366
|
+
status: "failed",
|
|
367
|
+
error: e instanceof Error ? e : new Error(String(e)),
|
|
368
|
+
steps: {},
|
|
369
|
+
input: inputData
|
|
235
370
|
};
|
|
236
|
-
await writer.write(e);
|
|
237
|
-
} catch {
|
|
238
371
|
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
372
|
+
}
|
|
373
|
+
const res = await this.inngestStep.run(
|
|
374
|
+
`workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,
|
|
375
|
+
async () => {
|
|
376
|
+
if (result.status === "failed") {
|
|
377
|
+
await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
|
|
378
|
+
type: "watch",
|
|
379
|
+
runId: executionContext.runId,
|
|
380
|
+
data: {
|
|
381
|
+
type: "workflow-step-result",
|
|
382
|
+
payload: {
|
|
383
|
+
id: step.id,
|
|
384
|
+
status: "failed",
|
|
385
|
+
error: result?.error,
|
|
386
|
+
payload: prevOutput
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
return { executionContext, result: { status: "failed", error: result?.error, endedAt: Date.now() } };
|
|
391
|
+
} else if (result.status === "suspended") {
|
|
392
|
+
const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
|
|
393
|
+
const stepRes = stepResult;
|
|
394
|
+
return stepRes?.status === "suspended";
|
|
395
|
+
});
|
|
396
|
+
for (const [stepName, stepResult] of suspendedSteps) {
|
|
397
|
+
const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
|
|
398
|
+
executionContext.suspendedPaths[step.id] = executionContext.executionPath;
|
|
399
|
+
await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
|
|
400
|
+
type: "watch",
|
|
401
|
+
runId: executionContext.runId,
|
|
402
|
+
data: {
|
|
403
|
+
type: "workflow-step-suspended",
|
|
404
|
+
payload: {
|
|
405
|
+
id: step.id,
|
|
406
|
+
status: "suspended"
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
return {
|
|
411
|
+
executionContext,
|
|
412
|
+
result: {
|
|
413
|
+
status: "suspended",
|
|
414
|
+
suspendedAt: Date.now(),
|
|
415
|
+
payload: stepResult.payload,
|
|
416
|
+
suspendPayload: {
|
|
417
|
+
...stepResult?.suspendPayload,
|
|
418
|
+
__workflow_meta: { runId, path: suspendPath }
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
return {
|
|
424
|
+
executionContext,
|
|
425
|
+
result: {
|
|
426
|
+
status: "suspended",
|
|
427
|
+
suspendedAt: Date.now(),
|
|
428
|
+
payload: {}
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
} else if (result.status === "tripwire") {
|
|
432
|
+
await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
|
|
433
|
+
type: "watch",
|
|
434
|
+
runId: executionContext.runId,
|
|
435
|
+
data: {
|
|
436
|
+
type: "workflow-step-result",
|
|
437
|
+
payload: {
|
|
438
|
+
id: step.id,
|
|
439
|
+
status: "tripwire",
|
|
440
|
+
error: result?.tripwire?.reason,
|
|
441
|
+
payload: prevOutput
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
});
|
|
445
|
+
return {
|
|
446
|
+
executionContext,
|
|
447
|
+
result: {
|
|
448
|
+
status: "tripwire",
|
|
449
|
+
tripwire: result?.tripwire,
|
|
450
|
+
endedAt: Date.now()
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
} else if (perStep || result.status === "paused") {
|
|
454
|
+
await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
|
|
455
|
+
type: "watch",
|
|
456
|
+
runId: executionContext.runId,
|
|
457
|
+
data: {
|
|
458
|
+
type: "workflow-step-result",
|
|
459
|
+
payload: {
|
|
460
|
+
id: step.id,
|
|
461
|
+
status: "paused"
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
|
|
466
|
+
type: "watch",
|
|
467
|
+
runId: executionContext.runId,
|
|
468
|
+
data: {
|
|
469
|
+
type: "workflow-step-finish",
|
|
470
|
+
payload: {
|
|
471
|
+
id: step.id,
|
|
472
|
+
metadata: {}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
return { executionContext, result: { status: "paused" } };
|
|
477
|
+
}
|
|
478
|
+
await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
|
|
479
|
+
type: "watch",
|
|
480
|
+
runId: executionContext.runId,
|
|
481
|
+
data: {
|
|
482
|
+
type: "workflow-step-result",
|
|
483
|
+
payload: {
|
|
484
|
+
id: step.id,
|
|
485
|
+
status: "success",
|
|
486
|
+
output: result?.result
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {
|
|
491
|
+
type: "watch",
|
|
492
|
+
runId: executionContext.runId,
|
|
493
|
+
data: {
|
|
494
|
+
type: "workflow-step-finish",
|
|
495
|
+
payload: {
|
|
496
|
+
id: step.id,
|
|
497
|
+
metadata: {}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
253
500
|
});
|
|
501
|
+
return { executionContext, result: { status: "success", output: result?.result, endedAt: Date.now() } };
|
|
254
502
|
}
|
|
255
|
-
|
|
256
|
-
|
|
503
|
+
);
|
|
504
|
+
Object.assign(executionContext, res.executionContext);
|
|
257
505
|
return {
|
|
258
|
-
|
|
259
|
-
|
|
506
|
+
...res.result,
|
|
507
|
+
startedAt,
|
|
508
|
+
payload: inputData,
|
|
509
|
+
resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
|
|
510
|
+
resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
|
|
260
511
|
};
|
|
261
512
|
}
|
|
262
513
|
};
|
|
263
|
-
var
|
|
264
|
-
#mastra;
|
|
514
|
+
var InngestPubSub = class extends PubSub {
|
|
265
515
|
inngest;
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
super(
|
|
271
|
-
const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(
|
|
272
|
-
([_, value]) => value !== void 0
|
|
273
|
-
);
|
|
274
|
-
this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : void 0;
|
|
275
|
-
this.#mastra = params.mastra;
|
|
516
|
+
workflowId;
|
|
517
|
+
publishFn;
|
|
518
|
+
subscriptions = /* @__PURE__ */ new Map();
|
|
519
|
+
constructor(inngest, workflowId, publishFn) {
|
|
520
|
+
super();
|
|
276
521
|
this.inngest = inngest;
|
|
522
|
+
this.workflowId = workflowId;
|
|
523
|
+
this.publishFn = publishFn;
|
|
277
524
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
525
|
+
/**
|
|
526
|
+
* Publish an event to Inngest's realtime system.
|
|
527
|
+
*
|
|
528
|
+
* Topic format: "workflow.events.v2.{runId}"
|
|
529
|
+
* Maps to Inngest channel: "workflow:{workflowId}:{runId}"
|
|
530
|
+
*/
|
|
531
|
+
async publish(topic, event) {
|
|
532
|
+
if (!this.publishFn) {
|
|
533
|
+
return;
|
|
283
534
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const storage = this.#mastra?.getStorage();
|
|
288
|
-
if (!storage) {
|
|
289
|
-
this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
|
|
290
|
-
return this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null;
|
|
535
|
+
const match = topic.match(/^workflow\.events\.v2\.(.+)$/);
|
|
536
|
+
if (!match) {
|
|
537
|
+
return;
|
|
291
538
|
}
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
} else if (step.type === "parallel" || step.type === "conditional") {
|
|
302
|
-
for (const subStep of step.steps) {
|
|
303
|
-
updateNested(subStep);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
};
|
|
307
|
-
if (this.executionGraph.steps.length) {
|
|
308
|
-
for (const step of this.executionGraph.steps) {
|
|
309
|
-
updateNested(step);
|
|
310
|
-
}
|
|
539
|
+
const runId = match[1];
|
|
540
|
+
try {
|
|
541
|
+
await this.publishFn({
|
|
542
|
+
channel: `workflow:${this.workflowId}:${runId}`,
|
|
543
|
+
topic: "watch",
|
|
544
|
+
data: event.data
|
|
545
|
+
});
|
|
546
|
+
} catch (err) {
|
|
547
|
+
console.error("InngestPubSub publish error:", err?.message ?? err);
|
|
311
548
|
}
|
|
312
549
|
}
|
|
313
550
|
/**
|
|
314
|
-
*
|
|
315
|
-
*
|
|
551
|
+
* Subscribe to events from Inngest's realtime system.
|
|
552
|
+
*
|
|
553
|
+
* Topic format: "workflow.events.v2.{runId}"
|
|
554
|
+
* Maps to Inngest channel: "workflow:{workflowId}:{runId}"
|
|
316
555
|
*/
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
556
|
+
async subscribe(topic, cb) {
|
|
557
|
+
const match = topic.match(/^workflow\.events\.v2\.(.+)$/);
|
|
558
|
+
if (!match || !match[1]) {
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
const runId = match[1];
|
|
562
|
+
if (this.subscriptions.has(topic)) {
|
|
563
|
+
this.subscriptions.get(topic).callbacks.add(cb);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
const callbacks = /* @__PURE__ */ new Set([cb]);
|
|
567
|
+
const channel = `workflow:${this.workflowId}:${runId}`;
|
|
568
|
+
const streamPromise = subscribe(
|
|
325
569
|
{
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
executionEngine: this.executionEngine,
|
|
330
|
-
executionGraph: this.executionGraph,
|
|
331
|
-
serializedStepGraph: this.serializedStepGraph,
|
|
332
|
-
mastra: this.#mastra,
|
|
333
|
-
retryConfig: this.retryConfig,
|
|
334
|
-
cleanup: () => this.runs.delete(runIdToUse),
|
|
335
|
-
workflowSteps: this.steps
|
|
570
|
+
channel,
|
|
571
|
+
topics: ["watch"],
|
|
572
|
+
app: this.inngest
|
|
336
573
|
},
|
|
337
|
-
|
|
574
|
+
(message) => {
|
|
575
|
+
const event = {
|
|
576
|
+
id: crypto.randomUUID(),
|
|
577
|
+
type: "watch",
|
|
578
|
+
runId,
|
|
579
|
+
data: message.data,
|
|
580
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
581
|
+
};
|
|
582
|
+
for (const callback of callbacks) {
|
|
583
|
+
callback(event);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
338
586
|
);
|
|
339
|
-
this.
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
587
|
+
this.subscriptions.set(topic, {
|
|
588
|
+
unsubscribe: () => {
|
|
589
|
+
streamPromise.then((stream) => stream.cancel()).catch((err) => {
|
|
590
|
+
console.error("InngestPubSub unsubscribe error:", err);
|
|
591
|
+
});
|
|
592
|
+
},
|
|
593
|
+
callbacks
|
|
343
594
|
});
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
suspendedPaths: {},
|
|
359
|
-
resumeLabels: {},
|
|
360
|
-
result: void 0,
|
|
361
|
-
error: void 0,
|
|
362
|
-
// @ts-ignore
|
|
363
|
-
timestamp: Date.now()
|
|
364
|
-
}
|
|
365
|
-
});
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Unsubscribe a callback from a topic.
|
|
598
|
+
* If no callbacks remain, the underlying Inngest subscription is cancelled.
|
|
599
|
+
*/
|
|
600
|
+
async unsubscribe(topic, cb) {
|
|
601
|
+
const sub = this.subscriptions.get(topic);
|
|
602
|
+
if (!sub) {
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
sub.callbacks.delete(cb);
|
|
606
|
+
if (sub.callbacks.size === 0) {
|
|
607
|
+
sub.unsubscribe();
|
|
608
|
+
this.subscriptions.delete(topic);
|
|
366
609
|
}
|
|
367
|
-
return run;
|
|
368
610
|
}
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
611
|
+
/**
|
|
612
|
+
* Flush any pending operations. No-op for Inngest.
|
|
613
|
+
*/
|
|
614
|
+
async flush() {
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Clean up all subscriptions during graceful shutdown.
|
|
618
|
+
*/
|
|
619
|
+
async close() {
|
|
620
|
+
for (const [, sub] of this.subscriptions) {
|
|
621
|
+
sub.unsubscribe();
|
|
372
622
|
}
|
|
373
|
-
this.
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
623
|
+
this.subscriptions.clear();
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
var InngestRun = class extends Run {
|
|
627
|
+
inngest;
|
|
628
|
+
serializedStepGraph;
|
|
629
|
+
#mastra;
|
|
630
|
+
constructor(params, inngest) {
|
|
631
|
+
super(params);
|
|
632
|
+
this.inngest = inngest;
|
|
633
|
+
this.serializedStepGraph = params.serializedStepGraph;
|
|
634
|
+
this.#mastra = params.mastra;
|
|
635
|
+
}
|
|
636
|
+
async getRuns(eventId) {
|
|
637
|
+
const maxRetries = 3;
|
|
638
|
+
let lastError = null;
|
|
639
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
640
|
+
try {
|
|
641
|
+
const response = await fetch(
|
|
642
|
+
`${this.inngest.apiBaseUrl ?? "https://api.inngest.com"}/v1/events/${eventId}/runs`,
|
|
643
|
+
{
|
|
644
|
+
headers: {
|
|
645
|
+
Authorization: `Bearer ${process.env.INNGEST_SIGNING_KEY}`
|
|
394
646
|
}
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
647
|
+
}
|
|
648
|
+
);
|
|
649
|
+
if (response.status === 429) {
|
|
650
|
+
const retryAfter = parseInt(response.headers.get("retry-after") || "2", 10);
|
|
651
|
+
await new Promise((resolve) => setTimeout(resolve, retryAfter * 1e3));
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
if (!response.ok) {
|
|
655
|
+
throw new Error(`Inngest API error: ${response.status} ${response.statusText}`);
|
|
656
|
+
}
|
|
657
|
+
const text = await response.text();
|
|
658
|
+
if (!text) {
|
|
659
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3 * (attempt + 1)));
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
const json = JSON.parse(text);
|
|
663
|
+
return json.data;
|
|
664
|
+
} catch (error) {
|
|
665
|
+
lastError = error;
|
|
666
|
+
if (attempt < maxRetries - 1) {
|
|
667
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt)));
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
throw new NonRetriableError(`Failed to get runs after ${maxRetries} attempts: ${lastError?.message}`);
|
|
672
|
+
}
|
|
673
|
+
async getRunOutput(eventId, maxWaitMs = 3e5) {
|
|
674
|
+
const startTime = Date.now();
|
|
675
|
+
const storage = this.#mastra?.getStorage();
|
|
676
|
+
const workflowsStore = await storage?.getStore("workflows");
|
|
677
|
+
while (Date.now() - startTime < maxWaitMs) {
|
|
678
|
+
let runs;
|
|
679
|
+
try {
|
|
680
|
+
runs = await this.getRuns(eventId);
|
|
681
|
+
} catch (error) {
|
|
682
|
+
if (error instanceof NonRetriableError) {
|
|
683
|
+
throw error;
|
|
684
|
+
}
|
|
685
|
+
throw new NonRetriableError(
|
|
686
|
+
`Failed to poll workflow status: ${error instanceof Error ? error.message : String(error)}`
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
if (runs?.[0]?.status === "Completed" && runs?.[0]?.event_id === eventId) {
|
|
690
|
+
return runs[0];
|
|
691
|
+
}
|
|
692
|
+
if (runs?.[0]?.status === "Failed") {
|
|
693
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
694
|
+
workflowName: this.workflowId,
|
|
695
|
+
runId: this.runId
|
|
696
|
+
});
|
|
697
|
+
if (snapshot?.context) {
|
|
698
|
+
snapshot.context = hydrateSerializedStepErrors(snapshot.context);
|
|
699
|
+
}
|
|
700
|
+
return {
|
|
701
|
+
output: {
|
|
702
|
+
result: {
|
|
703
|
+
steps: snapshot?.context,
|
|
704
|
+
status: "failed",
|
|
705
|
+
// Get the original error from NonRetriableError's cause (which contains the workflow result)
|
|
706
|
+
error: getErrorFromUnknown(runs?.[0]?.output?.cause?.error, { serializeStack: false })
|
|
403
707
|
}
|
|
404
|
-
},
|
|
405
|
-
on: (_event, _callback) => {
|
|
406
|
-
},
|
|
407
|
-
off: (_event, _callback) => {
|
|
408
|
-
},
|
|
409
|
-
once: (_event, _callback) => {
|
|
410
708
|
}
|
|
411
709
|
};
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
graph: this.executionGraph,
|
|
418
|
-
serializedStepGraph: this.serializedStepGraph,
|
|
419
|
-
input: inputData,
|
|
420
|
-
initialState,
|
|
421
|
-
emitter,
|
|
422
|
-
retryConfig: this.retryConfig,
|
|
423
|
-
runtimeContext: new RuntimeContext(),
|
|
424
|
-
// TODO
|
|
425
|
-
resume,
|
|
426
|
-
abortController: new AbortController(),
|
|
427
|
-
currentSpan: void 0,
|
|
428
|
-
// TODO: Pass actual parent AI span from workflow execution context
|
|
429
|
-
outputOptions
|
|
710
|
+
}
|
|
711
|
+
if (runs?.[0]?.status === "Cancelled") {
|
|
712
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
713
|
+
workflowName: this.workflowId,
|
|
714
|
+
runId: this.runId
|
|
430
715
|
});
|
|
431
|
-
|
|
716
|
+
return { output: { result: { steps: snapshot?.context, status: "canceled" } } };
|
|
717
|
+
}
|
|
718
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3 + Math.random() * 1e3));
|
|
719
|
+
}
|
|
720
|
+
throw new NonRetriableError(`Workflow did not complete within ${maxWaitMs}ms`);
|
|
721
|
+
}
|
|
722
|
+
async cancel() {
|
|
723
|
+
const storage = this.#mastra?.getStorage();
|
|
724
|
+
await this.inngest.send({
|
|
725
|
+
name: `cancel.workflow.${this.workflowId}`,
|
|
726
|
+
data: {
|
|
727
|
+
runId: this.runId
|
|
728
|
+
}
|
|
729
|
+
});
|
|
730
|
+
const workflowsStore = await storage?.getStore("workflows");
|
|
731
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
732
|
+
workflowName: this.workflowId,
|
|
733
|
+
runId: this.runId
|
|
734
|
+
});
|
|
735
|
+
if (snapshot) {
|
|
736
|
+
await workflowsStore?.persistWorkflowSnapshot({
|
|
737
|
+
workflowName: this.workflowId,
|
|
738
|
+
runId: this.runId,
|
|
739
|
+
resourceId: this.resourceId,
|
|
740
|
+
snapshot: {
|
|
741
|
+
...snapshot,
|
|
742
|
+
status: "canceled",
|
|
743
|
+
value: snapshot.value
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
async start(args) {
|
|
749
|
+
return this._start(args);
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Starts the workflow execution without waiting for completion (fire-and-forget).
|
|
753
|
+
* Returns immediately with the runId after sending the event to Inngest.
|
|
754
|
+
* The workflow executes independently in Inngest.
|
|
755
|
+
* Use this when you don't need to wait for the result or want to avoid polling failures.
|
|
756
|
+
*/
|
|
757
|
+
async startAsync(args) {
|
|
758
|
+
const workflowsStore = await this.#mastra.getStorage()?.getStore("workflows");
|
|
759
|
+
await workflowsStore?.persistWorkflowSnapshot({
|
|
760
|
+
workflowName: this.workflowId,
|
|
761
|
+
runId: this.runId,
|
|
762
|
+
resourceId: this.resourceId,
|
|
763
|
+
snapshot: {
|
|
764
|
+
runId: this.runId,
|
|
765
|
+
serializedStepGraph: this.serializedStepGraph,
|
|
766
|
+
status: "running",
|
|
767
|
+
value: {},
|
|
768
|
+
context: {},
|
|
769
|
+
activePaths: [],
|
|
770
|
+
suspendedPaths: {},
|
|
771
|
+
activeStepsPath: {},
|
|
772
|
+
resumeLabels: {},
|
|
773
|
+
waitingPaths: {},
|
|
774
|
+
timestamp: Date.now()
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
const inputDataToUse = await this._validateInput(args.inputData);
|
|
778
|
+
const initialStateToUse = await this._validateInitialState(args.initialState ?? {});
|
|
779
|
+
const eventOutput = await this.inngest.send({
|
|
780
|
+
name: `workflow.${this.workflowId}`,
|
|
781
|
+
data: {
|
|
782
|
+
inputData: inputDataToUse,
|
|
783
|
+
initialState: initialStateToUse,
|
|
784
|
+
runId: this.runId,
|
|
785
|
+
resourceId: this.resourceId,
|
|
786
|
+
outputOptions: args.outputOptions,
|
|
787
|
+
tracingOptions: args.tracingOptions,
|
|
788
|
+
requestContext: args.requestContext ? Object.fromEntries(args.requestContext.entries()) : {},
|
|
789
|
+
perStep: args.perStep
|
|
790
|
+
}
|
|
791
|
+
});
|
|
792
|
+
const eventId = eventOutput.ids[0];
|
|
793
|
+
if (!eventId) {
|
|
794
|
+
throw new Error("Event ID is not set");
|
|
795
|
+
}
|
|
796
|
+
return { runId: this.runId };
|
|
797
|
+
}
|
|
798
|
+
async _start({
|
|
799
|
+
inputData,
|
|
800
|
+
initialState,
|
|
801
|
+
outputOptions,
|
|
802
|
+
tracingOptions,
|
|
803
|
+
format,
|
|
804
|
+
requestContext,
|
|
805
|
+
perStep
|
|
806
|
+
}) {
|
|
807
|
+
const workflowsStore = await this.#mastra.getStorage()?.getStore("workflows");
|
|
808
|
+
await workflowsStore?.persistWorkflowSnapshot({
|
|
809
|
+
workflowName: this.workflowId,
|
|
810
|
+
runId: this.runId,
|
|
811
|
+
resourceId: this.resourceId,
|
|
812
|
+
snapshot: {
|
|
813
|
+
runId: this.runId,
|
|
814
|
+
serializedStepGraph: this.serializedStepGraph,
|
|
815
|
+
status: "running",
|
|
816
|
+
value: {},
|
|
817
|
+
context: {},
|
|
818
|
+
activePaths: [],
|
|
819
|
+
suspendedPaths: {},
|
|
820
|
+
activeStepsPath: {},
|
|
821
|
+
resumeLabels: {},
|
|
822
|
+
waitingPaths: {},
|
|
823
|
+
timestamp: Date.now()
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
const inputDataToUse = await this._validateInput(inputData);
|
|
827
|
+
const initialStateToUse = await this._validateInitialState(initialState ?? {});
|
|
828
|
+
const eventOutput = await this.inngest.send({
|
|
829
|
+
name: `workflow.${this.workflowId}`,
|
|
830
|
+
data: {
|
|
831
|
+
inputData: inputDataToUse,
|
|
832
|
+
initialState: initialStateToUse,
|
|
833
|
+
runId: this.runId,
|
|
834
|
+
resourceId: this.resourceId,
|
|
835
|
+
outputOptions,
|
|
836
|
+
tracingOptions,
|
|
837
|
+
format,
|
|
838
|
+
requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {},
|
|
839
|
+
perStep
|
|
840
|
+
}
|
|
841
|
+
});
|
|
842
|
+
const eventId = eventOutput.ids[0];
|
|
843
|
+
if (!eventId) {
|
|
844
|
+
throw new Error("Event ID is not set");
|
|
845
|
+
}
|
|
846
|
+
const runOutput = await this.getRunOutput(eventId);
|
|
847
|
+
const result = runOutput?.output?.result;
|
|
848
|
+
this.hydrateFailedResult(result);
|
|
849
|
+
if (result.status !== "suspended") {
|
|
850
|
+
this.cleanup?.();
|
|
851
|
+
}
|
|
852
|
+
return result;
|
|
853
|
+
}
|
|
854
|
+
async resume(params) {
|
|
855
|
+
const p = this._resume(params).then((result) => {
|
|
856
|
+
if (result.status !== "suspended") {
|
|
857
|
+
this.closeStreamAction?.().catch(() => {
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
return result;
|
|
861
|
+
});
|
|
862
|
+
this.executionResults = p;
|
|
863
|
+
return p;
|
|
864
|
+
}
|
|
865
|
+
async _resume(params) {
|
|
866
|
+
const storage = this.#mastra?.getStorage();
|
|
867
|
+
let steps = [];
|
|
868
|
+
if (typeof params.step === "string") {
|
|
869
|
+
steps = params.step.split(".");
|
|
870
|
+
} else {
|
|
871
|
+
steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
|
|
872
|
+
(step) => typeof step === "string" ? step : step?.id
|
|
873
|
+
);
|
|
874
|
+
}
|
|
875
|
+
const workflowsStore = await storage?.getStore("workflows");
|
|
876
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
877
|
+
workflowName: this.workflowId,
|
|
878
|
+
runId: this.runId
|
|
879
|
+
});
|
|
880
|
+
const suspendedStep = this.workflowSteps[steps?.[0] ?? ""];
|
|
881
|
+
const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);
|
|
882
|
+
const persistedRequestContext = snapshot?.requestContext ?? {};
|
|
883
|
+
const newRequestContext = params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {};
|
|
884
|
+
const mergedRequestContext = { ...persistedRequestContext, ...newRequestContext };
|
|
885
|
+
const eventOutput = await this.inngest.send({
|
|
886
|
+
name: `workflow.${this.workflowId}`,
|
|
887
|
+
data: {
|
|
888
|
+
inputData: resumeDataToUse,
|
|
889
|
+
initialState: snapshot?.value ?? {},
|
|
890
|
+
runId: this.runId,
|
|
891
|
+
workflowId: this.workflowId,
|
|
892
|
+
stepResults: snapshot?.context,
|
|
893
|
+
resume: {
|
|
894
|
+
steps,
|
|
895
|
+
stepResults: snapshot?.context,
|
|
896
|
+
resumePayload: resumeDataToUse,
|
|
897
|
+
resumePath: steps?.[0] ? snapshot?.suspendedPaths?.[steps?.[0]] : void 0
|
|
898
|
+
},
|
|
899
|
+
requestContext: mergedRequestContext,
|
|
900
|
+
perStep: params.perStep
|
|
901
|
+
}
|
|
902
|
+
});
|
|
903
|
+
const eventId = eventOutput.ids[0];
|
|
904
|
+
if (!eventId) {
|
|
905
|
+
throw new Error("Event ID is not set");
|
|
906
|
+
}
|
|
907
|
+
const runOutput = await this.getRunOutput(eventId);
|
|
908
|
+
const result = runOutput?.output?.result;
|
|
909
|
+
this.hydrateFailedResult(result);
|
|
910
|
+
return result;
|
|
911
|
+
}
|
|
912
|
+
async timeTravel(params) {
|
|
913
|
+
const p = this._timeTravel(params).then((result) => {
|
|
914
|
+
if (result.status !== "suspended") {
|
|
915
|
+
this.closeStreamAction?.().catch(() => {
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
return result;
|
|
919
|
+
});
|
|
920
|
+
this.executionResults = p;
|
|
921
|
+
return p;
|
|
922
|
+
}
|
|
923
|
+
async _timeTravel(params) {
|
|
924
|
+
if (!params.step || Array.isArray(params.step) && params.step?.length === 0) {
|
|
925
|
+
throw new Error("Step is required and must be a valid step or array of steps");
|
|
926
|
+
}
|
|
927
|
+
let steps = [];
|
|
928
|
+
if (typeof params.step === "string") {
|
|
929
|
+
steps = params.step.split(".");
|
|
930
|
+
} else {
|
|
931
|
+
steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
|
|
932
|
+
(step) => typeof step === "string" ? step : step?.id
|
|
933
|
+
);
|
|
934
|
+
}
|
|
935
|
+
if (steps.length === 0) {
|
|
936
|
+
throw new Error("No steps provided to timeTravel");
|
|
937
|
+
}
|
|
938
|
+
const storage = this.#mastra?.getStorage();
|
|
939
|
+
const workflowsStore = await storage?.getStore("workflows");
|
|
940
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
941
|
+
workflowName: this.workflowId,
|
|
942
|
+
runId: this.runId
|
|
943
|
+
});
|
|
944
|
+
if (!snapshot) {
|
|
945
|
+
await workflowsStore?.persistWorkflowSnapshot({
|
|
946
|
+
workflowName: this.workflowId,
|
|
947
|
+
runId: this.runId,
|
|
948
|
+
resourceId: this.resourceId,
|
|
949
|
+
snapshot: {
|
|
950
|
+
runId: this.runId,
|
|
951
|
+
serializedStepGraph: this.serializedStepGraph,
|
|
952
|
+
status: "pending",
|
|
953
|
+
value: {},
|
|
954
|
+
context: {},
|
|
955
|
+
activePaths: [],
|
|
956
|
+
suspendedPaths: {},
|
|
957
|
+
activeStepsPath: {},
|
|
958
|
+
resumeLabels: {},
|
|
959
|
+
waitingPaths: {},
|
|
960
|
+
timestamp: Date.now()
|
|
961
|
+
}
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
if (snapshot?.status === "running") {
|
|
965
|
+
throw new Error("This workflow run is still running, cannot time travel");
|
|
966
|
+
}
|
|
967
|
+
let inputDataToUse = params.inputData;
|
|
968
|
+
if (inputDataToUse && steps.length === 1) {
|
|
969
|
+
inputDataToUse = await this._validateTimetravelInputData(params.inputData, this.workflowSteps[steps[0]]);
|
|
970
|
+
}
|
|
971
|
+
const timeTravelData = createTimeTravelExecutionParams({
|
|
972
|
+
steps,
|
|
973
|
+
inputData: inputDataToUse,
|
|
974
|
+
resumeData: params.resumeData,
|
|
975
|
+
context: params.context,
|
|
976
|
+
nestedStepsContext: params.nestedStepsContext,
|
|
977
|
+
snapshot: snapshot ?? { context: {} },
|
|
978
|
+
graph: this.executionGraph,
|
|
979
|
+
initialState: params.initialState,
|
|
980
|
+
perStep: params.perStep
|
|
981
|
+
});
|
|
982
|
+
const eventOutput = await this.inngest.send({
|
|
983
|
+
name: `workflow.${this.workflowId}`,
|
|
984
|
+
data: {
|
|
985
|
+
initialState: timeTravelData.state,
|
|
986
|
+
runId: this.runId,
|
|
987
|
+
workflowId: this.workflowId,
|
|
988
|
+
stepResults: timeTravelData.stepResults,
|
|
989
|
+
timeTravel: timeTravelData,
|
|
990
|
+
tracingOptions: params.tracingOptions,
|
|
991
|
+
outputOptions: params.outputOptions,
|
|
992
|
+
requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {},
|
|
993
|
+
perStep: params.perStep
|
|
994
|
+
}
|
|
995
|
+
});
|
|
996
|
+
const eventId = eventOutput.ids[0];
|
|
997
|
+
if (!eventId) {
|
|
998
|
+
throw new Error("Event ID is not set");
|
|
999
|
+
}
|
|
1000
|
+
const runOutput = await this.getRunOutput(eventId);
|
|
1001
|
+
const result = runOutput?.output?.result;
|
|
1002
|
+
this.hydrateFailedResult(result);
|
|
1003
|
+
return result;
|
|
1004
|
+
}
|
|
1005
|
+
watch(cb) {
|
|
1006
|
+
let active = true;
|
|
1007
|
+
const streamPromise = subscribe(
|
|
1008
|
+
{
|
|
1009
|
+
channel: `workflow:${this.workflowId}:${this.runId}`,
|
|
1010
|
+
topics: ["watch"],
|
|
1011
|
+
app: this.inngest
|
|
1012
|
+
},
|
|
1013
|
+
(message) => {
|
|
1014
|
+
if (active) {
|
|
1015
|
+
cb(message.data);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
);
|
|
1019
|
+
return () => {
|
|
1020
|
+
active = false;
|
|
1021
|
+
streamPromise.then(async (stream) => {
|
|
1022
|
+
return stream.cancel();
|
|
1023
|
+
}).catch((err) => {
|
|
1024
|
+
console.error(err);
|
|
1025
|
+
});
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
streamLegacy({ inputData, requestContext } = {}) {
|
|
1029
|
+
const { readable, writable } = new TransformStream();
|
|
1030
|
+
const writer = writable.getWriter();
|
|
1031
|
+
void writer.write({
|
|
1032
|
+
// @ts-ignore
|
|
1033
|
+
type: "start",
|
|
1034
|
+
// @ts-ignore
|
|
1035
|
+
payload: { runId: this.runId }
|
|
1036
|
+
});
|
|
1037
|
+
const unwatch = this.watch(async (event) => {
|
|
1038
|
+
try {
|
|
1039
|
+
const e = {
|
|
1040
|
+
...event,
|
|
1041
|
+
type: event.type.replace("workflow-", "")
|
|
1042
|
+
};
|
|
1043
|
+
if (e.type === "step-output") {
|
|
1044
|
+
e.type = e.payload.output.type;
|
|
1045
|
+
e.payload = e.payload.output.payload;
|
|
1046
|
+
}
|
|
1047
|
+
await writer.write(e);
|
|
1048
|
+
} catch {
|
|
1049
|
+
}
|
|
1050
|
+
});
|
|
1051
|
+
this.closeStreamAction = async () => {
|
|
1052
|
+
await writer.write({
|
|
1053
|
+
type: "finish",
|
|
1054
|
+
// @ts-ignore
|
|
1055
|
+
payload: { runId: this.runId }
|
|
1056
|
+
});
|
|
1057
|
+
unwatch();
|
|
1058
|
+
try {
|
|
1059
|
+
await writer.close();
|
|
1060
|
+
} catch (err) {
|
|
1061
|
+
console.error("Error closing stream:", err);
|
|
1062
|
+
} finally {
|
|
1063
|
+
writer.releaseLock();
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
this.executionResults = this._start({ inputData, requestContext, format: "legacy" }).then((result) => {
|
|
1067
|
+
if (result.status !== "suspended") {
|
|
1068
|
+
this.closeStreamAction?.().catch(() => {
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
return result;
|
|
1072
|
+
});
|
|
1073
|
+
return {
|
|
1074
|
+
stream: readable,
|
|
1075
|
+
getWorkflowState: () => this.executionResults
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
stream({
|
|
1079
|
+
inputData,
|
|
1080
|
+
requestContext,
|
|
1081
|
+
tracingOptions,
|
|
1082
|
+
closeOnSuspend = true,
|
|
1083
|
+
initialState,
|
|
1084
|
+
outputOptions,
|
|
1085
|
+
perStep
|
|
1086
|
+
} = {}) {
|
|
1087
|
+
if (this.closeStreamAction && this.streamOutput) {
|
|
1088
|
+
return this.streamOutput;
|
|
1089
|
+
}
|
|
1090
|
+
this.closeStreamAction = async () => {
|
|
1091
|
+
};
|
|
1092
|
+
const self = this;
|
|
1093
|
+
const stream = new ReadableStream({
|
|
1094
|
+
async start(controller) {
|
|
1095
|
+
const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {
|
|
1096
|
+
controller.enqueue({
|
|
1097
|
+
type,
|
|
1098
|
+
runId: self.runId,
|
|
1099
|
+
from,
|
|
1100
|
+
payload: {
|
|
1101
|
+
stepName: payload?.id,
|
|
1102
|
+
...payload
|
|
1103
|
+
}
|
|
1104
|
+
});
|
|
1105
|
+
});
|
|
1106
|
+
self.closeStreamAction = async () => {
|
|
1107
|
+
unwatch();
|
|
1108
|
+
try {
|
|
1109
|
+
await controller.close();
|
|
1110
|
+
} catch (err) {
|
|
1111
|
+
console.error("Error closing stream:", err);
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
const executionResultsPromise = self._start({
|
|
1115
|
+
inputData,
|
|
1116
|
+
requestContext,
|
|
1117
|
+
// tracingContext, // We are not able to pass a reference to a span here, what to do?
|
|
1118
|
+
initialState,
|
|
1119
|
+
tracingOptions,
|
|
1120
|
+
outputOptions,
|
|
1121
|
+
format: "vnext",
|
|
1122
|
+
perStep
|
|
1123
|
+
});
|
|
1124
|
+
let executionResults;
|
|
1125
|
+
try {
|
|
1126
|
+
executionResults = await executionResultsPromise;
|
|
1127
|
+
if (closeOnSuspend) {
|
|
1128
|
+
self.closeStreamAction?.().catch(() => {
|
|
1129
|
+
});
|
|
1130
|
+
} else if (executionResults.status !== "suspended") {
|
|
1131
|
+
self.closeStreamAction?.().catch(() => {
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
if (self.streamOutput) {
|
|
1135
|
+
self.streamOutput.updateResults(
|
|
1136
|
+
executionResults
|
|
1137
|
+
);
|
|
1138
|
+
}
|
|
1139
|
+
} catch (err) {
|
|
1140
|
+
self.streamOutput?.rejectResults(err);
|
|
1141
|
+
self.closeStreamAction?.().catch(() => {
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
});
|
|
1146
|
+
this.streamOutput = new WorkflowRunOutput({
|
|
1147
|
+
runId: this.runId,
|
|
1148
|
+
workflowId: this.workflowId,
|
|
1149
|
+
stream
|
|
1150
|
+
});
|
|
1151
|
+
return this.streamOutput;
|
|
1152
|
+
}
|
|
1153
|
+
timeTravelStream({
|
|
1154
|
+
inputData,
|
|
1155
|
+
resumeData,
|
|
1156
|
+
initialState,
|
|
1157
|
+
step,
|
|
1158
|
+
context,
|
|
1159
|
+
nestedStepsContext,
|
|
1160
|
+
requestContext,
|
|
1161
|
+
// tracingContext,
|
|
1162
|
+
tracingOptions,
|
|
1163
|
+
outputOptions,
|
|
1164
|
+
perStep
|
|
1165
|
+
}) {
|
|
1166
|
+
this.closeStreamAction = async () => {
|
|
1167
|
+
};
|
|
1168
|
+
const self = this;
|
|
1169
|
+
const stream = new ReadableStream({
|
|
1170
|
+
async start(controller) {
|
|
1171
|
+
const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {
|
|
1172
|
+
controller.enqueue({
|
|
1173
|
+
type,
|
|
1174
|
+
runId: self.runId,
|
|
1175
|
+
from,
|
|
1176
|
+
payload: {
|
|
1177
|
+
stepName: payload?.id,
|
|
1178
|
+
...payload
|
|
1179
|
+
}
|
|
1180
|
+
});
|
|
1181
|
+
});
|
|
1182
|
+
self.closeStreamAction = async () => {
|
|
1183
|
+
unwatch();
|
|
1184
|
+
try {
|
|
1185
|
+
controller.close();
|
|
1186
|
+
} catch (err) {
|
|
1187
|
+
console.error("Error closing stream:", err);
|
|
1188
|
+
}
|
|
1189
|
+
};
|
|
1190
|
+
const executionResultsPromise = self._timeTravel({
|
|
1191
|
+
inputData,
|
|
1192
|
+
step,
|
|
1193
|
+
context,
|
|
1194
|
+
nestedStepsContext,
|
|
1195
|
+
resumeData,
|
|
1196
|
+
initialState,
|
|
1197
|
+
requestContext,
|
|
1198
|
+
tracingOptions,
|
|
1199
|
+
outputOptions,
|
|
1200
|
+
perStep
|
|
1201
|
+
});
|
|
1202
|
+
self.executionResults = executionResultsPromise;
|
|
1203
|
+
let executionResults;
|
|
1204
|
+
try {
|
|
1205
|
+
executionResults = await executionResultsPromise;
|
|
1206
|
+
self.closeStreamAction?.().catch(() => {
|
|
1207
|
+
});
|
|
1208
|
+
if (self.streamOutput) {
|
|
1209
|
+
self.streamOutput.updateResults(executionResults);
|
|
1210
|
+
}
|
|
1211
|
+
} catch (err) {
|
|
1212
|
+
self.streamOutput?.rejectResults(err);
|
|
1213
|
+
self.closeStreamAction?.().catch(() => {
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
});
|
|
1218
|
+
this.streamOutput = new WorkflowRunOutput({
|
|
1219
|
+
runId: this.runId,
|
|
1220
|
+
workflowId: this.workflowId,
|
|
1221
|
+
stream
|
|
1222
|
+
});
|
|
1223
|
+
return this.streamOutput;
|
|
1224
|
+
}
|
|
1225
|
+
/**
|
|
1226
|
+
* Hydrates errors in a failed workflow result back to proper Error instances.
|
|
1227
|
+
* This ensures error.cause chains and custom properties are preserved.
|
|
1228
|
+
*/
|
|
1229
|
+
hydrateFailedResult(result) {
|
|
1230
|
+
if (result.status === "failed") {
|
|
1231
|
+
result.error = getErrorFromUnknown(result.error, { serializeStack: false });
|
|
1232
|
+
if (result.steps) {
|
|
1233
|
+
hydrateSerializedStepErrors(result.steps);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
|
|
1239
|
+
// src/workflow.ts
|
|
1240
|
+
var InngestWorkflow = class _InngestWorkflow extends Workflow {
|
|
1241
|
+
#mastra;
|
|
1242
|
+
inngest;
|
|
1243
|
+
function;
|
|
1244
|
+
cronFunction;
|
|
1245
|
+
flowControlConfig;
|
|
1246
|
+
cronConfig;
|
|
1247
|
+
constructor(params, inngest) {
|
|
1248
|
+
const { concurrency, rateLimit, throttle, debounce, priority, cron, inputData, initialState, ...workflowParams } = params;
|
|
1249
|
+
super(workflowParams);
|
|
1250
|
+
this.engineType = "inngest";
|
|
1251
|
+
const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(
|
|
1252
|
+
([_, value]) => value !== void 0
|
|
1253
|
+
);
|
|
1254
|
+
this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : void 0;
|
|
1255
|
+
this.#mastra = params.mastra;
|
|
1256
|
+
this.inngest = inngest;
|
|
1257
|
+
if (cron) {
|
|
1258
|
+
this.cronConfig = { cron, inputData, initialState };
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
async listWorkflowRuns(args) {
|
|
1262
|
+
const storage = this.#mastra?.getStorage();
|
|
1263
|
+
if (!storage) {
|
|
1264
|
+
this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
|
|
1265
|
+
return { runs: [], total: 0 };
|
|
1266
|
+
}
|
|
1267
|
+
const workflowsStore = await storage.getStore("workflows");
|
|
1268
|
+
if (!workflowsStore) {
|
|
1269
|
+
return { runs: [], total: 0 };
|
|
1270
|
+
}
|
|
1271
|
+
return workflowsStore.listWorkflowRuns({ workflowName: this.id, ...args ?? {} });
|
|
1272
|
+
}
|
|
1273
|
+
__registerMastra(mastra) {
|
|
1274
|
+
super.__registerMastra(mastra);
|
|
1275
|
+
this.#mastra = mastra;
|
|
1276
|
+
this.executionEngine.__registerMastra(mastra);
|
|
1277
|
+
const updateNested = (step) => {
|
|
1278
|
+
if ((step.type === "step" || step.type === "loop" || step.type === "foreach") && step.step instanceof _InngestWorkflow) {
|
|
1279
|
+
step.step.__registerMastra(mastra);
|
|
1280
|
+
} else if (step.type === "parallel" || step.type === "conditional") {
|
|
1281
|
+
for (const subStep of step.steps) {
|
|
1282
|
+
updateNested(subStep);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
if (this.executionGraph.steps.length) {
|
|
1287
|
+
for (const step of this.executionGraph.steps) {
|
|
1288
|
+
updateNested(step);
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
async createRun(options) {
|
|
1293
|
+
const runIdToUse = options?.runId || randomUUID();
|
|
1294
|
+
const existingInMemoryRun = this.runs.get(runIdToUse);
|
|
1295
|
+
const newRun = new InngestRun(
|
|
1296
|
+
{
|
|
1297
|
+
workflowId: this.id,
|
|
1298
|
+
runId: runIdToUse,
|
|
1299
|
+
resourceId: options?.resourceId,
|
|
1300
|
+
executionEngine: this.executionEngine,
|
|
1301
|
+
executionGraph: this.executionGraph,
|
|
1302
|
+
serializedStepGraph: this.serializedStepGraph,
|
|
1303
|
+
mastra: this.#mastra,
|
|
1304
|
+
retryConfig: this.retryConfig,
|
|
1305
|
+
cleanup: () => this.runs.delete(runIdToUse),
|
|
1306
|
+
workflowSteps: this.steps,
|
|
1307
|
+
workflowEngineType: this.engineType,
|
|
1308
|
+
validateInputs: this.options.validateInputs
|
|
1309
|
+
},
|
|
1310
|
+
this.inngest
|
|
1311
|
+
);
|
|
1312
|
+
const run = existingInMemoryRun ?? newRun;
|
|
1313
|
+
this.runs.set(runIdToUse, run);
|
|
1314
|
+
const shouldPersistSnapshot = this.options.shouldPersistSnapshot({
|
|
1315
|
+
workflowStatus: run.workflowRunStatus,
|
|
1316
|
+
stepResults: {}
|
|
1317
|
+
});
|
|
1318
|
+
const existingStoredRun = await this.getWorkflowRunById(runIdToUse, {
|
|
1319
|
+
withNestedWorkflows: false
|
|
1320
|
+
});
|
|
1321
|
+
const existsInStorage = existingStoredRun && !existingStoredRun.isFromInMemory;
|
|
1322
|
+
if (!existsInStorage && shouldPersistSnapshot) {
|
|
1323
|
+
const workflowsStore = await this.mastra?.getStorage()?.getStore("workflows");
|
|
1324
|
+
await workflowsStore?.persistWorkflowSnapshot({
|
|
1325
|
+
workflowName: this.id,
|
|
1326
|
+
runId: runIdToUse,
|
|
1327
|
+
resourceId: options?.resourceId,
|
|
1328
|
+
snapshot: {
|
|
1329
|
+
runId: runIdToUse,
|
|
1330
|
+
status: "pending",
|
|
1331
|
+
value: {},
|
|
1332
|
+
context: {},
|
|
1333
|
+
activePaths: [],
|
|
1334
|
+
activeStepsPath: {},
|
|
1335
|
+
waitingPaths: {},
|
|
1336
|
+
serializedStepGraph: this.serializedStepGraph,
|
|
1337
|
+
suspendedPaths: {},
|
|
1338
|
+
resumeLabels: {},
|
|
1339
|
+
result: void 0,
|
|
1340
|
+
error: void 0,
|
|
1341
|
+
timestamp: Date.now()
|
|
1342
|
+
}
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
return run;
|
|
1346
|
+
}
|
|
1347
|
+
//createCronFunction is only called if cronConfig.cron is defined.
|
|
1348
|
+
createCronFunction() {
|
|
1349
|
+
if (this.cronFunction) {
|
|
1350
|
+
return this.cronFunction;
|
|
1351
|
+
}
|
|
1352
|
+
this.cronFunction = this.inngest.createFunction(
|
|
1353
|
+
{
|
|
1354
|
+
id: `workflow.${this.id}.cron`,
|
|
1355
|
+
retries: 0,
|
|
1356
|
+
cancelOn: [{ event: `cancel.workflow.${this.id}` }],
|
|
1357
|
+
...this.flowControlConfig
|
|
1358
|
+
},
|
|
1359
|
+
{ cron: this.cronConfig?.cron ?? "" },
|
|
1360
|
+
async () => {
|
|
1361
|
+
const run = await this.createRun();
|
|
1362
|
+
const result = await run.start({
|
|
1363
|
+
inputData: this.cronConfig?.inputData,
|
|
1364
|
+
initialState: this.cronConfig?.initialState
|
|
1365
|
+
});
|
|
1366
|
+
return { result, runId: run.runId };
|
|
1367
|
+
}
|
|
1368
|
+
);
|
|
1369
|
+
return this.cronFunction;
|
|
1370
|
+
}
|
|
1371
|
+
getFunction() {
|
|
1372
|
+
if (this.function) {
|
|
1373
|
+
return this.function;
|
|
1374
|
+
}
|
|
1375
|
+
this.function = this.inngest.createFunction(
|
|
1376
|
+
{
|
|
1377
|
+
id: `workflow.${this.id}`,
|
|
1378
|
+
retries: 0,
|
|
1379
|
+
cancelOn: [{ event: `cancel.workflow.${this.id}` }],
|
|
1380
|
+
// Spread flow control configuration
|
|
1381
|
+
...this.flowControlConfig
|
|
1382
|
+
},
|
|
1383
|
+
{ event: `workflow.${this.id}` },
|
|
1384
|
+
async ({ event, step, attempt, publish }) => {
|
|
1385
|
+
let {
|
|
1386
|
+
inputData,
|
|
1387
|
+
initialState,
|
|
1388
|
+
runId,
|
|
1389
|
+
resourceId,
|
|
1390
|
+
resume,
|
|
1391
|
+
outputOptions,
|
|
1392
|
+
format,
|
|
1393
|
+
timeTravel,
|
|
1394
|
+
perStep,
|
|
1395
|
+
tracingOptions
|
|
1396
|
+
} = event.data;
|
|
1397
|
+
if (!runId) {
|
|
1398
|
+
runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {
|
|
1399
|
+
return randomUUID();
|
|
1400
|
+
});
|
|
1401
|
+
}
|
|
1402
|
+
const pubsub = new InngestPubSub(this.inngest, this.id, publish);
|
|
1403
|
+
const requestContext = new RequestContext(Object.entries(event.data.requestContext ?? {}));
|
|
1404
|
+
const mastra = this.#mastra;
|
|
1405
|
+
const tracingPolicy = this.options.tracingPolicy;
|
|
1406
|
+
const workflowSpanData = await step.run(`workflow.${this.id}.span.start`, async () => {
|
|
1407
|
+
const observability = mastra?.observability?.getSelectedInstance({ requestContext });
|
|
1408
|
+
if (!observability) return void 0;
|
|
1409
|
+
const span = observability.startSpan({
|
|
1410
|
+
type: SpanType.WORKFLOW_RUN,
|
|
1411
|
+
name: `workflow run: '${this.id}'`,
|
|
1412
|
+
entityType: EntityType.WORKFLOW_RUN,
|
|
1413
|
+
entityId: this.id,
|
|
1414
|
+
input: inputData,
|
|
1415
|
+
metadata: {
|
|
1416
|
+
resourceId,
|
|
1417
|
+
runId
|
|
1418
|
+
},
|
|
1419
|
+
tracingPolicy,
|
|
1420
|
+
tracingOptions,
|
|
1421
|
+
requestContext
|
|
1422
|
+
});
|
|
1423
|
+
return span?.exportSpan();
|
|
1424
|
+
});
|
|
1425
|
+
const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);
|
|
1426
|
+
let result;
|
|
1427
|
+
try {
|
|
1428
|
+
result = await engine.execute({
|
|
1429
|
+
workflowId: this.id,
|
|
1430
|
+
runId,
|
|
1431
|
+
resourceId,
|
|
1432
|
+
graph: this.executionGraph,
|
|
1433
|
+
serializedStepGraph: this.serializedStepGraph,
|
|
1434
|
+
input: inputData,
|
|
1435
|
+
initialState,
|
|
1436
|
+
pubsub,
|
|
1437
|
+
retryConfig: this.retryConfig,
|
|
1438
|
+
requestContext,
|
|
1439
|
+
resume,
|
|
1440
|
+
timeTravel,
|
|
1441
|
+
perStep,
|
|
1442
|
+
format,
|
|
1443
|
+
abortController: new AbortController(),
|
|
1444
|
+
// For Inngest, we don't pass workflowSpan - step spans use tracingIds instead
|
|
1445
|
+
workflowSpan: void 0,
|
|
1446
|
+
// Pass tracing IDs for durable span operations
|
|
1447
|
+
tracingIds: workflowSpanData ? {
|
|
1448
|
+
traceId: workflowSpanData.traceId,
|
|
1449
|
+
workflowSpanId: workflowSpanData.id
|
|
1450
|
+
} : void 0,
|
|
1451
|
+
outputOptions,
|
|
1452
|
+
outputWriter: async (chunk) => {
|
|
1453
|
+
try {
|
|
1454
|
+
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
1455
|
+
type: "watch",
|
|
1456
|
+
runId,
|
|
1457
|
+
data: chunk
|
|
1458
|
+
});
|
|
1459
|
+
} catch (err) {
|
|
1460
|
+
this.logger.debug?.("Failed to publish watch event:", err);
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
});
|
|
1464
|
+
} catch (error) {
|
|
1465
|
+
throw error;
|
|
1466
|
+
}
|
|
1467
|
+
await step.run(`workflow.${this.id}.finalize`, async () => {
|
|
1468
|
+
if (result.status !== "paused") {
|
|
1469
|
+
await engine.invokeLifecycleCallbacksInternal({
|
|
1470
|
+
status: result.status,
|
|
1471
|
+
result: "result" in result ? result.result : void 0,
|
|
1472
|
+
error: "error" in result ? result.error : void 0,
|
|
1473
|
+
steps: result.steps,
|
|
1474
|
+
tripwire: "tripwire" in result ? result.tripwire : void 0,
|
|
1475
|
+
runId,
|
|
1476
|
+
workflowId: this.id,
|
|
1477
|
+
resourceId,
|
|
1478
|
+
input: inputData,
|
|
1479
|
+
requestContext,
|
|
1480
|
+
state: result.state ?? initialState ?? {}
|
|
1481
|
+
});
|
|
1482
|
+
}
|
|
1483
|
+
if (workflowSpanData) {
|
|
1484
|
+
const observability = mastra?.observability?.getSelectedInstance({ requestContext });
|
|
1485
|
+
if (observability) {
|
|
1486
|
+
const workflowSpan = observability.rebuildSpan(workflowSpanData);
|
|
1487
|
+
if (result.status === "failed") {
|
|
1488
|
+
workflowSpan.error({
|
|
1489
|
+
error: result.error instanceof Error ? result.error : new Error(String(result.error)),
|
|
1490
|
+
attributes: { status: "failed" }
|
|
1491
|
+
});
|
|
1492
|
+
} else {
|
|
1493
|
+
workflowSpan.end({
|
|
1494
|
+
output: result.status === "success" ? result.result : void 0,
|
|
1495
|
+
attributes: { status: result.status }
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
432
1500
|
if (result.status === "failed") {
|
|
433
1501
|
throw new NonRetriableError(`Workflow failed`, {
|
|
434
1502
|
cause: result
|
|
@@ -455,1086 +1523,725 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
|
|
|
455
1523
|
});
|
|
456
1524
|
}
|
|
457
1525
|
getFunctions() {
|
|
458
|
-
return [
|
|
1526
|
+
return [
|
|
1527
|
+
this.getFunction(),
|
|
1528
|
+
...this.cronConfig?.cron ? [this.createCronFunction()] : [],
|
|
1529
|
+
...this.getNestedFunctions(this.executionGraph.steps)
|
|
1530
|
+
];
|
|
459
1531
|
}
|
|
460
1532
|
};
|
|
461
|
-
function
|
|
462
|
-
|
|
1533
|
+
function prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }) {
|
|
1534
|
+
const wfs = mastra.listWorkflows();
|
|
1535
|
+
const workflowFunctions = Array.from(
|
|
1536
|
+
new Set(
|
|
1537
|
+
Object.values(wfs).flatMap((wf) => {
|
|
1538
|
+
if (wf instanceof InngestWorkflow) {
|
|
1539
|
+
wf.__registerMastra(mastra);
|
|
1540
|
+
return wf.getFunctions();
|
|
1541
|
+
}
|
|
1542
|
+
return [];
|
|
1543
|
+
})
|
|
1544
|
+
)
|
|
1545
|
+
);
|
|
1546
|
+
return {
|
|
1547
|
+
...registerOptions,
|
|
1548
|
+
client: inngest,
|
|
1549
|
+
functions: [...workflowFunctions, ...userFunctions]
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
function createServe(adapter) {
|
|
1553
|
+
return (options) => {
|
|
1554
|
+
const serveOptions = prepareServeOptions(options);
|
|
1555
|
+
return adapter(serveOptions);
|
|
1556
|
+
};
|
|
1557
|
+
}
|
|
1558
|
+
var serve = createServe(serve$1);
|
|
1559
|
+
|
|
1560
|
+
// src/types.ts
|
|
1561
|
+
var _compatibilityCheck = true;
|
|
1562
|
+
|
|
1563
|
+
// src/index.ts
|
|
1564
|
+
function isInngestWorkflow(input) {
|
|
1565
|
+
return input instanceof InngestWorkflow;
|
|
1566
|
+
}
|
|
1567
|
+
function isAgent(input) {
|
|
1568
|
+
return input instanceof Agent;
|
|
1569
|
+
}
|
|
1570
|
+
function isToolStep(input) {
|
|
1571
|
+
return input instanceof Tool;
|
|
463
1572
|
}
|
|
464
|
-
function
|
|
465
|
-
return
|
|
1573
|
+
function isStepParams(input) {
|
|
1574
|
+
return input !== null && typeof input === "object" && "id" in input && "execute" in input && !(input instanceof Agent) && !(input instanceof Tool) && !(input instanceof InngestWorkflow);
|
|
466
1575
|
}
|
|
467
|
-
function
|
|
1576
|
+
function isProcessor(obj) {
|
|
1577
|
+
return obj !== null && typeof obj === "object" && "id" in obj && typeof obj.id === "string" && !(obj instanceof Agent) && !(obj instanceof Tool) && !(obj instanceof InngestWorkflow) && (typeof obj.processInput === "function" || typeof obj.processInputStep === "function" || typeof obj.processOutputStream === "function" || typeof obj.processOutputResult === "function" || typeof obj.processOutputStep === "function");
|
|
1578
|
+
}
|
|
1579
|
+
function createStep(params, agentOrToolOptions) {
|
|
1580
|
+
if (isInngestWorkflow(params)) {
|
|
1581
|
+
return params;
|
|
1582
|
+
}
|
|
468
1583
|
if (isAgent(params)) {
|
|
469
|
-
return
|
|
470
|
-
id: params.name,
|
|
471
|
-
description: params.getDescription(),
|
|
472
|
-
// @ts-ignore
|
|
473
|
-
inputSchema: z.object({
|
|
474
|
-
prompt: z.string()
|
|
475
|
-
}),
|
|
476
|
-
// @ts-ignore
|
|
477
|
-
outputSchema: z.object({
|
|
478
|
-
text: z.string()
|
|
479
|
-
}),
|
|
480
|
-
execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, runtimeContext, abortSignal, abort, tracingContext }) => {
|
|
481
|
-
let streamPromise = {};
|
|
482
|
-
streamPromise.promise = new Promise((resolve, reject) => {
|
|
483
|
-
streamPromise.resolve = resolve;
|
|
484
|
-
streamPromise.reject = reject;
|
|
485
|
-
});
|
|
486
|
-
const toolData = {
|
|
487
|
-
name: params.name,
|
|
488
|
-
args: inputData
|
|
489
|
-
};
|
|
490
|
-
if ((await params.getLLM()).getModel().specificationVersion === `v2`) {
|
|
491
|
-
const { fullStream } = await params.stream(inputData.prompt, {
|
|
492
|
-
runtimeContext,
|
|
493
|
-
tracingContext,
|
|
494
|
-
onFinish: (result) => {
|
|
495
|
-
streamPromise.resolve(result.text);
|
|
496
|
-
},
|
|
497
|
-
abortSignal
|
|
498
|
-
});
|
|
499
|
-
if (abortSignal.aborted) {
|
|
500
|
-
return abort();
|
|
501
|
-
}
|
|
502
|
-
await emitter.emit("watch-v2", {
|
|
503
|
-
type: "tool-call-streaming-start",
|
|
504
|
-
...toolData ?? {}
|
|
505
|
-
});
|
|
506
|
-
for await (const chunk of fullStream) {
|
|
507
|
-
if (chunk.type === "text-delta") {
|
|
508
|
-
await emitter.emit("watch-v2", {
|
|
509
|
-
type: "tool-call-delta",
|
|
510
|
-
...toolData ?? {},
|
|
511
|
-
argsTextDelta: chunk.payload.text
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
} else {
|
|
516
|
-
const { fullStream } = await params.streamLegacy(inputData.prompt, {
|
|
517
|
-
runtimeContext,
|
|
518
|
-
tracingContext,
|
|
519
|
-
onFinish: (result) => {
|
|
520
|
-
streamPromise.resolve(result.text);
|
|
521
|
-
},
|
|
522
|
-
abortSignal
|
|
523
|
-
});
|
|
524
|
-
if (abortSignal.aborted) {
|
|
525
|
-
return abort();
|
|
526
|
-
}
|
|
527
|
-
await emitter.emit("watch-v2", {
|
|
528
|
-
type: "tool-call-streaming-start",
|
|
529
|
-
...toolData ?? {}
|
|
530
|
-
});
|
|
531
|
-
for await (const chunk of fullStream) {
|
|
532
|
-
if (chunk.type === "text-delta") {
|
|
533
|
-
await emitter.emit("watch-v2", {
|
|
534
|
-
type: "tool-call-delta",
|
|
535
|
-
...toolData ?? {},
|
|
536
|
-
argsTextDelta: chunk.textDelta
|
|
537
|
-
});
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
await emitter.emit("watch-v2", {
|
|
542
|
-
type: "tool-call-streaming-finish",
|
|
543
|
-
...toolData ?? {}
|
|
544
|
-
});
|
|
545
|
-
return {
|
|
546
|
-
text: await streamPromise.promise
|
|
547
|
-
};
|
|
548
|
-
},
|
|
549
|
-
component: params.component
|
|
550
|
-
};
|
|
1584
|
+
return createStepFromAgent(params, agentOrToolOptions);
|
|
551
1585
|
}
|
|
552
|
-
if (
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
return
|
|
557
|
-
// TODO: tool probably should have strong id type
|
|
558
|
-
// @ts-ignore
|
|
559
|
-
id: params.id,
|
|
560
|
-
description: params.description,
|
|
561
|
-
inputSchema: params.inputSchema,
|
|
562
|
-
outputSchema: params.outputSchema,
|
|
563
|
-
execute: async ({ inputData, mastra, runtimeContext, tracingContext, suspend, resumeData }) => {
|
|
564
|
-
return params.execute({
|
|
565
|
-
context: inputData,
|
|
566
|
-
mastra: wrapMastra(mastra, tracingContext),
|
|
567
|
-
runtimeContext,
|
|
568
|
-
tracingContext,
|
|
569
|
-
suspend,
|
|
570
|
-
resumeData
|
|
571
|
-
});
|
|
572
|
-
},
|
|
573
|
-
component: "TOOL"
|
|
574
|
-
};
|
|
1586
|
+
if (isToolStep(params)) {
|
|
1587
|
+
return createStepFromTool(params, agentOrToolOptions);
|
|
1588
|
+
}
|
|
1589
|
+
if (isStepParams(params)) {
|
|
1590
|
+
return createStepFromParams(params);
|
|
575
1591
|
}
|
|
1592
|
+
if (isProcessor(params)) {
|
|
1593
|
+
return createStepFromProcessor(params);
|
|
1594
|
+
}
|
|
1595
|
+
throw new Error("Invalid input: expected StepParams, Agent, ToolStep, Processor, or InngestWorkflow");
|
|
1596
|
+
}
|
|
1597
|
+
function createStepFromParams(params) {
|
|
576
1598
|
return {
|
|
577
1599
|
id: params.id,
|
|
578
1600
|
description: params.description,
|
|
579
1601
|
inputSchema: params.inputSchema,
|
|
1602
|
+
stateSchema: params.stateSchema,
|
|
580
1603
|
outputSchema: params.outputSchema,
|
|
581
1604
|
resumeSchema: params.resumeSchema,
|
|
582
1605
|
suspendSchema: params.suspendSchema,
|
|
583
|
-
|
|
1606
|
+
scorers: params.scorers,
|
|
1607
|
+
retries: params.retries,
|
|
1608
|
+
execute: params.execute.bind(params)
|
|
584
1609
|
};
|
|
585
1610
|
}
|
|
586
|
-
function
|
|
1611
|
+
function createStepFromAgent(params, agentOrToolOptions) {
|
|
1612
|
+
const options = agentOrToolOptions ?? {};
|
|
1613
|
+
const outputSchema = options?.structuredOutput?.schema ?? z.object({ text: z.string() });
|
|
1614
|
+
const { retries, scorers, ...agentOptions } = options ?? {};
|
|
587
1615
|
return {
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
inputSchema: workflow.inputSchema,
|
|
612
|
-
outputSchema: workflow.outputSchema,
|
|
613
|
-
steps: workflow.stepDefs,
|
|
614
|
-
mastra: workflow.mastra
|
|
615
|
-
});
|
|
616
|
-
wf.setStepFlow(workflow.stepGraph);
|
|
617
|
-
wf.commit();
|
|
618
|
-
return wf;
|
|
619
|
-
}
|
|
620
|
-
};
|
|
621
|
-
}
|
|
622
|
-
var InngestExecutionEngine = class extends DefaultExecutionEngine {
|
|
623
|
-
inngestStep;
|
|
624
|
-
inngestAttempts;
|
|
625
|
-
constructor(mastra, inngestStep, inngestAttempts = 0, options) {
|
|
626
|
-
super({ mastra, options });
|
|
627
|
-
this.inngestStep = inngestStep;
|
|
628
|
-
this.inngestAttempts = inngestAttempts;
|
|
629
|
-
}
|
|
630
|
-
async execute(params) {
|
|
631
|
-
await params.emitter.emit("watch-v2", {
|
|
632
|
-
type: "workflow-start",
|
|
633
|
-
payload: { runId: params.runId }
|
|
634
|
-
});
|
|
635
|
-
const result = await super.execute(params);
|
|
636
|
-
await params.emitter.emit("watch-v2", {
|
|
637
|
-
type: "workflow-finish",
|
|
638
|
-
payload: { runId: params.runId }
|
|
639
|
-
});
|
|
640
|
-
return result;
|
|
641
|
-
}
|
|
642
|
-
async fmtReturnValue(executionSpan, emitter, stepResults, lastOutput, error) {
|
|
643
|
-
const base = {
|
|
644
|
-
status: lastOutput.status,
|
|
645
|
-
steps: stepResults
|
|
646
|
-
};
|
|
647
|
-
if (lastOutput.status === "success") {
|
|
648
|
-
await emitter.emit("watch", {
|
|
649
|
-
type: "watch",
|
|
650
|
-
payload: {
|
|
651
|
-
workflowState: {
|
|
652
|
-
status: lastOutput.status,
|
|
653
|
-
steps: stepResults,
|
|
654
|
-
result: lastOutput.output
|
|
655
|
-
}
|
|
656
|
-
},
|
|
657
|
-
eventTimestamp: Date.now()
|
|
658
|
-
});
|
|
659
|
-
base.result = lastOutput.output;
|
|
660
|
-
} else if (lastOutput.status === "failed") {
|
|
661
|
-
base.error = error instanceof Error ? error?.stack ?? error.message : lastOutput?.error instanceof Error ? lastOutput.error.message : lastOutput.error ?? error ?? "Unknown error";
|
|
662
|
-
await emitter.emit("watch", {
|
|
663
|
-
type: "watch",
|
|
664
|
-
payload: {
|
|
665
|
-
workflowState: {
|
|
666
|
-
status: lastOutput.status,
|
|
667
|
-
steps: stepResults,
|
|
668
|
-
result: null,
|
|
669
|
-
error: base.error
|
|
670
|
-
}
|
|
671
|
-
},
|
|
672
|
-
eventTimestamp: Date.now()
|
|
673
|
-
});
|
|
674
|
-
} else if (lastOutput.status === "suspended") {
|
|
675
|
-
await emitter.emit("watch", {
|
|
676
|
-
type: "watch",
|
|
677
|
-
payload: {
|
|
678
|
-
workflowState: {
|
|
679
|
-
status: lastOutput.status,
|
|
680
|
-
steps: stepResults,
|
|
681
|
-
result: null,
|
|
682
|
-
error: null
|
|
683
|
-
}
|
|
684
|
-
},
|
|
685
|
-
eventTimestamp: Date.now()
|
|
686
|
-
});
|
|
687
|
-
const suspendedStepIds = Object.entries(stepResults).flatMap(([stepId, stepResult]) => {
|
|
688
|
-
if (stepResult?.status === "suspended") {
|
|
689
|
-
const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
|
|
690
|
-
return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
|
|
691
|
-
}
|
|
692
|
-
return [];
|
|
1616
|
+
id: params.name,
|
|
1617
|
+
description: params.getDescription(),
|
|
1618
|
+
inputSchema: z.object({
|
|
1619
|
+
prompt: z.string()
|
|
1620
|
+
}),
|
|
1621
|
+
outputSchema,
|
|
1622
|
+
retries,
|
|
1623
|
+
scorers,
|
|
1624
|
+
execute: async ({
|
|
1625
|
+
inputData,
|
|
1626
|
+
runId,
|
|
1627
|
+
[PUBSUB_SYMBOL]: pubsub,
|
|
1628
|
+
[STREAM_FORMAT_SYMBOL]: streamFormat,
|
|
1629
|
+
requestContext,
|
|
1630
|
+
tracingContext,
|
|
1631
|
+
abortSignal,
|
|
1632
|
+
abort,
|
|
1633
|
+
writer
|
|
1634
|
+
}) => {
|
|
1635
|
+
let streamPromise = {};
|
|
1636
|
+
streamPromise.promise = new Promise((resolve, reject) => {
|
|
1637
|
+
streamPromise.resolve = resolve;
|
|
1638
|
+
streamPromise.reject = reject;
|
|
693
1639
|
});
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
writableStream,
|
|
713
|
-
tracingContext
|
|
714
|
-
}) {
|
|
715
|
-
let { duration, fn } = entry;
|
|
716
|
-
const sleepSpan = tracingContext?.currentSpan?.createChildSpan({
|
|
717
|
-
type: AISpanType.WORKFLOW_SLEEP,
|
|
718
|
-
name: `sleep: ${duration ? `${duration}ms` : "dynamic"}`,
|
|
719
|
-
attributes: {
|
|
720
|
-
durationMs: duration,
|
|
721
|
-
sleepType: fn ? "dynamic" : "fixed"
|
|
722
|
-
},
|
|
723
|
-
tracingPolicy: this.options?.tracingPolicy
|
|
724
|
-
});
|
|
725
|
-
if (fn) {
|
|
726
|
-
const stepCallId = randomUUID();
|
|
727
|
-
duration = await this.inngestStep.run(`workflow.${workflowId}.sleep.${entry.id}`, async () => {
|
|
728
|
-
return await fn({
|
|
729
|
-
runId,
|
|
730
|
-
workflowId,
|
|
731
|
-
mastra: this.mastra,
|
|
732
|
-
runtimeContext,
|
|
733
|
-
inputData: prevOutput,
|
|
734
|
-
state: executionContext.state,
|
|
735
|
-
setState: (state) => {
|
|
736
|
-
executionContext.state = state;
|
|
737
|
-
},
|
|
738
|
-
runCount: -1,
|
|
739
|
-
tracingContext: {
|
|
740
|
-
currentSpan: sleepSpan
|
|
741
|
-
},
|
|
742
|
-
getInitData: () => stepResults?.input,
|
|
743
|
-
getStepResult: getStepResult.bind(this, stepResults),
|
|
744
|
-
// TODO: this function shouldn't have suspend probably?
|
|
745
|
-
suspend: async (_suspendPayload) => {
|
|
746
|
-
},
|
|
747
|
-
bail: () => {
|
|
1640
|
+
let structuredResult = null;
|
|
1641
|
+
const toolData = {
|
|
1642
|
+
name: params.name,
|
|
1643
|
+
args: inputData
|
|
1644
|
+
};
|
|
1645
|
+
let stream;
|
|
1646
|
+
if ((await params.getModel()).specificationVersion === "v1") {
|
|
1647
|
+
const { fullStream } = await params.streamLegacy(inputData.prompt, {
|
|
1648
|
+
...agentOptions ?? {},
|
|
1649
|
+
requestContext,
|
|
1650
|
+
tracingContext,
|
|
1651
|
+
onFinish: (result) => {
|
|
1652
|
+
const resultWithObject = result;
|
|
1653
|
+
if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
|
|
1654
|
+
structuredResult = resultWithObject.object;
|
|
1655
|
+
}
|
|
1656
|
+
streamPromise.resolve(result.text);
|
|
1657
|
+
void agentOptions?.onFinish?.(result);
|
|
748
1658
|
},
|
|
749
|
-
|
|
750
|
-
|
|
1659
|
+
abortSignal
|
|
1660
|
+
});
|
|
1661
|
+
stream = fullStream;
|
|
1662
|
+
} else {
|
|
1663
|
+
const modelOutput = await params.stream(inputData.prompt, {
|
|
1664
|
+
...agentOptions ?? {},
|
|
1665
|
+
requestContext,
|
|
1666
|
+
tracingContext,
|
|
1667
|
+
onFinish: (result) => {
|
|
1668
|
+
const resultWithObject = result;
|
|
1669
|
+
if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
|
|
1670
|
+
structuredResult = resultWithObject.object;
|
|
1671
|
+
}
|
|
1672
|
+
streamPromise.resolve(result.text);
|
|
1673
|
+
void agentOptions?.onFinish?.(result);
|
|
751
1674
|
},
|
|
752
|
-
|
|
753
|
-
// TODO: add streamVNext support
|
|
754
|
-
[STREAM_FORMAT_SYMBOL]: executionContext.format,
|
|
755
|
-
engine: { step: this.inngestStep },
|
|
756
|
-
abortSignal: abortController?.signal,
|
|
757
|
-
writer: new ToolStream(
|
|
758
|
-
{
|
|
759
|
-
prefix: "workflow-step",
|
|
760
|
-
callId: stepCallId,
|
|
761
|
-
name: "sleep",
|
|
762
|
-
runId
|
|
763
|
-
},
|
|
764
|
-
writableStream
|
|
765
|
-
)
|
|
1675
|
+
abortSignal
|
|
766
1676
|
});
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
1677
|
+
stream = modelOutput.fullStream;
|
|
1678
|
+
}
|
|
1679
|
+
if (streamFormat === "legacy") {
|
|
1680
|
+
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
1681
|
+
type: "watch",
|
|
1682
|
+
runId,
|
|
1683
|
+
data: { type: "tool-call-streaming-start", ...toolData ?? {} }
|
|
1684
|
+
});
|
|
1685
|
+
for await (const chunk of stream) {
|
|
1686
|
+
if (chunk.type === "text-delta") {
|
|
1687
|
+
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
1688
|
+
type: "watch",
|
|
1689
|
+
runId,
|
|
1690
|
+
data: { type: "tool-call-delta", ...toolData ?? {}, argsTextDelta: chunk.textDelta }
|
|
1691
|
+
});
|
|
1692
|
+
}
|
|
771
1693
|
}
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
try {
|
|
775
|
-
await this.inngestStep.sleep(entry.id, !duration || duration < 0 ? 0 : duration);
|
|
776
|
-
sleepSpan?.end();
|
|
777
|
-
} catch (e) {
|
|
778
|
-
sleepSpan?.error({ error: e });
|
|
779
|
-
throw e;
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
async executeSleepUntil({
|
|
783
|
-
workflowId,
|
|
784
|
-
runId,
|
|
785
|
-
entry,
|
|
786
|
-
prevOutput,
|
|
787
|
-
stepResults,
|
|
788
|
-
emitter,
|
|
789
|
-
abortController,
|
|
790
|
-
runtimeContext,
|
|
791
|
-
executionContext,
|
|
792
|
-
writableStream,
|
|
793
|
-
tracingContext
|
|
794
|
-
}) {
|
|
795
|
-
let { date, fn } = entry;
|
|
796
|
-
const sleepUntilSpan = tracingContext?.currentSpan?.createChildSpan({
|
|
797
|
-
type: AISpanType.WORKFLOW_SLEEP,
|
|
798
|
-
name: `sleepUntil: ${date ? date.toISOString() : "dynamic"}`,
|
|
799
|
-
attributes: {
|
|
800
|
-
untilDate: date,
|
|
801
|
-
durationMs: date ? Math.max(0, date.getTime() - Date.now()) : void 0,
|
|
802
|
-
sleepType: fn ? "dynamic" : "fixed"
|
|
803
|
-
},
|
|
804
|
-
tracingPolicy: this.options?.tracingPolicy
|
|
805
|
-
});
|
|
806
|
-
if (fn) {
|
|
807
|
-
date = await this.inngestStep.run(`workflow.${workflowId}.sleepUntil.${entry.id}`, async () => {
|
|
808
|
-
const stepCallId = randomUUID();
|
|
809
|
-
return await fn({
|
|
1694
|
+
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
1695
|
+
type: "watch",
|
|
810
1696
|
runId,
|
|
811
|
-
|
|
812
|
-
mastra: this.mastra,
|
|
813
|
-
runtimeContext,
|
|
814
|
-
inputData: prevOutput,
|
|
815
|
-
state: executionContext.state,
|
|
816
|
-
setState: (state) => {
|
|
817
|
-
executionContext.state = state;
|
|
818
|
-
},
|
|
819
|
-
runCount: -1,
|
|
820
|
-
tracingContext: {
|
|
821
|
-
currentSpan: sleepUntilSpan
|
|
822
|
-
},
|
|
823
|
-
getInitData: () => stepResults?.input,
|
|
824
|
-
getStepResult: getStepResult.bind(this, stepResults),
|
|
825
|
-
// TODO: this function shouldn't have suspend probably?
|
|
826
|
-
suspend: async (_suspendPayload) => {
|
|
827
|
-
},
|
|
828
|
-
bail: () => {
|
|
829
|
-
},
|
|
830
|
-
abort: () => {
|
|
831
|
-
abortController?.abort();
|
|
832
|
-
},
|
|
833
|
-
[EMITTER_SYMBOL]: emitter,
|
|
834
|
-
[STREAM_FORMAT_SYMBOL]: executionContext.format,
|
|
835
|
-
// TODO: add streamVNext support
|
|
836
|
-
engine: { step: this.inngestStep },
|
|
837
|
-
abortSignal: abortController?.signal,
|
|
838
|
-
writer: new ToolStream(
|
|
839
|
-
{
|
|
840
|
-
prefix: "workflow-step",
|
|
841
|
-
callId: stepCallId,
|
|
842
|
-
name: "sleep",
|
|
843
|
-
runId
|
|
844
|
-
},
|
|
845
|
-
writableStream
|
|
846
|
-
)
|
|
1697
|
+
data: { type: "tool-call-streaming-finish", ...toolData ?? {} }
|
|
847
1698
|
});
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
|
|
1699
|
+
} else {
|
|
1700
|
+
for await (const chunk of stream) {
|
|
1701
|
+
await writer.write(chunk);
|
|
1702
|
+
}
|
|
851
1703
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1704
|
+
if (abortSignal.aborted) {
|
|
1705
|
+
return abort();
|
|
1706
|
+
}
|
|
1707
|
+
if (structuredResult !== null) {
|
|
1708
|
+
return structuredResult;
|
|
1709
|
+
}
|
|
1710
|
+
return {
|
|
1711
|
+
text: await streamPromise.promise
|
|
1712
|
+
};
|
|
1713
|
+
},
|
|
1714
|
+
component: params.component
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
function createStepFromTool(params, agentOrToolOptions) {
|
|
1718
|
+
const toolOpts = agentOrToolOptions;
|
|
1719
|
+
if (!params.inputSchema || !params.outputSchema) {
|
|
1720
|
+
throw new Error("Tool must have input and output schemas defined");
|
|
1721
|
+
}
|
|
1722
|
+
return {
|
|
1723
|
+
id: params.id,
|
|
1724
|
+
description: params.description,
|
|
1725
|
+
inputSchema: params.inputSchema,
|
|
1726
|
+
outputSchema: params.outputSchema,
|
|
1727
|
+
resumeSchema: params.resumeSchema,
|
|
1728
|
+
suspendSchema: params.suspendSchema,
|
|
1729
|
+
retries: toolOpts?.retries,
|
|
1730
|
+
scorers: toolOpts?.scorers,
|
|
1731
|
+
execute: async ({
|
|
1732
|
+
inputData,
|
|
1733
|
+
mastra,
|
|
1734
|
+
requestContext,
|
|
1735
|
+
tracingContext,
|
|
1736
|
+
suspend,
|
|
1737
|
+
resumeData,
|
|
1738
|
+
runId,
|
|
1739
|
+
workflowId,
|
|
1740
|
+
state,
|
|
1741
|
+
setState
|
|
1742
|
+
}) => {
|
|
1743
|
+
const toolContext = {
|
|
1744
|
+
mastra,
|
|
1745
|
+
requestContext,
|
|
1746
|
+
tracingContext,
|
|
1747
|
+
workflow: {
|
|
1748
|
+
runId,
|
|
1749
|
+
resumeData,
|
|
1750
|
+
suspend,
|
|
1751
|
+
workflowId,
|
|
1752
|
+
state,
|
|
1753
|
+
setState
|
|
856
1754
|
}
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
1755
|
+
};
|
|
1756
|
+
return params.execute(inputData, toolContext);
|
|
1757
|
+
},
|
|
1758
|
+
component: "TOOL"
|
|
1759
|
+
};
|
|
1760
|
+
}
|
|
1761
|
+
function createStepFromProcessor(processor) {
|
|
1762
|
+
const getProcessorEntityType = (phase) => {
|
|
1763
|
+
switch (phase) {
|
|
1764
|
+
case "input":
|
|
1765
|
+
return EntityType.INPUT_PROCESSOR;
|
|
1766
|
+
case "inputStep":
|
|
1767
|
+
return EntityType.INPUT_STEP_PROCESSOR;
|
|
1768
|
+
case "outputStream":
|
|
1769
|
+
case "outputResult":
|
|
1770
|
+
return EntityType.OUTPUT_PROCESSOR;
|
|
1771
|
+
case "outputStep":
|
|
1772
|
+
return EntityType.OUTPUT_STEP_PROCESSOR;
|
|
1773
|
+
default:
|
|
1774
|
+
return EntityType.OUTPUT_PROCESSOR;
|
|
862
1775
|
}
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
1776
|
+
};
|
|
1777
|
+
const getSpanNamePrefix = (phase) => {
|
|
1778
|
+
switch (phase) {
|
|
1779
|
+
case "input":
|
|
1780
|
+
return "input processor";
|
|
1781
|
+
case "inputStep":
|
|
1782
|
+
return "input step processor";
|
|
1783
|
+
case "outputStream":
|
|
1784
|
+
return "output stream processor";
|
|
1785
|
+
case "outputResult":
|
|
1786
|
+
return "output processor";
|
|
1787
|
+
case "outputStep":
|
|
1788
|
+
return "output step processor";
|
|
1789
|
+
default:
|
|
1790
|
+
return "processor";
|
|
869
1791
|
}
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
1792
|
+
};
|
|
1793
|
+
const hasPhaseMethod = (phase) => {
|
|
1794
|
+
switch (phase) {
|
|
1795
|
+
case "input":
|
|
1796
|
+
return !!processor.processInput;
|
|
1797
|
+
case "inputStep":
|
|
1798
|
+
return !!processor.processInputStep;
|
|
1799
|
+
case "outputStream":
|
|
1800
|
+
return !!processor.processOutputStream;
|
|
1801
|
+
case "outputResult":
|
|
1802
|
+
return !!processor.processOutputResult;
|
|
1803
|
+
case "outputStep":
|
|
1804
|
+
return !!processor.processOutputStep;
|
|
1805
|
+
default:
|
|
1806
|
+
return false;
|
|
878
1807
|
}
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
currentStep: {
|
|
916
|
-
id: step.id,
|
|
917
|
-
status: "running"
|
|
918
|
-
},
|
|
919
|
-
workflowState: {
|
|
920
|
-
status: "running",
|
|
921
|
-
steps: {
|
|
922
|
-
...stepResults,
|
|
923
|
-
[step.id]: {
|
|
924
|
-
status: "running"
|
|
925
|
-
}
|
|
926
|
-
},
|
|
927
|
-
result: null,
|
|
928
|
-
error: null
|
|
929
|
-
}
|
|
930
|
-
},
|
|
931
|
-
eventTimestamp: Date.now()
|
|
932
|
-
});
|
|
933
|
-
await emitter.emit("watch-v2", {
|
|
934
|
-
type: "workflow-step-start",
|
|
935
|
-
payload: {
|
|
936
|
-
id: step.id,
|
|
937
|
-
status: "running",
|
|
938
|
-
payload: inputData,
|
|
939
|
-
startedAt: startedAt2
|
|
940
|
-
}
|
|
941
|
-
});
|
|
942
|
-
return startedAt2;
|
|
1808
|
+
};
|
|
1809
|
+
return {
|
|
1810
|
+
id: `processor:${processor.id}`,
|
|
1811
|
+
description: processor.name ?? `Processor ${processor.id}`,
|
|
1812
|
+
inputSchema: ProcessorStepSchema,
|
|
1813
|
+
outputSchema: ProcessorStepOutputSchema,
|
|
1814
|
+
execute: async ({ inputData, requestContext, tracingContext }) => {
|
|
1815
|
+
const input = inputData;
|
|
1816
|
+
const {
|
|
1817
|
+
phase,
|
|
1818
|
+
messages,
|
|
1819
|
+
messageList,
|
|
1820
|
+
stepNumber,
|
|
1821
|
+
systemMessages,
|
|
1822
|
+
part,
|
|
1823
|
+
streamParts,
|
|
1824
|
+
state,
|
|
1825
|
+
finishReason,
|
|
1826
|
+
toolCalls,
|
|
1827
|
+
text,
|
|
1828
|
+
retryCount,
|
|
1829
|
+
// inputStep phase fields for model/tools configuration
|
|
1830
|
+
model,
|
|
1831
|
+
tools,
|
|
1832
|
+
toolChoice,
|
|
1833
|
+
activeTools,
|
|
1834
|
+
providerOptions,
|
|
1835
|
+
modelSettings,
|
|
1836
|
+
structuredOutput,
|
|
1837
|
+
steps
|
|
1838
|
+
} = input;
|
|
1839
|
+
const abort = (reason, options) => {
|
|
1840
|
+
throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
|
|
1841
|
+
};
|
|
1842
|
+
if (!hasPhaseMethod(phase)) {
|
|
1843
|
+
return input;
|
|
943
1844
|
}
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
const
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
function: step.getFunction(),
|
|
958
|
-
data: {
|
|
959
|
-
inputData,
|
|
960
|
-
initialState: executionContext.state ?? snapshot?.value ?? {},
|
|
961
|
-
runId,
|
|
962
|
-
resume: {
|
|
963
|
-
runId,
|
|
964
|
-
steps: resume.steps.slice(1),
|
|
965
|
-
stepResults: snapshot?.context,
|
|
966
|
-
resumePayload: resume.resumePayload,
|
|
967
|
-
// @ts-ignore
|
|
968
|
-
resumePath: snapshot?.suspendedPaths?.[resume.steps?.[1]]
|
|
969
|
-
},
|
|
970
|
-
outputOptions: { includeState: true }
|
|
971
|
-
}
|
|
972
|
-
});
|
|
973
|
-
result = invokeResp.result;
|
|
974
|
-
runId = invokeResp.runId;
|
|
975
|
-
executionContext.state = invokeResp.result.state;
|
|
976
|
-
} else {
|
|
977
|
-
const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
|
|
978
|
-
function: step.getFunction(),
|
|
979
|
-
data: {
|
|
980
|
-
inputData,
|
|
981
|
-
initialState: executionContext.state ?? {},
|
|
982
|
-
outputOptions: { includeState: true }
|
|
983
|
-
}
|
|
984
|
-
});
|
|
985
|
-
result = invokeResp.result;
|
|
986
|
-
runId = invokeResp.runId;
|
|
987
|
-
executionContext.state = invokeResp.result.state;
|
|
1845
|
+
const currentSpan = tracingContext?.currentSpan;
|
|
1846
|
+
const parentSpan = phase === "inputStep" || phase === "outputStep" ? currentSpan?.findParent(SpanType.MODEL_STEP) || currentSpan : currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan;
|
|
1847
|
+
const processorSpan = phase !== "outputStream" ? parentSpan?.createChildSpan({
|
|
1848
|
+
type: SpanType.PROCESSOR_RUN,
|
|
1849
|
+
name: `${getSpanNamePrefix(phase)}: ${processor.id}`,
|
|
1850
|
+
entityType: getProcessorEntityType(phase),
|
|
1851
|
+
entityId: processor.id,
|
|
1852
|
+
entityName: processor.name ?? processor.id,
|
|
1853
|
+
input: { phase, messageCount: messages?.length },
|
|
1854
|
+
attributes: {
|
|
1855
|
+
processorExecutor: "workflow",
|
|
1856
|
+
// Read processorIndex from processor (set in combineProcessorsIntoWorkflow)
|
|
1857
|
+
processorIndex: processor.processorIndex
|
|
988
1858
|
}
|
|
989
|
-
}
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1859
|
+
}) : void 0;
|
|
1860
|
+
const processorTracingContext = processorSpan ? { currentSpan: processorSpan } : tracingContext;
|
|
1861
|
+
const baseContext = {
|
|
1862
|
+
abort,
|
|
1863
|
+
retryCount: retryCount ?? 0,
|
|
1864
|
+
requestContext,
|
|
1865
|
+
tracingContext: processorTracingContext
|
|
1866
|
+
};
|
|
1867
|
+
const passThrough = {
|
|
1868
|
+
phase,
|
|
1869
|
+
// Auto-create MessageList from messages if not provided
|
|
1870
|
+
// This enables running processor workflows from the UI where messageList can't be serialized
|
|
1871
|
+
messageList: messageList ?? (Array.isArray(messages) ? new MessageList().add(messages, "input").addSystem(systemMessages ?? []) : void 0),
|
|
1872
|
+
stepNumber,
|
|
1873
|
+
systemMessages,
|
|
1874
|
+
streamParts,
|
|
1875
|
+
state,
|
|
1876
|
+
finishReason,
|
|
1877
|
+
toolCalls,
|
|
1878
|
+
text,
|
|
1879
|
+
retryCount,
|
|
1880
|
+
// inputStep phase fields for model/tools configuration
|
|
1881
|
+
model,
|
|
1882
|
+
tools,
|
|
1883
|
+
toolChoice,
|
|
1884
|
+
activeTools,
|
|
1885
|
+
providerOptions,
|
|
1886
|
+
modelSettings,
|
|
1887
|
+
structuredOutput,
|
|
1888
|
+
steps
|
|
1889
|
+
};
|
|
1890
|
+
const executePhaseWithSpan = async (fn) => {
|
|
1891
|
+
try {
|
|
1892
|
+
const result = await fn();
|
|
1893
|
+
processorSpan?.end({ output: result });
|
|
1894
|
+
return result;
|
|
1895
|
+
} catch (error) {
|
|
1896
|
+
if (error instanceof TripWire) {
|
|
1897
|
+
processorSpan?.end({ output: { tripwire: error.message } });
|
|
1898
|
+
} else {
|
|
1899
|
+
processorSpan?.error({ error, endSpan: true });
|
|
1900
|
+
}
|
|
1901
|
+
throw error;
|
|
1002
1902
|
}
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
id:
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
},
|
|
1016
|
-
workflowState: {
|
|
1017
|
-
status: "running",
|
|
1018
|
-
steps: stepResults,
|
|
1019
|
-
result: null,
|
|
1020
|
-
error: null
|
|
1021
|
-
}
|
|
1022
|
-
},
|
|
1023
|
-
eventTimestamp: Date.now()
|
|
1024
|
-
});
|
|
1025
|
-
await emitter.emit("watch-v2", {
|
|
1026
|
-
type: "workflow-step-result",
|
|
1027
|
-
payload: {
|
|
1028
|
-
id: step.id,
|
|
1029
|
-
status: "failed",
|
|
1030
|
-
error: result?.error,
|
|
1031
|
-
payload: prevOutput
|
|
1903
|
+
};
|
|
1904
|
+
return executePhaseWithSpan(async () => {
|
|
1905
|
+
switch (phase) {
|
|
1906
|
+
case "input": {
|
|
1907
|
+
if (processor.processInput) {
|
|
1908
|
+
if (!passThrough.messageList) {
|
|
1909
|
+
throw new MastraError({
|
|
1910
|
+
category: ErrorCategory.USER,
|
|
1911
|
+
domain: ErrorDomain.MASTRA_WORKFLOW,
|
|
1912
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
1913
|
+
text: `Processor ${processor.id} requires messageList or messages for processInput phase`
|
|
1914
|
+
});
|
|
1032
1915
|
}
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
for (const [stepName, stepResult] of suspendedSteps) {
|
|
1041
|
-
const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
|
|
1042
|
-
executionContext.suspendedPaths[step.id] = executionContext.executionPath;
|
|
1043
|
-
await emitter.emit("watch", {
|
|
1044
|
-
type: "watch",
|
|
1045
|
-
payload: {
|
|
1046
|
-
currentStep: {
|
|
1047
|
-
id: step.id,
|
|
1048
|
-
status: "suspended",
|
|
1049
|
-
payload: stepResult.payload,
|
|
1050
|
-
suspendPayload: {
|
|
1051
|
-
...stepResult?.suspendPayload,
|
|
1052
|
-
__workflow_meta: { runId, path: suspendPath }
|
|
1053
|
-
}
|
|
1054
|
-
},
|
|
1055
|
-
workflowState: {
|
|
1056
|
-
status: "running",
|
|
1057
|
-
steps: stepResults,
|
|
1058
|
-
result: null,
|
|
1059
|
-
error: null
|
|
1060
|
-
}
|
|
1061
|
-
},
|
|
1062
|
-
eventTimestamp: Date.now()
|
|
1916
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
1917
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
1918
|
+
const result = await processor.processInput({
|
|
1919
|
+
...baseContext,
|
|
1920
|
+
messages,
|
|
1921
|
+
messageList: passThrough.messageList,
|
|
1922
|
+
systemMessages: systemMessages ?? []
|
|
1063
1923
|
});
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1924
|
+
if (result instanceof MessageList) {
|
|
1925
|
+
if (result !== passThrough.messageList) {
|
|
1926
|
+
throw new MastraError({
|
|
1927
|
+
category: ErrorCategory.USER,
|
|
1928
|
+
domain: ErrorDomain.MASTRA_WORKFLOW,
|
|
1929
|
+
id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
|
|
1930
|
+
text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
|
|
1931
|
+
});
|
|
1069
1932
|
}
|
|
1933
|
+
return {
|
|
1934
|
+
...passThrough,
|
|
1935
|
+
messages: result.get.all.db(),
|
|
1936
|
+
systemMessages: result.getAllSystemMessages()
|
|
1937
|
+
};
|
|
1938
|
+
} else if (Array.isArray(result)) {
|
|
1939
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
1940
|
+
result,
|
|
1941
|
+
passThrough.messageList,
|
|
1942
|
+
idsBeforeProcessing,
|
|
1943
|
+
check,
|
|
1944
|
+
"input"
|
|
1945
|
+
);
|
|
1946
|
+
return { ...passThrough, messages: result };
|
|
1947
|
+
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
1948
|
+
const typedResult = result;
|
|
1949
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
1950
|
+
typedResult.messages,
|
|
1951
|
+
passThrough.messageList,
|
|
1952
|
+
idsBeforeProcessing,
|
|
1953
|
+
check,
|
|
1954
|
+
"input"
|
|
1955
|
+
);
|
|
1956
|
+
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
1957
|
+
return {
|
|
1958
|
+
...passThrough,
|
|
1959
|
+
messages: typedResult.messages,
|
|
1960
|
+
systemMessages: typedResult.systemMessages
|
|
1961
|
+
};
|
|
1962
|
+
}
|
|
1963
|
+
return { ...passThrough, messages };
|
|
1964
|
+
}
|
|
1965
|
+
return { ...passThrough, messages };
|
|
1966
|
+
}
|
|
1967
|
+
case "inputStep": {
|
|
1968
|
+
if (processor.processInputStep) {
|
|
1969
|
+
if (!passThrough.messageList) {
|
|
1970
|
+
throw new MastraError({
|
|
1971
|
+
category: ErrorCategory.USER,
|
|
1972
|
+
domain: ErrorDomain.MASTRA_WORKFLOW,
|
|
1973
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
1974
|
+
text: `Processor ${processor.id} requires messageList or messages for processInputStep phase`
|
|
1975
|
+
});
|
|
1976
|
+
}
|
|
1977
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
1978
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
1979
|
+
const result = await processor.processInputStep({
|
|
1980
|
+
...baseContext,
|
|
1981
|
+
messages,
|
|
1982
|
+
messageList: passThrough.messageList,
|
|
1983
|
+
stepNumber: stepNumber ?? 0,
|
|
1984
|
+
systemMessages: systemMessages ?? [],
|
|
1985
|
+
// Pass model/tools configuration fields - types match ProcessInputStepArgs
|
|
1986
|
+
model,
|
|
1987
|
+
tools,
|
|
1988
|
+
toolChoice,
|
|
1989
|
+
activeTools,
|
|
1990
|
+
providerOptions,
|
|
1991
|
+
modelSettings,
|
|
1992
|
+
structuredOutput,
|
|
1993
|
+
steps: steps ?? []
|
|
1070
1994
|
});
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1995
|
+
const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {
|
|
1996
|
+
messageList: passThrough.messageList,
|
|
1997
|
+
processor,
|
|
1998
|
+
stepNumber: stepNumber ?? 0
|
|
1999
|
+
});
|
|
2000
|
+
if (validatedResult.messages) {
|
|
2001
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
2002
|
+
validatedResult.messages,
|
|
2003
|
+
passThrough.messageList,
|
|
2004
|
+
idsBeforeProcessing,
|
|
2005
|
+
check
|
|
2006
|
+
);
|
|
2007
|
+
}
|
|
2008
|
+
if (validatedResult.systemMessages) {
|
|
2009
|
+
passThrough.messageList.replaceAllSystemMessages(validatedResult.systemMessages);
|
|
2010
|
+
}
|
|
2011
|
+
return { ...passThrough, messages, ...validatedResult };
|
|
2012
|
+
}
|
|
2013
|
+
return { ...passThrough, messages };
|
|
2014
|
+
}
|
|
2015
|
+
case "outputStream": {
|
|
2016
|
+
if (processor.processOutputStream) {
|
|
2017
|
+
const spanKey = `__outputStreamSpan_${processor.id}`;
|
|
2018
|
+
const mutableState = state ?? {};
|
|
2019
|
+
let processorSpan2 = mutableState[spanKey];
|
|
2020
|
+
if (!processorSpan2 && parentSpan) {
|
|
2021
|
+
processorSpan2 = parentSpan.createChildSpan({
|
|
2022
|
+
type: SpanType.PROCESSOR_RUN,
|
|
2023
|
+
name: `output stream processor: ${processor.id}`,
|
|
2024
|
+
entityType: EntityType.OUTPUT_PROCESSOR,
|
|
2025
|
+
entityId: processor.id,
|
|
2026
|
+
entityName: processor.name ?? processor.id,
|
|
2027
|
+
input: { phase, streamParts: [] },
|
|
2028
|
+
attributes: {
|
|
2029
|
+
processorExecutor: "workflow",
|
|
2030
|
+
processorIndex: processor.processorIndex
|
|
1079
2031
|
}
|
|
2032
|
+
});
|
|
2033
|
+
mutableState[spanKey] = processorSpan2;
|
|
2034
|
+
}
|
|
2035
|
+
if (processorSpan2) {
|
|
2036
|
+
processorSpan2.input = {
|
|
2037
|
+
phase,
|
|
2038
|
+
streamParts: streamParts ?? [],
|
|
2039
|
+
totalChunks: (streamParts ?? []).length
|
|
2040
|
+
};
|
|
2041
|
+
}
|
|
2042
|
+
const processorTracingContext2 = processorSpan2 ? { currentSpan: processorSpan2 } : baseContext.tracingContext;
|
|
2043
|
+
let result;
|
|
2044
|
+
try {
|
|
2045
|
+
result = await processor.processOutputStream({
|
|
2046
|
+
...baseContext,
|
|
2047
|
+
tracingContext: processorTracingContext2,
|
|
2048
|
+
part,
|
|
2049
|
+
streamParts: streamParts ?? [],
|
|
2050
|
+
state: mutableState,
|
|
2051
|
+
messageList: passThrough.messageList
|
|
2052
|
+
// Optional for stream processing
|
|
2053
|
+
});
|
|
2054
|
+
if (part && part.type === "finish") {
|
|
2055
|
+
processorSpan2?.end({ output: result });
|
|
2056
|
+
delete mutableState[spanKey];
|
|
1080
2057
|
}
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
currentStep: {
|
|
1087
|
-
id: step.id,
|
|
1088
|
-
status: "suspended",
|
|
1089
|
-
payload: {}
|
|
1090
|
-
},
|
|
1091
|
-
workflowState: {
|
|
1092
|
-
status: "running",
|
|
1093
|
-
steps: stepResults,
|
|
1094
|
-
result: null,
|
|
1095
|
-
error: null
|
|
2058
|
+
} catch (error) {
|
|
2059
|
+
if (error instanceof TripWire) {
|
|
2060
|
+
processorSpan2?.end({ output: { tripwire: error.message } });
|
|
2061
|
+
} else {
|
|
2062
|
+
processorSpan2?.error({ error, endSpan: true });
|
|
1096
2063
|
}
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
});
|
|
1100
|
-
return {
|
|
1101
|
-
executionContext,
|
|
1102
|
-
result: {
|
|
1103
|
-
status: "suspended",
|
|
1104
|
-
payload: {}
|
|
1105
|
-
}
|
|
1106
|
-
};
|
|
1107
|
-
}
|
|
1108
|
-
await emitter.emit("watch", {
|
|
1109
|
-
type: "watch",
|
|
1110
|
-
payload: {
|
|
1111
|
-
currentStep: {
|
|
1112
|
-
id: step.id,
|
|
1113
|
-
status: "success",
|
|
1114
|
-
output: result?.result
|
|
1115
|
-
},
|
|
1116
|
-
workflowState: {
|
|
1117
|
-
status: "running",
|
|
1118
|
-
steps: stepResults,
|
|
1119
|
-
result: null,
|
|
1120
|
-
error: null
|
|
2064
|
+
delete mutableState[spanKey];
|
|
2065
|
+
throw error;
|
|
1121
2066
|
}
|
|
1122
|
-
|
|
1123
|
-
eventTimestamp: Date.now()
|
|
1124
|
-
});
|
|
1125
|
-
await emitter.emit("watch-v2", {
|
|
1126
|
-
type: "workflow-step-result",
|
|
1127
|
-
payload: {
|
|
1128
|
-
id: step.id,
|
|
1129
|
-
status: "success",
|
|
1130
|
-
output: result?.result
|
|
1131
|
-
}
|
|
1132
|
-
});
|
|
1133
|
-
await emitter.emit("watch-v2", {
|
|
1134
|
-
type: "workflow-step-finish",
|
|
1135
|
-
payload: {
|
|
1136
|
-
id: step.id,
|
|
1137
|
-
metadata: {}
|
|
2067
|
+
return { ...passThrough, state: mutableState, part: result };
|
|
1138
2068
|
}
|
|
1139
|
-
|
|
1140
|
-
return { executionContext, result: { status: "success", output: result?.result } };
|
|
1141
|
-
}
|
|
1142
|
-
);
|
|
1143
|
-
Object.assign(executionContext, res.executionContext);
|
|
1144
|
-
return {
|
|
1145
|
-
...res.result,
|
|
1146
|
-
startedAt,
|
|
1147
|
-
endedAt: Date.now(),
|
|
1148
|
-
payload: inputData,
|
|
1149
|
-
resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
|
|
1150
|
-
resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
|
|
1151
|
-
};
|
|
1152
|
-
}
|
|
1153
|
-
let stepRes;
|
|
1154
|
-
try {
|
|
1155
|
-
stepRes = await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}`, async () => {
|
|
1156
|
-
let execResults;
|
|
1157
|
-
let suspended;
|
|
1158
|
-
let bailed;
|
|
1159
|
-
try {
|
|
1160
|
-
if (validationError) {
|
|
1161
|
-
throw validationError;
|
|
2069
|
+
return { ...passThrough, part };
|
|
1162
2070
|
}
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
inputData,
|
|
1173
|
-
resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
|
|
1174
|
-
tracingContext: {
|
|
1175
|
-
currentSpan: stepAISpan
|
|
1176
|
-
},
|
|
1177
|
-
getInitData: () => stepResults?.input,
|
|
1178
|
-
getStepResult: getStepResult.bind(this, stepResults),
|
|
1179
|
-
suspend: async (suspendPayload, suspendOptions) => {
|
|
1180
|
-
executionContext.suspendedPaths[step.id] = executionContext.executionPath;
|
|
1181
|
-
if (suspendOptions?.resumeLabel) {
|
|
1182
|
-
executionContext.resumeLabels[suspendOptions.resumeLabel] = step.id;
|
|
2071
|
+
case "outputResult": {
|
|
2072
|
+
if (processor.processOutputResult) {
|
|
2073
|
+
if (!passThrough.messageList) {
|
|
2074
|
+
throw new MastraError({
|
|
2075
|
+
category: ErrorCategory.USER,
|
|
2076
|
+
domain: ErrorDomain.MASTRA_WORKFLOW,
|
|
2077
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
2078
|
+
text: `Processor ${processor.id} requires messageList or messages for processOutputResult phase`
|
|
2079
|
+
});
|
|
1183
2080
|
}
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
suspendPayload: suspended.payload,
|
|
1232
|
-
payload: inputData,
|
|
1233
|
-
suspendedAt: Date.now(),
|
|
1234
|
-
startedAt,
|
|
1235
|
-
resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
|
|
1236
|
-
resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
|
|
1237
|
-
};
|
|
1238
|
-
} else if (bailed) {
|
|
1239
|
-
execResults = {
|
|
1240
|
-
status: "bailed",
|
|
1241
|
-
output: bailed.payload,
|
|
1242
|
-
payload: inputData,
|
|
1243
|
-
endedAt: Date.now(),
|
|
1244
|
-
startedAt
|
|
1245
|
-
};
|
|
1246
|
-
}
|
|
1247
|
-
await emitter.emit("watch", {
|
|
1248
|
-
type: "watch",
|
|
1249
|
-
payload: {
|
|
1250
|
-
currentStep: {
|
|
1251
|
-
id: step.id,
|
|
1252
|
-
...execResults
|
|
1253
|
-
},
|
|
1254
|
-
workflowState: {
|
|
1255
|
-
status: "running",
|
|
1256
|
-
steps: { ...stepResults, [step.id]: execResults },
|
|
1257
|
-
result: null,
|
|
1258
|
-
error: null
|
|
1259
|
-
}
|
|
1260
|
-
},
|
|
1261
|
-
eventTimestamp: Date.now()
|
|
1262
|
-
});
|
|
1263
|
-
if (execResults.status === "suspended") {
|
|
1264
|
-
await emitter.emit("watch-v2", {
|
|
1265
|
-
type: "workflow-step-suspended",
|
|
1266
|
-
payload: {
|
|
1267
|
-
id: step.id,
|
|
1268
|
-
...execResults
|
|
1269
|
-
}
|
|
1270
|
-
});
|
|
1271
|
-
} else {
|
|
1272
|
-
await emitter.emit("watch-v2", {
|
|
1273
|
-
type: "workflow-step-result",
|
|
1274
|
-
payload: {
|
|
1275
|
-
id: step.id,
|
|
1276
|
-
...execResults
|
|
1277
|
-
}
|
|
1278
|
-
});
|
|
1279
|
-
await emitter.emit("watch-v2", {
|
|
1280
|
-
type: "workflow-step-finish",
|
|
1281
|
-
payload: {
|
|
1282
|
-
id: step.id,
|
|
1283
|
-
metadata: {}
|
|
2081
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
2082
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
2083
|
+
const result = await processor.processOutputResult({
|
|
2084
|
+
...baseContext,
|
|
2085
|
+
messages,
|
|
2086
|
+
messageList: passThrough.messageList
|
|
2087
|
+
});
|
|
2088
|
+
if (result instanceof MessageList) {
|
|
2089
|
+
if (result !== passThrough.messageList) {
|
|
2090
|
+
throw new MastraError({
|
|
2091
|
+
category: ErrorCategory.USER,
|
|
2092
|
+
domain: ErrorDomain.MASTRA_WORKFLOW,
|
|
2093
|
+
id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
|
|
2094
|
+
text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
|
|
2095
|
+
});
|
|
2096
|
+
}
|
|
2097
|
+
return {
|
|
2098
|
+
...passThrough,
|
|
2099
|
+
messages: result.get.all.db(),
|
|
2100
|
+
systemMessages: result.getAllSystemMessages()
|
|
2101
|
+
};
|
|
2102
|
+
} else if (Array.isArray(result)) {
|
|
2103
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
2104
|
+
result,
|
|
2105
|
+
passThrough.messageList,
|
|
2106
|
+
idsBeforeProcessing,
|
|
2107
|
+
check,
|
|
2108
|
+
"response"
|
|
2109
|
+
);
|
|
2110
|
+
return { ...passThrough, messages: result };
|
|
2111
|
+
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
2112
|
+
const typedResult = result;
|
|
2113
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
2114
|
+
typedResult.messages,
|
|
2115
|
+
passThrough.messageList,
|
|
2116
|
+
idsBeforeProcessing,
|
|
2117
|
+
check,
|
|
2118
|
+
"response"
|
|
2119
|
+
);
|
|
2120
|
+
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
2121
|
+
return {
|
|
2122
|
+
...passThrough,
|
|
2123
|
+
messages: typedResult.messages,
|
|
2124
|
+
systemMessages: typedResult.systemMessages
|
|
2125
|
+
};
|
|
2126
|
+
}
|
|
2127
|
+
return { ...passThrough, messages };
|
|
1284
2128
|
}
|
|
1285
|
-
|
|
1286
|
-
}
|
|
1287
|
-
stepAISpan?.end({ output: execResults });
|
|
1288
|
-
return { result: execResults, executionContext, stepResults };
|
|
1289
|
-
});
|
|
1290
|
-
} catch (e) {
|
|
1291
|
-
const stepFailure = e instanceof Error ? e?.cause : {
|
|
1292
|
-
status: "failed",
|
|
1293
|
-
error: e instanceof Error ? e.message : String(e),
|
|
1294
|
-
payload: inputData,
|
|
1295
|
-
startedAt,
|
|
1296
|
-
endedAt: Date.now()
|
|
1297
|
-
};
|
|
1298
|
-
stepRes = {
|
|
1299
|
-
result: stepFailure,
|
|
1300
|
-
executionContext,
|
|
1301
|
-
stepResults: {
|
|
1302
|
-
...stepResults,
|
|
1303
|
-
[step.id]: stepFailure
|
|
1304
|
-
}
|
|
1305
|
-
};
|
|
1306
|
-
}
|
|
1307
|
-
if (disableScorers !== false && stepRes.result.status === "success") {
|
|
1308
|
-
await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}.score`, async () => {
|
|
1309
|
-
if (step.scorers) {
|
|
1310
|
-
await this.runScorers({
|
|
1311
|
-
scorers: step.scorers,
|
|
1312
|
-
runId: executionContext.runId,
|
|
1313
|
-
input: inputData,
|
|
1314
|
-
output: stepRes.result,
|
|
1315
|
-
workflowId: executionContext.workflowId,
|
|
1316
|
-
stepId: step.id,
|
|
1317
|
-
runtimeContext,
|
|
1318
|
-
disableScorers,
|
|
1319
|
-
tracingContext: { currentSpan: stepAISpan }
|
|
1320
|
-
});
|
|
1321
|
-
}
|
|
1322
|
-
});
|
|
1323
|
-
}
|
|
1324
|
-
Object.assign(executionContext.suspendedPaths, stepRes.executionContext.suspendedPaths);
|
|
1325
|
-
Object.assign(stepResults, stepRes.stepResults);
|
|
1326
|
-
executionContext.state = stepRes.executionContext.state;
|
|
1327
|
-
return stepRes.result;
|
|
1328
|
-
}
|
|
1329
|
-
async persistStepUpdate({
|
|
1330
|
-
workflowId,
|
|
1331
|
-
runId,
|
|
1332
|
-
stepResults,
|
|
1333
|
-
resourceId,
|
|
1334
|
-
executionContext,
|
|
1335
|
-
serializedStepGraph,
|
|
1336
|
-
workflowStatus,
|
|
1337
|
-
result,
|
|
1338
|
-
error
|
|
1339
|
-
}) {
|
|
1340
|
-
await this.inngestStep.run(
|
|
1341
|
-
`workflow.${workflowId}.run.${runId}.path.${JSON.stringify(executionContext.executionPath)}.stepUpdate`,
|
|
1342
|
-
async () => {
|
|
1343
|
-
const shouldPersistSnapshot = this.options.shouldPersistSnapshot({ stepResults, workflowStatus });
|
|
1344
|
-
if (!shouldPersistSnapshot) {
|
|
1345
|
-
return;
|
|
1346
|
-
}
|
|
1347
|
-
await this.mastra?.getStorage()?.persistWorkflowSnapshot({
|
|
1348
|
-
workflowName: workflowId,
|
|
1349
|
-
runId,
|
|
1350
|
-
resourceId,
|
|
1351
|
-
snapshot: {
|
|
1352
|
-
runId,
|
|
1353
|
-
value: executionContext.state,
|
|
1354
|
-
context: stepResults,
|
|
1355
|
-
activePaths: [],
|
|
1356
|
-
suspendedPaths: executionContext.suspendedPaths,
|
|
1357
|
-
resumeLabels: executionContext.resumeLabels,
|
|
1358
|
-
waitingPaths: {},
|
|
1359
|
-
serializedStepGraph,
|
|
1360
|
-
status: workflowStatus,
|
|
1361
|
-
result,
|
|
1362
|
-
error,
|
|
1363
|
-
// @ts-ignore
|
|
1364
|
-
timestamp: Date.now()
|
|
2129
|
+
return { ...passThrough, messages };
|
|
1365
2130
|
}
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
prevStep,
|
|
1376
|
-
stepResults,
|
|
1377
|
-
serializedStepGraph,
|
|
1378
|
-
resume,
|
|
1379
|
-
executionContext,
|
|
1380
|
-
emitter,
|
|
1381
|
-
abortController,
|
|
1382
|
-
runtimeContext,
|
|
1383
|
-
writableStream,
|
|
1384
|
-
disableScorers,
|
|
1385
|
-
tracingContext
|
|
1386
|
-
}) {
|
|
1387
|
-
const conditionalSpan = tracingContext?.currentSpan?.createChildSpan({
|
|
1388
|
-
type: AISpanType.WORKFLOW_CONDITIONAL,
|
|
1389
|
-
name: `conditional: '${entry.conditions.length} conditions'`,
|
|
1390
|
-
input: prevOutput,
|
|
1391
|
-
attributes: {
|
|
1392
|
-
conditionCount: entry.conditions.length
|
|
1393
|
-
},
|
|
1394
|
-
tracingPolicy: this.options?.tracingPolicy
|
|
1395
|
-
});
|
|
1396
|
-
let execResults;
|
|
1397
|
-
const truthyIndexes = (await Promise.all(
|
|
1398
|
-
entry.conditions.map(
|
|
1399
|
-
(cond, index) => this.inngestStep.run(`workflow.${workflowId}.conditional.${index}`, async () => {
|
|
1400
|
-
const evalSpan = conditionalSpan?.createChildSpan({
|
|
1401
|
-
type: AISpanType.WORKFLOW_CONDITIONAL_EVAL,
|
|
1402
|
-
name: `condition: '${index}'`,
|
|
1403
|
-
input: prevOutput,
|
|
1404
|
-
attributes: {
|
|
1405
|
-
conditionIndex: index
|
|
1406
|
-
},
|
|
1407
|
-
tracingPolicy: this.options?.tracingPolicy
|
|
1408
|
-
});
|
|
1409
|
-
try {
|
|
1410
|
-
const result = await cond({
|
|
1411
|
-
runId,
|
|
1412
|
-
workflowId,
|
|
1413
|
-
mastra: this.mastra,
|
|
1414
|
-
runtimeContext,
|
|
1415
|
-
runCount: -1,
|
|
1416
|
-
inputData: prevOutput,
|
|
1417
|
-
state: executionContext.state,
|
|
1418
|
-
setState: (state) => {
|
|
1419
|
-
executionContext.state = state;
|
|
1420
|
-
},
|
|
1421
|
-
tracingContext: {
|
|
1422
|
-
currentSpan: evalSpan
|
|
1423
|
-
},
|
|
1424
|
-
getInitData: () => stepResults?.input,
|
|
1425
|
-
getStepResult: getStepResult.bind(this, stepResults),
|
|
1426
|
-
// TODO: this function shouldn't have suspend probably?
|
|
1427
|
-
suspend: async (_suspendPayload) => {
|
|
1428
|
-
},
|
|
1429
|
-
bail: () => {
|
|
1430
|
-
},
|
|
1431
|
-
abort: () => {
|
|
1432
|
-
abortController.abort();
|
|
1433
|
-
},
|
|
1434
|
-
[EMITTER_SYMBOL]: emitter,
|
|
1435
|
-
[STREAM_FORMAT_SYMBOL]: executionContext.format,
|
|
1436
|
-
// TODO: add streamVNext support
|
|
1437
|
-
engine: {
|
|
1438
|
-
step: this.inngestStep
|
|
1439
|
-
},
|
|
1440
|
-
abortSignal: abortController.signal,
|
|
1441
|
-
writer: new ToolStream(
|
|
1442
|
-
{
|
|
1443
|
-
prefix: "workflow-step",
|
|
1444
|
-
callId: randomUUID(),
|
|
1445
|
-
name: "conditional",
|
|
1446
|
-
runId
|
|
1447
|
-
},
|
|
1448
|
-
writableStream
|
|
1449
|
-
)
|
|
1450
|
-
});
|
|
1451
|
-
evalSpan?.end({
|
|
1452
|
-
output: result,
|
|
1453
|
-
attributes: {
|
|
1454
|
-
result: !!result
|
|
2131
|
+
case "outputStep": {
|
|
2132
|
+
if (processor.processOutputStep) {
|
|
2133
|
+
if (!passThrough.messageList) {
|
|
2134
|
+
throw new MastraError({
|
|
2135
|
+
category: ErrorCategory.USER,
|
|
2136
|
+
domain: ErrorDomain.MASTRA_WORKFLOW,
|
|
2137
|
+
id: "PROCESSOR_MISSING_MESSAGE_LIST",
|
|
2138
|
+
text: `Processor ${processor.id} requires messageList or messages for processOutputStep phase`
|
|
2139
|
+
});
|
|
1455
2140
|
}
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
2141
|
+
const idsBeforeProcessing = messages.map((m) => m.id);
|
|
2142
|
+
const check = passThrough.messageList.makeMessageSourceChecker();
|
|
2143
|
+
const result = await processor.processOutputStep({
|
|
2144
|
+
...baseContext,
|
|
2145
|
+
messages,
|
|
2146
|
+
messageList: passThrough.messageList,
|
|
2147
|
+
stepNumber: stepNumber ?? 0,
|
|
2148
|
+
finishReason,
|
|
2149
|
+
toolCalls,
|
|
2150
|
+
text,
|
|
2151
|
+
systemMessages: systemMessages ?? [],
|
|
2152
|
+
steps: steps ?? []
|
|
2153
|
+
});
|
|
2154
|
+
if (result instanceof MessageList) {
|
|
2155
|
+
if (result !== passThrough.messageList) {
|
|
2156
|
+
throw new MastraError({
|
|
2157
|
+
category: ErrorCategory.USER,
|
|
2158
|
+
domain: ErrorDomain.MASTRA_WORKFLOW,
|
|
2159
|
+
id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
|
|
2160
|
+
text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
|
|
2161
|
+
});
|
|
2162
|
+
}
|
|
2163
|
+
return {
|
|
2164
|
+
...passThrough,
|
|
2165
|
+
messages: result.get.all.db(),
|
|
2166
|
+
systemMessages: result.getAllSystemMessages()
|
|
2167
|
+
};
|
|
2168
|
+
} else if (Array.isArray(result)) {
|
|
2169
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
2170
|
+
result,
|
|
2171
|
+
passThrough.messageList,
|
|
2172
|
+
idsBeforeProcessing,
|
|
2173
|
+
check,
|
|
2174
|
+
"response"
|
|
2175
|
+
);
|
|
2176
|
+
return { ...passThrough, messages: result };
|
|
2177
|
+
} else if (result && "messages" in result && "systemMessages" in result) {
|
|
2178
|
+
const typedResult = result;
|
|
2179
|
+
ProcessorRunner.applyMessagesToMessageList(
|
|
2180
|
+
typedResult.messages,
|
|
2181
|
+
passThrough.messageList,
|
|
2182
|
+
idsBeforeProcessing,
|
|
2183
|
+
check,
|
|
2184
|
+
"response"
|
|
2185
|
+
);
|
|
2186
|
+
passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
|
|
2187
|
+
return {
|
|
2188
|
+
...passThrough,
|
|
2189
|
+
messages: typedResult.messages,
|
|
2190
|
+
systemMessages: typedResult.systemMessages
|
|
2191
|
+
};
|
|
1463
2192
|
}
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
})
|
|
1468
|
-
)
|
|
1469
|
-
)).filter((index) => index !== null);
|
|
1470
|
-
const stepsToRun = entry.steps.filter((_, index) => truthyIndexes.includes(index));
|
|
1471
|
-
conditionalSpan?.update({
|
|
1472
|
-
attributes: {
|
|
1473
|
-
truthyIndexes,
|
|
1474
|
-
selectedSteps: stepsToRun.map((s) => s.type === "step" ? s.step.id : `control-${s.type}`)
|
|
1475
|
-
}
|
|
1476
|
-
});
|
|
1477
|
-
const results = await Promise.all(
|
|
1478
|
-
stepsToRun.map(
|
|
1479
|
-
(step, index) => this.executeEntry({
|
|
1480
|
-
workflowId,
|
|
1481
|
-
runId,
|
|
1482
|
-
entry: step,
|
|
1483
|
-
serializedStepGraph,
|
|
1484
|
-
prevStep,
|
|
1485
|
-
stepResults,
|
|
1486
|
-
resume,
|
|
1487
|
-
executionContext: {
|
|
1488
|
-
workflowId,
|
|
1489
|
-
runId,
|
|
1490
|
-
executionPath: [...executionContext.executionPath, index],
|
|
1491
|
-
suspendedPaths: executionContext.suspendedPaths,
|
|
1492
|
-
resumeLabels: executionContext.resumeLabels,
|
|
1493
|
-
retryConfig: executionContext.retryConfig,
|
|
1494
|
-
executionSpan: executionContext.executionSpan,
|
|
1495
|
-
state: executionContext.state
|
|
1496
|
-
},
|
|
1497
|
-
emitter,
|
|
1498
|
-
abortController,
|
|
1499
|
-
runtimeContext,
|
|
1500
|
-
writableStream,
|
|
1501
|
-
disableScorers,
|
|
1502
|
-
tracingContext: {
|
|
1503
|
-
currentSpan: conditionalSpan
|
|
1504
|
-
}
|
|
1505
|
-
})
|
|
1506
|
-
)
|
|
1507
|
-
);
|
|
1508
|
-
const hasFailed = results.find((result) => result.result.status === "failed");
|
|
1509
|
-
const hasSuspended = results.find((result) => result.result.status === "suspended");
|
|
1510
|
-
if (hasFailed) {
|
|
1511
|
-
execResults = { status: "failed", error: hasFailed.result.error };
|
|
1512
|
-
} else if (hasSuspended) {
|
|
1513
|
-
execResults = { status: "suspended", suspendPayload: hasSuspended.result.suspendPayload };
|
|
1514
|
-
} else {
|
|
1515
|
-
execResults = {
|
|
1516
|
-
status: "success",
|
|
1517
|
-
output: results.reduce((acc, result, index) => {
|
|
1518
|
-
if (result.result.status === "success") {
|
|
1519
|
-
acc[stepsToRun[index].step.id] = result.output;
|
|
2193
|
+
return { ...passThrough, messages };
|
|
2194
|
+
}
|
|
2195
|
+
return { ...passThrough, messages };
|
|
1520
2196
|
}
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
}
|
|
1525
|
-
if (execResults.status === "failed") {
|
|
1526
|
-
conditionalSpan?.error({
|
|
1527
|
-
error: new Error(execResults.error)
|
|
2197
|
+
default:
|
|
2198
|
+
return { ...passThrough, messages };
|
|
2199
|
+
}
|
|
1528
2200
|
});
|
|
1529
|
-
}
|
|
1530
|
-
|
|
1531
|
-
|
|
2201
|
+
},
|
|
2202
|
+
component: "PROCESSOR"
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
function init(inngest) {
|
|
2206
|
+
return {
|
|
2207
|
+
createWorkflow(params) {
|
|
2208
|
+
return new InngestWorkflow(
|
|
2209
|
+
params,
|
|
2210
|
+
inngest
|
|
2211
|
+
);
|
|
2212
|
+
},
|
|
2213
|
+
createStep,
|
|
2214
|
+
cloneStep(step, opts) {
|
|
2215
|
+
return {
|
|
2216
|
+
id: opts.id,
|
|
2217
|
+
description: step.description,
|
|
2218
|
+
inputSchema: step.inputSchema,
|
|
2219
|
+
outputSchema: step.outputSchema,
|
|
2220
|
+
resumeSchema: step.resumeSchema,
|
|
2221
|
+
suspendSchema: step.suspendSchema,
|
|
2222
|
+
stateSchema: step.stateSchema,
|
|
2223
|
+
execute: step.execute,
|
|
2224
|
+
retries: step.retries,
|
|
2225
|
+
scorers: step.scorers,
|
|
2226
|
+
component: step.component
|
|
2227
|
+
};
|
|
2228
|
+
},
|
|
2229
|
+
cloneWorkflow(workflow, opts) {
|
|
2230
|
+
const wf = new Workflow({
|
|
2231
|
+
id: opts.id,
|
|
2232
|
+
inputSchema: workflow.inputSchema,
|
|
2233
|
+
outputSchema: workflow.outputSchema,
|
|
2234
|
+
steps: workflow.stepDefs,
|
|
2235
|
+
mastra: workflow.mastra,
|
|
2236
|
+
options: workflow.options
|
|
1532
2237
|
});
|
|
2238
|
+
wf.setStepFlow(workflow.stepGraph);
|
|
2239
|
+
wf.commit();
|
|
2240
|
+
return wf;
|
|
1533
2241
|
}
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
};
|
|
2242
|
+
};
|
|
2243
|
+
}
|
|
1537
2244
|
|
|
1538
|
-
export { InngestExecutionEngine, InngestRun, InngestWorkflow, createStep, init, serve };
|
|
2245
|
+
export { InngestExecutionEngine, InngestPubSub, InngestRun, InngestWorkflow, _compatibilityCheck, createServe, createStep, init, serve };
|
|
1539
2246
|
//# sourceMappingURL=index.js.map
|
|
1540
2247
|
//# sourceMappingURL=index.js.map
|