@mastra/inngest 1.8.0-alpha.1 → 1.8.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @mastra/inngest
2
2
 
3
+ ## 1.8.0-alpha.2
4
+
5
+ ### Minor Changes
6
+
7
+ - Added support for the fine-grained authorization (FGA) `actor` signal on the Inngest execution engine. ([#18674](https://github.com/mastra-ai/mastra/pull/18674))
8
+
9
+ Workflows running on the Inngest engine can now pass a trusted `actor` through `run.start()`, `startAsync()`, `resume()`, `stream()`, and `timeTravel()`. The signal is re-threaded across durable step and nested-workflow boundaries, so every nested agent, tool, and memory FGA check sees the same actor. Previously `actor` was only threaded through the default engine, so trusted background workflows on Inngest lost the membership bypass at each step re-entry.
10
+
11
+ **Usage**
12
+
13
+ ```ts
14
+ const run = await workflow.createRun();
15
+ await run.start({
16
+ inputData,
17
+ requestContext, // includes organizationId / tenant scope
18
+ actor: { actorKind: 'system', sourceWorkflow: 'nightly-sync' },
19
+ });
20
+ ```
21
+
22
+ ### Patch Changes
23
+
24
+ - Updated dependencies [[`8be63b0`](https://github.com/mastra-ai/mastra/commit/8be63b015fb8d72cea1220f05e7dc3bb997cc249), [`345eecc`](https://github.com/mastra-ai/mastra/commit/345eecce6ba519b5d987f0e10b5de4c8e5734580), [`ee14cae`](https://github.com/mastra-ai/mastra/commit/ee14cae244805783bde518a6142de28b744b169c)]:
25
+ - @mastra/core@1.48.0-alpha.7
26
+
3
27
  ## 1.8.0-alpha.1
4
28
 
5
29
  ### Minor Changes
@@ -270,7 +270,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
270
270
  pubsub,
271
271
  startedAt,
272
272
  perStep,
273
- stepSpan
273
+ stepSpan,
274
+ actor
274
275
  } = params;
275
276
  const nestedTracingContext = executionContext.tracingIds?.traceId ? {
276
277
  traceId: executionContext.tracingIds.traceId,
@@ -303,7 +304,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
303
304
  },
304
305
  outputOptions: { includeState: true },
305
306
  perStep,
306
- tracingOptions: nestedTracingContext
307
+ tracingOptions: nestedTracingContext,
308
+ actor
307
309
  }
308
310
  });
309
311
  result = invokeResp.result;
@@ -332,7 +334,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
332
334
  runId: executionContext.runId,
333
335
  outputOptions: { includeState: true },
334
336
  perStep,
335
- tracingOptions: nestedTracingContext
337
+ tracingOptions: nestedTracingContext,
338
+ actor
336
339
  }
337
340
  });
338
341
  result = invokeResp.result;
@@ -346,7 +349,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
346
349
  initialState: executionContext.state ?? {},
347
350
  outputOptions: { includeState: true },
348
351
  perStep,
349
- tracingOptions: nestedTracingContext
352
+ tracingOptions: nestedTracingContext,
353
+ actor
350
354
  }
351
355
  });
352
356
  result = invokeResp.result;
@@ -864,6 +868,7 @@ var InngestRun = class extends Run {
864
868
  outputOptions: args.outputOptions,
865
869
  tracingOptions: args.tracingOptions,
866
870
  requestContext: args.requestContext ? Object.fromEntries(args.requestContext.entries()) : {},
871
+ actor: args.actor,
867
872
  perStep: args.perStep
868
873
  }
869
874
  });
@@ -880,6 +885,7 @@ var InngestRun = class extends Run {
880
885
  tracingOptions,
881
886
  format,
882
887
  requestContext,
888
+ actor,
883
889
  perStep
884
890
  }) {
885
891
  const workflowsStore = await this.#mastra.getStorage()?.getStore("workflows");
@@ -915,6 +921,7 @@ var InngestRun = class extends Run {
915
921
  tracingOptions,
916
922
  format,
917
923
  requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {},
924
+ actor,
918
925
  perStep
919
926
  }
920
927
  });
@@ -1011,6 +1018,13 @@ var InngestRun = class extends Run {
1011
1018
  resumePath: steps?.[0] ? snapshot?.suspendedPaths?.[steps?.[0]] : void 0
1012
1019
  },
1013
1020
  requestContext: mergedRequestContext,
1021
+ // `actor` is a per-call trust signal, not rehydrated from the snapshot like
1022
+ // `requestContext` is above. This intentionally matches the default engine,
1023
+ // which passes `actor: params.actor` on resume and never reads it from the
1024
+ // snapshot (see packages/core/src/workflows/workflow.ts `_resume`). The caller
1025
+ // (a trusted background system) re-supplies `actor` on each resume; we never
1026
+ // persist a membership-bypass signal into durable storage.
1027
+ actor: params.actor,
1014
1028
  perStep: params.perStep
1015
1029
  }
1016
1030
  });
@@ -1167,6 +1181,7 @@ var InngestRun = class extends Run {
1167
1181
  tracingOptions: params.tracingOptions,
1168
1182
  outputOptions: params.outputOptions,
1169
1183
  requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {},
1184
+ actor: params.actor,
1170
1185
  perStep: params.perStep
1171
1186
  }
1172
1187
  });
@@ -1220,7 +1235,11 @@ var InngestRun = class extends Run {
1220
1235
  });
1221
1236
  };
1222
1237
  }
