@mastra/inngest 0.0.0-fix-local-pkg-cwd-20251224015404 → 0.0.0-fix-agent-network-schema-20260119184437

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,11 +1,14 @@
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';
1
5
  import { Tool } from '@mastra/core/tools';
2
6
  import { DefaultExecutionEngine, createTimeTravelExecutionParams, Run, hydrateSerializedStepErrors, Workflow } from '@mastra/core/workflows';
3
7
  import { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';
4
8
  import { z } from 'zod';
5
9
  import { randomUUID } from 'crypto';
6
10
  import { RequestContext } from '@mastra/core/di';
7
- import { RetryAfterError, NonRetriableError } from 'inngest';
8
- import { getErrorFromUnknown } from '@mastra/core/error';
11
+ import { NonRetriableError } from 'inngest';
9
12
  import { subscribe } from '@inngest/realtime';
10
13
  import { PubSub } from '@mastra/core/events';
11
14
  import { ReadableStream } from 'stream/web';
@@ -58,38 +61,46 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
58
61
  * After retries exhausted, error propagates here and we return a failed result.
59
62
  */
60
63
  async executeStepWithRetry(stepId, runStep, params) {
61
- try {
62
- const result = await this.wrapDurableOperation(stepId, runStep, { delay: params.delay });
63
- return { ok: true, result };
64
- } catch (e) {
65
- const cause = e?.cause;
66
- if (cause?.status === "failed") {
67
- params.stepSpan?.error({
68
- error: e,
69
- attributes: { status: "failed" }
70
- });
71
- if (cause.error && !(cause.error instanceof Error)) {
72
- cause.error = getErrorFromUnknown(cause.error, { serializeStack: false });
73
- }
74
- return { ok: false, error: cause };
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));
75
67
  }
76
- const errorInstance = getErrorFromUnknown(e, {
77
- serializeStack: false,
78
- fallbackMessage: "Unknown step execution error"
79
- });
80
- params.stepSpan?.error({
81
- error: errorInstance,
82
- attributes: { status: "failed" }
83
- });
84
- return {
85
- ok: false,
86
- error: {
87
- status: "failed",
88
- error: errorInstance,
89
- endedAt: Date.now()
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
+ };
90
100
  }
91
- };
101
+ }
92
102
  }
103
+ return { ok: false, error: { status: "failed", error: new Error("Unknown error"), endedAt: Date.now() } };
93
104
  }
94
105
  /**
95
106
  * Use Inngest's sleep primitive for durability
@@ -105,28 +116,32 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
105
116
  }
106
117
  /**
107
118
  * Wrap durable operations in Inngest step.run() for durability.
108
- * If retryConfig is provided, throws RetryAfterError INSIDE step.run() to trigger
109
- * Inngest's step-level retry mechanism (not function-level retry).
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.
110
128
  */
111
- async wrapDurableOperation(operationId, operationFn, retryConfig) {
129
+ async wrapDurableOperation(operationId, operationFn) {
112
130
  return this.inngestStep.run(operationId, async () => {
113
131
  try {
114
132
  return await operationFn();
115
133
  } catch (e) {
116
- if (retryConfig) {
117
- const errorInstance = getErrorFromUnknown(e, {
118
- serializeStack: false,
119
- fallbackMessage: "Unknown step execution error"
120
- });
121
- throw new RetryAfterError(errorInstance.message, retryConfig.delay, {
122
- cause: {
123
- status: "failed",
124
- error: errorInstance,
125
- endedAt: Date.now()
126
- }
127
- });
128
- }
129
- throw 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
+ });
130
145
  }
131
146
  });
132
147
  }
