@mastra/inngest 0.0.0-bundle-recursion-20251030002519 → 0.0.0-bundle-version-20260121091645

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,263 +1,1053 @@
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';
2
- import { ReadableStream } from 'stream/web';
10
+ import { RequestContext } from '@mastra/core/di';
11
+ import { NonRetriableError } from 'inngest';
3
12
  import { subscribe } from '@inngest/realtime';
4
- import { wrapMastra, AISpanType } from '@mastra/core/ai-tracing';
5
- import { RuntimeContext } from '@mastra/core/di';
13
+ import { PubSub } from '@mastra/core/events';
14
+ import { ReadableStream } from 'stream/web';
6
15
  import { ChunkFrom, WorkflowRunOutput } from '@mastra/core/stream';
7
- import { ToolStream, Tool } from '@mastra/core/tools';
8
- import { Run, Workflow, DefaultExecutionEngine, createDeprecationProxy, getStepResult, runCountDeprecationMessage, validateStepInput } from '@mastra/core/workflows';
9
- import { EMITTER_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
10
- import { NonRetriableError, RetryAfterError } from 'inngest';
11
16
  import { serve as serve$1 } from 'inngest/hono';
12
- import { z } from 'zod';
13
17
 
14
18
  // src/index.ts
15
- function serve({
16
- mastra,
17
- inngest,
18
- functions: userFunctions = [],
19
- registerOptions
20
- }) {
21
- const wfs = mastra.getWorkflows();
22
- const workflowFunctions = Array.from(
23
- new Set(
24
- Object.values(wfs).flatMap((wf) => {
25
- if (wf instanceof InngestWorkflow) {
26
- wf.__registerMastra(mastra);
27
- return wf.getFunctions();
28
- }
29
- return [];
30
- })
31
- )
32
- );
33
- return serve$1({
34
- ...registerOptions,
35
- client: inngest,
36
- functions: [...workflowFunctions, ...userFunctions]
37
- });
38
- }
39
- var InngestRun = class extends Run {
40
- inngest;
41
- serializedStepGraph;
42
- #mastra;
43
- constructor(params, inngest) {
44
- super(params);
45
- this.inngest = inngest;
46
- this.serializedStepGraph = params.serializedStepGraph;
47
- 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;
48
26
  }
49
- async getRuns(eventId) {
50
- const response = await fetch(`${this.inngest.apiBaseUrl ?? "https://api.inngest.com"}/v1/events/${eventId}/runs`, {
51
- headers: {
52
- Authorization: `Bearer ${process.env.INNGEST_SIGNING_KEY}`
53
- }
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"
54
41
  });
55
- const json = await response.json();
56
- return json.data;
42
+ return errorInstance.toJSON();
57
43
  }
58
- async getRunOutput(eventId) {
59
- let runs = await this.getRuns(eventId);
60
- while (runs?.[0]?.status !== "Completed" || runs?.[0]?.event_id !== eventId) {
61
- await new Promise((resolve) => setTimeout(resolve, 1e3));
62
- runs = await this.getRuns(eventId);
63
- if (runs?.[0]?.status === "Failed") {
64
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
65
- workflowName: this.workflowId,
66
- runId: this.runId
67
- });
68
- return {
69
- output: { result: { steps: snapshot?.context, status: "failed", error: runs?.[0]?.output?.message } }
70
- };
71
- }
72
- if (runs?.[0]?.status === "Cancelled") {
73
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
74
- workflowName: this.workflowId,
75
- runId: this.runId
76
- });
77
- return { output: { result: { steps: snapshot?.context, status: "canceled" } } };
78
- }
79
- }
80
- return runs?.[0];
44
+ /**
45
+ * Detect InngestWorkflow instances for special nested workflow handling
46
+ */
47
+ isNestedWorkflowStep(step) {
48
+ return step instanceof InngestWorkflow;
81
49
  }
82
- async sendEvent(event, data) {
83
- await this.inngest.send({
84
- name: `user-event-${event}`,
85
- data
86
- });
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;
87
57
  }
88
- async cancel() {
89
- await this.inngest.send({
90
- name: `cancel.workflow.${this.workflowId}`,
91
- data: {
92
- runId: this.runId
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));
93
67
  }
94
- });
95
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
96
- workflowName: this.workflowId,
97
- runId: this.runId
98
- });
99
- if (snapshot) {
100
- await this.#mastra?.storage?.persistWorkflowSnapshot({
101
- workflowName: this.workflowId,
102
- runId: this.runId,
103
- resourceId: this.resourceId,
104
- snapshot: {
105
- ...snapshot,
106
- status: "canceled"
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
+ };
107
100
  }
108
- });
101
+ }
109
102
  }
103
+ return { ok: false, error: { status: "failed", error: new Error("Unknown error"), endedAt: Date.now() } };
110
104
  }
111
- async start(params) {
112
- return this._start(params);
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);
113
110
  }
114
- async _start({
115
- inputData,
116
- initialState,
117
- outputOptions,
118
- tracingOptions,
119
- format
120
- }) {
121
- await this.#mastra.getStorage()?.persistWorkflowSnapshot({
122
- workflowName: this.workflowId,
123
- runId: this.runId,
124
- resourceId: this.resourceId,
125
- snapshot: {
126
- runId: this.runId,
127
- serializedStepGraph: this.serializedStepGraph,
128
- value: {},
129
- context: {},
130
- activePaths: [],
131
- suspendedPaths: {},
132
- resumeLabels: {},
133
- waitingPaths: {},
134
- timestamp: Date.now(),
135
- status: "running"
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
+ });
136
145
  }
137
146
  });
138
- const inputDataToUse = await this._validateInput(inputData);
139
- const initialStateToUse = await this._validateInitialState(initialState ?? {});
140
- const eventOutput = await this.inngest.send({
141
- name: `workflow.${this.workflowId}`,
142
- data: {
143
- inputData: inputDataToUse,
144
- initialState: initialStateToUse,
145
- runId: this.runId,
146
- resourceId: this.resourceId,
147
- outputOptions,
148
- tracingOptions,
149
- format
150
- }
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
184
+ });
185
+ return span?.exportSpan();
151
186
  });
152
- const eventId = eventOutput.ids[0];
153
- if (!eventId) {
154
- throw new Error("Event ID is not set");
155
- }
156
- const runOutput = await this.getRunOutput(eventId);
157
- const result = runOutput?.output?.result;
158
- if (result.status === "failed") {
159
- result.error = new Error(result.error);
160
- }
161
- if (result.status !== "suspended") {
162
- this.cleanup?.();
187
+ if (exportedSpan) {
188
+ const observability = this.mastra?.observability?.getSelectedInstance({});
189
+ return observability?.rebuildSpan(exportedSpan);
163
190
  }
164
- return result;
191
+ return void 0;
165
192
  }
166
- async resume(params) {
167
- const p = this._resume(params).then((result) => {
168
- if (result.status !== "suspended") {
169
- this.closeStreamAction?.().catch(() => {
170
- });
171
- }
172
- return result;
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);
173
201
  });
174
- this.executionResults = p;
175
- return p;
176
202
  }
177
- async _resume(params) {
178
- const steps = (Array.isArray(params.step) ? params.step : [params.step]).map(
179
- (step) => typeof step === "string" ? step : step?.id
180
- );
181
- const snapshot = await this.#mastra?.storage?.loadWorkflowSnapshot({
182
- workflowName: this.workflowId,
183
- runId: this.runId
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);
184
211
  });