1223
- streamLegacy({ inputData, requestContext } = {}) {
1238
+ streamLegacy({
1239
+ inputData,
1240
+ requestContext,
1241
+ actor
1242
+ } = {}) {
1224
1243
  const { readable, writable } = new TransformStream();
1225
1244
  const writer = writable.getWriter();
1226
1245
  void writer.write({
@@ -1257,7 +1276,7 @@ var InngestRun = class extends Run {
1257
1276
  writer.releaseLock();
1258
1277
  }
1259
1278
  };
1260
- this.executionResults = this._start({ inputData, requestContext, format: "legacy" }).then((result) => {
1279
+ this.executionResults = this._start({ inputData, requestContext, actor, format: "legacy" }).then((result) => {
1261
1280
  if (result.status !== "suspended") {
1262
1281
  this.closeStreamAction?.().catch(() => {
1263
1282
  });
@@ -1272,6 +1291,7 @@ var InngestRun = class extends Run {
1272
1291
  stream({
1273
1292
  inputData,
1274
1293
  requestContext,
1294
+ actor,
1275
1295
  tracingOptions,
1276
1296
  closeOnSuspend = true,
1277
1297
  initialState,
@@ -1308,6 +1328,7 @@ var InngestRun = class extends Run {
1308
1328
  const executionResultsPromise = self._start({
1309
1329
  inputData,
1310
1330
  requestContext,
1331
+ actor,
1311
1332
  // tracingContext, // We are not able to pass a reference to a span here, what to do?
1312
1333
  initialState,
1313
1334
  tracingOptions,
@@ -1352,6 +1373,7 @@ var InngestRun = class extends Run {
1352
1373
  context,
1353
1374
  nestedStepsContext,
1354
1375
  requestContext,
1376
+ actor,
1355
1377
  // tracingContext,
1356
1378
  tracingOptions,
1357
1379
  outputOptions,
@@ -1389,6 +1411,7 @@ var InngestRun = class extends Run {
1389
1411
  resumeData,
1390
1412
  initialState,
1391
1413
  requestContext,
1414
+ actor,
1392
1415
  tracingOptions,
1393
1416
  outputOptions,
1394
1417
  perStep
@@ -1635,7 +1658,8 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1635
1658
  format,
1636
1659
  timeTravel,
1637
1660
  perStep,
1638
- tracingOptions
1661
+ tracingOptions,
1662
+ actor
1639
1663
  } = event.data;
1640
1664
  if (!runId) {
1641
1665
  runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {
@@ -1681,6 +1705,7 @@ var InngestWorkflow = class _InngestWorkflow extends Workflow {
1681
1705
  pubsub,
1682
1706
  retryConfig: this.retryConfig,
1683
1707
  requestContext,
1708
+ actor,
1684
1709
  resume,
1685
1710
  timeTravel,
1686
1711
  perStep,
@@ -1906,5 +1931,5 @@ async function connect(options) {
1906
1931
  }
1907
1932
 
1908
1933
  export { InngestExecutionEngine, InngestPubSub, InngestRun, InngestWorkflow, collectInngestFunctions, connect };
1909
- //# sourceMappingURL=chunk-5BEMBEWN.js.map
1910
- //# sourceMappingURL=chunk-5BEMBEWN.js.map
1934
+ //# sourceMappingURL=chunk-6AX2K2MQ.js.map
1935
+ //# sourceMappingURL=chunk-6AX2K2MQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/execution-engine.ts","../src/pubsub.ts","../src/run.ts","../src/workflow.ts","../src/functions.ts","../src/connect.ts"],"names":["subscribe","getErrorFromUnknown","createTimeTravelExecutionParams","randomUUID","NonRetriableError"],"mappings":";;;;;;;;;;;;;AAqBO,IAAM,sBAAA,GAAN,cAAqC,sBAAA,CA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A,CAAE,QAAQ,CAAA,QAAA,KAAY;AAC3C,QAAA,IAAI,oBAAoB,eAAA,EAAiB;AACvC,UAAA,QAAA,CAAS,iBAAiB,MAAM,CAAA;AAChC,UAAA,OAAO,SAAS,YAAA,EAAa;AAAA,QAC/B;AACA,QAAA,OAAO,EAAC;AAAA,MACV,CAAC;AAAA;AACH,GACF;AAEA,EAAA,OAAO,CAAC,GAAG,iBAAA,EAAmB,GAAG,aAAa,CAAA;AAChD;;;ACmBA,eAAsB,QAAQ,OAAA,EAA+B;AAC3D,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,WAAW,eAAA,EAAiB,GAAG,gBAAe,GAAI,OAAA;AAC3E,EAAA,MAAM,YAAA,GAAe,uBAAA,CAAwB,EAAE,MAAA,EAAQ,WAAW,CAAA;AAElE,EAAA,IAAI,YAAA,CAAa,WAAW,CAAA,EAAG;AAC7B,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN;AAAA,KAGF;AAAA,EACF;AAEA,EAAA,MAAM,EAAE,OAAA,EAAS,aAAA,EAAc,GAAI,MAAM,OAAO,iBAAiB,CAAA;AAEjE,EAAA,OAAO,aAAA,CAAc;AAAA;AAAA;AAAA,IAGnB,GAAG,cAAA;AAAA,IACH,GAAG,eAAA;AAAA,IACH,MAAM,CAAC,EAAE,QAAQ,OAAA,EAAS,SAAA,EAAW,cAAc;AAAA,GACpD,CAAA;AACH","file":"chunk-6AX2K2MQ.js","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { ActorSignal } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { getErrorFromUnknown } from '@mastra/core/error';\nimport type { SerializedError } from '@mastra/core/error';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { EntityType } from '@mastra/core/observability';\nimport { DefaultExecutionEngine, createTimeTravelExecutionParams } from '@mastra/core/workflows';\nimport type {\n ExecutionContext,\n Step,\n StepResult,\n StepFailure,\n ExecutionEngineOptions,\n TimeTravelExecutionParams,\n WorkflowResult,\n} from '@mastra/core/workflows';\nimport type { Inngest, BaseContext } from 'inngest';\nimport { InngestWorkflow } from './workflow';\n\nexport class InngestExecutionEngine extends DefaultExecutionEngine {\n private inngestStep: BaseContext<Inngest>['step'];\n private inngestAttempts: number;\n\n constructor(\n mastra: Mastra,\n inngestStep: BaseContext<Inngest>['step'],\n inngestAttempts: number = 0,\n options: ExecutionEngineOptions,\n ) {\n super({ mastra, options });\n this.inngestStep = inngestStep;\n this.inngestAttempts = inngestAttempts;\n }\n\n // =============================================================================\n // Hook Overrides\n // =============================================================================\n\n /**\n * Format errors while preserving Error instances and their custom properties.\n * Uses getErrorFromUnknown to ensure all error properties are preserved.\n */\n protected formatResultError(\n error: Error | string | undefined,\n lastOutput: StepResult<any, any, any, any>,\n ): SerializedError {\n const outputError = (lastOutput as StepFailure<any, any, any, any>)?.error;\n const errorSource = error || outputError;\n const errorInstance = getErrorFromUnknown(errorSource, {\n serializeStack: true, // Include stack in JSON for better debugging in Inngest\n fallbackMessage: 'Unknown workflow error',\n });\n return errorInstance.toJSON();\n }\n\n /**\n * Detect InngestWorkflow instances for special nested workflow handling\n */\n isNestedWorkflowStep(step: Step<any, any, any>): boolean {\n return step instanceof InngestWorkflow;\n }\n\n /**\n * Inngest requires requestContext serialization for memoization.\n * When steps are replayed, the original function doesn't re-execute,\n * so requestContext modifications must be captured and restored.\n */\n requiresDurableContextSerialization(): boolean {\n return true;\n }\n\n /**\n * Execute a step with retry logic for Inngest.\n * Retries are handled via step-level retry (RetryAfterError thrown INSIDE step.run()).\n * After retries exhausted, error propagates here and we return a failed result.\n */\n async executeStepWithRetry<T>(\n stepId: string,\n runStep: () => Promise<T>,\n params: {\n retries: number;\n delay: number;\n stepSpan?: any;\n workflowId: string;\n runId: string;\n },\n ): Promise<{ ok: true; result: T } | { ok: false; error: { status: 'failed'; error: Error; endedAt: number } }> {\n for (let i = 0; i < params.retries + 1; i++) {\n if (i > 0 && params.delay) {\n await new Promise(resolve => setTimeout(resolve, params.delay));\n }\n try {\n //removed retry config with RetryAfterError from wrapDurableOperation, since we're manually handling retries here\n const result = await this.wrapDurableOperation(stepId, runStep);\n return { ok: true, result };\n } catch (e) {\n if (i === params.retries) {\n // After step-level retries exhausted, extract failure from error cause\n const cause = (e as any)?.cause;\n if (cause?.status === 'failed') {\n params.stepSpan?.error({\n error: e,\n attributes: { status: 'failed' },\n });\n // Ensure cause.error is an Error instance\n if (cause.error && !(cause.error instanceof Error)) {\n cause.error = getErrorFromUnknown(cause.error, { serializeStack: false });\n }\n return { ok: false, error: cause };\n }\n\n // Fallback for other errors - preserve the original error instance\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n params.stepSpan?.error({\n error: errorInstance,\n attributes: { status: 'failed' },\n });\n return {\n ok: false,\n error: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n },\n };\n }\n }\n }\n // Should never reach here, but TypeScript needs it\n return { ok: false, error: { status: 'failed', error: new Error('Unknown error'), endedAt: Date.now() } };\n }\n\n /**\n * Use Inngest's sleep primitive for durability\n */\n async executeSleepDuration(duration: number, sleepId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleep(`workflow.${workflowId}.sleep.${sleepId}`, duration < 0 ? 0 : duration);\n }\n\n /**\n * Use Inngest's sleepUntil primitive for durability\n */\n async executeSleepUntilDate(date: Date, sleepUntilId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleepUntil(`workflow.${workflowId}.sleepUntil.${sleepUntilId}`, date);\n }\n\n /**\n * Wrap durable operations in Inngest step.run() for durability.\n *\n * IMPORTANT: Errors are wrapped with a cause structure before throwing.\n * This is necessary because Inngest's error serialization (serialize-error-cjs)\n * only captures standard Error properties (message, name, stack, code, cause).\n * Custom properties like statusCode, responseHeaders from AI SDK errors would\n * be lost. By putting our serialized error (via getErrorFromUnknown with toJSON())\n * in the cause property, we ensure custom properties survive serialization.\n * The cause property is in serialize-error-cjs's allowlist, and when the cause\n * object is finally JSON.stringify'd, our error's toJSON() is called.\n */\n async wrapDurableOperation<T>(operationId: string, operationFn: () => Promise<T>): Promise<T> {\n const result = await this.inngestStep.run(operationId, async () => {\n try {\n const fnResult = await operationFn();\n return fnResult;\n } catch (e) {\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n throw new Error(errorInstance.message, {\n cause: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n },\n });\n }\n });\n return result as T;\n }\n\n /**\n * Provide Inngest step primitive in engine context\n */\n getEngineContext(): Record<string, any> {\n return { step: this.inngestStep };\n }\n\n /**\n * For Inngest, lifecycle callbacks are invoked in the workflow's finalize step\n * (wrapped in step.run for durability), not in execute(). Override to skip.\n */\n public async invokeLifecycleCallbacks(_result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n // No-op: Inngest handles callbacks in workflow.ts finalize step\n }\n\n /**\n * Actually invoke the lifecycle callbacks. Called from workflow.ts finalize step.\n */\n public async invokeLifecycleCallbacksInternal(result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n return super.invokeLifecycleCallbacks(result);\n }\n\n // =============================================================================\n // Durable Span Lifecycle Hooks\n // =============================================================================\n\n /**\n * Create a step span durably - on first execution, creates and exports span.\n * On replay, returns cached span data without re-creating.\n */\n async createStepSpan(params: {\n parentSpan: any;\n stepId: string;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n entityType?: string;\n entityId?: string;\n tracingPolicy?: any;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided (e.g., for steps inside control-flow),\n // otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n entityType: options.entityType as EntityType | undefined,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a step span durably.\n */\n async endStepSpan(params: {\n span: any;\n operationId: string;\n endOptions: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on step span durably.\n */\n async errorStepSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Create a generic child span durably (for control-flow operations).\n * On first execution, creates and exports span. On replay, returns cached span data.\n */\n async createChildSpan(params: {\n parentSpan: any;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n attributes?: Record<string, unknown>;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided, otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n tracingPolicy: this.options?.tracingPolicy,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a generic child span durably (for control-flow operations).\n */\n async endChildSpan(params: {\n span: any;\n operationId: string;\n endOptions?: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on a generic child span durably (for control-flow operations).\n */\n async errorChildSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Execute nested InngestWorkflow using inngestStep.invoke() for durability.\n * This MUST be called directly (not inside step.run()) due to Inngest constraints.\n */\n async executeWorkflowStep(params: {\n step: Step<string, any, any>;\n stepResults: Record<string, StepResult<any, any, any, any>>;\n executionContext: ExecutionContext;\n resume?: {\n steps: string[];\n resumePayload: any;\n runId?: string;\n };\n timeTravel?: TimeTravelExecutionParams;\n prevOutput: any;\n inputData: any;\n pubsub: PubSub;\n startedAt: number;\n perStep?: boolean;\n stepSpan?: any;\n actor?: ActorSignal;\n }): Promise<StepResult<any, any, any, any> | null> {\n // Only handle InngestWorkflow instances\n if (!(params.step instanceof InngestWorkflow)) {\n return null;\n }\n\n const {\n step,\n stepResults,\n executionContext,\n resume,\n timeTravel,\n prevOutput,\n inputData,\n pubsub,\n startedAt,\n perStep,\n stepSpan,\n actor,\n } = params;\n\n // Build trace context to propagate to nested workflow\n const nestedTracingContext = executionContext.tracingIds?.traceId\n ? {\n traceId: executionContext.tracingIds.traceId,\n parentSpanId: stepSpan?.id,\n }\n : undefined;\n\n const isResume = !!resume?.steps?.length;\n let result: WorkflowResult<any, any, any, any>;\n let runId: string;\n\n const isTimeTravel = !!(timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === step.id);\n\n try {\n if (isResume) {\n runId = stepResults[resume?.steps?.[0] ?? '']?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: runId,\n });\n\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n initialState: executionContext.state ?? snapshot?.value ?? {},\n runId: runId,\n resume: {\n runId: runId,\n steps: resume.steps.slice(1),\n stepResults: snapshot?.context as any,\n resumePayload: resume.resumePayload,\n resumePath: resume.steps?.[1] ? (snapshot?.suspendedPaths?.[resume.steps?.[1]] as any) : undefined,\n },\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n actor,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else if (isTimeTravel) {\n const workflowsStoreForTimeTravel = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = (await workflowsStoreForTimeTravel?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: executionContext.runId,\n })) ?? { context: {} };\n const timeTravelParams = createTimeTravelExecutionParams({\n steps: timeTravel.steps.slice(1),\n inputData: timeTravel.inputData,\n resumeData: timeTravel.resumeData,\n context: (timeTravel.nestedStepResults?.[step.id] ?? {}) as any,\n nestedStepsContext: (timeTravel.nestedStepResults ?? {}) as any,\n snapshot,\n graph: step.buildExecutionGraph(),\n });\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n timeTravel: timeTravelParams,\n initialState: executionContext.state ?? {},\n runId: executionContext.runId,\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n actor,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else {\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n initialState: executionContext.state ?? {},\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n actor,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n }\n } catch (e) {\n // Nested workflow threw an error (likely from finalization step)\n // The error cause should contain the workflow result with runId\n const errorCause = (e as any)?.cause;\n\n // Try to extract runId from error cause or generate new one\n if (errorCause && typeof errorCause === 'object') {\n result = errorCause as WorkflowResult<any, any, any, any>;\n // The runId might be in the result's steps metadata\n runId = errorCause.runId || randomUUID();\n } else {\n // Fallback: if we can't get the result from error, construct a basic failed result\n runId = randomUUID();\n result = {\n status: 'failed',\n error: e instanceof Error ? e : new Error(String(e)),\n steps: {},\n input: inputData,\n } as WorkflowResult<any, any, any, any>;\n }\n }\n\n const res = await this.inngestStep.run(\n `workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,\n async () => {\n if (result.status === 'failed') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'failed',\n error: result?.error,\n payload: prevOutput,\n },\n },\n });\n\n return { executionContext, result: { status: 'failed', error: result?.error, endedAt: Date.now() } };\n } else if (result.status === 'suspended') {\n const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {\n const stepRes: StepResult<any, any, any, any> = stepResult as StepResult<any, any, any, any>;\n return stepRes?.status === 'suspended';\n });\n\n for (const [stepName, stepResult] of suspendedSteps) {\n const suspendPath: string[] = [stepName, ...(stepResult?.suspendPayload?.__workflow_meta?.path ?? [])];\n executionContext.suspendedPaths[step.id] = executionContext.executionPath;\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-suspended',\n payload: {\n id: step.id,\n status: 'suspended',\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: stepResult.payload,\n suspendPayload: {\n ...(stepResult as any)?.suspendPayload,\n __workflow_meta: { runId: runId, path: suspendPath },\n },\n },\n };\n }\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: {},\n },\n };\n } else if (result.status === 'tripwire') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'tripwire',\n error: result?.tripwire?.reason,\n payload: prevOutput,\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'tripwire',\n tripwire: result?.tripwire,\n endedAt: Date.now(),\n },\n };\n } else if (perStep || result.status === 'paused') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'paused',\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n return { executionContext, result: { status: 'paused' } };\n }\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'success',\n output: result?.result,\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n\n return { executionContext, result: { status: 'success', output: result?.result, endedAt: Date.now() } };\n },\n );\n\n Object.assign(executionContext, res.executionContext);\n return {\n ...res.result,\n startedAt,\n payload: inputData,\n resumedAt: resume?.steps[0] === step.id ? startedAt : undefined,\n resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : undefined,\n } as StepResult<any, any, any, any>;\n }\n}\n","import { PubSub } from '@mastra/core/events';\nimport type { Event } from '@mastra/core/events';\nimport type { Inngest } from 'inngest';\nimport { subscribe } from 'inngest/realtime';\n\n/**\n * Build a TopicRef compatible with Inngest SDK v4's `inngest.realtime.publish()`.\n * The runtime only requires `channel` and `topic`; `config.schema` is optional and\n * we leave it absent so no validation runs.\n */\nfunction buildTopicRef(channel: string, topic: string) {\n return { channel, topic, config: {} as any };\n}\n\n/**\n * Parse a topic string and extract the runId and topic type.\n *\n * Supported formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * - \"agent.stream.{runId}\" - agent stream events\n *\n * @returns { runId, topicType } or null if not a recognized format\n */\nfunction parseTopic(topic: string): { runId: string; topicType: 'workflow' | 'agent' } | null {\n // Try workflow format first\n const workflowMatch = topic.match(/^workflow\\.events\\.v2\\.(.+)$/);\n if (workflowMatch && workflowMatch[1]) {\n return { runId: workflowMatch[1], topicType: 'workflow' };\n }\n\n // Try agent stream format\n const agentMatch = topic.match(/^agent\\.stream\\.(.+)$/);\n if (agentMatch && agentMatch[1]) {\n return { runId: agentMatch[1], topicType: 'agent' };\n }\n\n return null;\n}\n\n/**\n * PubSub implementation for Inngest workflows.\n *\n * This bridges the PubSub abstract class interface with Inngest's realtime system:\n * - publish() uses `inngest.realtime.publish()` (Inngest SDK v4 client API).\n * This is non-durable: it executes immediately and is not memoized as a step.\n * When called inside an Inngest function it auto-includes the current runId.\n * - subscribe() uses `inngest/realtime` subscribe for real-time streaming.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> Inngest channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events (for InngestAgent)\n * -> Inngest channel: \"agent:{runId}\", topic: \"agent-stream\"\n */\nexport class InngestPubSub extends PubSub {\n private inngest: Inngest;\n private workflowId: string;\n private subscriptions: Map<\n string,\n {\n unsubscribe: () => void;\n callbacks: Set<(event: Event, ack?: () => Promise<void>) => void>;\n }\n > = new Map();\n\n constructor(inngest: Inngest, workflowId: string) {\n super();\n this.inngest = inngest;\n this.workflowId = workflowId;\n }\n\n /**\n * Publish an event to Inngest's realtime system.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events\n * -> channel: \"agent:{runId}\", topic: \"agent-stream\"\n * (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)\n */\n async publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>): Promise<void> {\n const parsed = parseTopic(topic);\n if (!parsed) {\n return; // Ignore unrecognized topic formats\n }\n\n const { runId, topicType } = parsed;\n\n // Use different Inngest topics and channels for different event types\n // Agent stream events use a runId-only channel so nested workflows publish to the same channel\n const inngestTopic = topicType === 'agent' ? 'agent-stream' : 'watch';\n const channel = topicType === 'agent' ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;\n\n try {\n // For agent stream events, send the full event structure so subscribers can access type/runId/data\n // For workflow events, send just the data (existing behavior)\n const dataToSend = topicType === 'agent' ? event : event.data;\n await this.inngest.realtime.publish(buildTopicRef(channel, inngestTopic), dataToSend);\n } catch (err: any) {\n // For agent stream terminal events, rethrow — losing a finish/error event\n // causes the client stream to hang indefinitely\n if (topicType === 'agent' && (event.type === 'finish' || event.type === 'error')) {\n throw err;\n }\n // Non-terminal events: log but don't throw\n console.error('InngestPubSub publish error:', err?.message ?? err);\n }\n }\n\n /**\n * Subscribe to events from Inngest's realtime system.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events\n * -> channel: \"agent:{runId}\", topic: \"agent-stream\"\n * (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)\n */\n async subscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const parsed = parseTopic(topic);\n if (!parsed) {\n return; // Ignore unrecognized topic formats\n }\n\n const { runId, topicType } = parsed;\n\n // Check if we already have a subscription for this topic\n if (this.subscriptions.has(topic)) {\n this.subscriptions.get(topic)!.callbacks.add(cb);\n return;\n }\n\n const callbacks = new Set<(event: Event, ack?: () => Promise<void>) => void>([cb]);\n\n // Use different Inngest topics and channels for different event types\n // Agent stream events use a runId-only channel so nested workflows publish to the same channel\n const inngestTopic = topicType === 'agent' ? 'agent-stream' : 'watch';\n const channel = topicType === 'agent' ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;\n\n // Await the subscribe call to ensure the WebSocket connection is established\n // before we consider the subscription \"ready\". This prevents race conditions\n // where the workflow triggers before the subscription can receive events.\n const stream = await subscribe(\n {\n channel,\n topics: [inngestTopic],\n app: this.inngest,\n },\n (message: any) => {\n // For agent stream events, message.data is the full AgentStreamEvent structure (type, runId, data)\n // For workflow events, wrap message.data in a PubSub Event format\n // IMPORTANT: Always generate a unique `id` and `createdAt` for every event.\n // CachingPubSub deduplicates events by `id` — without a unique id, all events\n // after the first would be filtered out (since undefined === undefined in the seen set).\n let event: Event;\n if (topicType === 'agent' && message.data?.type && message.data?.runId) {\n // Agent stream event - spread the AgentStreamEvent data and add required Event fields\n event = {\n id: crypto.randomUUID(),\n createdAt: new Date(),\n ...message.data,\n } as unknown as Event;\n } else {\n // Workflow event or fallback - wrap in standard Event format\n event = {\n id: crypto.randomUUID(),\n type: inngestTopic,\n runId,\n data: message.data,\n createdAt: new Date(),\n };\n }\n\n for (const callback of callbacks) {\n callback(event);\n }\n },\n );\n\n this.subscriptions.set(topic, {\n unsubscribe: () => {\n try {\n void stream.cancel();\n } catch (err) {\n console.error('InngestPubSub unsubscribe error:', err);\n }\n },\n callbacks,\n });\n }\n\n /**\n * Unsubscribe a callback from a topic.\n * If no callbacks remain, the underlying Inngest subscription is cancelled.\n */\n async unsubscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const sub = this.subscriptions.get(topic);\n if (!sub) {\n return;\n }\n\n sub.callbacks.delete(cb);\n\n // If no more callbacks, cancel the subscription\n if (sub.callbacks.size === 0) {\n sub.unsubscribe();\n this.subscriptions.delete(topic);\n }\n }\n\n /**\n * Flush any pending operations. No-op for Inngest.\n */\n async flush(): Promise<void> {\n // No-op for Inngest\n }\n\n /**\n * Clean up all subscriptions during graceful shutdown.\n */\n async close(): Promise<void> {\n for (const [, sub] of this.subscriptions) {\n sub.unsubscribe();\n }\n this.subscriptions.clear();\n }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport type { ActorSignal } from '@mastra/core/auth/ee';\nimport { getErrorFromUnknown } from '@mastra/core/error';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { TracingContext, TracingOptions } from '@mastra/core/observability';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { WorkflowRunOutput, ChunkFrom } from '@mastra/core/stream';\nimport { createTimeTravelExecutionParams, Run, hydrateSerializedStepErrors } from '@mastra/core/workflows';\nimport type {\n ExecutionEngine,\n ExecutionGraph,\n OutputWriter,\n SerializedStepFlowEntry,\n Step,\n StepWithComponent,\n StreamEvent,\n TimeTravelContext,\n WorkflowEngineType,\n WorkflowResult,\n WorkflowStreamEvent,\n} from '@mastra/core/workflows';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport { subscribe } from 'inngest/realtime';\nimport type { InngestEngineType } from './types';\n\nexport class InngestRun<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType\n >[],\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n> extends Run<TEngineType, TSteps, TState, TInput, TOutput> {\n private inngest: Inngest;\n serializedStepGraph: SerializedStepFlowEntry[];\n #mastra: Mastra;\n\n constructor(\n params: {\n workflowId: string;\n runId: string;\n resourceId?: string;\n executionEngine: ExecutionEngine;\n executionGraph: ExecutionGraph;\n serializedStepGraph: SerializedStepFlowEntry[];\n mastra?: Mastra;\n retryConfig?: {\n attempts?: number;\n delay?: number;\n };\n cleanup?: () => void;\n workflowSteps: Record<string, StepWithComponent>;\n workflowEngineType: WorkflowEngineType;\n validateInputs?: boolean;\n },\n inngest: Inngest,\n ) {\n super(params);\n this.inngest = inngest;\n this.serializedStepGraph = params.serializedStepGraph;\n this.#mastra = params.mastra!;\n }\n\n /**\n * Get run output using hybrid approach: realtime subscription + polling fallback.\n * Resolves as soon as either method detects completion.\n */\n async getRunOutput(_eventId: string, maxWaitMs = 300000) {\n const storage = this.#mastra?.getStorage();\n const workflowsStore = await storage?.getStore('workflows');\n if (!workflowsStore) {\n throw new NonRetriableError(`Workflow storage is required to retrieve output for run ${this.runId}`);\n }\n return new Promise<any>((resolve, reject) => {\n let resolved = false;\n let unsubscribe: (() => void) | null = null;\n let pollTimeoutId: NodeJS.Timeout | null = null;\n\n const cleanup = () => {\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch {\n // Ignore unsubscribe errors\n }\n }\n if (pollTimeoutId) {\n clearTimeout(pollTimeoutId);\n }\n };\n\n const handleResult = (result: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve(result);\n }\n };\n\n const handleError = (error: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(error);\n }\n };\n\n // Start realtime subscription for workflow-finish event\n let realtimeStreamPromise: ReturnType<typeof subscribe> | null = null;\n\n const startRealtimeSubscription = async () => {\n try {\n realtimeStreamPromise = subscribe(\n {\n channel: `workflow:${this.workflowId}:${this.runId}`,\n topics: ['watch'],\n app: this.inngest,\n },\n async (message: any) => {\n if (resolved) return;\n\n const event = message.data;\n\n if (event?.type === 'workflow-finish') {\n // Got the finish event - load snapshot and resolve\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot?.context) {\n snapshot.context = hydrateSerializedStepErrors(snapshot.context);\n }\n\n const realtimeResult: Record<string, unknown> = {\n steps: snapshot?.context,\n status: event.payload?.status ?? snapshot?.status,\n input: (snapshot?.context as Record<string, unknown>)?.input,\n };\n const resultValue = event.payload?.result ?? snapshot?.result;\n if (resultValue !== undefined) realtimeResult.result = resultValue;\n const rawError = event.payload?.error ?? snapshot?.error;\n if (rawError) {\n realtimeResult.error = getErrorFromUnknown(rawError, { serializeStack: false });\n }\n if (snapshot?.value !== undefined) realtimeResult.state = snapshot.value;\n const result = { output: { result: realtimeResult } };\n\n handleResult(result, 'realtime');\n }\n },\n );\n\n // Set unsubscribe immediately so cleanup can cancel even before await resolves\n unsubscribe = () => {\n realtimeStreamPromise?.then(stream => stream.cancel().catch(() => {})).catch(() => {});\n };\n\n await realtimeStreamPromise;\n } catch {\n // Realtime subscription failed - polling will still work as fallback\n }\n };\n\n // Start polling by checking our own workflow snapshot store directly.\n // This avoids the Inngest runs API which has a 15-second response cache.\n const startPolling = async () => {\n const startTime = Date.now();\n\n const poll = async () => {\n if (resolved) {\n return;\n }\n if (Date.now() - startTime >= maxWaitMs) {\n handleError(new NonRetriableError(`Workflow did not complete within ${maxWaitMs}ms`), 'polling-timeout');\n return;\n }\n\n try {\n const snapshot = await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n // Still running or in an intermediate state — schedule next poll\n // 'running' = initial state, 'waiting' = sleeping/waiting, 'pending' = not yet started\n if (\n !snapshot ||\n snapshot.status === 'running' ||\n snapshot.status === 'waiting' ||\n snapshot.status === 'pending'\n ) {\n pollTimeoutId = setTimeout(poll, 150 + Math.random() * 100);\n return;\n }\n\n if (snapshot.context) {\n snapshot.context = hydrateSerializedStepErrors(snapshot.context);\n }\n\n const pollingResult: Record<string, unknown> = {\n steps: snapshot.context,\n status: snapshot.status,\n input: (snapshot.context as Record<string, unknown>)?.input,\n };\n if (snapshot.result !== undefined) pollingResult.result = snapshot.result;\n if (snapshot.error !== undefined) {\n pollingResult.error = getErrorFromUnknown(snapshot.error, { serializeStack: false });\n }\n if (snapshot.value !== undefined) pollingResult.state = snapshot.value;\n\n handleResult({ output: { result: pollingResult } }, `polling-${snapshot.status}`);\n } catch (error) {\n if (error instanceof NonRetriableError) {\n handleError(error, 'polling-non-retriable');\n return;\n }\n handleError(\n new NonRetriableError(\n `Failed to poll workflow status: ${error instanceof Error ? error.message : String(error)}`,\n ),\n 'polling-error',\n );\n }\n };\n\n // Start first poll\n void poll();\n };\n\n // Start both in parallel\n void startRealtimeSubscription();\n void startPolling();\n });\n }\n\n async cancel() {\n const storage = this.#mastra?.getStorage();\n\n await this.inngest.send({\n name: `cancel.workflow.${this.workflowId}`,\n data: {\n runId: this.runId,\n },\n });\n\n const workflowsStore = await storage?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot) {\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n ...snapshot,\n status: 'canceled' as any,\n value: snapshot.value,\n },\n });\n }\n }\n\n async start(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext;\n actor?: ActorSignal;\n outputWriter?: OutputWriter;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n return this._start(args);\n }\n\n /**\n * Starts the workflow execution without waiting for completion (fire-and-forget).\n * Returns immediately with the runId after sending the event to Inngest.\n * The workflow executes independently in Inngest.\n * Use this when you don't need to wait for the result or want to avoid polling failures.\n */\n async startAsync(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext;\n actor?: ActorSignal;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<{ runId: string }> {\n // Persist initial snapshot\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n // Validate inputs\n const inputDataToUse = await this._validateInput(args.inputData);\n const initialStateToUse = await this._validateInitialState(args.initialState ?? ({} as TState));\n\n // Send event to Inngest (fire-and-forget)\n const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions: args.outputOptions,\n tracingOptions: args.tracingOptions,\n requestContext: args.requestContext ? Object.fromEntries(args.requestContext.entries()) : {},\n actor: args.actor,\n perStep: args.perStep,\n },\n });\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n\n // Return immediately - NO POLLING\n return { runId: this.runId };\n }\n\n async _start({\n inputData,\n initialState,\n outputOptions,\n tracingOptions,\n format,\n requestContext,\n actor,\n perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n initialState?: TState;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n format?: 'legacy' | 'vnext' | undefined;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n const inputDataToUse = await this._validateInput(inputData);\n const initialStateToUse = await this._validateInitialState(initialState ?? ({} as TState));\n\n const eventName = `workflow.${this.workflowId}`;\n\n const eventOutput = await this.inngest.send({\n name: eventName,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions,\n tracingOptions,\n format,\n requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {},\n actor,\n perStep,\n },\n });\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n\n const runOutput = await this.getRunOutput(eventId);\n const result = runOutput?.output?.result;\n\n this.hydrateFailedResult(result);\n\n // Only include state when explicitly requested, matching core engine behavior\n if (!outputOptions?.includeState) {\n delete result.state;\n }\n\n if (result.status !== 'suspended') {\n this.cleanup?.();\n }\n return result;\n }\n\n async resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const p = this._resume(params).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n this.executionResults = p;\n return p;\n }\n\n /**\n * Performs all resume preparation and dispatches the resume event to Inngest,\n * but does NOT wait for the workflow result. Shared by `_resume()` (which polls\n * for the result afterwards) and `resumeAsync()` (which returns immediately).\n *\n * Send-time failures (invalid resume data, event send failure) reject synchronously,\n * and the snapshot is rolled back to its prior state on send failure.\n */\n async _resumeAndSendEvent<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<{ eventId: string }> {\n const storage = this.#mastra?.getStorage();\n\n const workflowsStore = await storage?.getStore('workflows');\n if (!workflowsStore) {\n throw new NonRetriableError(`Workflow storage is required to resume run ${this.runId}`);\n }\n const snapshot = await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (!snapshot) {\n throw new NonRetriableError(`Cannot resume run ${this.runId}: snapshot not found`);\n }\n\n // Support label-based resume: look up step from resumeLabels\n const snapshotResumeLabel = params.label ? snapshot.resumeLabels?.[params.label] : undefined;\n const stepParam = snapshotResumeLabel?.stepId ?? params.step;\n\n let steps: string[] = [];\n if (stepParam) {\n if (typeof stepParam === 'string') {\n steps = stepParam.split('.');\n } else {\n steps = (Array.isArray(stepParam) ? stepParam : [stepParam]).map(step =>\n typeof step === 'string' ? step : step?.id,\n );\n }\n }\n\n const suspendedStep = this.workflowSteps[steps?.[0] ?? ''];\n\n const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);\n\n // Merge persisted requestContext from snapshot with any new values from params\n const persistedRequestContext = (snapshot as any)?.requestContext ?? {};\n const newRequestContext = params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {};\n const mergedRequestContext = { ...persistedRequestContext, ...newRequestContext };\n\n // Mark the snapshot as 'running' before sending the event so that\n // snapshot-based polling doesn't return the stale suspended/paused result.\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n ...snapshot,\n status: 'running',\n result: undefined,\n error: undefined,\n timestamp: Date.now(),\n } as any,\n });\n\n let eventOutput;\n try {\n eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: resumeDataToUse,\n initialState: snapshot?.value ?? {},\n runId: this.runId,\n workflowId: this.workflowId,\n stepResults: snapshot?.context as any,\n resume: {\n steps,\n stepResults: snapshot?.context as any,\n resumePayload: resumeDataToUse,\n resumePath: steps?.[0] ? (snapshot?.suspendedPaths?.[steps?.[0]] as any) : undefined,\n },\n requestContext: mergedRequestContext,\n // `actor` is a per-call trust signal, not rehydrated from the snapshot like\n // `requestContext` is above. This intentionally matches the default engine,\n // which passes `actor: params.actor` on resume and never reads it from the\n // snapshot (see packages/core/src/workflows/workflow.ts `_resume`). The caller\n // (a trusted background system) re-supplies `actor` on each resume; we never\n // persist a membership-bypass signal into durable storage.\n actor: params.actor,\n perStep: params.perStep,\n },\n });\n } catch (err) {\n // Rollback: restore the original snapshot so the run isn't stuck in 'running'.\n // The rollback itself can fail (e.g. transient storage error); log it but\n // always rethrow the original error so the underlying failure isn't masked.\n try {\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: snapshot as any,\n });\n } catch (rollbackErr) {\n console.error('Failed to rollback snapshot during resume error recovery:', rollbackErr);\n }\n throw err;\n }\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n\n return { eventId };\n }\n\n async _resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const { eventId } = await this._resumeAndSendEvent(params);\n const runOutput = await this.getRunOutput(eventId);\n const result = runOutput?.output?.result;\n this.hydrateFailedResult(result);\n return result;\n }\n\n /**\n * Resumes a suspended workflow without waiting for completion (fire-and-forget).\n * Returns immediately with the runId after sending the resume event to Inngest.\n * The workflow continues executing independently in Inngest.\n *\n * Mirrors `startAsync()`: send-time failures (invalid resume data, event send\n * failure) still reject synchronously and roll back the snapshot, but the result\n * is never polled via `getRunOutput()`. This avoids the polling-based 404 race when\n * you don't need the resolved result inline.\n *\n * NOTE: this is exposed over HTTP / the client SDK as `resume-no-wait` / `resumeNoWait()`,\n * not `resumeAsync`, because the existing `resumeAsync()` client/server surface awaits the\n * full workflow result. TODO(v2): consolidate so `resumeAsync` consistently means\n * fire-and-forget across core, client SDK and HTTP routes (breaking change deferred to v2).\n */\n async resumeAsync<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n perStep?: boolean;\n }): Promise<{ runId: string }> {\n await this._resumeAndSendEvent(params);\n // Return immediately - NO POLLING\n return { runId: this.runId };\n }\n\n async timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const p = this._timeTravel(params).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n this.executionResults = p;\n return p;\n }\n\n async _timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }) {\n if (!params.step || (Array.isArray(params.step) && params.step?.length === 0)) {\n throw new Error('Step is required and must be a valid step or array of steps');\n }\n\n let steps: string[] = [];\n if (typeof params.step === 'string') {\n steps = params.step.split('.');\n } else {\n steps = (Array.isArray(params.step) ? params.step : [params.step]).map(step =>\n typeof step === 'string' ? step : step?.id,\n );\n }\n\n if (steps.length === 0) {\n throw new Error('No steps provided to timeTravel');\n }\n\n const storage = this.#mastra?.getStorage();\n const workflowsStore = await storage?.getStore('workflows');\n if (!workflowsStore) {\n throw new NonRetriableError(`Workflow storage is required to time-travel run ${this.runId}`);\n }\n\n const snapshot = await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n let snapshotForRollback = snapshot;\n if (!snapshot) {\n const pendingSnapshot = {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'pending' as const,\n value: {},\n context: {} as any,\n activePaths: [] as number[],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n };\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: pendingSnapshot,\n });\n snapshotForRollback = pendingSnapshot;\n }\n\n if (snapshot?.status === 'running') {\n throw new Error('This workflow run is still running, cannot time travel');\n }\n\n let inputDataToUse = params.inputData;\n\n if (inputDataToUse && steps.length === 1) {\n inputDataToUse = await this._validateTimetravelInputData(params.inputData, this.workflowSteps[steps[0]!]!);\n }\n\n const timeTravelData = createTimeTravelExecutionParams({\n steps,\n inputData: inputDataToUse,\n resumeData: params.resumeData,\n context: params.context,\n nestedStepsContext: params.nestedStepsContext,\n snapshot: (snapshot ?? { context: {} }) as any,\n graph: this.executionGraph,\n initialState: params.initialState,\n perStep: params.perStep,\n });\n\n // Save previous snapshot for rollback if send fails\n const previousSnapshot = snapshotForRollback;\n\n // Mark the snapshot as 'running' before sending the event so that\n // snapshot-based polling doesn't return the stale result from a previous run.\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n let eventOutput;\n try {\n eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n initialState: timeTravelData.state,\n runId: this.runId,\n workflowId: this.workflowId,\n stepResults: timeTravelData.stepResults,\n timeTravel: timeTravelData,\n tracingOptions: params.tracingOptions,\n outputOptions: params.outputOptions,\n requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {},\n actor: params.actor,\n perStep: params.perStep,\n },\n });\n } catch (err) {\n // Rollback: restore the previous snapshot so the run isn't stuck in 'running'.\n // The rollback itself can fail (e.g. transient storage error); log it but\n // always rethrow the original error so the underlying failure isn't masked.\n if (previousSnapshot) {\n try {\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: previousSnapshot as any,\n });\n } catch (rollbackErr) {\n console.error('Failed to rollback snapshot during time-travel error recovery:', rollbackErr);\n }\n }\n throw err;\n }\n\n const eventId = eventOutput.ids[0];\n if (!eventId) {\n throw new Error('Event ID is not set');\n }\n const runOutput = await this.getRunOutput(eventId);\n const result = runOutput?.output?.result;\n this.hydrateFailedResult(result);\n\n // Only include state when explicitly requested, matching core engine behavior\n if (!params.outputOptions?.includeState) {\n delete result.state;\n }\n\n return result;\n }\n\n watch(cb: (event: WorkflowStreamEvent) => void): () => void {\n let active = true;\n const streamPromise = subscribe(\n {\n channel: `workflow:${this.workflowId}:${this.runId}`,\n topics: ['watch'],\n app: this.inngest,\n },\n (message: any) => {\n if (active) {\n cb(message.data);\n }\n },\n );\n\n return () => {\n active = false;\n streamPromise\n .then(async (stream: Awaited<typeof streamPromise>) => {\n return stream.cancel();\n })\n .catch(err => {\n console.error(err);\n });\n };\n }\n\n streamLegacy({\n inputData,\n requestContext,\n actor,\n }: { inputData?: TInput; requestContext?: RequestContext; actor?: ActorSignal } = {}): {\n stream: ReadableStream<StreamEvent>;\n getWorkflowState: () => Promise<WorkflowResult<TState, TInput, TOutput, TSteps>>;\n } {\n const { readable, writable } = new TransformStream<StreamEvent, StreamEvent>();\n\n const writer = writable.getWriter();\n void writer.write({\n // @ts-expect-error - stream event type mismatch\n type: 'start',\n payload: { runId: this.runId },\n });\n\n const unwatch = this.watch(async event => {\n try {\n const e: any = {\n ...event,\n type: event.type.replace('workflow-', ''),\n };\n\n if (e.type === 'step-output') {\n e.type = e.payload.output.type;\n e.payload = e.payload.output.payload;\n }\n // watch events are data stream events, so we need to cast them to the correct type\n await writer.write(e as any);\n } catch {}\n });\n\n this.closeStreamAction = async () => {\n await writer.write({\n type: 'finish',\n // @ts-expect-error - stream event type mismatch\n payload: { runId: this.runId },\n });\n unwatch();\n\n try {\n await writer.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n } finally {\n writer.releaseLock();\n }\n };\n\n this.executionResults = this._start({ inputData, requestContext, actor, format: 'legacy' }).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n return {\n stream: readable as ReadableStream<StreamEvent>,\n getWorkflowState: () => this.executionResults!,\n };\n }\n\n stream({\n inputData,\n requestContext,\n actor,\n tracingOptions,\n closeOnSuspend = true,\n initialState,\n outputOptions,\n perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n closeOnSuspend?: boolean;\n initialState?: TState;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n } = {}): WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n if (this.closeStreamAction && this.streamOutput) {\n return this.streamOutput;\n }\n\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n // TODO: fix this, watch doesn't have a type\n const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n await controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n\n const executionResultsPromise = self._start({\n inputData,\n requestContext,\n actor,\n // tracingContext, // We are not able to pass a reference to a span here, what to do?\n initialState,\n tracingOptions,\n outputOptions,\n format: 'vnext',\n perStep,\n });\n let executionResults;\n try {\n executionResults = await executionResultsPromise;\n\n if (closeOnSuspend) {\n // always close stream, even if the workflow is suspended\n // this will trigger a finish event with workflow status set to suspended\n self.closeStreamAction?.().catch(() => {});\n } else if (executionResults.status !== 'suspended') {\n self.closeStreamAction?.().catch(() => {});\n }\n if (self.streamOutput) {\n self.streamOutput.updateResults(\n executionResults as unknown as WorkflowResult<TState, TInput, TOutput, TSteps>,\n );\n }\n } catch (err) {\n self.streamOutput?.rejectResults(err as unknown as Error);\n self.closeStreamAction?.().catch(() => {});\n }\n },\n });\n\n this.streamOutput = new WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>>({\n runId: this.runId,\n workflowId: this.workflowId,\n stream,\n });\n\n return this.streamOutput;\n }\n\n timeTravelStream<TTravelInput>({\n inputData,\n resumeData,\n initialState,\n step,\n context,\n nestedStepsContext,\n requestContext,\n actor,\n // tracingContext,\n tracingOptions,\n outputOptions,\n perStep,\n }: {\n inputData?: TTravelInput;\n initialState?: TState;\n resumeData?: any;\n step:\n | Step<string, any, any, any, any, any, TEngineType>\n | [...Step<string, any, any, any, any, any, TEngineType>[], Step<string, any, any, any, any, any, TEngineType>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n actor?: ActorSignal;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }) {\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n // TODO: fix this, watch doesn't have a type\n const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n const executionResultsPromise = self._timeTravel({\n inputData,\n step,\n context,\n nestedStepsContext,\n resumeData,\n initialState,\n requestContext,\n actor,\n tracingOptions,\n outputOptions,\n perStep,\n });\n\n self.executionResults = executionResultsPromise;\n\n let executionResults;\n try {\n executionResults = await executionResultsPromise;\n self.closeStreamAction?.().catch(() => {});\n\n if (self.streamOutput) {\n self.streamOutput.updateResults(executionResults);\n }\n } catch (err) {\n self.streamOutput?.rejectResults(err as unknown as Error);\n self.closeStreamAction?.().catch(() => {});\n }\n },\n });\n\n this.streamOutput = new WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>>({\n runId: this.runId,\n workflowId: this.workflowId,\n stream,\n });\n\n return this.streamOutput;\n }\n\n /**\n * Hydrates errors in a failed workflow result back to proper Error instances.\n * This ensures error.cause chains and custom properties are preserved.\n */\n private hydrateFailedResult(result: WorkflowResult<TState, TInput, TOutput, TSteps>): void {\n if (result.status === 'failed') {\n // Ensure error is a proper Error instance with all properties preserved\n result.error = getErrorFromUnknown(result.error, { serializeStack: false });\n // Re-hydrate serialized errors in step results\n if (result.steps) {\n hydrateSerializedStepErrors(result.steps);\n }\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { emitErrorEvent } from '@mastra/core/agent/durable';\nimport { RequestContext } from '@mastra/core/di';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { SpanType, EntityType } from '@mastra/core/observability';\nimport type { WorkflowRuns } from '@mastra/core/storage';\nimport { Workflow } from '@mastra/core/workflows';\nimport type {\n Step,\n StepResult,\n WorkflowConfig,\n StepFlowEntry,\n WorkflowResult,\n WorkflowRunState,\n WorkflowStreamEvent,\n Run,\n} from '@mastra/core/workflows';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport { InngestExecutionEngine } from './execution-engine';\nimport { InngestPubSub } from './pubsub';\nimport { InngestRun } from './run';\nimport type {\n InngestEngineType,\n InngestFlowControlConfig,\n InngestFlowCronConfig,\n InngestWorkflowConfig,\n} from './types';\n\nexport class InngestWorkflow<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType\n >[],\n TWorkflowId extends string = string,\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TPrevSchema = TInput,\n> extends Workflow<TEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrevSchema> {\n #mastra: Mastra;\n public inngest: Inngest;\n\n private function: ReturnType<Inngest['createFunction']> | undefined;\n private cronFunction: ReturnType<Inngest['createFunction']> | undefined;\n private readonly flowControlConfig?: InngestFlowControlConfig;\n private readonly cronConfig?: InngestFlowCronConfig<TInput, TState>;\n /**\n * Optional override that lets a host (e.g. `createInngestAgent`) provide the\n * PubSub instance used by workflow steps for publishing chunk/finish events.\n * When set, the workflow function uses this factory instead of constructing\n * a fresh `InngestPubSub`. This is what lets `DurableAgent.observe()` see\n * cached history when the agent wraps its PubSub in a `CachingPubSub`.\n */\n #pubsubFactory?: (defaultPubsub: PubSub) => PubSub;\n\n constructor(\n params: InngestWorkflowConfig<\n TWorkflowId,\n TState,\n TInput,\n TOutput,\n TSteps & Step<string, any, any, any, any, any, InngestEngineType>[]\n >,\n inngest: Inngest,\n ) {\n const { concurrency, rateLimit, throttle, debounce, priority, cron, inputData, initialState, ...workflowParams } =\n params;\n\n super(workflowParams as WorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps>);\n\n this.engineType = 'inngest';\n\n const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(\n ([_, value]) => value !== undefined,\n );\n\n this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : undefined;\n\n this.#mastra = params.mastra!;\n this.inngest = inngest;\n\n if (cron) {\n this.cronConfig = { cron, inputData, initialState };\n }\n }\n\n async listWorkflowRuns(args?: {\n fromDate?: Date;\n toDate?: Date;\n perPage?: number | false;\n page?: number;\n resourceId?: string;\n }) {\n const storage = this.#mastra?.getStorage();\n if (!storage) {\n this.logger.debug('Cannot get workflow runs. Mastra engine is not initialized');\n return { runs: [], total: 0 };\n }\n\n const workflowsStore = await storage.getStore('workflows');\n if (!workflowsStore) {\n return { runs: [], total: 0 };\n }\n return workflowsStore.listWorkflowRuns({ workflowName: this.id, ...(args ?? {}) }) as unknown as WorkflowRuns;\n }\n\n /**\n * Override the PubSub used inside the durable workflow function. Callers like\n * `createInngestAgent` use this to route workflow event publishes through the\n * agent's `CachingPubSub`, so `observe()` can replay cached history.\n *\n * The factory receives the workflow's own default `InngestPubSub` (constructed\n * with this workflow's id) as input. Hosts should wrap that instance rather\n * than substitute it, so workflow-event channels (which encode the workflow\n * id) remain workflow-local. Returning a `CachingPubSub` wrapping the default\n * is the canonical pattern.\n *\n * The factory is propagated to every nested `InngestWorkflow` in the step\n * graph. Nested workflows run as their own Inngest functions and resolve\n * their own pubsub at runtime; each invocation passes its own workflow-local\n * default into the same factory, so the host can share cross-workflow state\n * (e.g. a single agent-scoped cache) without collapsing per-workflow channel\n * isolation.\n */\n __setPubsubFactory(factory: (defaultPubsub: PubSub) => PubSub) {\n this.#pubsubFactory = factory;\n const updateNested = (step: StepFlowEntry) => {\n if (\n (step.type === 'step' || step.type === 'loop' || step.type === 'foreach') &&\n step.step instanceof InngestWorkflow\n ) {\n step.step.__setPubsubFactory(factory);\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n for (const subStep of step.steps) {\n updateNested(subStep);\n }\n }\n };\n for (const step of this.executionGraph.steps) {\n updateNested(step);\n }\n }\n\n /**\n * Test-only accessor for the configured pubsub factory. Lets tests verify that\n * a host (e.g. `createInngestAgent`) wired the workflow to its agent pubsub\n * without having to drive a real Inngest invocation.\n */\n __getPubsubFactory(): ((defaultPubsub: PubSub) => PubSub) | undefined {\n return this.#pubsubFactory;\n }\n\n __registerMastra(mastra: Mastra) {\n super.__registerMastra(mastra);\n this.#mastra = mastra;\n this.executionEngine.__registerMastra(mastra);\n const updateNested = (step: StepFlowEntry) => {\n if (\n (step.type === 'step' || step.type === 'loop' || step.type === 'foreach') &&\n step.step instanceof InngestWorkflow\n ) {\n step.step.__registerMastra(mastra);\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n for (const subStep of step.steps) {\n updateNested(subStep);\n }\n }\n };\n\n if (this.executionGraph.steps.length) {\n for (const step of this.executionGraph.steps) {\n updateNested(step);\n }\n }\n }\n\n async createRun(options?: {\n runId?: string;\n resourceId?: string;\n }): Promise<Run<TEngineType, TSteps, TState, TInput, TOutput>> {\n const runIdToUse = options?.runId || randomUUID();\n\n // Return a new Run instance with object parameters\n const existingInMemoryRun = this.runs.get(runIdToUse);\n const newRun = new InngestRun<TEngineType, TSteps, TState, TInput, TOutput>(\n {\n workflowId: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n executionEngine: this.executionEngine,\n executionGraph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n mastra: this.#mastra,\n retryConfig: this.retryConfig,\n cleanup: () => this.runs.delete(runIdToUse),\n workflowSteps: this.steps,\n workflowEngineType: this.engineType,\n validateInputs: this.options.validateInputs,\n },\n this.inngest,\n );\n const run = (existingInMemoryRun ?? newRun) as Run<TEngineType, TSteps, TState, TInput, TOutput>;\n\n this.runs.set(runIdToUse, run);\n\n const shouldPersistSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: run.workflowRunStatus,\n stepResults: {},\n });\n\n const existingStoredRun = await this.getWorkflowRunById(runIdToUse, {\n withNestedWorkflows: false,\n });\n\n // Check if run exists in persistent storage (not just in-memory)\n const existsInStorage = existingStoredRun && !existingStoredRun.isFromInMemory;\n\n if (!existsInStorage && shouldPersistSnapshot) {\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n snapshot: {\n runId: runIdToUse,\n status: 'pending',\n value: {},\n context: {},\n activePaths: [],\n activeStepsPath: {},\n waitingPaths: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: {},\n resumeLabels: {},\n result: undefined,\n error: undefined,\n timestamp: Date.now(),\n },\n });\n }\n\n return run;\n }\n\n //createCronFunction is only called if cronConfig.cron is defined.\n private createCronFunction() {\n if (this.cronFunction) {\n return this.cronFunction;\n }\n this.cronFunction = this.inngest.createFunction(\n {\n id: `workflow.${this.id}.cron`,\n retries: 0,\n cancelOn: [{ event: `cancel.workflow.${this.id}` }],\n triggers: { cron: this.cronConfig?.cron ?? '' },\n ...this.flowControlConfig,\n },\n async () => {\n const run = await this.createRun();\n // @ts-expect-error - cron inputData type mismatch\n const result = await run.start({\n inputData: this.cronConfig?.inputData,\n initialState: this.cronConfig?.initialState,\n });\n return { result, runId: run.runId };\n },\n );\n return this.cronFunction;\n }\n\n getFunction(): ReturnType<Inngest['createFunction']> {\n if (this.function) {\n return this.function;\n }\n\n // Always set function-level retries to 0, since retries are handled at the step level via executeStepWithRetry\n // which uses either step.retries or retryConfig.attempts (step.retries takes precedence).\n // step.retries is not accessible at function level, so we handle retries manually in executeStepWithRetry.\n // This is why we set retries to 0 here.\n this.function = this.inngest.createFunction(\n {\n id: `workflow.${this.id}`,\n retries: 0,\n cancelOn: [{ event: `cancel.workflow.${this.id}` }],\n triggers: { event: `workflow.${this.id}` },\n // Spread flow control configuration\n ...this.flowControlConfig,\n },\n async ({ event, step, attempt }) => {\n let {\n inputData,\n initialState,\n runId,\n resourceId,\n resume,\n outputOptions,\n format,\n timeTravel,\n perStep,\n tracingOptions,\n actor,\n } = event.data;\n\n if (!runId) {\n runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {\n return randomUUID();\n });\n }\n\n // Create InngestPubSub instance. Publishes go through `inngest.realtime.publish()`\n // (Inngest SDK v4 client API), which auto-includes the current runId from the\n // function's async context.\n //\n // The default is constructed with `this.id` so workflow-event channels stay\n // workflow-local (InngestPubSub encodes the workflowId in `workflow:<id>:<runId>`).\n // Hosts (e.g. `createInngestAgent`) can override via `__setPubsubFactory` to\n // wrap this default - typically with a `CachingPubSub` so `observe()` can replay\n // cached history - without disturbing per-workflow channel isolation.\n const defaultPubsub = new InngestPubSub(this.inngest, this.id);\n const pubsub: PubSub = this.#pubsubFactory?.(defaultPubsub) ?? defaultPubsub;\n\n // Create requestContext before execute so we can reuse it in finalize\n const requestContext: RequestContext = new RequestContext(Object.entries(event.data.requestContext ?? {}));\n\n // Store mastra reference for use in proxy closure\n const mastra = this.#mastra;\n const tracingPolicy = this.options.tracingPolicy;\n\n // Create the workflow root span durably - exports SPAN_STARTED immediately on first execution\n // On replay, returns memoized ExportedSpan data without re-creating the span\n const workflowSpanData = await step.run(`workflow.${this.id}.span.start`, async () => {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (!observability) return undefined;\n\n const span = observability.startSpan({\n type: SpanType.WORKFLOW_RUN,\n name: `workflow run: '${this.id}'`,\n entityType: EntityType.WORKFLOW_RUN,\n entityId: this.id,\n entityName: this.id,\n input: inputData,\n metadata: {\n resourceId,\n runId,\n },\n tracingPolicy,\n tracingOptions,\n requestContext,\n });\n\n return span?.exportSpan();\n });\n\n const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);\n\n let result: WorkflowResult<TState, TInput, TOutput, TSteps>;\n try {\n result = await engine.execute<TState, TInput, WorkflowResult<TState, TInput, TOutput, TSteps>>({\n workflowId: this.id,\n runId,\n resourceId,\n graph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n input: inputData,\n initialState,\n pubsub,\n retryConfig: this.retryConfig,\n requestContext,\n actor,\n resume,\n timeTravel,\n perStep,\n format,\n abortController: new AbortController(),\n // For Inngest, we don't pass workflowSpan - step spans use tracingIds instead\n workflowSpan: undefined,\n // Pass tracing IDs for durable span operations\n tracingIds: workflowSpanData\n ? {\n traceId: workflowSpanData.traceId,\n workflowSpanId: workflowSpanData.id,\n }\n : undefined,\n outputOptions,\n outputWriter: async (chunk: WorkflowStreamEvent) => {\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: chunk,\n });\n } catch (err) {\n this.logger.debug?.('Failed to publish watch event:', err);\n }\n },\n });\n } catch (executionError) {\n // Execution threw an exception (not just returned failed status)\n // Create a failed result to pass to finalize\n result = {\n status: 'failed',\n steps: {},\n state: initialState ?? {},\n error: executionError instanceof Error ? executionError : new Error(String(executionError)),\n } as WorkflowResult<TState, TInput, TOutput, TSteps>;\n }\n\n // Final step to invoke lifecycle callbacks and end workflow span.\n // This step is memoized by step.run.\n let finalizeError: unknown;\n let finalizeErrored = false;\n try {\n await step.run(`workflow.${this.id}.finalize`, async () => {\n // For durable agent workflows, emit error event on failure so the\n // client's stream can receive the error and close properly.\n if (result.status === 'failed' && inputData?.__workflowKind === 'durable-agent' && inputData?.runId) {\n const error = result.error instanceof Error ? result.error : new Error(String(result.error));\n try {\n await emitErrorEvent(pubsub, inputData.runId, error);\n } catch (e) {\n this.logger.debug?.('Failed to emit error event:', e);\n }\n }\n\n if (result.status !== 'paused') {\n // Invoke lifecycle callbacks (onFinish and onError)\n await engine.invokeLifecycleCallbacksInternal({\n status: result.status,\n result: 'result' in result ? result.result : undefined,\n error: 'error' in result ? result.error : undefined,\n steps: result.steps,\n tripwire: 'tripwire' in result ? result.tripwire : undefined,\n runId,\n workflowId: this.id,\n resourceId,\n input: inputData,\n requestContext,\n state: result.state ?? initialState ?? {},\n });\n }\n\n // End the workflow span with appropriate status\n // The workflow span was already created and SPAN_STARTED was exported in the span.start step\n if (workflowSpanData) {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n // Rebuild the span from cached data to call end/error\n const workflowSpan = observability.rebuildSpan(workflowSpanData);\n\n if (result.status === 'failed') {\n workflowSpan.error({\n error: result.error instanceof Error ? result.error : new Error(String(result.error)),\n attributes: { status: 'failed' },\n });\n } else {\n workflowSpan.end({\n output: result.status === 'success' ? result.result : undefined,\n attributes: { status: result.status },\n });\n }\n }\n }\n\n // Ensure final snapshot is persisted BEFORE publishing workflow-finish\n // This fixes a race condition where getRunOutput reads the snapshot before it's fully written\n const shouldPersistFinalSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: result.status,\n stepResults: result.steps,\n });\n if (shouldPersistFinalSnapshot) {\n const workflowsStore = await mastra?.getStorage()?.getStore('workflows');\n if (workflowsStore) {\n // For suspended workflows, read existing snapshot to preserve suspendedPaths and resumeLabels\n // which were set correctly by the handlers during execution\n let existingSnapshot:\n | { suspendedPaths?: Record<string, number[]>; resumeLabels?: Record<string, any> }\n | undefined;\n if (result.status === 'suspended') {\n existingSnapshot =\n (await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.id,\n runId,\n })) ?? undefined;\n }\n\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.id,\n runId,\n resourceId,\n snapshot: {\n runId,\n status: result.status,\n value: result.state ?? initialState ?? {},\n context: toSnapshotContext(result.steps),\n activePaths: [],\n activeStepsPath: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: existingSnapshot?.suspendedPaths ?? {},\n waitingPaths: {},\n resumeLabels: existingSnapshot?.resumeLabels ?? result.resumeLabels ?? {},\n result: result.status === 'success' ? toSnapshotResult(result.result) : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n timestamp: Date.now(),\n },\n });\n }\n }\n\n // Publish workflow-finish event for realtime subscribers (best-effort)\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: {\n type: 'workflow-finish',\n payload: {\n status: result.status,\n result: result.status === 'success' ? result.result : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n },\n },\n });\n } catch (publishError) {\n this.logger.debug?.('Failed to publish workflow-finish event:', publishError);\n }\n\n // Throw after span ended for failed workflows\n if (result.status === 'failed') {\n throw new NonRetriableError(`Workflow failed`, {\n cause: result,\n });\n }\n\n return result;\n });\n } catch (error) {\n finalizeErrored = true;\n finalizeError = error;\n } finally {\n // Keep this outside step.run memoization, but guaranteed on all paths.\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n try {\n await observability.flush();\n } catch (flushError) {\n this.logger.debug?.('Failed to flush observability:', flushError);\n }\n }\n }\n\n if (finalizeErrored) {\n throw finalizeError;\n }\n\n return { result, runId };\n },\n );\n return this.function;\n }\n\n getNestedFunctions(steps: StepFlowEntry[]): ReturnType<Inngest['createFunction']>[] {\n return steps.flatMap(step => {\n if (step.type === 'step' || step.type === 'loop' || step.type === 'foreach') {\n if (step.step instanceof InngestWorkflow) {\n return [step.step.getFunction(), ...step.step.getNestedFunctions(step.step.executionGraph.steps)];\n }\n return [];\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n return this.getNestedFunctions(step.steps);\n }\n\n return [];\n });\n }\n\n getFunctions(): ReturnType<Inngest['createFunction']>[] {\n return [\n this.getFunction(),\n ...(this.cronConfig?.cron ? [this.createCronFunction()] : []),\n ...this.getNestedFunctions(this.executionGraph.steps),\n ];\n }\n}\n\n/**\n * Converts runtime step results to the serialized context shape expected by WorkflowRunState.\n * StepResult is a structural subset of SerializedStepResult (widening), so no data\n * transformation is needed — this bridges the generic type mismatch at the persistence boundary.\n */\nfunction toSnapshotContext(steps: Record<string, StepResult<any, any, any, any>>): WorkflowRunState['context'] {\n return steps as unknown as WorkflowRunState['context'];\n}\n\n/**\n * Converts a workflow output value to the record shape expected by WorkflowRunState.result.\n * Workflow outputs are generic (TOutput) but the snapshot schema stores them as Record<string, any>.\n */\nfunction toSnapshotResult(output: unknown): WorkflowRunState['result'] {\n return output as WorkflowRunState['result'];\n}\n","import type { Mastra } from '@mastra/core/mastra';\nimport type { InngestFunction } from 'inngest';\nimport { InngestWorkflow } from './workflow';\n\nexport function collectInngestFunctions({\n mastra,\n functions: userFunctions = [],\n}: {\n mastra: Mastra;\n functions?: InngestFunction.Like[];\n}) {\n const workflows = mastra.listWorkflows();\n const workflowFunctions = Array.from(\n new Set(\n Object.values(workflows).flatMap(workflow => {\n if (workflow instanceof InngestWorkflow) {\n workflow.__registerMastra(mastra);\n return workflow.getFunctions();\n }\n return [];\n }),\n ),\n );\n\n return [...workflowFunctions, ...userFunctions];\n}\n","import type { Mastra } from '@mastra/core/mastra';\nimport type { Inngest, InngestFunction, RegisterOptions } from 'inngest';\nimport type { connect as inngestConnect } from 'inngest/connect';\nimport { collectInngestFunctions } from './functions';\n\ntype InngestConnectOptions = Parameters<typeof inngestConnect>[0];\n\nexport interface MastraConnectOptions extends Omit<InngestConnectOptions, 'apps'> {\n mastra: Mastra;\n inngest: Inngest;\n /**\n * Optional array of additional Inngest functions to expose through the same Connect worker.\n */\n functions?: InngestFunction.Like[];\n /**\n * Forwarded to Inngest as part of the app registration (timeout, signing key overrides, etc.).\n *\n * When a field is present in both `registerOptions` and the top-level Connect options\n * (e.g. `signingKey`), `registerOptions` wins. This matches the override behavior of\n * `serve()` so the two surfaces stay consistent.\n */\n registerOptions?: RegisterOptions;\n}\n\n/**\n * Connect Mastra workflows to Inngest using an outbound worker connection.\n *\n * Use this instead of `serve()` when the worker process should not expose an inbound HTTP\n * endpoint. The same workflow functions collected by `serve()` are forwarded to\n * `inngest/connect`, alongside any additional user functions.\n *\n * If the Mastra instance has no `InngestWorkflow` and no additional `functions` are\n * provided, a warning is emitted because the worker would otherwise idle forever with\n * nothing to execute.\n *\n * @example Worker process\n * ```ts\n * import { connect } from '@mastra/inngest/connect';\n * import { mastra } from './mastra';\n * import { inngest } from './mastra/inngest';\n *\n * await connect({ mastra, inngest });\n * ```\n */\nexport async function connect(options: MastraConnectOptions) {\n const { mastra, inngest, functions, registerOptions, ...connectOptions } = options;\n const appFunctions = collectInngestFunctions({ mastra, functions });\n\n if (appFunctions.length === 0) {\n console.warn(\n '[@mastra/inngest] connect() was called with no Inngest workflows and no additional functions. ' +\n 'The worker will connect to Inngest but has nothing to execute. ' +\n 'Register at least one InngestWorkflow on the Mastra instance or pass `functions: [...]`.',\n );\n }\n\n const { connect: connectWorker } = await import('inngest/connect');\n\n return connectWorker({\n // Top-level Connect options first, then registerOptions so they take precedence\n // for any overlapping keys (e.g. `signingKey`). This matches serve()'s behavior.\n ...connectOptions,\n ...registerOptions,\n apps: [{ client: inngest, functions: appFunctions }],\n });\n}\n"]}