@@ -148,6 +163,96 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
148
163
  async invokeLifecycleCallbacksInternal(result) {
149
164
  return super.invokeLifecycleCallbacks(result);
150
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();
186
+ });
187
+ if (exportedSpan) {
188
+ const observability = this.mastra?.observability?.getSelectedInstance({});
189
+ return observability?.rebuildSpan(exportedSpan);
190
+ }
191
+ return void 0;
192
+ }
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);
201
+ });
202
+ }
203
+ /**
204
+ * Record error on step span durably.
205
+ */
206
+ async errorStepSpan(params) {
207
+ const { span, operationId, errorOptions } = params;
208
+ if (!span) return;
209
+ await this.wrapDurableOperation(operationId, async () => {
210
+ span.error(errorOptions);
211
+ });
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();
229
+ });
230
+ if (exportedSpan) {
231
+ const observability = this.mastra?.observability?.getSelectedInstance({});
232
+ return observability?.rebuildSpan(exportedSpan);
233
+ }
234
+ return void 0;
235
+ }
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
+ });
245
+ }
246
+ /**
247
+ * Record error on a generic child span durably (for control-flow operations).
248
+ */
249
+ async errorChildSpan(params) {
250
+ const { span, operationId, errorOptions } = params;
251
+ if (!span) return;
252
+ await this.wrapDurableOperation(operationId, async () => {
253
+ span.error(errorOptions);
254
+ });
255
+ }
151
256
  /**
152
257
  * Execute nested InngestWorkflow using inngestStep.invoke() for durability.
153
258
  * This MUST be called directly (not inside step.run()) due to Inngest constraints.
@@ -166,8 +271,13 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
166
271
  inputData,
167
272
  pubsub,
168
273
  startedAt,
169
- perStep
274
+ perStep,
275
+ stepSpan
170
276
  } = params;
277
+ const nestedTracingContext = executionContext.tracingIds?.traceId ? {
278
+ traceId: executionContext.tracingIds.traceId,
279
+ parentSpanId: stepSpan?.id
280
+ } : void 0;
171
281
  const isResume = !!resume?.steps?.length;
172
282
  let result;
173
283
  let runId;
@@ -194,7 +304,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
194
304
  resumePath: resume.steps?.[1] ? snapshot?.suspendedPaths?.[resume.steps?.[1]] : void 0
195
305
  },
196
306
  outputOptions: { includeState: true },
197
- perStep
307
+ perStep,
308
+ tracingOptions: nestedTracingContext
198
309
  }
199
310
  });
200
311
  result = invokeResp.result;
@@ -222,7 +333,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
222
333
  initialState: executionContext.state ?? {},
223
334
  runId: executionContext.runId,
224
335
  outputOptions: { includeState: true },
225
- perStep
336
+ perStep,
337
+ tracingOptions: nestedTracingContext
226
338
  }
227
339
  });
228
340
  result = invokeResp.result;
@@ -235,7 +347,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
235
347
  inputData,
236
348
  initialState: executionContext.state ?? {},
237
349
  outputOptions: { includeState: true },
238
- perStep
350
+ perStep,
351
+ tracingOptions: nestedTracingContext
239
352
  }
240
353
  });
241
354
  result = invokeResp.result;
@@ -632,8 +745,8 @@ var InngestRun = class extends Run {
632
745
  });
633
746
  }
634
747
  }
635
- async start(params) {
636
- return this._start(params);
748
+ async start(args) {
749
+ return this._start(args);
637
750
  }
638
751
  /**
639
752
  * Starts the workflow execution without waiting for completion (fire-and-forget).
@@ -641,7 +754,7 @@ var InngestRun = class extends Run {
641
754
  * The workflow executes independently in Inngest.
642
755
  * Use this when you don't need to wait for the result or want to avoid polling failures.
643
756
  */