185
- const suspendedStep = this.workflowSteps[steps?.[0] ?? ""];
186
- const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);
187
- const eventOutput = await this.inngest.send({
188
- name: `workflow.${this.workflowId}`,
189
- data: {
190
- inputData: resumeDataToUse,
191
- initialState: snapshot?.value ?? {},
192
- runId: this.runId,
193
- workflowId: this.workflowId,
194
- stepResults: snapshot?.context,
195
- resume: {
196
- steps,
197
- stepResults: snapshot?.context,
198
- resumePayload: resumeDataToUse,
199
- // @ts-ignore
200
- resumePath: snapshot?.suspendedPaths?.[steps?.[0]]
201
- }
202
- }
212
+ }
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();
203
229
  });
204
- const eventId = eventOutput.ids[0];
205
- if (!eventId) {
206
- throw new Error("Event ID is not set");
207
- }
208
- const runOutput = await this.getRunOutput(eventId);
209
- const result = runOutput?.output?.result;
210
- if (result.status === "failed") {
211
- result.error = new Error(result.error);
230
+ if (exportedSpan) {
231
+ const observability = this.mastra?.observability?.getSelectedInstance({});
232
+ return observability?.rebuildSpan(exportedSpan);
212
233
  }
213
- return result;
234
+ return void 0;
214
235
  }
215
- watch(cb, type = "watch") {
216
- let active = true;
217
- const streamPromise = subscribe(
218
- {
219
- channel: `workflow:${this.workflowId}:${this.runId}`,
220
- topics: [type],
221
- app: this.inngest
222
- },
223
- (message) => {
224
- if (active) {
225
- cb(message.data);
226
- }
227
- }
228
- );
229
- return () => {
230
- active = false;
231
- streamPromise.then(async (stream) => {
232
- return stream.cancel();
233
- }).catch((err) => {
234
- console.error(err);
235
- });
236
- };
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);
244
+ });
237
245
  }
238
- streamLegacy({ inputData, runtimeContext } = {}) {
239
- const { readable, writable } = new TransformStream();
240
- const writer = writable.getWriter();
241
- const unwatch = this.watch(async (event) => {
242
- try {
243
- await writer.write({
244
- // @ts-ignore
245
- type: "start",
246
- // @ts-ignore
247
- payload: { runId: this.runId }
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);
254
+ });
255
+ }
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
248
292
  });
249
- const e = {
250
- ...event,
251
- type: event.type.replace("workflow-", "")
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;
357
+ }
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
252
370
  };
