@mastra/inngest 1.9.0-alpha.3 → 1.9.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{connect-B0G8lWOq.js → connect-BNxXqMuc.js} +47 -14
- package/dist/connect-BNxXqMuc.js.map +1 -0
- package/dist/{connect-D0fx6R62.cjs → connect-TUP1s9EP.cjs} +47 -14
- package/dist/connect-TUP1s9EP.cjs.map +1 -0
- package/dist/connect.cjs +1 -1
- package/dist/connect.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/pubsub.d.ts +6 -0
- package/dist/pubsub.d.ts.map +1 -1
- package/package.json +6 -6
- package/dist/connect-B0G8lWOq.js.map +0 -1
- package/dist/connect-D0fx6R62.cjs.map +0 -1
|
@@ -646,6 +646,7 @@ function buildTopicRef(channel, topic) {
|
|
|
646
646
|
* Supported formats:
|
|
647
647
|
* - "workflow.events.v2.{runId}" - workflow events
|
|
648
648
|
* - "agent.stream.{runId}" - agent stream events
|
|
649
|
+
* - "agent.control.{runId}" - agent control events (cross-process abort)
|
|
649
650
|
*
|
|
650
651
|
* @returns { runId, topicType } or null if not a recognized format
|
|
651
652
|
*/
|
|
@@ -655,14 +656,32 @@ function parseTopic(topic) {
|
|
|
655
656
|
runId: workflowMatch[1],
|
|
656
657
|
topicType: "workflow"
|
|
657
658
|
};
|
|
658
|
-
const
|
|
659
|
-
if (
|
|
660
|
-
runId:
|
|
661
|
-
topicType: "agent"
|
|
659
|
+
const agentStreamMatch = topic.match(/^agent\.stream\.(.+)$/);
|
|
660
|
+
if (agentStreamMatch && agentStreamMatch[1]) return {
|
|
661
|
+
runId: agentStreamMatch[1],
|
|
662
|
+
topicType: "agent-stream"
|
|
663
|
+
};
|
|
664
|
+
const agentControlMatch = topic.match(/^agent\.control\.(.+)$/);
|
|
665
|
+
if (agentControlMatch && agentControlMatch[1]) return {
|
|
666
|
+
runId: agentControlMatch[1],
|
|
667
|
+
topicType: "agent-control"
|
|
662
668
|
};
|
|
663
669
|
return null;
|
|
664
670
|
}
|
|
665
671
|
/**
|
|
672
|
+
* Warn once per unrecognized topic family so a missing topic mapping never fails
|
|
673
|
+
* silently again (dropped `agent.control.*` aborts shipped invisibly — see #22543).
|
|
674
|
+
* Deduped on the topic's leading two segments so run-scoped topics neither spam
|
|
675
|
+
* the logs nor grow the set unboundedly.
|
|
676
|
+
*/
|
|
677
|
+
const warnedUnrecognizedTopics = /* @__PURE__ */ new Set();
|
|
678
|
+
function warnUnrecognizedTopic(topic) {
|
|
679
|
+
const family = topic.split(".").slice(0, 2).join(".");
|
|
680
|
+
if (warnedUnrecognizedTopics.has(family)) return;
|
|
681
|
+
warnedUnrecognizedTopics.add(family);
|
|
682
|
+
console.warn(`InngestPubSub: ignoring unrecognized topic format "${topic}"`);
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
666
685
|
* PubSub implementation for Inngest workflows.
|
|
667
686
|
*
|
|
668
687
|
* This bridges the PubSub abstract class interface with Inngest's realtime system:
|
|
@@ -676,6 +695,8 @@ function parseTopic(topic) {
|
|
|
676
695
|
* -> Inngest channel: "workflow:{workflowId}:{runId}", topic: "watch"
|
|
677
696
|
* - "agent.stream.{runId}" - agent stream events (for InngestAgent)
|
|
678
697
|
* -> Inngest channel: "agent:{runId}", topic: "agent-stream"
|
|
698
|
+
* - "agent.control.{runId}" - agent control events (cross-process abort)
|
|
699
|
+
* -> Inngest channel: "agent:{runId}", topic: "agent-control"
|
|
679
700
|
*/
|
|
680
701
|
var InngestPubSub = class extends PubSub {
|
|
681
702
|
inngest;
|
|
@@ -698,18 +719,24 @@ var InngestPubSub = class extends PubSub {
|
|
|
698
719
|
* - "agent.stream.{runId}" - agent stream events
|
|
699
720
|
* -> channel: "agent:{runId}", topic: "agent-stream"
|
|
700
721
|
* (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)
|
|
722
|
+
* - "agent.control.{runId}" - agent control events (cross-process abort)
|
|
723
|
+
* -> channel: "agent:{runId}", topic: "agent-control"
|
|
701
724
|
*/
|
|
702
725
|
async publish(topic, event) {
|
|
703
726
|
const parsed = parseTopic(topic);
|
|
704
|
-
if (!parsed)
|
|
727
|
+
if (!parsed) {
|
|
728
|
+
warnUnrecognizedTopic(topic);
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
705
731
|
const { runId, topicType } = parsed;
|
|
706
|
-
const
|
|
707
|
-
const
|
|
732
|
+
const isAgentTopic = topicType === "agent-stream" || topicType === "agent-control";
|
|
733
|
+
const inngestTopic = isAgentTopic ? topicType : "watch";
|
|
734
|
+
const channel = isAgentTopic ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;
|
|
708
735
|
try {
|
|
709
|
-
const dataToSend =
|
|
736
|
+
const dataToSend = isAgentTopic ? event : event.data;
|
|
710
737
|
await this.inngest.realtime.publish(buildTopicRef(channel, inngestTopic), dataToSend);
|
|
711
738
|
} catch (err) {
|
|
712
|
-
if (topicType === "agent" && (event.type === "finish" || event.type === "error")) throw err;
|
|
739
|
+
if (topicType === "agent-control" || topicType === "agent-stream" && (event.type === "finish" || event.type === "error")) throw err;
|
|
713
740
|
console.error("InngestPubSub publish error:", err?.message ?? err);
|
|
714
741
|
}
|
|
715
742
|
}
|
|
@@ -722,24 +749,30 @@ var InngestPubSub = class extends PubSub {
|
|
|
722
749
|
* - "agent.stream.{runId}" - agent stream events
|
|
723
750
|
* -> channel: "agent:{runId}", topic: "agent-stream"
|
|
724
751
|
* (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)
|
|
752
|
+
* - "agent.control.{runId}" - agent control events (cross-process abort)
|
|
753
|
+
* -> channel: "agent:{runId}", topic: "agent-control"
|
|
725
754
|
*/
|
|
726
755
|
async subscribe(topic, cb) {
|
|
727
756
|
const parsed = parseTopic(topic);
|
|
728
|
-
if (!parsed)
|
|
757
|
+
if (!parsed) {
|
|
758
|
+
warnUnrecognizedTopic(topic);
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
729
761
|
const { runId, topicType } = parsed;
|
|
730
762
|
if (this.subscriptions.has(topic)) {
|
|
731
763
|
this.subscriptions.get(topic).callbacks.add(cb);
|
|
732
764
|
return;
|
|
733
765
|
}
|
|
734
766
|
const callbacks = /* @__PURE__ */ new Set([cb]);
|
|
735
|
-
const
|
|
767
|
+
const isAgentTopic = topicType === "agent-stream" || topicType === "agent-control";
|
|
768
|
+
const inngestTopic = isAgentTopic ? topicType : "watch";
|
|
736
769
|
const subscription = await subscribe({
|
|
737
|
-
channel:
|
|
770
|
+
channel: isAgentTopic ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`,
|
|
738
771
|
topics: [inngestTopic],
|
|
739
772
|
app: this.inngest,
|
|
740
773
|
onMessage: (message) => {
|
|
741
774
|
let event;
|
|
742
|
-
if (
|
|
775
|
+
if (isAgentTopic && message.data?.type && message.data?.runId) event = {
|
|
743
776
|
id: crypto.randomUUID(),
|
|
744
777
|
createdAt: /* @__PURE__ */ new Date(),
|
|
745
778
|
...message.data
|
|
@@ -1980,4 +2013,4 @@ async function connect(options) {
|
|
|
1980
2013
|
//#endregion
|
|
1981
2014
|
export { buildDurableResumeEventData as a, InngestPubSub as c, InngestRun as i, InngestExecutionEngine as l, collectInngestFunctions as n, buildDurableTriggerEventData as o, InngestWorkflow as r, mergeResumeRequestContext as s, connect as t };
|
|
1982
2015
|
|
|
1983
|
-
//# sourceMappingURL=connect-
|
|
2016
|
+
//# sourceMappingURL=connect-BNxXqMuc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-BNxXqMuc.js","names":["stepRes","#mastra","#mastra","#pubsubFactory"],"sources":["../src/nested-workflow-output.ts","../src/execution-engine.ts","../src/pubsub.ts","../src/durable-event-payload.ts","../src/run.ts","../src/workflow.ts","../src/functions.ts","../src/connect.ts"],"sourcesContent":["import type { WorkflowResult } from '@mastra/core/workflows';\n\nexport const NESTED_WORKFLOW_OUTPUT_MODE = {\n DEFAULT: 'default',\n COMPACT: 'compact',\n} as const;\n\nexport type NestedWorkflowOutputMode = (typeof NESTED_WORKFLOW_OUTPUT_MODE)[keyof typeof NESTED_WORKFLOW_OUTPUT_MODE];\n\ntype AnyWorkflowResult = WorkflowResult<any, any, any, any>;\ntype WorkflowResultWithStatus<TStatus extends AnyWorkflowResult['status']> = Extract<\n AnyWorkflowResult,\n { status: TStatus }\n>;\n\nexport type NestedWorkflowResult =\n | Pick<WorkflowResultWithStatus<'success'>, 'status' | 'state' | 'result'>\n | Pick<WorkflowResultWithStatus<'failed'>, 'status' | 'state' | 'error'>\n | Pick<WorkflowResultWithStatus<'tripwire'>, 'status' | 'state' | 'tripwire'>\n | Pick<WorkflowResultWithStatus<'suspended'>, 'status' | 'state' | 'steps' | 'resumeLabels'>\n | Pick<WorkflowResultWithStatus<'paused'>, 'status' | 'state'>;\n\n/**\n * Normalizes an optional nested workflow output mode to an explicit mode.\n *\n * @param mode - The output mode requested by the invoking workflow.\n * @returns The requested compact mode, or the default mode when compact output was not requested.\n */\nexport function resolveNestedWorkflowOutputMode(\n mode: NestedWorkflowOutputMode | undefined = NESTED_WORKFLOW_OUTPUT_MODE.DEFAULT,\n): NestedWorkflowOutputMode {\n return mode === NESTED_WORKFLOW_OUTPUT_MODE.COMPACT\n ? NESTED_WORKFLOW_OUTPUT_MODE.COMPACT\n : NESTED_WORKFLOW_OUTPUT_MODE.DEFAULT;\n}\n\n/**\n * Keeps only the status-specific fields consumed by a parent workflow after\n * `step.invoke()`. Suspended results retain steps so the parent can construct\n * the nested resume path; completed results do not carry the child input or\n * internal step history into the parent's memoized run state.\n *\n * @param result - The complete result returned by the nested workflow.\n * @returns The status-specific fields required by the invoking parent workflow.\n */\nexport function compactNestedWorkflowResult(result: AnyWorkflowResult): NestedWorkflowResult {\n switch (result.status) {\n case 'success':\n return { status: result.status, result: result.result, state: result.state };\n case 'failed':\n return { status: result.status, error: result.error, state: result.state };\n case 'tripwire':\n return { status: result.status, tripwire: result.tripwire, state: result.state };\n case 'suspended':\n // resumeLabels travels with a suspended result so the parent can re-register\n // the child's labels and stay able to name each parked leaf.\n return { status: result.status, steps: result.steps, state: result.state, resumeLabels: result.resumeLabels };\n case 'paused':\n return { status: result.status, state: result.state };\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\nimport type { ActorSignal } from '@mastra/core/auth/ee';\nimport type { RequestContext } from '@mastra/core/di';\nimport { getErrorFromUnknown, MastraNonRetryableError } 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} from '@mastra/core/workflows';\nimport type { Inngest, BaseContext } from 'inngest';\nimport { NonRetriableError } from 'inngest';\nimport type { NestedWorkflowResult } from './nested-workflow-output';\nimport { NESTED_WORKFLOW_OUTPUT_MODE } from './nested-workflow-output';\nimport { InngestWorkflow } from './workflow';\n\nfunction isNonRetryableStepFailure(error: unknown): boolean {\n if (error instanceof MastraNonRetryableError || error instanceof NonRetriableError) {\n return true;\n }\n\n if (error instanceof Error && error.cause !== undefined && isNonRetryableStepFailure(error.cause)) {\n return true;\n }\n\n if (error && typeof error === 'object') {\n const record = error as {\n nonRetryable?: true;\n error?: unknown;\n name?: string;\n isNonRetryable?: boolean;\n };\n\n if (record.nonRetryable) {\n return true;\n }\n\n if (record.name === 'MastraNonRetryableError' || record.isNonRetryable) {\n return true;\n }\n\n if (record.error !== undefined && isNonRetryableStepFailure(record.error)) {\n return true;\n }\n }\n\n return false;\n}\n\nconst retryCountStorage = new AsyncLocalStorage<number>();\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 private parentStream?: { workflowId: string; runId: string },\n ) {\n super({ mastra, options });\n this.inngestStep = inngestStep;\n this.inngestAttempts = inngestAttempts;\n }\n\n override getOrGenerateRetryCount(_stepId: string): number {\n return retryCountStorage.getStore() ?? 0;\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<\n | { ok: true; result: T }\n | { ok: false; error: { status: 'failed'; error: Error; endedAt: number; nonRetryable?: true } }\n > {\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 retryCountStorage.run(i, () => this.wrapDurableOperation(stepId, runStep));\n return { ok: true, result };\n } catch (e) {\n const isNonRetryable = isNonRetryableStepFailure(e);\n\n if (isNonRetryable || 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 {\n ok: false,\n error: {\n ...cause,\n ...(isNonRetryable && { nonRetryable: true as const }),\n },\n };\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 ...(isNonRetryable && { nonRetryable: true as const }),\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 const isNonRetryable = isNonRetryableStepFailure(e);\n throw new Error(errorInstance.message, {\n cause: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n ...(isNonRetryable && { nonRetryable: true as const }),\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 attributes?: Record<string, unknown>;\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 * @param params - The nested workflow step and its current execution state.\n * @returns The nested workflow step result, or null when the step is not an Inngest workflow.\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 requestContext?: RequestContext;\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 requestContext: parentRequestContext,\n } = params;\n const forwardedRequestContext = parentRequestContext\n ? this.serializeRequestContext(parentRequestContext)\n : (inputData?.requestContextEntries ?? {});\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 parentStream = this.parentStream ?? {\n workflowId: executionContext.workflowId,\n runId: executionContext.runId,\n };\n const isResume = !!resume?.steps?.length;\n // New invocations return compact output; legacy memoized WorkflowResult\n // envelopes are structural supersets of this parent-facing contract.\n let result: NestedWorkflowResult;\n let runId: string;\n\n const isTimeTravel = !!(timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === step.id);\n\n // The nested run id must be derivable on every replay pass: core strips\n // `suspendPayload` (omitPriorCompletionFields) and persists the stripped step\n // result before this branch runs, so nothing stored on it survives Inngest's\n // re-execution from the snapshot. The default engine runs nested workflows\n // under the parent's run id (Workflow.execute → createRun({ runId })), so\n // derive the same way here; foreach iterations get a per-index suffix so\n // concurrent iterations don't share a snapshot row (executionContext.foreachIndex\n // is set per iteration by the foreach handler and is stable across replays).\n const derivedNestedRunId =\n executionContext.foreachIndex !== undefined\n ? `${executionContext.runId}-foreach-${executionContext.foreachIndex}`\n : executionContext.runId;\n\n try {\n if (isResume) {\n runId = stepResults[resume?.steps?.[0] ?? '']?.suspendPayload?.__workflow_meta?.runId ?? derivedNestedRunId;\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 nestedResumeSteps = resume.steps.slice(1);\n let replayOnly = false;\n if (nestedResumeSteps.length === 0) {\n const suspendedStepIds = Object.keys(snapshot?.suspendedPaths ?? {});\n if (suspendedStepIds.length === 0) {\n // The child is no longer suspended: step.invoke parks the parent until the\n // child finishes, so Inngest re-executes this block to deliver the memoized\n // result. Replay the invoke (same durable id) instead of throwing, which\n // would discard a child run that already completed.\n replayOnly = true;\n } else if (suspendedStepIds.length > 1) {\n const pathStrings = suspendedStepIds.map(stepId => `[${stepId}]`);\n throw new Error(\n `Multiple suspended steps found: ${pathStrings.join(', ')}. ` +\n 'Please specify which step to resume using the \"step\" parameter.',\n );\n } else {\n nestedResumeSteps.push(suspendedStepIds[0]!);\n }\n }\n const nestedResumeStepId = nestedResumeSteps[0];\n\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n requestContext: forwardedRequestContext,\n parentStream,\n runId: runId,\n ...(replayOnly\n ? { initialState: executionContext.state ?? {} }\n : {\n resume: {\n runId: runId,\n steps: nestedResumeSteps,\n resumePayload: resume.resumePayload,\n resumePath: nestedResumeStepId\n ? (snapshot?.suspendedPaths?.[nestedResumeStepId] as any)\n : undefined,\n },\n }),\n outputOptions: { includeState: true, includeResumeLabels: true },\n nestedWorkflowOutputMode: NESTED_WORKFLOW_OUTPUT_MODE.COMPACT,\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 requestContext: forwardedRequestContext,\n parentStream,\n runId: executionContext.runId,\n outputOptions: { includeState: true, includeResumeLabels: true },\n nestedWorkflowOutputMode: NESTED_WORKFLOW_OUTPUT_MODE.COMPACT,\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 // Name the child run on its trigger event. `cancelOn` matches a cancel\n // event against `data.runId` on the trigger, so a nested run invoked\n // without one cannot be cancelled by id — and it would take the\n // unnamed-run branch, warning about advice the caller cannot act on.\n // Derived (not random) so every replay pass addresses the same child\n // snapshot — see `derivedNestedRunId` above.\n const nestedRunId = derivedNestedRunId;\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 requestContext: forwardedRequestContext,\n parentStream,\n runId: nestedRunId,\n outputOptions: { includeState: true, includeResumeLabels: true },\n nestedWorkflowOutputMode: NESTED_WORKFLOW_OUTPUT_MODE.COMPACT,\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 // Compact nested failures carry the workflow result and runId in the cause.\n const errorCause = e && typeof e === 'object' && 'cause' in e ? e.cause : undefined;\n\n // Try to extract runId from error cause or generate new one\n if (errorCause && typeof errorCause === 'object' && 'status' in errorCause && errorCause.status === 'failed') {\n result = errorCause as Extract<NestedWorkflowResult, { status: 'failed' }>;\n runId = 'runId' in errorCause && typeof errorCause.runId === 'string' ? errorCause.runId : randomUUID();\n } else {\n // Log before flattening: Error objects don't survive snapshot\n // serialization (JSON.stringify(new Error('x')) is `{}`), so without\n // this the real cause never surfaces past \"Workflow failed\".\n this.logger?.error(\n `Nested workflow step ${step.id} failed: ` + (e instanceof Error ? (e.stack ?? e.message) : String(e)),\n );\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 };\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 // Re-register the nested run's resume labels on the parent so the outer snapshot is\n // self-describing about every parked leaf (e.g. `resumeLabels[toolCallId]`). Without\n // this a caller can only target the outer step, and concurrent suspensions inside the\n // nested workflow become impossible to disambiguate. Mirrors `Workflow.execute()` in\n // packages/core/src/workflows/workflow.ts.\n for (const label of Object.keys((result as any)?.resumeLabels ?? {})) {\n executionContext.resumeLabels[label] = { stepId: step.id };\n }\n\n // Keep the nested workflow metadata (foreachIndex, foreachOutput, resumeLabels) when\n // propagating a suspension to the parent — only runId and path change as we move up.\n // Per-iteration `__streamState` blobs are stripped from the propagated copies: they can\n // be large and resume reads them from the nested run's own snapshot, so the parent only\n // needs the identifying fields.\n const nestedMeta = (stepResult as any)?.suspendPayload?.__workflow_meta ?? {};\n const propagatedForeachOutput = Array.isArray(nestedMeta.foreachOutput)\n ? nestedMeta.foreachOutput.map((entry: any) => {\n if (entry?.status !== 'suspended' || !entry.suspendPayload) return entry;\n const { __streamState: _streamState, ...suspendPayload } = entry.suspendPayload;\n return { ...entry, suspendPayload };\n })\n : undefined;\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: {\n ...nestedMeta,\n ...(propagatedForeachOutput ? { foreachOutput: propagatedForeachOutput } : {}),\n runId: runId,\n path: suspendPath,\n },\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 * - \"agent.control.{runId}\" - agent control events (cross-process abort)\n *\n * @returns { runId, topicType } or null if not a recognized format\n */\nfunction parseTopic(topic: string): { runId: string; topicType: 'workflow' | 'agent-stream' | 'agent-control' } | 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 agentStreamMatch = topic.match(/^agent\\.stream\\.(.+)$/);\n if (agentStreamMatch && agentStreamMatch[1]) {\n return { runId: agentStreamMatch[1], topicType: 'agent-stream' };\n }\n\n // Try agent control format\n const agentControlMatch = topic.match(/^agent\\.control\\.(.+)$/);\n if (agentControlMatch && agentControlMatch[1]) {\n return { runId: agentControlMatch[1], topicType: 'agent-control' };\n }\n\n return null;\n}\n\n/**\n * Warn once per unrecognized topic family so a missing topic mapping never fails\n * silently again (dropped `agent.control.*` aborts shipped invisibly — see #22543).\n * Deduped on the topic's leading two segments so run-scoped topics neither spam\n * the logs nor grow the set unboundedly.\n */\nconst warnedUnrecognizedTopics = new Set<string>();\nfunction warnUnrecognizedTopic(topic: string): void {\n const family = topic.split('.').slice(0, 2).join('.');\n if (warnedUnrecognizedTopics.has(family)) return;\n warnedUnrecognizedTopics.add(family);\n console.warn(`InngestPubSub: ignoring unrecognized topic format \"${topic}\"`);\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 * - \"agent.control.{runId}\" - agent control events (cross-process abort)\n * -> Inngest channel: \"agent:{runId}\", topic: \"agent-control\"\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 async publishWorkflowWatchTo(workflowId: string, runId: string, data: unknown): Promise<void> {\n await this.inngest.realtime.publish(buildTopicRef(`workflow:${workflowId}:${runId}`, 'watch'), data);\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 * - \"agent.control.{runId}\" - agent control events (cross-process abort)\n * -> channel: \"agent:{runId}\", topic: \"agent-control\"\n */\n async publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>): Promise<void> {\n const parsed = parseTopic(topic);\n if (!parsed) {\n warnUnrecognizedTopic(topic);\n return; // Ignore unrecognized topic formats\n }\n\n const { runId, topicType } = parsed;\n\n // Agent stream/control events share the runId-only channel (so nested workflows\n // publish to the same channel) but use separate Inngest topics so control\n // traffic never reaches stream consumers.\n const isAgentTopic = topicType === 'agent-stream' || topicType === 'agent-control';\n const inngestTopic = isAgentTopic ? topicType : 'watch';\n const channel = isAgentTopic ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;\n\n try {\n // For agent stream/control 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 = isAgentTopic ? event : event.data;\n await this.inngest.realtime.publish(buildTopicRef(channel, inngestTopic), dataToSend);\n } catch (err: any) {\n // Rethrow when losing the event would break the caller:\n // - agent control events: a dropped abort-request means a remote run cannot be\n // stopped; core's requestRemoteAbort() catches and logs with agentId/runId context\n // - agent stream terminal events: losing a finish/error event causes the client\n // stream to hang indefinitely\n if (\n topicType === 'agent-control' ||\n (topicType === 'agent-stream' && (event.type === 'finish' || event.type === 'error'))\n ) {\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 * - \"agent.control.{runId}\" - agent control events (cross-process abort)\n * -> channel: \"agent:{runId}\", topic: \"agent-control\"\n */\n async subscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const parsed = parseTopic(topic);\n if (!parsed) {\n warnUnrecognizedTopic(topic);\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 // Agent stream/control events share the runId-only channel (so nested workflows\n // publish to the same channel) but use separate Inngest topics so control\n // traffic never reaches stream consumers.\n const isAgentTopic = topicType === 'agent-stream' || topicType === 'agent-control';\n const inngestTopic = isAgentTopic ? topicType : 'watch';\n const channel = isAgentTopic ? `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 subscription = await subscribe({\n channel,\n topics: [inngestTopic],\n app: this.inngest,\n onMessage: (message: any) => {\n // For agent stream/control events, message.data is the full event 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 (isAgentTopic && 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 subscription.close();\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 type { ActorSignal } from '@mastra/core/auth/ee';\nimport type { TracingOptions } from '@mastra/core/observability';\nimport { MASTRA_AUTH_TOKEN_KEY } from '@mastra/core/request-context';\nimport type { RequestContext } from '@mastra/core/request-context';\n\n/**\n * Single source of truth for the `data` payload of the `workflow.<id>` events\n * that drive durable execution in `@mastra/inngest`.\n *\n * Two independent public surfaces send these events: `InngestRun`\n * (`start`/`startAsync`/`resume`/`timeTravel`) and the durable-agent wrapper\n * built by `createInngestAgent` (`stream`/`resume`). They used to build the\n * payload separately, and the same class of bug shipped repeatedly as a result:\n * a per-call signal was added to one side and silently dropped on the other\n * (`actor` in #19426, `requestContext` in #19223).\n *\n * The builders below exist to make that failure mode structural rather than a\n * matter of remembering. Their argument types are explicit — adding a new\n * per-call signal means adding a field here, which makes every caller that\n * does not supply it visible. Do not widen these args to a passthrough object.\n *\n * Caller-specific concerns (snapshot persistence and rollback, tracing span\n * construction, pubsub subscription ordering, result polling) legitimately\n * differ between the two surfaces and deliberately stay at the call sites.\n */\n\n/** Per-call signals that every durable event carries, regardless of sender. */\ninterface PerCallSignals {\n /**\n * Actor signal used for FGA checks and tool execution. Always a per-call\n * value: it is supplied fresh on every start and resume and is never read\n * back from a persisted snapshot, so a membership-bypass signal is never\n * written to durable storage. This matches the default engine, which passes\n * `actor: params.actor` on resume (see `packages/core/src/workflows/workflow.ts`\n * `_resume`).\n */\n actor?: ActorSignal;\n /** Whether the run emits per-step output. */\n perStep?: boolean;\n}\n\n/**\n * Flatten a `RequestContext` into the plain JSON object the event carries.\n * Absent context serializes to `{}`, never `undefined`.\n */\nexport function serializeRequestContext(requestContext?: RequestContext<any>): Record<string, any> {\n // `toJSON()` rather than `entries()`: it drops values that cannot survive the\n // JSON round trip through `inngest.send()` (functions, RPC proxies, cyclic\n // references). Passing those through raw makes the send throw.\n const obj = requestContext ? requestContext.toJSON() : {};\n // Never hand the framework-managed bearer token to `inngest.send()`: Inngest\n // durably retains and displays event payloads, so a live token would land in\n // third-party storage on every durable start and resume. A resumed\n // authenticated request supplies its own fresh token. Matches\n // `DefaultExecutionEngine.serializeRequestContext`.\n delete obj[MASTRA_AUTH_TOKEN_KEY];\n return obj;\n}\n\n/**\n * Resume request-context rule: values persisted in the snapshot are the base,\n * and anything the caller supplies on this resume call overrides them.\n */\nexport function mergeResumeRequestContext(\n snapshotRequestContext: Record<string, any> | undefined,\n requestContext?: RequestContext<any>,\n): Record<string, any> {\n return { ...(snapshotRequestContext ?? {}), ...serializeRequestContext(requestContext) };\n}\n\nexport function buildDurableTriggerEventData(\n args: PerCallSignals & {\n inputData: any;\n runId: string;\n resourceId?: string;\n /** Already-serialized request context, or a `RequestContext` to serialize. */\n requestContext?: RequestContext<any> | Record<string, any>;\n initialState?: any;\n outputOptions?: Record<string, any>;\n tracingOptions?: TracingOptions;\n format?: string;\n workflowId?: string;\n },\n): Record<string, any> {\n const { requestContext, ...rest } = args;\n return {\n ...rest,\n requestContext: toRequestContextEntries(requestContext),\n };\n}\n\nexport function buildDurableResumeEventData(\n args: PerCallSignals & {\n inputData: any;\n runId: string;\n resourceId?: string;\n /**\n * Already merged via `mergeResumeRequestContext`, or a `RequestContext`\n * when there is no snapshot context to merge with.\n */\n requestContext?: RequestContext<any> | Record<string, any>;\n resume: {\n steps: string[];\n resumePayload: any;\n resumePath?: any;\n };\n tracingOptions?: TracingOptions;\n workflowId?: string;\n },\n): Record<string, any> {\n const { requestContext, ...rest } = args;\n return {\n ...rest,\n requestContext: toRequestContextEntries(requestContext),\n };\n}\n\nexport function buildDurableTimeTravelEventData(\n args: PerCallSignals & {\n runId: string;\n workflowId: string;\n initialState?: any;\n stepResults?: any;\n timeTravel: any;\n requestContext?: RequestContext<any> | Record<string, any>;\n outputOptions?: Record<string, any>;\n tracingOptions?: TracingOptions;\n },\n): Record<string, any> {\n const { requestContext, ...rest } = args;\n return {\n ...rest,\n requestContext: toRequestContextEntries(requestContext),\n };\n}\n\nfunction toRequestContextEntries(requestContext?: RequestContext<any> | Record<string, any>): Record<string, any> {\n if (!requestContext) return {};\n // Probe `toJSON`, the method `serializeRequestContext` actually calls, so the\n // check stays aligned with the branch it guards.\n return typeof (requestContext as RequestContext<any>).toJSON === 'function'\n ? serializeRequestContext(requestContext as RequestContext<any>)\n : (requestContext as Record<string, any>);\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 { Realtime } from 'inngest/realtime';\nimport {\n buildDurableResumeEventData,\n buildDurableTimeTravelEventData,\n buildDurableTriggerEventData,\n mergeResumeRequestContext,\n} from './durable-event-payload';\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 TRequestContext = unknown,\n> extends Run<TEngineType, TSteps, TState, TInput, TOutput, TRequestContext> {\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 realtimeSubscriptionPromise: Promise<Realtime.Subscribe.CallbackSubscription> | null = null;\n\n const startRealtimeSubscription = async () => {\n try {\n realtimeSubscriptionPromise = subscribe({\n channel: `workflow:${this.workflowId}:${this.runId}`,\n topics: ['watch'],\n app: this.inngest,\n onMessage: 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 close the subscription even before setup resolves.\n unsubscribe = () => {\n realtimeSubscriptionPromise?.then(subscription => subscription.close()).catch(() => {});\n };\n\n await realtimeSubscriptionPromise;\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<TRequestContext>;\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<TRequestContext>;\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: buildDurableTriggerEventData({\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,\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<TRequestContext>;\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: buildDurableTriggerEventData({\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions,\n tracingOptions,\n format,\n requestContext,\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<TRequestContext>;\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<TRequestContext>;\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 mergedRequestContext = mergeResumeRequestContext((snapshot as any)?.requestContext, params.requestContext);\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: buildDurableResumeEventData({\n inputData: resumeDataToUse,\n runId: this.runId,\n workflowId: this.workflowId,\n resume: {\n steps,\n resumePayload: resumeDataToUse,\n resumePath: steps?.[0] ? (snapshot?.suspendedPaths?.[steps?.[0]] as any) : undefined,\n },\n requestContext: mergedRequestContext,\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<TRequestContext>;\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 if (result.status !== 'suspended') {\n this.cleanup?.();\n }\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<TRequestContext>;\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<TRequestContext>;\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<TRequestContext>;\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: buildDurableTimeTravelEventData({\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,\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<TRequestContext>; 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<TRequestContext>;\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 const unwatch = self.watch(async (event: WorkflowStreamEvent) => {\n const { type, from = ChunkFrom.WORKFLOW, payload } = event;\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<TRequestContext>;\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 const unwatch = self.watch(async (event: WorkflowStreamEvent) => {\n const { type, from = ChunkFrom.WORKFLOW, payload } = event;\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, getEntryWorkflow, isSingleStepEntry } 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 {\n compactNestedWorkflowResult,\n NESTED_WORKFLOW_OUTPUT_MODE,\n resolveNestedWorkflowOutputMode,\n} from './nested-workflow-output';\nimport { InngestPubSub } from './pubsub';\nimport { InngestRun } from './run';\nimport type {\n InngestEngineType,\n InngestFlowControlConfig,\n InngestFlowCronConfig,\n InngestWorkflowConfig,\n} from './types';\n\n/**\n * Resolves the nested `InngestWorkflow` wrapped by a graph entry, if any.\n * Handles both plain single-step entries and `loop` / `foreach` entries whose\n * body is a `SingleStepEntry` wrapper (so `{ type: 'step', step: workflow }`\n * bodies are unwrapped correctly).\n */\nfunction getNestedInngestWorkflow(entry: StepFlowEntry): InngestWorkflow | null {\n let nested: unknown = null;\n if (entry.type === 'loop' || entry.type === 'foreach') {\n nested = getEntryWorkflow(entry.step);\n } else if (isSingleStepEntry(entry)) {\n nested = getEntryWorkflow(entry);\n }\n return nested instanceof InngestWorkflow ? nested : null;\n}\n\nexport class InngestWorkflow<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType, any>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType,\n unknown\n >[],\n TWorkflowId extends string = string,\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TPrevSchema = TInput,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> extends Workflow<TEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrevSchema, TRequestContext> {\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, any>[],\n TRequestContext\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, TRequestContext>);\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 const nested = getNestedInngestWorkflow(step);\n if (nested) {\n nested.__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 const nested = getNestedInngestWorkflow(step);\n if (nested) {\n nested.__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 disableScorers?: boolean;\n pubsub?: PubSub;\n }): Promise<Run<TEngineType, TSteps, TState, TInput, TOutput, TRequestContext>> {\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, TRequestContext>(\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, TRequestContext>;\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 // Not scoped by `match` like the event-triggered function above: a cron\n // trigger carries no event data to match a runId against, and the run\n // is created inside the function, so the canceller has no id to name.\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 /**\n * Gets the durable Inngest function that executes this workflow.\n *\n * @returns The memoized Inngest function for this workflow.\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 // `match` scopes the cancellation to the run the cancel event names.\n // Without it Inngest cancels every in-flight run of this function, and\n // since all durable agents share one function, cancelling a single run\n // tore down every other run in the deployment — only the targeted run's\n // snapshot was marked canceled, so the rest simply vanished.\n // Every event that triggers this function carries `data.runId`, and\n // `Run.cancel()` sends the same field.\n cancelOn: [{ event: `cancel.workflow.${this.id}`, match: 'data.runId' }],\n triggers: { event: `workflow.${this.id}` },\n // Spread flow control configuration\n ...this.flowControlConfig,\n },\n /**\n * Executes a workflow invocation from its Inngest trigger event.\n *\n * @param context - The Inngest event, durable step tools, and current attempt.\n * @returns The workflow result and run identifier returned to Inngest.\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 parentStream,\n nestedWorkflowOutputMode: requestedNestedWorkflowOutputMode,\n } = event.data;\n const nestedWorkflowOutputMode = resolveNestedWorkflowOutputMode(requestedNestedWorkflowOutputMode);\n const shouldCompactNestedWorkflowOutput = nestedWorkflowOutputMode === NESTED_WORKFLOW_OUTPUT_MODE.COMPACT;\n\n if (!runId) {\n // Reached when a trigger event arrives without a run id — an event sent\n // directly rather than through `createRun()`, which always supplies one.\n // The id generated here never reaches the trigger event that `cancelOn`\n // matches against, so `cancel.workflow.${this.id}` cannot target this\n // run. Warn rather than reject: an unnamed run is still a valid way to\n // start a workflow, it just can't be cancelled by id afterwards.\n runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {\n return randomUUID();\n });\n this.logger.warn?.(\n `Workflow \"${this.id}\" was triggered without a runId, so run \"${runId}\" cannot be cancelled by id. ` +\n `Send \\`data.runId\\` on the trigger event (or start the run with createRun()) to make it cancellable.`,\n );\n }\n\n if (resume && (initialState === undefined || resume.stepResults === undefined)) {\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.id,\n runId,\n });\n\n initialState ??= snapshot?.value;\n if (resume.stepResults === undefined && snapshot?.context !== undefined) {\n resume = { ...resume, stepResults: snapshot.context };\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, parentStream);\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 // Nested functions have workflow-local channels; send writer chunks\n // directly to the outermost run without forwarding lifecycle events.\n if (parentStream) {\n try {\n await defaultPubsub.publishWorkflowWatchTo(parentStream.workflowId, parentStream.runId, chunk);\n } catch (err) {\n this.logger.debug?.('Failed to publish parent watch event:', err);\n }\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 const returnedResult = shouldCompactNestedWorkflowOutput ? compactNestedWorkflowResult(result) : result;\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 /**\n * Finalizes workflow lifecycle reporting in a memoized Inngest step.\n *\n * @returns The workflow result, or only its status for compact nested invocations.\n */\n const finalizeWorkflow = 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 requestContext: requestContext.toJSON(),\n tracingContext: workflowSpanData\n ? {\n traceId: workflowSpanData.traceId,\n spanId: workflowSpanData.id,\n }\n : 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: shouldCompactNestedWorkflowOutput ? { ...returnedResult, runId } : result,\n });\n }\n\n return shouldCompactNestedWorkflowOutput ? { status: result.status } : result;\n };\n await step.run(`workflow.${this.id}.finalize`, finalizeWorkflow);\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: returnedResult, runId };\n },\n );\n return this.function;\n }\n\n getNestedFunctions(steps: StepFlowEntry[]): ReturnType<Inngest['createFunction']>[] {\n return steps.flatMap(step => {\n const nested = getNestedInngestWorkflow(step);\n if (nested) {\n return [nested.getFunction(), ...nested.getNestedFunctions(nested.executionGraph.steps)];\n }\n 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 ap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