644
- async startAsync(params) {
757
+ async startAsync(args) {
645
758
  const workflowsStore = await this.#mastra.getStorage()?.getStore("workflows");
646
759
  await workflowsStore?.persistWorkflowSnapshot({
647
760
  workflowName: this.workflowId,
@@ -661,8 +774,8 @@ var InngestRun = class extends Run {
661
774
  timestamp: Date.now()
662
775
  }
663
776
  });
664
- const inputDataToUse = await this._validateInput(params.inputData);
665
- const initialStateToUse = await this._validateInitialState(params.initialState ?? {});
777
+ const inputDataToUse = await this._validateInput(args.inputData);
778
+ const initialStateToUse = await this._validateInitialState(args.initialState ?? {});
666
779
  const eventOutput = await this.inngest.send({
667
780
  name: `workflow.${this.workflowId}`,
668
781
  data: {
@@ -670,10 +783,10 @@ var InngestRun = class extends Run {
670
783
  initialState: initialStateToUse,
671
784
  runId: this.runId,
672
785
  resourceId: this.resourceId,
673
- outputOptions: params.outputOptions,
674
- tracingOptions: params.tracingOptions,
675
- requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {},
676
- perStep: params.perStep
786
+ outputOptions: args.outputOptions,
787
+ tracingOptions: args.tracingOptions,
788
+ requestContext: args.requestContext ? Object.fromEntries(args.requestContext.entries()) : {},
789
+ perStep: args.perStep
677
790
  }
678
791
  });
679
792
  const eventId = eventOutput.ids[0];
@@ -1037,9 +1150,6 @@ var InngestRun = class extends Run {
1037
1150
  });
1038
1151
  return this.streamOutput;
1039
1152
  }
1040
- streamVNext(args = {}) {
1041
- return this.stream(args);
1042
- }
1043
1153
  timeTravelStream({
1044
1154
  inputData,
1045
1155
  resumeData,
@@ -1048,6 +1158,7 @@ var InngestRun = class extends Run {
1048
1158
  context,
1049
1159
  nestedStepsContext,
1050
1160
  requestContext,
1161
+ // tracingContext,
1051
1162
  tracingOptions,
1052
1163
  outputOptions,
1053
1164
  perStep
@@ -1130,9 +1241,11 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1130
1241
  #mastra;
1131
1242
  inngest;
1132
1243
  function;
1244
+ cronFunction;
1133
1245
  flowControlConfig;
1246
+ cronConfig;
1134
1247
  constructor(params, inngest) {
1135
- const { concurrency, rateLimit, throttle, debounce, priority, ...workflowParams } = params;
1248
+ const { concurrency, rateLimit, throttle, debounce, priority, cron, inputData, initialState, ...workflowParams } = params;
1136
1249
  super(workflowParams);
1137
1250
  this.engineType = "inngest";
1138
1251
  const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(
@@ -1141,6 +1254,9 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1141
1254
  this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : void 0;
1142
1255
  this.#mastra = params.mastra;
1143
1256
  this.inngest = inngest;
1257
+ if (cron) {
1258
+ this.cronConfig = { cron, inputData, initialState };
1259
+ }
1144
1260
  }
1145
1261
  async listWorkflowRuns(args) {
1146
1262
  const storage = this.#mastra?.getStorage();
@@ -1154,19 +1270,6 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1154
1270
  }
1155
1271
  return workflowsStore.listWorkflowRuns({ workflowName: this.id, ...args ?? {} });
1156
1272
  }
1157
- async getWorkflowRunById(runId) {
1158
- const storage = this.#mastra?.getStorage();
1159
- if (!storage) {
1160
- this.logger.debug("Cannot get workflow runs. Mastra engine is not initialized");
1161
- return this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null;
1162
- }
1163
- const workflowsStore = await storage.getStore("workflows");
1164
- if (!workflowsStore) {
1165
- return this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null;
1166
- }
1167
- const run = await workflowsStore.getWorkflowRunById({ runId, workflowName: this.id });
1168
- return run ?? (this.runs.get(runId) ? { ...this.runs.get(runId), workflowName: this.id } : null);
1169
- }
1170
1273
  __registerMastra(mastra) {
1171
1274
  super.__registerMastra(mastra);
1172
1275
  this.#mastra = mastra;
@@ -1188,7 +1291,8 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1188
1291
  }
1189
1292
  async createRun(options) {
1190
1293
  const runIdToUse = options?.runId || randomUUID();
1191
- const run = this.runs.get(runIdToUse) ?? new InngestRun(
1294
+ const existingInMemoryRun = this.runs.get(runIdToUse);
1295
+ const newRun = new InngestRun(
1192
1296
  {
1193
1297
  workflowId: this.id,
1194
1298
  runId: runIdToUse,
@@ -1205,15 +1309,17 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1205
1309
  },
1206
1310
  this.inngest
1207
1311
  );
1312
+ const run = existingInMemoryRun ?? newRun;
1208
1313
  this.runs.set(runIdToUse, run);
1209
1314
  const shouldPersistSnapshot = this.options.shouldPersistSnapshot({
1210
1315
  workflowStatus: run.workflowRunStatus,
1211
1316
  stepResults: {}
1212
1317
  });
1213
- const workflowSnapshotInStorage = await this.getWorkflowRunExecutionResult(runIdToUse, {
1318
+ const existingStoredRun = await this.getWorkflowRunById(runIdToUse, {
1214
1319
  withNestedWorkflows: false
1215
1320
  });
1216
- if (!workflowSnapshotInStorage && shouldPersistSnapshot) {
1321
+ const existsInStorage = existingStoredRun && !existingStoredRun.isFromInMemory;
1322
+ if (!existsInStorage && shouldPersistSnapshot) {
1217
1323
  const workflowsStore = await this.mastra?.getStorage()?.getStore("workflows");
1218
1324
  await workflowsStore?.persistWorkflowSnapshot({
1219
1325
  workflowName: this.id,
@@ -1238,6 +1344,30 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1238
1344
  }
1239
1345
  return run;
1240
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
+ }
1241
1371
  getFunction() {
1242
1372
  if (this.function) {
1243
1373
  return this.function;
@@ -1245,54 +1375,127 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1245
1375
  this.function = this.inngest.createFunction(
1246
1376
  {
1247
1377
  id: `workflow.${this.id}`,
1248
- retries: Math.min(this.retryConfig?.attempts ?? 0, 20),
1378
+ retries: 0,
1249
1379
  cancelOn: [{ event: `cancel.workflow.${this.id}` }],
1250
1380
  // Spread flow control configuration
1251
1381
  ...this.flowControlConfig
1252
1382
  },
1253
1383
  { event: `workflow.${this.id}` },
1254
1384
  async ({ event, step, attempt, publish }) => {
1255
- let { inputData, initialState, runId, resourceId, resume, outputOptions, format, timeTravel, perStep } = 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;
1256
1397
  if (!runId) {
1257
1398
  runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {
1258
1399
  return randomUUID();
1259
1400
  });
1260
1401
  }
1261
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
+ });
1262
1425
  const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);
1263
- const result = await engine.execute({
1264
- workflowId: this.id,
1265
- runId,
1266
- resourceId,
1267
- graph: this.executionGraph,
1268
- serializedStepGraph: this.serializedStepGraph,
1269
- input: inputData,
1270
- initialState,
1271
- pubsub,
1272
- retryConfig: this.retryConfig,
1273
- requestContext: new RequestContext(Object.entries(event.data.requestContext ?? {})),
1274
- resume,
1275
- timeTravel,
1276
- perStep,
1277
- format,
1278
- abortController: new AbortController(),
1279
- // currentSpan: undefined, // TODO: Pass actual parent Span from workflow execution context
1280
- outputOptions,
1281
- outputWriter: async (chunk) => {
1282
- try {
1283
- await pubsub.publish(`workflow.events.v2.${runId}`, {
1284
- type: "watch",
1285
- runId,
1286
- data: chunk
1287
- });
1288
- } catch (err) {
1289
- this.logger.debug?.("Failed to publish watch event:", err);
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
+ }
1290
1462
  }
1291
- }
1292
- });
1463
+ });
1464
+ } catch (error) {
1465
+ throw error;
1466
+ }
1293
1467
  await step.run(`workflow.${this.id}.finalize`, async () => {
1294
1468
  if (result.status !== "paused") {
1295
- await engine.invokeLifecycleCallbacksInternal(result);
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
+ }
1296
1499
  }
1297
1500
  if (result.status === "failed") {
1298
1501
  throw new NonRetriableError(`Workflow failed`, {
@@ -1320,15 +1523,14 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1320
1523
  });
1321
1524
  }
1322
1525
  getFunctions() {
1323
- 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
+ ];
1324
1531
  }
1325
1532
  };
1326
- function serve({
1327
- mastra,
1328
- inngest,
1329
- functions: userFunctions = [],
1330
- registerOptions
1331
- }) {
1533
+ function prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }) {
1332
1534
  const wfs = mastra.listWorkflows();
1333
1535
  const workflowFunctions = Array.from(
1334
1536
  new Set(
@@ -1341,177 +1543,181 @@ function serve({
1341
1543
  })
1342
1544
  )
1343
1545
  );
1344
- return serve$1({
1546
+ return {
1345
1547
  ...registerOptions,
1346
1548
  client: inngest,
1347
1549
  functions: [...workflowFunctions, ...userFunctions]
1348
- });
1550
+ };
1349
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);
1350
1559
 
1351
1560
  // src/types.ts
1352
1561
  var _compatibilityCheck = true;
1353
1562
 
1354
1563
  // src/index.ts
1355
- function isAgent(params) {
1356
- return params?.component === "AGENT";
1564
+ function isInngestWorkflow(input) {
1565
+ return input instanceof InngestWorkflow;
1566
+ }
1567
+ function isAgent(input) {
1568
+ return input instanceof Agent;
1569
+ }
1570
+ function isToolStep(input) {
1571
+ return input instanceof Tool;
1357
1572
  }
1358
- function isTool(params) {
1359
- return params instanceof Tool;
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);
1360
1575
  }
1361
- function isInngestWorkflow(params) {
1362
- return params instanceof InngestWorkflow;
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");
1363
1578
  }
1364
- function createStep(params, agentOptions) {
1579
+ function createStep(params, agentOrToolOptions) {
1365
1580
  if (isInngestWorkflow(params)) {
1366
1581
  return params;
1367
1582
  }
1368
1583
  if (isAgent(params)) {
1369
- const outputSchema = agentOptions?.structuredOutput?.schema ?? z.object({ text: z.string() });
1370
- return {
1371
- id: params.name,
1372
- description: params.getDescription(),
1373
- inputSchema: z.object({
1374
- prompt: z.string()
1375
- // resourceId: z.string().optional(),
1376
- // threadId: z.string().optional(),
1377
- }),
1378
- outputSchema,
1379
- execute: async ({
1380
- inputData,
1381
- runId,
1382
- [PUBSUB_SYMBOL]: pubsub,
1383
- [STREAM_FORMAT_SYMBOL]: streamFormat,
1384
- requestContext,
1385
- tracingContext,
1386
- abortSignal,
1387
- abort,
1388
- writer
1389
- }) => {
1390
- let streamPromise = {};
1391
- streamPromise.promise = new Promise((resolve, reject) => {
1392
- streamPromise.resolve = resolve;
1393
- streamPromise.reject = reject;
1584
+ return createStepFromAgent(params, agentOrToolOptions);
1585
+ }
1586
+ if (isToolStep(params)) {
1587
+ return createStepFromTool(params, agentOrToolOptions);
1588
+ }
1589
+ if (isStepParams(params)) {
1590
+ return createStepFromParams(params);
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) {
1598
+ return {
1599
+ id: params.id,
1600
+ description: params.description,
1601
+ inputSchema: params.inputSchema,
1602
+ stateSchema: params.stateSchema,
1603
+ outputSchema: params.outputSchema,
1604
+ resumeSchema: params.resumeSchema,
1605
+ suspendSchema: params.suspendSchema,
1606
+ scorers: params.scorers,
1607
+ retries: params.retries,
1608
+ execute: params.execute.bind(params)
1609
+ };
1610
+ }
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 ?? {};
1615
+ return {
1616
+ id: params.name,
1617
+ description: params.getDescription(),
1618
+ inputSchema: z.object({
1619
+ prompt: z.string()
1620
+ }),
1621
+ outputSchema,
1622
+ retries,
1623
+ scorers,
1624
+ execute: async ({
1625
+ inputData,
1626
+ runId,
1627
+ [PUBSUB_SYMBOL]: pubsub,
1628
+ [STREAM_FORMAT_SYMBOL]: streamFormat,
1629
+ requestContext,
1630
+ tracingContext,
1631
+ abortSignal,
1632
+ abort,
1633
+ writer
1634
+ }) => {
1635
+ let streamPromise = {};
1636
+ streamPromise.promise = new Promise((resolve, reject) => {
1637
+ streamPromise.resolve = resolve;
1638
+ streamPromise.reject = reject;
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
1394
1660
  });
1395
- let structuredResult = null;
1396
- const toolData = {
1397
- name: params.name,
1398
- args: inputData
1399
- };
1400
- let stream;
1401
- if ((await params.getModel()).specificationVersion === "v1") {
1402
- const { fullStream } = await params.streamLegacy(inputData.prompt, {
1403
- ...agentOptions ?? {},
1404
- // resourceId: inputData.resourceId,
1405
- // threadId: inputData.threadId,
1406
- requestContext,
1407
- tracingContext,
1408
- onFinish: (result) => {
1409
- const resultWithObject = result;
1410
- if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
1411
- structuredResult = resultWithObject.object;
1412
- }
1413
- streamPromise.resolve(result.text);
1414
- void agentOptions?.onFinish?.(result);
1415
- },
1416
- abortSignal
1417
- });
1418
- stream = fullStream;
1419
- } else {
1420
- const modelOutput = await params.stream(inputData.prompt, {
1421
- ...agentOptions ?? {},
1422
- requestContext,
1423
- tracingContext,
1424
- onFinish: (result) => {
1425
- const resultWithObject = result;
1426
- if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {
1427
- structuredResult = resultWithObject.object;
1428
- }
1429
- streamPromise.resolve(result.text);
1430
- void agentOptions?.onFinish?.(result);
1431
- },
1432
- abortSignal
1433
- });
1434
- stream = modelOutput.fullStream;
1435
- }
1436
- if (streamFormat === "legacy") {
1437
- await pubsub.publish(`workflow.events.v2.${runId}`, {
1438
- type: "watch",
1439
- runId,
1440
- data: { type: "tool-call-streaming-start", ...toolData ?? {} }
1441
- });
1442
- for await (const chunk of stream) {
1443
- if (chunk.type === "text-delta") {
1444
- await pubsub.publish(`workflow.events.v2.${runId}`, {
1445
- type: "watch",
1446
- runId,
1447
- data: { type: "tool-call-delta", ...toolData ?? {}, argsTextDelta: chunk.textDelta }
1448
- });
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;
1449
1671
  }
1450
- }
1451
- await pubsub.publish(`workflow.events.v2.${runId}`, {
1452
- type: "watch",
1453
- runId,
1454
- data: { type: "tool-call-streaming-finish", ...toolData ?? {} }
1455
- });
1456
- } else {
1457
- for await (const chunk of stream) {
1458
- await writer.write(chunk);
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
+ });
1459
1692
  }
1460
1693
  }
1461
- if (abortSignal.aborted) {
1462
- return abort();
1463
- }
1464
- if (structuredResult !== null) {
1465
- return structuredResult;
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);
1466
1702
  }
1467
- return {
1468
- text: await streamPromise.promise
1469
- };
1470
- },
1471
- component: params.component
1472
- };
1473
- }
1474
- if (isTool(params)) {
1475
- if (!params.inputSchema || !params.outputSchema) {
1476
- throw new Error("Tool must have input and output schemas defined");
1477
- }
1478
- return {
1479
- // TODO: tool probably should have strong id type
1480
- id: params.id,
1481
- description: params.description,
1482
- inputSchema: params.inputSchema,
1483
- outputSchema: params.outputSchema,
1484
- suspendSchema: params.suspendSchema,
1485
- resumeSchema: params.resumeSchema,
1486
- execute: async ({
1487
- inputData,
1488
- mastra,
1489
- requestContext,
1490
- tracingContext,
1491
- suspend,
1492
- resumeData,
1493
- runId,
1494
- workflowId,
1495
- state,
1496
- setState
1497
- }) => {
1498
- const toolContext = {
1499
- mastra,
1500
- requestContext,
1501
- tracingContext,
1502
- workflow: {
1503
- runId,
1504
- resumeData,
1505
- suspend,
1506
- workflowId,
1507
- state,
1508
- setState
1509
- }
1510
- };
1511
- return params.execute(inputData, toolContext);
1512
- },
1513
- component: "TOOL"
1514
- };
1703
+ }
1704
+ if (abortSignal.aborted) {
1705
+ return abort();
1706
+ }
1707
+ if (structuredResult !== null) {
1708
+ return structuredResult;
1709
+ }
1710
+ return {
1711
+ text: await streamPromise.promise
1712
+ };
1713
+ },
1714
+ component: params.component
1715
+ };
1716
+ }
1717
+ function createStepFromTool(params, agentOrToolOptions) {
1718
+ const toolOpts = agentOrToolOptions;
1719
+ if (!params.inputSchema || !params.outputSchema) {
1720
+ throw new Error("Tool must have input and output schemas defined");
1515
1721
  }
1516
1722
  return {
1517
1723
  id: params.id,
@@ -1520,7 +1726,480 @@ function createStep(params, agentOptions) {
1520
1726
  outputSchema: params.outputSchema,
1521
1727
  resumeSchema: params.resumeSchema,
1522
1728
  suspendSchema: params.suspendSchema,
1523
- execute: params.execute
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
1754
+ }
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;
1775
+ }
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";
1791
+ }
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;
1807
+ }
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;
1844
+ }
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
1858
+ }
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;
1902
+ }
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
+ });
1915
+ }
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 ?? []
1923
+ });
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
+ });
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
1999
+ });
2000
+ if (validatedResult.messages) {
2001
+ ProcessorRunner.applyMessagesToMessageList(
2002
+ validatedResult.messages,
2003
+ passThrough.messageList,
2004
+ idsBeforeProcessing,
2005
+ check
2006
+ );
2007
+ }
2008
+ if (validatedResult.systemMessages) {
2009
+ passThrough.messageList.replaceAllSystemMessages(validatedResult.systemMessages);
2010
+ }
2011
+ return { ...passThrough, messages, ...validatedResult };
2012
+ }
2013
+ return { ...passThrough, messages };
2014
+ }
2015
+ case "outputStream": {
2016
+ if (processor.processOutputStream) {
2017
+ const spanKey = `__outputStreamSpan_${processor.id}`;
2018
+ const mutableState = state ?? {};
2019
+ let processorSpan2 = mutableState[spanKey];
2020
+ if (!processorSpan2 && parentSpan) {
2021
+ processorSpan2 = parentSpan.createChildSpan({
2022
+ type: SpanType.PROCESSOR_RUN,
2023
+ name: `output stream processor: ${processor.id}`,
2024
+ entityType: EntityType.OUTPUT_PROCESSOR,
2025
+ entityId: processor.id,
2026
+ entityName: processor.name ?? processor.id,
2027
+ input: { phase, streamParts: [] },
2028
+ attributes: {
2029
+ processorExecutor: "workflow",
2030
+ processorIndex: processor.processorIndex
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];
2057
+ }
2058
+ } catch (error) {
2059
+ if (error instanceof TripWire) {
2060
+ processorSpan2?.end({ output: { tripwire: error.message } });
2061
+ } else {
2062
+ processorSpan2?.error({ error, endSpan: true });
2063
+ }
2064
+ delete mutableState[spanKey];
2065
+ throw error;
2066
+ }
2067
+ return { ...passThrough, state: mutableState, part: result };
2068
+ }
2069
+ return { ...passThrough, part };
2070
+ }
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
+ });
2096
+ }
2097
+ return {
2098
+ ...passThrough,
2099
+ messages: result.get.all.db(),
2100
+ systemMessages: result.getAllSystemMessages()
2101
+ };
2102
+ } else if (Array.isArray(result)) {
2103
+ ProcessorRunner.applyMessagesToMessageList(
2104
+ result,
2105
+ passThrough.messageList,
2106
+ idsBeforeProcessing,
2107
+ check,
2108
+ "response"
2109
+ );
2110
+ return { ...passThrough, messages: result };
2111
+ } else if (result && "messages" in result && "systemMessages" in result) {
2112
+ const typedResult = result;
2113
+ ProcessorRunner.applyMessagesToMessageList(
2114
+ typedResult.messages,
2115
+ passThrough.messageList,
2116
+ idsBeforeProcessing,
2117
+ check,
2118
+ "response"
2119
+ );
2120
+ passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
2121
+ return {
2122
+ ...passThrough,
2123
+ messages: typedResult.messages,
2124
+ systemMessages: typedResult.systemMessages
2125
+ };
2126
+ }
2127
+ return { ...passThrough, messages };
2128
+ }
2129
+ return { ...passThrough, messages };
2130
+ }
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
+ });
2140
+ }
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
+ };
2192
+ }
2193
+ return { ...passThrough, messages };
2194
+ }
2195
+ return { ...passThrough, messages };
2196
+ }
2197
+ default:
2198
+ return { ...passThrough, messages };
2199
+ }
2200
+ });
2201
+ },
2202
+ component: "PROCESSOR"
1524
2203
  };
1525
2204
  }
1526
2205
  function init(inngest) {
@@ -1563,6 +2242,6 @@ function init(inngest) {
1563
2242
  };
1564
2243
  }
1565
2244
 
1566
- export { InngestExecutionEngine, InngestPubSub, InngestRun, InngestWorkflow, _compatibilityCheck, createStep, init, serve };
2245
+ export { InngestExecutionEngine, InngestPubSub, InngestRun, InngestWorkflow, _compatibilityCheck, createServe, createStep, init, serve };
1567
2246
  //# sourceMappingURL=index.js.map
1568
2247
  //# sourceMappingURL=index.js.map