253
- if (e.type === "step-output") {
371
+ }
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
+ }
500
+ });
501
+ return { executionContext, result: { status: "success", output: result?.result, endedAt: Date.now() } };
502
+ }
503
+ );
504
+ Object.assign(executionContext, res.executionContext);
505
+ return {
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
511
+ };
512
+ }
513
+ };
514
+ var InngestPubSub = class extends PubSub {
515
+ inngest;
516
+ workflowId;
517
+ publishFn;
518
+ subscriptions = /* @__PURE__ */ new Map();
519
+ constructor(inngest, workflowId, publishFn) {
520
+ super();
521
+ this.inngest = inngest;
522
+ this.workflowId = workflowId;
523
+ this.publishFn = publishFn;
524
+ }
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;
534
+ }
535
+ const match = topic.match(/^workflow\.events\.v2\.(.+)$/);
536
+ if (!match) {
537
+ return;
538
+ }
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);
548
+ }
549
+ }
550
+ /**
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}"
555
+ */
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(
569
+ {
570
+ channel,
571
+ topics: ["watch"],
572
+ app: this.inngest
573
+ },
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
+ }
586
+ );
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
594
+ });
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);
609
+ }
610
+ }
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();
622
+ }
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}`
646
+ }
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 })
707
+ }
708
+ }
709
+ };
710
+ }
711
+ if (runs?.[0]?.status === "Cancelled") {
712
+ const snapshot = await workflowsStore?.loadWorkflowSnapshot({
713
+ workflowName: this.workflowId,
714
+ runId: this.runId
715
+ });
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") {
254
1044
  e.type = e.payload.output.type;
255
1045
  e.payload = e.payload.output.payload;
256
1046
  }
257
1047
  await writer.write(e);
258
1048
  } catch {
259
1049
  }
260
- }, "watch-v2");
1050
+ });
261
1051
  this.closeStreamAction = async () => {
262
1052
  await writer.write({
263
1053
  type: "finish",
@@ -273,7 +1063,7 @@ var InngestRun = class extends Run {
273
1063
  writer.releaseLock();
274
1064
  }
275
1065
  };
276
- this.executionResults = this._start({ inputData, runtimeContext, format: "legacy" }).then((result) => {
1066
+ this.executionResults = this._start({ inputData, requestContext, format: "legacy" }).then((result) => {
277
1067
  if (result.status !== "suspended") {
278
1068
  this.closeStreamAction?.().catch(() => {
279
1069
  });
@@ -287,11 +1077,12 @@ var InngestRun = class extends Run {
287
1077
  }
288
1078
  stream({
289
1079
  inputData,
290
- runtimeContext,
1080
+ requestContext,
291
1081
  tracingOptions,
292
1082
  closeOnSuspend = true,
293
1083
  initialState,
294
- outputOptions
1084
+ outputOptions,
1085
+ perStep
295
1086
  } = {}) {
296
1087
  if (this.closeStreamAction && this.streamOutput) {
297
1088
  return this.streamOutput;
@@ -311,38 +1102,111 @@ var InngestRun = class extends Run {
311
1102
  ...payload
312
1103
  }
313
1104
  });
314
- }, "watch-v2");
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
+ });
315
1182
  self.closeStreamAction = async () => {
316
1183
  unwatch();
317
1184
  try {
318
- await controller.close();
1185
+ controller.close();
319
1186
  } catch (err) {
320
1187
  console.error("Error closing stream:", err);
321
1188
  }
322
1189
  };
323
- const executionResultsPromise = self._start({
1190
+ const executionResultsPromise = self._timeTravel({
324
1191
  inputData,
325
- runtimeContext,
326
- // tracingContext, // We are not able to pass a reference to a span here, what to do?
1192
+ step,
1193
+ context,
1194
+ nestedStepsContext,
1195
+ resumeData,
327
1196
  initialState,
1197
+ requestContext,
328
1198
  tracingOptions,
329
1199
  outputOptions,
330
- format: "vnext"
1200
+ perStep
331
1201
  });
1202
+ self.executionResults = executionResultsPromise;
332
1203
  let executionResults;
333
1204
  try {
334
1205
  executionResults = await executionResultsPromise;
335
- if (closeOnSuspend) {
336
- self.closeStreamAction?.().catch(() => {
337
- });
338
- } else if (executionResults.status !== "suspended") {
339
- self.closeStreamAction?.().catch(() => {
340
- });
341
- }
1206
+ self.closeStreamAction?.().catch(() => {
1207
+ });
342
1208
  if (self.streamOutput) {
343
- self.streamOutput.updateResults(
344
- executionResults
345
- );
1209
+ self.streamOutput.updateResults(executionResults);
346
1210
  }
347
1211
  } catch (err) {
348
1212
  self.streamOutput?.rejectResults(err);
@@ -358,43 +1222,56 @@ var InngestRun = class extends Run {
358
1222
  });
359
1223
  return this.streamOutput;
360
1224
  }
361
- streamVNext(args = {}) {
362
- return this.stream(args);
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
+ }
363
1236
  }
364
1237
  };
1238
+
1239
+ // src/workflow.ts
365
1240
  var InngestWorkflow = class _InngestWorkflow extends Workflow {
366
1241
  #mastra;
367
1242
  inngest;
368
1243
  function;
1244
+ cronFunction;
369
1245
  flowControlConfig;
1246
+ cronConfig;
370
1247
  constructor(params, inngest) {
371
- const { concurrency, rateLimit, throttle, debounce, priority, ...workflowParams } = params;
1248
+ const { concurrency, rateLimit, throttle, debounce, priority, cron, inputData, initialState, ...workflowParams } = params;
372
1249
  super(workflowParams);
1250
+ this.engineType = "inngest";
373
1251
  const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(
374
1252
  ([_, value]) => value !== void 0
375
1253
  );
376
1254
  this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : void 0;
377
1255
  this.#mastra = params.mastra;
378
1256
  this.inngest = inngest;
1257
+ if (cron) {
1258
+ this.cronConfig = { cron, inputData, initialState };
1259
+ }
379
1260
  }
380
- async getWorkflowRuns(args) {
1261
+ async listWorkflowRuns(args) {
381
1262
  const storage = this.#mastra?.getStorage();
382
1263
  if (!storage) {
383
1264
  this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
384
1265
  return { runs: [], total: 0 };
385
1266
  }
386
- return storage.getWorkflowRuns({ workflowName: this.id, ...args ?? {} });
387
- }
388
- async getWorkflowRunById(runId) {
389
- const storage = this.#mastra?.getStorage();
390
- if (!storage) {
391
- this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
392
- return this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null;
1267
+ const workflowsStore = await storage.getStore("workflows");
1268
+ if (!workflowsStore) {
1269
+ return { runs: [], total: 0 };
393
1270
  }
394
- const run = await storage.getWorkflowRunById({ runId, workflowName: this.id });
395
- return run ?? (this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null);
1271
+ return workflowsStore.listWorkflowRuns({ workflowName: this.id, ...args ?? {} });
396
1272
  }
397
1273
  __registerMastra(mastra) {
1274
+ super.__registerMastra(mastra);
398
1275
  this.#mastra = mastra;
399
1276
  this.executionEngine.__registerMastra(mastra);
400
1277
  const updateNested = (step) => {
@@ -412,18 +1289,10 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
412
1289
  }
413
1290
  }
414
1291
  }
415
- /**
416
- * @deprecated Use createRunAsync() instead.
417
- * @throws {Error} Always throws an error directing users to use createRunAsync()
418
- */
419
- createRun(_options) {
420
- throw new Error(
421
- "createRun() has been deprecated. Please use createRunAsync() instead.\n\nMigration guide:\n Before: const run = workflow.createRun();\n After: const run = await workflow.createRunAsync();\n\nNote: createRunAsync() is an async method, so make sure your calling function is async."
422
- );
423
- }
424
- async createRunAsync(options) {
1292
+ async createRun(options) {
425
1293
  const runIdToUse = options?.runId || randomUUID();
426
- const run = this.runs.get(runIdToUse) ?? new InngestRun(
1294
+ const existingInMemoryRun = this.runs.get(runIdToUse);
1295
+ const newRun = new InngestRun(
427
1296
  {
428
1297
  workflowId: this.id,
429
1298
  runId: runIdToUse,
@@ -434,18 +1303,25 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
434
1303
  mastra: this.#mastra,
435
1304
  retryConfig: this.retryConfig,
436
1305
  cleanup: () => this.runs.delete(runIdToUse),
437
- workflowSteps: this.steps
1306
+ workflowSteps: this.steps,
1307
+ workflowEngineType: this.engineType,
1308
+ validateInputs: this.options.validateInputs
438
1309
  },
439
1310
  this.inngest
440
1311
  );
1312
+ const run = existingInMemoryRun ?? newRun;
441
1313
  this.runs.set(runIdToUse, run);
442
1314
  const shouldPersistSnapshot = this.options.shouldPersistSnapshot({
443
1315
  workflowStatus: run.workflowRunStatus,
444
1316
  stepResults: {}
445
1317
  });
446
- const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse, false);
447
- if (!workflowSnapshotInStorage && shouldPersistSnapshot) {
448
- await this.mastra?.getStorage()?.persistWorkflowSnapshot({
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({
449
1325
  workflowName: this.id,
450
1326
  runId: runIdToUse,
451
1327
  resourceId: options?.resourceId,
@@ -455,19 +1331,43 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
455
1331
  value: {},
456
1332
  context: {},
457
1333
  activePaths: [],
1334
+ activeStepsPath: {},
458
1335
  waitingPaths: {},
459
1336
  serializedStepGraph: this.serializedStepGraph,
460
1337
  suspendedPaths: {},
461
1338
  resumeLabels: {},
462
1339
  result: void 0,
463
1340
  error: void 0,
464
- // @ts-ignore
465
1341
  timestamp: Date.now()
466
1342
  }
467
1343
  });
468
1344
  }
469
1345
  return run;
470
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
+ }
471
1371
  getFunction() {
472
1372
  if (this.function) {
473
1373
  return this.function;
@@ -475,68 +1375,128 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
475
1375
  this.function = this.inngest.createFunction(
476
1376
  {
477
1377
  id: `workflow.${this.id}`,
478
- // @ts-ignore
479
- retries: this.retryConfig?.attempts ?? 0,
1378
+ retries: 0,
480
1379
  cancelOn: [{ event: `cancel.workflow.${this.id}` }],
481
1380
  // Spread flow control configuration
482
1381
  ...this.flowControlConfig
483
1382
  },
484
1383
  { event: `workflow.${this.id}` },
485
1384
  async ({ event, step, attempt, publish }) => {
486
- let { inputData, initialState, runId, resourceId, resume, outputOptions, format } = event.data;
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;
487
1397
  if (!runId) {
488
1398
  runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {
489
1399
  return randomUUID();
490
1400
  });
491
1401
  }
492
- const emitter = {
493
- emit: async (event2, data) => {
494
- if (!publish) {
495
- return;
496
- }
497
- try {
498
- await publish({
499
- channel: `workflow:${this.id}:${runId}`,
500
- topic: event2,
501
- data
502
- });
503
- } catch (err) {
504
- this.logger.error("Error emitting event: " + (err?.stack ?? err?.message ?? err));
505
- }
506
- },
507
- on: (_event, _callback) => {
508
- },
509
- off: (_event, _callback) => {
510
- },
511
- once: (_event, _callback) => {
512
- }
513
- };
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
+ });
514
1425
  const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);
515
- const result = await engine.execute({
516
- workflowId: this.id,
517
- runId,
518
- resourceId,
519
- graph: this.executionGraph,
520
- serializedStepGraph: this.serializedStepGraph,
521
- input: inputData,
522
- initialState,
523
- emitter,
524
- retryConfig: this.retryConfig,
525
- runtimeContext: new RuntimeContext(),
526
- // TODO
527
- resume,
528
- format,
529
- abortController: new AbortController(),
530
- // currentSpan: undefined, // TODO: Pass actual parent AI span from workflow execution context
531
- outputOptions,
532
- writableStream: new WritableStream({
533
- write(chunk) {
534
- void emitter.emit("watch-v2", chunk).catch(() => {
535
- });
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
+ }
536
1462
  }
537
- })
538
- });
1463
+ });
1464
+ } catch (error) {
1465
+ throw error;
1466
+ }
539
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
+ }
540
1500
  if (result.status === "failed") {
541
1501
  throw new NonRetriableError(`Workflow failed`, {
542
1502
  cause: result
@@ -563,1126 +1523,725 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
563
1523
  });
564
1524
  }
565
1525
  getFunctions() {
566
- return [this.getFunction(), ...this.getNestedFunctions(this.executionGraph.steps)];
1526
+ return [
1527
+ this.getFunction(),
1528
+ ...this.cronConfig?.cron ? [this.createCronFunction()] : [],
1529
+ ...this.getNestedFunctions(this.executionGraph.steps)
1530
+ ];
567
1531
  }
568
1532
  };
569
- function isAgent(params) {
570
- return params?.component === "AGENT";
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;
571
1569
  }
572
- function isTool(params) {
573
- return params instanceof Tool;
1570
+ function isToolStep(input) {
1571
+ return input instanceof Tool;
574
1572
  }
575
- function createStep(params, agentOptions) {
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);
1575
+ }
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
+ }
576
1583
  if (isAgent(params)) {
577
- return {
578
- id: params.name,
579
- description: params.getDescription(),
580
- // @ts-ignore
581
- inputSchema: z.object({
582
- prompt: z.string()
583
- // resourceId: z.string().optional(),
584
- // threadId: z.string().optional(),
585
- }),
586
- // @ts-ignore
587
- outputSchema: z.object({
588
- text: z.string()
589
- }),
590
- execute: async ({
591
- inputData,
592
- [EMITTER_SYMBOL]: emitter,
593
- [STREAM_FORMAT_SYMBOL]: streamFormat,
594
- runtimeContext,
595
- tracingContext,
596
- abortSignal,
597
- abort,
598
- writer
599
- }) => {
600
- let streamPromise = {};
601
- streamPromise.promise = new Promise((resolve, reject) => {
602
- streamPromise.resolve = resolve;
603
- streamPromise.reject = reject;
604
- });
605
- const toolData = {
606
- name: params.name,
607
- args: inputData
608
- };
609
- let stream;
610
- if ((await params.getModel()).specificationVersion === "v1") {
611
- const { fullStream } = await params.streamLegacy(inputData.prompt, {
612
- ...agentOptions ?? {},
613
- // resourceId: inputData.resourceId,
614
- // threadId: inputData.threadId,
615
- runtimeContext,
616
- tracingContext,
617
- onFinish: (result) => {
618
- streamPromise.resolve(result.text);
619
- void agentOptions?.onFinish?.(result);
620
- },
621
- abortSignal
622
- });
623
- stream = fullStream;
624
- } else {
625
- const modelOutput = await params.stream(inputData.prompt, {
626
- ...agentOptions ?? {},
627
- runtimeContext,
628
- tracingContext,
629
- onFinish: (result) => {
630
- streamPromise.resolve(result.text);
631
- void agentOptions?.onFinish?.(result);
632
- },
633
- abortSignal
634
- });
635
- stream = modelOutput.fullStream;
636
- }
637
- if (streamFormat === "legacy") {
638
- await emitter.emit("watch-v2", {
639
- type: "tool-call-streaming-start",
640
- ...toolData ?? {}
641
- });
642
- for await (const chunk of stream) {
643
- if (chunk.type === "text-delta") {
644
- await emitter.emit("watch-v2", {
645
- type: "tool-call-delta",
646
- ...toolData ?? {},
647
- argsTextDelta: chunk.textDelta
648
- });
649
- }
650
- }
651
- await emitter.emit("watch-v2", {
652
- type: "tool-call-streaming-finish",
653
- ...toolData ?? {}
654
- });
655
- } else {
656
- for await (const chunk of stream) {
657
- await writer.write(chunk);
658
- }
659
- }
660
- if (abortSignal.aborted) {
661
- return abort();
662
- }
663
- return {
664
- text: await streamPromise.promise
665
- };
666
- },
667
- component: params.component
668
- };
1584
+ return createStepFromAgent(params, agentOrToolOptions);
669
1585
  }
670
- if (isTool(params)) {
671
- if (!params.inputSchema || !params.outputSchema) {
672
- throw new Error("Tool must have input and output schemas defined");
673
- }
674
- return {
675
- // TODO: tool probably should have strong id type
676
- // @ts-ignore
677
- id: params.id,
678
- description: params.description,
679
- inputSchema: params.inputSchema,
680
- outputSchema: params.outputSchema,
681
- execute: async ({ inputData, mastra, runtimeContext, tracingContext, suspend, resumeData }) => {
682
- return params.execute({
683
- context: inputData,
684
- mastra: wrapMastra(mastra, tracingContext),
685
- runtimeContext,
686
- tracingContext,
687
- suspend,
688
- resumeData
689
- });
690
- },
691
- component: "TOOL"
692
- };
1586
+ if (isToolStep(params)) {
1587
+ return createStepFromTool(params, agentOrToolOptions);
1588
+ }
1589
+ if (isStepParams(params)) {
1590
+ return createStepFromParams(params);
693
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) {
694
1598
  return {
695
1599
  id: params.id,
696
1600
  description: params.description,
697
1601
  inputSchema: params.inputSchema,
1602
+ stateSchema: params.stateSchema,
698
1603
  outputSchema: params.outputSchema,
699
1604
  resumeSchema: params.resumeSchema,
700
1605
  suspendSchema: params.suspendSchema,
701
- execute: params.execute
1606
+ scorers: params.scorers,
1607
+ retries: params.retries,
1608
+ execute: params.execute.bind(params)
702
1609
  };
703
1610
  }
704
- function init(inngest) {
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 ?? {};
705
1615
  return {
706
- createWorkflow(params) {
707
- return new InngestWorkflow(
708
- params,
709
- inngest
710
- );
711
- },
712
- createStep,
713
- cloneStep(step, opts) {
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;
1639
+ });
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);
1658
+ },
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);
1674
+ },
1675
+ abortSignal
1676
+ });
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
+ }
1693
+ }
1694
+ await pubsub.publish(`workflow.events.v2.${runId}`, {
1695
+ type: "watch",
1696
+ runId,
1697
+ data: { type: "tool-call-streaming-finish", ...toolData ?? {} }
1698
+ });
1699
+ } else {
1700
+ for await (const chunk of stream) {
1701
+ await writer.write(chunk);
1702
+ }
1703
+ }
1704
+ if (abortSignal.aborted) {
1705
+ return abort();
1706
+ }
1707
+ if (structuredResult !== null) {
1708
+ return structuredResult;
1709
+ }
714
1710
  return {
715
- id: opts.id,
716
- description: step.description,
717
- inputSchema: step.inputSchema,
718
- outputSchema: step.outputSchema,
719
- resumeSchema: step.resumeSchema,
720
- suspendSchema: step.suspendSchema,
721
- stateSchema: step.stateSchema,
722
- execute: step.execute,
723
- component: step.component
1711
+ text: await streamPromise.promise
724
1712
  };
725
1713
  },
726
- cloneWorkflow(workflow, opts) {
727
- const wf = new Workflow({
728
- id: opts.id,
729
- inputSchema: workflow.inputSchema,
730
- outputSchema: workflow.outputSchema,
731
- steps: workflow.stepDefs,
732
- mastra: workflow.mastra
733
- });
734
- wf.setStepFlow(workflow.stepGraph);
735
- wf.commit();
736
- return wf;
737
- }
1714
+ component: params.component
738
1715
  };
739
1716
  }
740
- var InngestExecutionEngine = class extends DefaultExecutionEngine {
741
- inngestStep;
742
- inngestAttempts;
743
- constructor(mastra, inngestStep, inngestAttempts = 0, options) {
744
- super({ mastra, options });
745
- this.inngestStep = inngestStep;
746
- this.inngestAttempts = inngestAttempts;
747
- }
748
- async fmtReturnValue(emitter, stepResults, lastOutput, error) {
749
- const base = {
750
- status: lastOutput.status,
751
- steps: stepResults
752
- };
753
- if (lastOutput.status === "success") {
754
- await emitter.emit("watch", {
755
- type: "watch",
756
- payload: {
757
- workflowState: {
758
- status: lastOutput.status,
759
- steps: stepResults,
760
- result: lastOutput.output
761
- }
762
- },
763
- eventTimestamp: Date.now()
764
- });
765
- base.result = lastOutput.output;
766
- } else if (lastOutput.status === "failed") {
767
- base.error = error instanceof Error ? error?.stack ?? error.message : lastOutput?.error instanceof Error ? lastOutput.error.message : lastOutput.error ?? error ?? "Unknown error";
768
- await emitter.emit("watch", {
769
- type: "watch",
770
- payload: {
771
- workflowState: {
772
- status: lastOutput.status,
773
- steps: stepResults,
774
- result: null,
775
- error: base.error
776
- }
777
- },
778
- eventTimestamp: Date.now()
779
- });
780
- } else if (lastOutput.status === "suspended") {
781
- await emitter.emit("watch", {
782
- type: "watch",
783
- payload: {
784
- workflowState: {
785
- status: lastOutput.status,
786
- steps: stepResults,
787
- result: null,
788
- error: null
789
- }
790
- },
791
- eventTimestamp: Date.now()
792
- });
793
- const suspendedStepIds = Object.entries(stepResults).flatMap(([stepId, stepResult]) => {
794
- if (stepResult?.status === "suspended") {
795
- const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
796
- return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
797
- }
798
- return [];
799
- });
800
- base.suspended = suspendedStepIds;
801
- }
802
- return base;
803
- }
804
- // async executeSleep({ id, duration }: { id: string; duration: number }): Promise<void> {
805
- // await this.inngestStep.sleep(id, duration);
806
- // }
807
- async executeSleep({
808
- workflowId,
809
- runId,
810
- entry,
811
- prevOutput,
812
- stepResults,
813
- emitter,
814
- abortController,
815
- runtimeContext,
816
- executionContext,
817
- writableStream,
818
- tracingContext
819
- }) {
820
- let { duration, fn } = entry;
821
- const sleepSpan = tracingContext?.currentSpan?.createChildSpan({
822
- type: AISpanType.WORKFLOW_SLEEP,
823
- name: `sleep: ${duration ? `${duration}ms` : "dynamic"}`,
824
- attributes: {
825
- durationMs: duration,
826
- sleepType: fn ? "dynamic" : "fixed"
827
- },
828
- tracingPolicy: this.options?.tracingPolicy
829
- });
830
- if (fn) {
831
- const stepCallId = randomUUID();
832
- duration = await this.inngestStep.run(`workflow.${workflowId}.sleep.${entry.id}`, async () => {
833
- return await fn(
834
- createDeprecationProxy(
835
- {
836
- runId,
837
- workflowId,
838
- mastra: this.mastra,
839
- runtimeContext,
840
- inputData: prevOutput,
841
- state: executionContext.state,
842
- setState: (state) => {
843
- executionContext.state = state;
844
- },
845
- runCount: -1,
846
- retryCount: -1,
847
- tracingContext: {
848
- currentSpan: sleepSpan
849
- },
850
- getInitData: () => stepResults?.input,
851
- getStepResult: getStepResult.bind(this, stepResults),
852
- // TODO: this function shouldn't have suspend probably?
853
- suspend: async (_suspendPayload) => {
854
- },
855
- bail: () => {
856
- },
857
- abort: () => {
858
- abortController?.abort();
859
- },
860
- [EMITTER_SYMBOL]: emitter,
861
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
862
- engine: { step: this.inngestStep },
863
- abortSignal: abortController?.signal,
864
- writer: new ToolStream(
865
- {
866
- prefix: "workflow-step",
867
- callId: stepCallId,
868
- name: "sleep",
869
- runId
870
- },
871
- writableStream
872
- )
873
- },
874
- {
875
- paramName: "runCount",
876
- deprecationMessage: runCountDeprecationMessage,
877
- logger: this.logger
878
- }
879
- )
880
- );
881
- });
882
- sleepSpan?.update({
883
- attributes: {
884
- durationMs: duration
885
- }
886
- });
887
- }
888
- try {
889
- await this.inngestStep.sleep(entry.id, !duration || duration < 0 ? 0 : duration);
890
- sleepSpan?.end();
891
- } catch (e) {
892
- sleepSpan?.error({ error: e });
893
- throw e;
894
- }
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");
895
1721
  }
896
- async executeSleepUntil({
897
- workflowId,
898
- runId,
899
- entry,
900
- prevOutput,
901
- stepResults,
902
- emitter,
903
- abortController,
904
- runtimeContext,
905
- executionContext,
906
- writableStream,
907
- tracingContext
908
- }) {
909
- let { date, fn } = entry;
910
- const sleepUntilSpan = tracingContext?.currentSpan?.createChildSpan({
911
- type: AISpanType.WORKFLOW_SLEEP,
912
- name: `sleepUntil: ${date ? date.toISOString() : "dynamic"}`,
913
- attributes: {
914
- untilDate: date,
915
- durationMs: date ? Math.max(0, date.getTime() - Date.now()) : void 0,
916
- sleepType: fn ? "dynamic" : "fixed"
917
- },
918
- tracingPolicy: this.options?.tracingPolicy
919
- });
920
- if (fn) {
921
- date = await this.inngestStep.run(`workflow.${workflowId}.sleepUntil.${entry.id}`, async () => {
922
- const stepCallId = randomUUID();
923
- return await fn(
924
- createDeprecationProxy(
925
- {
926
- runId,
927
- workflowId,
928
- mastra: this.mastra,
929
- runtimeContext,
930
- inputData: prevOutput,
931
- state: executionContext.state,
932
- setState: (state) => {
933
- executionContext.state = state;
934
- },
935
- runCount: -1,
936
- retryCount: -1,
937
- tracingContext: {
938
- currentSpan: sleepUntilSpan
939
- },
940
- getInitData: () => stepResults?.input,
941
- getStepResult: getStepResult.bind(this, stepResults),
942
- // TODO: this function shouldn't have suspend probably?
943
- suspend: async (_suspendPayload) => {
944
- },
945
- bail: () => {
946
- },
947
- abort: () => {
948
- abortController?.abort();
949
- },
950
- [EMITTER_SYMBOL]: emitter,
951
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
952
- engine: { step: this.inngestStep },
953
- abortSignal: abortController?.signal,
954
- writer: new ToolStream(
955
- {
956
- prefix: "workflow-step",
957
- callId: stepCallId,
958
- name: "sleep",
959
- runId
960
- },
961
- writableStream
962
- )
963
- },
964
- {
965
- paramName: "runCount",
966
- deprecationMessage: runCountDeprecationMessage,
967
- logger: this.logger
968
- }
969
- )
970
- );
971
- });
972
- if (date && !(date instanceof Date)) {
973
- date = new Date(date);
974
- }
975
- const time = !date ? 0 : date.getTime() - Date.now();
976
- sleepUntilSpan?.update({
977
- attributes: {
978
- durationMs: Math.max(0, time)
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
979
1754
  }
980
- });
981
- }
982
- if (!(date instanceof Date)) {
983
- sleepUntilSpan?.end();
984
- return;
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;
985
1775
  }
986
- try {
987
- await this.inngestStep.sleepUntil(entry.id, date);
988
- sleepUntilSpan?.end();
989
- } catch (e) {
990
- sleepUntilSpan?.error({ error: e });
991
- throw e;
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";
992
1791
  }
993
- }
994
- async executeWaitForEvent({ event, timeout }) {
995
- const eventData = await this.inngestStep.waitForEvent(`user-event-${event}`, {
996
- event: `user-event-${event}`,
997
- timeout: timeout ?? 5e3
998
- });
999
- if (eventData === null) {
1000
- throw "Timeout waiting for event";
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;
1001
1807
  }
1002
- return eventData?.data;
1003
- }
1004
- async executeStep({
1005
- step,
1006
- stepResults,
1007
- executionContext,
1008
- resume,
1009
- prevOutput,
1010
- emitter,
1011
- abortController,
1012
- runtimeContext,
1013
- tracingContext,
1014
- writableStream,
1015
- disableScorers
1016
- }) {
1017
- const stepAISpan = tracingContext?.currentSpan?.createChildSpan({
1018
- name: `workflow step: '${step.id}'`,
1019
- type: AISpanType.WORKFLOW_STEP,
1020
- input: prevOutput,
1021
- attributes: {
1022
- stepId: step.id
1023
- },
1024
- tracingPolicy: this.options?.tracingPolicy
1025
- });
1026
- const { inputData, validationError } = await validateStepInput({
1027
- prevOutput,
1028
- step,
1029
- validateInputs: this.options?.validateInputs ?? false
1030
- });
1031
- const startedAt = await this.inngestStep.run(
1032
- `workflow.${executionContext.workflowId}.run.${executionContext.runId}.step.${step.id}.running_ev`,
1033
- async () => {
1034
- const startedAt2 = Date.now();
1035
- await emitter.emit("watch", {
1036
- type: "watch",
1037
- payload: {
1038
- currentStep: {
1039
- id: step.id,
1040
- status: "running"
1041
- },
1042
- workflowState: {
1043
- status: "running",
1044
- steps: {
1045
- ...stepResults,
1046
- [step.id]: {
1047
- status: "running"
1048
- }
1049
- },
1050
- result: null,
1051
- error: null
1052
- }
1053
- },
1054
- eventTimestamp: Date.now()
1055
- });
1056
- await emitter.emit("watch-v2", {
1057
- type: "workflow-step-start",
1058
- payload: {
1059
- id: step.id,
1060
- status: "running",
1061
- payload: inputData,
1062
- startedAt: startedAt2
1063
- }
1064
- });
1065
- 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;
1066
1844
  }
1067
- );
1068
- if (step instanceof InngestWorkflow) {
1069
- const isResume = !!resume?.steps?.length;
1070
- let result;
1071
- let runId;
1072
- try {
1073
- if (isResume) {
1074
- runId = stepResults[resume?.steps?.[0]]?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();
1075
- const snapshot = await this.mastra?.getStorage()?.loadWorkflowSnapshot({
1076
- workflowName: step.id,
1077
- runId
1078
- });
1079
- const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
1080
- function: step.getFunction(),
1081
- data: {
1082
- inputData,
1083
- initialState: executionContext.state ?? snapshot?.value ?? {},
1084
- runId,
1085
- resume: {
1086
- runId,
1087
- steps: resume.steps.slice(1),
1088
- stepResults: snapshot?.context,
1089
- resumePayload: resume.resumePayload,
1090
- // @ts-ignore
1091
- resumePath: snapshot?.suspendedPaths?.[resume.steps?.[1]]
1092
- },
1093
- outputOptions: { includeState: true }
1094
- }
1095
- });
1096
- result = invokeResp.result;
1097
- runId = invokeResp.runId;
1098
- executionContext.state = invokeResp.result.state;
1099
- } else {
1100
- const invokeResp = await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {
1101
- function: step.getFunction(),
1102
- data: {
1103
- inputData,
1104
- initialState: executionContext.state ?? {},
1105
- outputOptions: { includeState: true }
1106
- }
1107
- });
1108
- result = invokeResp.result;
1109
- runId = invokeResp.runId;
1110
- 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
1111
1858
  }
1112
- } catch (e) {
1113
- const errorCause = e?.cause;
1114
- if (errorCause && typeof errorCause === "object") {
1115
- result = errorCause;
1116
- runId = errorCause.runId || randomUUID();
1117
- } else {
1118
- runId = randomUUID();
1119
- result = {
1120
- status: "failed",
1121
- error: e instanceof Error ? e : new Error(String(e)),
1122
- steps: {},
1123
- input: inputData
1124
- };
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;
1125
1902
  }
1126
- }
1127
- const res = await this.inngestStep.run(
1128
- `workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,
1129
- async () => {
1130
- if (result.status === "failed") {
1131
- await emitter.emit("watch", {
1132
- type: "watch",
1133
- payload: {
1134
- currentStep: {
1135
- id: step.id,
1136
- status: "failed",
1137
- error: result?.error
1138
- },
1139
- workflowState: {
1140
- status: "running",
1141
- steps: stepResults,
1142
- result: null,
1143
- error: null
1144
- }
1145
- },
1146
- eventTimestamp: Date.now()
1147
- });
1148
- await emitter.emit("watch-v2", {
1149
- type: "workflow-step-result",
1150
- payload: {
1151
- id: step.id,
1152
- status: "failed",
1153
- error: result?.error,
1154
- 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
+ });
1155
1915
  }
1156
- });
1157
- return { executionContext, result: { status: "failed", error: result?.error } };
1158
- } else if (result.status === "suspended") {
1159
- const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
1160
- const stepRes2 = stepResult;
1161
- return stepRes2?.status === "suspended";
1162
- });
1163
- for (const [stepName, stepResult] of suspendedSteps) {
1164
- const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
1165
- executionContext.suspendedPaths[step.id] = executionContext.executionPath;
1166
- await emitter.emit("watch", {
1167
- type: "watch",
1168
- payload: {
1169
- currentStep: {
1170
- id: step.id,
1171
- status: "suspended",
1172
- payload: stepResult.payload,
1173
- suspendPayload: {
1174
- ...stepResult?.suspendPayload,
1175
- __workflow_meta: { runId, path: suspendPath }
1176
- }
1177
- },
1178
- workflowState: {
1179
- status: "running",
1180
- steps: stepResults,
1181
- result: null,
1182
- error: null
1183
- }
1184
- },
1185
- 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 ?? []
1186
1923
  });
1187
- await emitter.emit("watch-v2", {
1188
- type: "workflow-step-suspended",
1189
- payload: {
1190
- id: step.id,
1191
- status: "suspended"
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
+ });
1192
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 ?? []
1994
+ });
1995
+ const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {
1996
+ messageList: passThrough.messageList,
1997
+ processor,
1998
+ stepNumber: stepNumber ?? 0
1193
1999
  });
1194
- return {
1195
- executionContext,
1196
- result: {
1197
- status: "suspended",
1198
- payload: stepResult.payload,
1199
- suspendPayload: {
1200
- ...stepResult?.suspendPayload,
1201
- __workflow_meta: { runId, path: suspendPath }
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
1202
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];
1203
2057
  }
1204
- };
1205
- }
1206
- await emitter.emit("watch", {
1207
- type: "watch",
1208
- payload: {
1209
- currentStep: {
1210
- id: step.id,
1211
- status: "suspended",
1212
- payload: {}
1213
- },
1214
- workflowState: {
1215
- status: "running",
1216
- steps: stepResults,
1217
- result: null,
1218
- 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 });
1219
2063
  }
1220
- },
1221
- eventTimestamp: Date.now()
1222
- });
1223
- return {
1224
- executionContext,
1225
- result: {
1226
- status: "suspended",
1227
- payload: {}
1228
- }
1229
- };
1230
- }
1231
- await emitter.emit("watch", {
1232
- type: "watch",
1233
- payload: {
1234
- currentStep: {
1235
- id: step.id,
1236
- status: "success",
1237
- output: result?.result
1238
- },
1239
- workflowState: {
1240
- status: "running",
1241
- steps: stepResults,
1242
- result: null,
1243
- error: null
2064
+ delete mutableState[spanKey];
2065
+ throw error;
1244
2066
  }
1245
- },
1246
- eventTimestamp: Date.now()
1247
- });
1248
- await emitter.emit("watch-v2", {
1249
- type: "workflow-step-result",
1250
- payload: {
1251
- id: step.id,
1252
- status: "success",
1253
- output: result?.result
2067
+ return { ...passThrough, state: mutableState, part: result };
1254
2068
  }
1255
- });
1256
- await emitter.emit("watch-v2", {
1257
- type: "workflow-step-finish",
1258
- payload: {
1259
- id: step.id,
1260
- metadata: {}
1261
- }
1262
- });
1263
- return { executionContext, result: { status: "success", output: result?.result } };
1264
- }
1265
- );
1266
- Object.assign(executionContext, res.executionContext);
1267
- return {
1268
- ...res.result,
1269
- startedAt,
1270
- endedAt: Date.now(),
1271
- payload: inputData,
1272
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1273
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1274
- };
1275
- }
1276
- const stepCallId = randomUUID();
1277
- let stepRes;
1278
- try {
1279
- stepRes = await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}`, async () => {
1280
- let execResults;
1281
- let suspended;
1282
- let bailed;
1283
- try {
1284
- if (validationError) {
1285
- throw validationError;
2069
+ return { ...passThrough, part };
1286
2070
  }
1287
- const result = await step.execute({
1288
- runId: executionContext.runId,
1289
- mastra: this.mastra,
1290
- runtimeContext,
1291
- writer: new ToolStream(
1292
- {
1293
- prefix: "workflow-step",
1294
- callId: stepCallId,
1295
- name: step.id,
1296
- runId: executionContext.runId
1297
- },
1298
- writableStream
1299
- ),
1300
- state: executionContext?.state ?? {},
1301
- setState: (state) => {
1302
- executionContext.state = state;
1303
- },
1304
- inputData,
1305
- resumeData: resume?.steps[0] === step.id ? resume?.resumePayload : void 0,
1306
- tracingContext: {
1307
- currentSpan: stepAISpan
1308
- },
1309
- getInitData: () => stepResults?.input,
1310
- getStepResult: getStepResult.bind(this, stepResults),
1311
- suspend: async (suspendPayload, suspendOptions) => {
1312
- executionContext.suspendedPaths[step.id] = executionContext.executionPath;
1313
- if (suspendOptions?.resumeLabel) {
1314
- const resumeLabel = Array.isArray(suspendOptions.resumeLabel) ? suspendOptions.resumeLabel : [suspendOptions.resumeLabel];
1315
- for (const label of resumeLabel) {
1316
- executionContext.resumeLabels[label] = {
1317
- stepId: step.id,
1318
- foreachIndex: executionContext.foreachIndex
1319
- };
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
+ });
2080
+ }
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
+ });
1320
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
+ };
1321
2126
  }
1322
- suspended = { payload: suspendPayload };
1323
- },
1324
- bail: (result2) => {
1325
- bailed = { payload: result2 };
1326
- },
1327
- resume: {
1328
- steps: resume?.steps?.slice(1) || [],
1329
- resumePayload: resume?.resumePayload,
1330
- // @ts-ignore
1331
- runId: stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId
1332
- },
1333
- [EMITTER_SYMBOL]: emitter,
1334
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
1335
- engine: {
1336
- step: this.inngestStep
1337
- },
1338
- abortSignal: abortController.signal
1339
- });
1340
- const endedAt = Date.now();
1341
- execResults = {
1342
- status: "success",
1343
- output: result,
1344
- startedAt,
1345
- endedAt,
1346
- payload: inputData,
1347
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1348
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1349
- };
1350
- } catch (e) {
1351
- const stepFailure = {
1352
- status: "failed",
1353
- payload: inputData,
1354
- error: e instanceof Error ? e.message : String(e),
1355
- endedAt: Date.now(),
1356
- startedAt,
1357
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1358
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1359
- };
1360
- execResults = stepFailure;
1361
- const fallbackErrorMessage = `Step ${step.id} failed`;
1362
- stepAISpan?.error({ error: new Error(execResults.error ?? fallbackErrorMessage) });
1363
- throw new RetryAfterError(execResults.error ?? fallbackErrorMessage, executionContext.retryConfig.delay, {
1364
- cause: execResults
1365
- });
1366
- }
1367
- if (suspended) {
1368
- execResults = {
1369
- status: "suspended",
1370
- suspendPayload: suspended.payload,
1371
- payload: inputData,
1372
- suspendedAt: Date.now(),
1373
- startedAt,
1374
- resumedAt: resume?.steps[0] === step.id ? startedAt : void 0,
1375
- resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : void 0
1376
- };
1377
- } else if (bailed) {
1378
- execResults = {
1379
- status: "bailed",
1380
- output: bailed.payload,
1381
- payload: inputData,
1382
- endedAt: Date.now(),
1383
- startedAt
1384
- };
1385
- }
1386
- await emitter.emit("watch", {
1387
- type: "watch",
1388
- payload: {
1389
- currentStep: {
1390
- id: step.id,
1391
- ...execResults
1392
- },
1393
- workflowState: {
1394
- status: "running",
1395
- steps: { ...stepResults, [step.id]: execResults },
1396
- result: null,
1397
- error: null
1398
- }
1399
- },
1400
- eventTimestamp: Date.now()
1401
- });
1402
- if (execResults.status === "suspended") {
1403
- await emitter.emit("watch-v2", {
1404
- type: "workflow-step-suspended",
1405
- payload: {
1406
- id: step.id,
1407
- ...execResults
1408
- }
1409
- });
1410
- } else {
1411
- await emitter.emit("watch-v2", {
1412
- type: "workflow-step-result",
1413
- payload: {
1414
- id: step.id,
1415
- ...execResults
1416
- }
1417
- });
1418
- await emitter.emit("watch-v2", {
1419
- type: "workflow-step-finish",
1420
- payload: {
1421
- id: step.id,
1422
- metadata: {}
2127
+ return { ...passThrough, messages };
1423
2128
  }
1424
- });
1425
- }
1426
- stepAISpan?.end({ output: execResults });
1427
- return { result: execResults, executionContext, stepResults };
1428
- });
1429
- } catch (e) {
1430
- const stepFailure = e instanceof Error ? e?.cause : {
1431
- status: "failed",
1432
- error: e instanceof Error ? e.message : String(e),
1433
- payload: inputData,
1434
- startedAt,
1435
- endedAt: Date.now()
1436
- };
1437
- stepRes = {
1438
- result: stepFailure,
1439
- executionContext,
1440
- stepResults: {
1441
- ...stepResults,
1442
- [step.id]: stepFailure
1443
- }
1444
- };
1445
- }
1446
- if (disableScorers !== false && stepRes.result.status === "success") {
1447
- await this.inngestStep.run(`workflow.${executionContext.workflowId}.step.${step.id}.score`, async () => {
1448
- if (step.scorers) {
1449
- await this.runScorers({
1450
- scorers: step.scorers,
1451
- runId: executionContext.runId,
1452
- input: inputData,
1453
- output: stepRes.result,
1454
- workflowId: executionContext.workflowId,
1455
- stepId: step.id,
1456
- runtimeContext,
1457
- disableScorers,
1458
- tracingContext: { currentSpan: stepAISpan }
1459
- });
1460
- }
1461
- });
1462
- }
1463
- Object.assign(executionContext.suspendedPaths, stepRes.executionContext.suspendedPaths);
1464
- Object.assign(stepResults, stepRes.stepResults);
1465
- executionContext.state = stepRes.executionContext.state;
1466
- return stepRes.result;
1467
- }
1468
- async persistStepUpdate({
1469
- workflowId,
1470
- runId,
1471
- stepResults,
1472
- resourceId,
1473
- executionContext,
1474
- serializedStepGraph,
1475
- workflowStatus,
1476
- result,
1477
- error
1478
- }) {
1479
- await this.inngestStep.run(
1480
- `workflow.${workflowId}.run.${runId}.path.${JSON.stringify(executionContext.executionPath)}.stepUpdate`,
1481
- async () => {
1482
- const shouldPersistSnapshot = this.options.shouldPersistSnapshot({ stepResults, workflowStatus });
1483
- if (!shouldPersistSnapshot) {
1484
- return;
1485
- }
1486
- await this.mastra?.getStorage()?.persistWorkflowSnapshot({
1487
- workflowName: workflowId,
1488
- runId,
1489
- resourceId,
1490
- snapshot: {
1491
- runId,
1492
- value: executionContext.state,
1493
- context: stepResults,
1494
- activePaths: [],
1495
- suspendedPaths: executionContext.suspendedPaths,
1496
- resumeLabels: executionContext.resumeLabels,
1497
- waitingPaths: {},
1498
- serializedStepGraph,
1499
- status: workflowStatus,
1500
- result,
1501
- error,
1502
- // @ts-ignore
1503
- timestamp: Date.now()
2129
+ return { ...passThrough, messages };
1504
2130
  }
1505
- });
1506
- }
1507
- );
1508
- }
1509
- async executeConditional({
1510
- workflowId,
1511
- runId,
1512
- entry,
1513
- prevOutput,
1514
- stepResults,
1515
- resume,
1516
- executionContext,
1517
- emitter,
1518
- abortController,
1519
- runtimeContext,
1520
- writableStream,
1521
- disableScorers,
1522
- tracingContext
1523
- }) {
1524
- const conditionalSpan = tracingContext?.currentSpan?.createChildSpan({
1525
- type: AISpanType.WORKFLOW_CONDITIONAL,
1526
- name: `conditional: '${entry.conditions.length} conditions'`,
1527
- input: prevOutput,
1528
- attributes: {
1529
- conditionCount: entry.conditions.length
1530
- },
1531
- tracingPolicy: this.options?.tracingPolicy
1532
- });
1533
- let execResults;
1534
- const truthyIndexes = (await Promise.all(
1535
- entry.conditions.map(
1536
- (cond, index) => this.inngestStep.run(`workflow.${workflowId}.conditional.${index}`, async () => {
1537
- const evalSpan = conditionalSpan?.createChildSpan({
1538
- type: AISpanType.WORKFLOW_CONDITIONAL_EVAL,
1539
- name: `condition: '${index}'`,
1540
- input: prevOutput,
1541
- attributes: {
1542
- conditionIndex: index
1543
- },
1544
- tracingPolicy: this.options?.tracingPolicy
1545
- });
1546
- try {
1547
- const result = await cond(
1548
- createDeprecationProxy(
1549
- {
1550
- runId,
1551
- workflowId,
1552
- mastra: this.mastra,
1553
- runtimeContext,
1554
- runCount: -1,
1555
- retryCount: -1,
1556
- inputData: prevOutput,
1557
- state: executionContext.state,
1558
- setState: (state) => {
1559
- executionContext.state = state;
1560
- },
1561
- tracingContext: {
1562
- currentSpan: evalSpan
1563
- },
1564
- getInitData: () => stepResults?.input,
1565
- getStepResult: getStepResult.bind(this, stepResults),
1566
- // TODO: this function shouldn't have suspend probably?
1567
- suspend: async (_suspendPayload) => {
1568
- },
1569
- bail: () => {
1570
- },
1571
- abort: () => {
1572
- abortController.abort();
1573
- },
1574
- [EMITTER_SYMBOL]: emitter,
1575
- [STREAM_FORMAT_SYMBOL]: executionContext.format,
1576
- engine: {
1577
- step: this.inngestStep
1578
- },
1579
- abortSignal: abortController.signal,
1580
- writer: new ToolStream(
1581
- {
1582
- prefix: "workflow-step",
1583
- callId: randomUUID(),
1584
- name: "conditional",
1585
- runId
1586
- },
1587
- writableStream
1588
- )
1589
- },
1590
- {
1591
- paramName: "runCount",
1592
- deprecationMessage: runCountDeprecationMessage,
1593
- logger: this.logger
1594
- }
1595
- )
1596
- );
1597
- evalSpan?.end({
1598
- output: result,
1599
- attributes: {
1600
- 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
+ });
1601
2140
  }
1602
- });
1603
- return result ? index : null;
1604
- } catch (e) {
1605
- evalSpan?.error({
1606
- error: e instanceof Error ? e : new Error(String(e)),
1607
- attributes: {
1608
- result: false
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
+ };
1609
2192
  }
1610
- });
1611
- return null;
2193
+ return { ...passThrough, messages };
2194
+ }
2195
+ return { ...passThrough, messages };
1612
2196
  }
1613
- })
1614
- )
1615
- )).filter((index) => index !== null);
1616
- const stepsToRun = entry.steps.filter((_, index) => truthyIndexes.includes(index));
1617
- conditionalSpan?.update({
1618
- attributes: {
1619
- truthyIndexes,
1620
- selectedSteps: stepsToRun.map((s) => s.type === "step" ? s.step.id : `control-${s.type}`)
1621
- }
1622
- });
1623
- const results = await Promise.all(
1624
- stepsToRun.map(async (step, index) => {
1625
- const currStepResult = stepResults[step.step.id];
1626
- if (currStepResult && currStepResult.status === "success") {
1627
- return currStepResult;
2197
+ default:
2198
+ return { ...passThrough, messages };
1628
2199
  }
1629
- const result = await this.executeStep({
1630
- step: step.step,
1631
- prevOutput,
1632
- stepResults,
1633
- resume,
1634
- executionContext: {
1635
- workflowId,
1636
- runId,
1637
- executionPath: [...executionContext.executionPath, index],
1638
- suspendedPaths: executionContext.suspendedPaths,
1639
- resumeLabels: executionContext.resumeLabels,
1640
- retryConfig: executionContext.retryConfig,
1641
- state: executionContext.state
1642
- },
1643
- emitter,
1644
- abortController,
1645
- runtimeContext,
1646
- writableStream,
1647
- disableScorers,
1648
- tracingContext: {
1649
- currentSpan: conditionalSpan
1650
- }
1651
- });
1652
- stepResults[step.step.id] = result;
1653
- return result;
1654
- })
1655
- );
1656
- const hasFailed = results.find((result) => result.status === "failed");
1657
- const hasSuspended = results.find((result) => result.status === "suspended");
1658
- if (hasFailed) {
1659
- execResults = { status: "failed", error: hasFailed.error };
1660
- } else if (hasSuspended) {
1661
- execResults = { status: "suspended", suspendPayload: hasSuspended.suspendPayload };
1662
- } else {
1663
- execResults = {
1664
- status: "success",
1665
- output: results.reduce((acc, result, index) => {
1666
- if (result.status === "success") {
1667
- acc[stepsToRun[index].step.id] = result.output;
1668
- }
1669
- return acc;
1670
- }, {})
1671
- };
1672
- }
1673
- if (execResults.status === "failed") {
1674
- conditionalSpan?.error({
1675
- error: new Error(execResults.error)
1676
2200
  });
1677
- } else {
1678
- conditionalSpan?.end({
1679
- output: execResults.output || execResults
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
1680
2237
  });
2238
+ wf.setStepFlow(workflow.stepGraph);
2239
+ wf.commit();
2240
+ return wf;
1681
2241
  }
1682
- return execResults;
1683
- }
1684
- };
2242
+ };
2243
+ }
1685
2244
 
1686
- export { InngestExecutionEngine, InngestRun, InngestWorkflow, createStep, init, serve };
2245
+ export { InngestExecutionEngine, InngestPubSub, InngestRun, InngestWorkflow, _compatibilityCheck, createServe, createStep, init, serve };
1687
2246
  //# sourceMappingURL=index.js.map
1688
2247
  //# sourceMappingURL=index.js.map