@mastra/inngest 1.2.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +224 -0
- package/dist/__tests__/adapters/_utils.d.ts +2 -2
- package/dist/__tests__/durable-agent.test.utils.d.ts +43 -0
- package/dist/__tests__/durable-agent.test.utils.d.ts.map +1 -0
- package/dist/durable-agent/create-inngest-agent.d.ts +300 -0
- package/dist/durable-agent/create-inngest-agent.d.ts.map +1 -0
- package/dist/durable-agent/create-inngest-agentic-workflow.d.ts +55 -0
- package/dist/durable-agent/create-inngest-agentic-workflow.d.ts.map +1 -0
- package/dist/durable-agent/index.d.ts +50 -0
- package/dist/durable-agent/index.d.ts.map +1 -0
- package/dist/execution-engine.d.ts.map +1 -1
- package/dist/index.cjs +637 -28
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +637 -31
- package/dist/index.js.map +1 -1
- package/dist/pubsub.d.ts +17 -6
- package/dist/pubsub.d.ts.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/workflow.d.ts.map +1 -1
- package/package.json +14 -12
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/execution-engine.ts","../src/pubsub.ts","../src/run.ts","../src/workflow.ts","../src/serve.ts","../src/types.ts","../src/index.ts"],"names":["otelContext","subscribe","getErrorFromUnknown","createTimeTravelExecutionParams","randomUUID","NonRetriableError","inngestServeHono","EntityType","SpanType","result","processorSpan","processorTracingContext","Workflow"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBO,IAAM,sBAAA,GAAN,cAAqC,sBAAA,CAAuB;AAAA,EACzD,WAAA;AAAA,EACA,eAAA;AAAA,EAER,WAAA,CACE,MAAA,EACA,WAAA,EACA,eAAA,GAA0B,GAC1B,OAAA,EACA;AACA,IAAA,KAAA,CAAM,EAAE,MAAA,EA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OAAA;AAAA,QACd,SAAS,IAAA,CAAK,OAAA;AAAA,QACd,SAAS,IAAA,CAAK,OAAA;AAAA,QACd,WAAW,IAAA,CAAK;AAAA,OAClB;AAAA,IACF,CAAA;AAAA,IACA,aAAA,CAgBE,UACA,IAAA,EACkF;AAClF,MAAA,MAAM,EAAA,GAAuF,IAAIG,QAAAA,CAAS;AAAA,QACxG,IAAI,IAAA,CAAK,EAAA;AAAA,QACT,aAAa,QAAA,CAAS,WAAA;AAAA,QACtB,cAAc,QAAA,CAAS,YAAA;AAAA,QACvB,OAAO,QAAA,CAAS,QAAA;AAAA,QAChB,QAAQ,QAAA,CAAS,MAAA;AAAA,QACjB,SAAS,QAAA,CAAS;AAAA,OACnB,CAAA;AAED,MAAA,EAAA,CAAG,WAAA,CAAY,SAAS,SAAS,CAAA;AACjC,MAAA,EAAA,CAAG,MAAA,EAAO;AACV,MAAA,OAAO,EAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { RequestContext } from '@mastra/core/di';\nimport { getErrorFromUnknown } from '@mastra/core/error';\nimport type { SerializedError } from '@mastra/core/error';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { EntityType } from '@mastra/core/observability';\nimport { DefaultExecutionEngine, createTimeTravelExecutionParams } from '@mastra/core/workflows';\nimport type {\n ExecutionContext,\n Step,\n StepResult,\n StepFailure,\n ExecutionEngineOptions,\n TimeTravelExecutionParams,\n WorkflowResult,\n} from '@mastra/core/workflows';\nimport type { Inngest, BaseContext } from 'inngest';\nimport { InngestWorkflow } from './workflow';\n\nexport class InngestExecutionEngine extends DefaultExecutionEngine {\n private inngestStep: BaseContext<Inngest>['step'];\n private inngestAttempts: number;\n\n constructor(\n mastra: Mastra,\n inngestStep: BaseContext<Inngest>['step'],\n inngestAttempts: number = 0,\n options: ExecutionEngineOptions,\n ) {\n super({ mastra, options });\n this.inngestStep = inngestStep;\n this.inngestAttempts = inngestAttempts;\n }\n\n // =============================================================================\n // Hook Overrides\n // =============================================================================\n\n /**\n * Format errors while preserving Error instances and their custom properties.\n * Uses getErrorFromUnknown to ensure all error properties are preserved.\n */\n protected formatResultError(\n error: Error | string | undefined,\n lastOutput: StepResult<any, any, any, any>,\n ): SerializedError {\n const outputError = (lastOutput as StepFailure<any, any, any, any>)?.error;\n const errorSource = error || outputError;\n const errorInstance = getErrorFromUnknown(errorSource, {\n serializeStack: true, // Include stack in JSON for better debugging in Inngest\n fallbackMessage: 'Unknown workflow error',\n });\n return errorInstance.toJSON();\n }\n\n /**\n * Detect InngestWorkflow instances for special nested workflow handling\n */\n isNestedWorkflowStep(step: Step<any, any, any>): boolean {\n return step instanceof InngestWorkflow;\n }\n\n /**\n * Inngest requires requestContext serialization for memoization.\n * When steps are replayed, the original function doesn't re-execute,\n * so requestContext modifications must be captured and restored.\n */\n requiresDurableContextSerialization(): boolean {\n return true;\n }\n\n /**\n * Execute a step with retry logic for Inngest.\n * Retries are handled via step-level retry (RetryAfterError thrown INSIDE step.run()).\n * After retries exhausted, error propagates here and we return a failed result.\n */\n async executeStepWithRetry<T>(\n stepId: string,\n runStep: () => Promise<T>,\n params: {\n retries: number;\n delay: number;\n stepSpan?: any;\n workflowId: string;\n runId: string;\n },\n ): Promise<{ ok: true; result: T } | { ok: false; error: { status: 'failed'; error: Error; endedAt: number } }> {\n for (let i = 0; i < params.retries + 1; i++) {\n if (i > 0 && params.delay) {\n await new Promise(resolve => setTimeout(resolve, params.delay));\n }\n try {\n //removed retry config with RetryAfterError from wrapDurableOperation, since we're manually handling retries here\n const result = await this.wrapDurableOperation(stepId, runStep);\n return { ok: true, result };\n } catch (e) {\n if (i === params.retries) {\n // After step-level retries exhausted, extract failure from error cause\n const cause = (e as any)?.cause;\n if (cause?.status === 'failed') {\n params.stepSpan?.error({\n error: e,\n attributes: { status: 'failed' },\n });\n // Ensure cause.error is an Error instance\n if (cause.error && !(cause.error instanceof Error)) {\n cause.error = getErrorFromUnknown(cause.error, { serializeStack: false });\n }\n return { ok: false, error: cause };\n }\n\n // Fallback for other errors - preserve the original error instance\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n params.stepSpan?.error({\n error: errorInstance,\n attributes: { status: 'failed' },\n });\n return {\n ok: false,\n error: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n },\n };\n }\n }\n }\n // Should never reach here, but TypeScript needs it\n return { ok: false, error: { status: 'failed', error: new Error('Unknown error'), endedAt: Date.now() } };\n }\n\n /**\n * Use Inngest's sleep primitive for durability\n */\n async executeSleepDuration(duration: number, sleepId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleep(`workflow.${workflowId}.sleep.${sleepId}`, duration < 0 ? 0 : duration);\n }\n\n /**\n * Use Inngest's sleepUntil primitive for durability\n */\n async executeSleepUntilDate(date: Date, sleepUntilId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleepUntil(`workflow.${workflowId}.sleepUntil.${sleepUntilId}`, date);\n }\n\n /**\n * Wrap durable operations in Inngest step.run() for durability.\n *\n * IMPORTANT: Errors are wrapped with a cause structure before throwing.\n * This is necessary because Inngest's error serialization (serialize-error-cjs)\n * only captures standard Error properties (message, name, stack, code, cause).\n * Custom properties like statusCode, responseHeaders from AI SDK errors would\n * be lost. By putting our serialized error (via getErrorFromUnknown with toJSON())\n * in the cause property, we ensure custom properties survive serialization.\n * The cause property is in serialize-error-cjs's allowlist, and when the cause\n * object is finally JSON.stringify'd, our error's toJSON() is called.\n */\n async wrapDurableOperation<T>(operationId: string, operationFn: () => Promise<T>): Promise<T> {\n const result = await this.inngestStep.run(operationId, async () => {\n try {\n const fnResult = await operationFn();\n return fnResult;\n } catch (e) {\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n throw new Error(errorInstance.message, {\n cause: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n },\n });\n }\n });\n return result as T;\n }\n\n /**\n * Provide Inngest step primitive in engine context\n */\n getEngineContext(): Record<string, any> {\n return { step: this.inngestStep };\n }\n\n /**\n * For Inngest, lifecycle callbacks are invoked in the workflow's finalize step\n * (wrapped in step.run for durability), not in execute(). Override to skip.\n */\n public async invokeLifecycleCallbacks(_result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n // No-op: Inngest handles callbacks in workflow.ts finalize step\n }\n\n /**\n * Actually invoke the lifecycle callbacks. Called from workflow.ts finalize step.\n */\n public async invokeLifecycleCallbacksInternal(result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n return super.invokeLifecycleCallbacks(result);\n }\n\n // =============================================================================\n // Durable Span Lifecycle Hooks\n // =============================================================================\n\n /**\n * Create a step span durably - on first execution, creates and exports span.\n * On replay, returns cached span data without re-creating.\n */\n async createStepSpan(params: {\n parentSpan: any;\n stepId: string;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n entityType?: string;\n entityId?: string;\n tracingPolicy?: any;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided (e.g., for steps inside control-flow),\n // otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n entityType: options.entityType as EntityType | undefined,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a step span durably.\n */\n async endStepSpan(params: {\n span: any;\n operationId: string;\n endOptions: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on step span durably.\n */\n async errorStepSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Create a generic child span durably (for control-flow operations).\n * On first execution, creates and exports span. On replay, returns cached span data.\n */\n async createChildSpan(params: {\n parentSpan: any;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n attributes?: Record<string, unknown>;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided, otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a generic child span durably (for control-flow operations).\n */\n async endChildSpan(params: {\n span: any;\n operationId: string;\n endOptions?: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on a generic child span durably (for control-flow operations).\n */\n async errorChildSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Execute nested InngestWorkflow using inngestStep.invoke() for durability.\n * This MUST be called directly (not inside step.run()) due to Inngest constraints.\n */\n async executeWorkflowStep(params: {\n step: Step<string, any, any>;\n stepResults: Record<string, StepResult<any, any, any, any>>;\n executionContext: ExecutionContext;\n resume?: {\n steps: string[];\n resumePayload: any;\n runId?: string;\n };\n timeTravel?: TimeTravelExecutionParams;\n prevOutput: any;\n inputData: any;\n pubsub: PubSub;\n startedAt: number;\n perStep?: boolean;\n stepSpan?: any;\n }): 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 } = params;\n\n // Build trace context to propagate to nested workflow\n const nestedTracingContext = executionContext.tracingIds?.traceId\n ? {\n traceId: executionContext.tracingIds.traceId,\n parentSpanId: stepSpan?.id,\n }\n : undefined;\n\n const isResume = !!resume?.steps?.length;\n let result: WorkflowResult<any, any, any, any>;\n let runId: string;\n\n const isTimeTravel = !!(timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === step.id);\n\n try {\n if (isResume) {\n runId = stepResults[resume?.steps?.[0] ?? '']?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: runId,\n });\n\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n initialState: executionContext.state ?? snapshot?.value ?? {},\n runId: runId,\n resume: {\n runId: runId,\n steps: resume.steps.slice(1),\n stepResults: snapshot?.context as any,\n resumePayload: resume.resumePayload,\n resumePath: resume.steps?.[1] ? (snapshot?.suspendedPaths?.[resume.steps?.[1]] as any) : undefined,\n },\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else if (isTimeTravel) {\n const workflowsStoreForTimeTravel = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = (await workflowsStoreForTimeTravel?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: executionContext.runId,\n })) ?? { context: {} };\n const timeTravelParams = createTimeTravelExecutionParams({\n steps: timeTravel.steps.slice(1),\n inputData: timeTravel.inputData,\n resumeData: timeTravel.resumeData,\n context: (timeTravel.nestedStepResults?.[step.id] ?? {}) as any,\n nestedStepsContext: (timeTravel.nestedStepResults ?? {}) as any,\n snapshot,\n graph: step.buildExecutionGraph(),\n });\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n timeTravel: timeTravelParams,\n initialState: executionContext.state ?? {},\n runId: executionContext.runId,\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else {\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n initialState: executionContext.state ?? {},\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n }\n } catch (e) {\n // Nested workflow threw an error (likely from finalization step)\n // The error cause should contain the workflow result with runId\n const errorCause = (e as any)?.cause;\n\n // Try to extract runId from error cause or generate new one\n if (errorCause && typeof errorCause === 'object') {\n result = errorCause as WorkflowResult<any, any, any, any>;\n // The runId might be in the result's steps metadata\n runId = errorCause.runId || randomUUID();\n } else {\n // Fallback: if we can't get the result from error, construct a basic failed result\n runId = randomUUID();\n result = {\n status: 'failed',\n error: e instanceof Error ? e : new Error(String(e)),\n steps: {},\n input: inputData,\n } as WorkflowResult<any, any, any, any>;\n }\n }\n\n const res = await this.inngestStep.run(\n `workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,\n async () => {\n if (result.status === 'failed') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'failed',\n error: result?.error,\n payload: prevOutput,\n },\n },\n });\n\n return { executionContext, result: { status: 'failed', error: result?.error, endedAt: Date.now() } };\n } else if (result.status === 'suspended') {\n const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {\n const stepRes: StepResult<any, any, any, any> = stepResult as StepResult<any, any, any, any>;\n return stepRes?.status === 'suspended';\n });\n\n for (const [stepName, stepResult] of suspendedSteps) {\n const suspendPath: string[] = [stepName, ...(stepResult?.suspendPayload?.__workflow_meta?.path ?? [])];\n executionContext.suspendedPaths[step.id] = executionContext.executionPath;\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-suspended',\n payload: {\n id: step.id,\n status: 'suspended',\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: stepResult.payload,\n suspendPayload: {\n ...(stepResult as any)?.suspendPayload,\n __workflow_meta: { runId: runId, path: suspendPath },\n },\n },\n };\n }\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: {},\n },\n };\n } else if (result.status === 'tripwire') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'tripwire',\n error: result?.tripwire?.reason,\n payload: prevOutput,\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'tripwire',\n tripwire: result?.tripwire,\n endedAt: Date.now(),\n },\n };\n } else if (perStep || result.status === 'paused') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'paused',\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n return { executionContext, result: { status: 'paused' } };\n }\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'success',\n output: result?.result,\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n\n return { executionContext, result: { status: 'success', output: result?.result, endedAt: Date.now() } };\n },\n );\n\n Object.assign(executionContext, res.executionContext);\n return {\n ...res.result,\n startedAt,\n payload: inputData,\n resumedAt: resume?.steps[0] === step.id ? startedAt : undefined,\n resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : undefined,\n } as StepResult<any, any, any, any>;\n }\n}\n","import { subscribe } from '@inngest/realtime';\nimport { PubSub } from '@mastra/core/events';\nimport type { Event } from '@mastra/core/events';\nimport type { Inngest } from 'inngest';\n\n/**\n * Type for Inngest's publish function, available inside Inngest function context.\n */\nexport type InngestPublishFn = (opts: { channel: string; topic: string; data: any }) => Promise<void>;\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's publish function (only available in function context)\n * - subscribe() uses @inngest/realtime subscribe for real-time streaming\n *\n * Topic format: \"workflow.events.v2.{runId}\"\n * Channel format: \"workflow:{workflowId}:{runId}\"\n */\nexport class InngestPubSub extends PubSub {\n private inngest: Inngest;\n private workflowId: string;\n private publishFn?: InngestPublishFn;\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, publishFn?: InngestPublishFn) {\n super();\n this.inngest = inngest;\n this.workflowId = workflowId;\n this.publishFn = publishFn;\n }\n\n /**\n * Publish an event to Inngest's realtime system.\n *\n * Topic format: \"workflow.events.v2.{runId}\"\n * Maps to Inngest channel: \"workflow:{workflowId}:{runId}\"\n */\n async publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>): Promise<void> {\n if (!this.publishFn) {\n // Silently ignore if no publish function (e.g., outside Inngest context)\n return;\n }\n\n // Parse topic to extract runId\n // Topic format: \"workflow.events.v2.{runId}\"\n const match = topic.match(/^workflow\\.events\\.v2\\.(.+)$/);\n if (!match) {\n return; // Ignore non-workflow topics\n }\n\n const runId = match[1];\n\n try {\n await this.publishFn({\n channel: `workflow:${this.workflowId}:${runId}`,\n topic: 'watch',\n data: event.data,\n });\n } catch (err: any) {\n // Log but don't throw - publishing failures shouldn't break workflow execution\n console.error('InngestPubSub publish error:', err?.message ?? err);\n }\n }\n\n /**\n * Subscribe to events from Inngest's realtime system.\n *\n * Topic format: \"workflow.events.v2.{runId}\"\n * Maps to Inngest channel: \"workflow:{workflowId}:{runId}\"\n */\n async subscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n // Parse topic: \"workflow.events.v2.{runId}\"\n const match = topic.match(/^workflow\\.events\\.v2\\.(.+)$/);\n if (!match || !match[1]) {\n return; // Ignore non-workflow topics\n }\n\n const runId: string = match[1];\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 const channel = `workflow:${this.workflowId}:${runId}`;\n\n const streamPromise = subscribe(\n {\n channel,\n topics: ['watch'],\n app: this.inngest,\n },\n (message: any) => {\n // Transform Inngest message to PubSub Event format\n const event: Event = {\n id: crypto.randomUUID(),\n type: 'watch',\n runId,\n data: message.data,\n createdAt: new Date(),\n };\n\n for (const callback of callbacks) {\n callback(event);\n }\n },\n );\n\n this.subscriptions.set(topic, {\n unsubscribe: () => {\n streamPromise\n .then(stream => stream.cancel())\n .catch(err => {\n console.error('InngestPubSub unsubscribe error:', err);\n });\n },\n callbacks,\n });\n }\n\n /**\n * Unsubscribe a callback from a topic.\n * If no callbacks remain, the underlying Inngest subscription is cancelled.\n */\n async unsubscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const sub = this.subscriptions.get(topic);\n if (!sub) {\n return;\n }\n\n sub.callbacks.delete(cb);\n\n // If no more callbacks, cancel the subscription\n if (sub.callbacks.size === 0) {\n sub.unsubscribe();\n this.subscriptions.delete(topic);\n }\n }\n\n /**\n * Flush any pending operations. No-op for Inngest.\n */\n async flush(): Promise<void> {\n // No-op for Inngest\n }\n\n /**\n * Clean up all subscriptions during graceful shutdown.\n */\n async close(): Promise<void> {\n for (const [, sub] of this.subscriptions) {\n sub.unsubscribe();\n }\n this.subscriptions.clear();\n }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport { subscribe } from '@inngest/realtime';\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 { context as otelContext } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport type { InngestEngineType } from './types';\n\nexport class InngestRun<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType\n >[],\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n> extends Run<TEngineType, TSteps, TState, TInput, TOutput> {\n private inngest: Inngest;\n serializedStepGraph: SerializedStepFlowEntry[];\n #mastra: Mastra;\n\n constructor(\n params: {\n workflowId: string;\n runId: string;\n resourceId?: string;\n executionEngine: ExecutionEngine;\n executionGraph: ExecutionGraph;\n serializedStepGraph: SerializedStepFlowEntry[];\n mastra?: Mastra;\n retryConfig?: {\n attempts?: number;\n delay?: number;\n };\n cleanup?: () => void;\n workflowSteps: Record<string, StepWithComponent>;\n workflowEngineType: WorkflowEngineType;\n validateInputs?: boolean;\n },\n inngest: Inngest,\n ) {\n super(params);\n this.inngest = inngest;\n this.serializedStepGraph = params.serializedStepGraph;\n this.#mastra = params.mastra!;\n }\n\n async getRuns(eventId: string) {\n const maxRetries = 3;\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n // Suppress OTel auto-instrumentation on polling fetch calls to avoid\n // excessive trace noise (see https://github.com/mastra-ai/mastra/issues/13892)\n const response = await otelContext.with(suppressTracing(otelContext.active()), () =>\n fetch(`${this.inngest.apiBaseUrl ?? 'https://api.inngest.com'}/v1/events/${eventId}/runs`, {\n headers: {\n Authorization: `Bearer ${process.env.INNGEST_SIGNING_KEY}`,\n },\n }),\n );\n\n // Handle rate limiting with retry\n if (response.status === 429) {\n const retryAfter = parseInt(response.headers.get('retry-after') || '2', 10);\n await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));\n continue;\n }\n\n // Non-OK responses\n if (!response.ok) {\n throw new Error(`Inngest API error: ${response.status} ${response.statusText}`);\n }\n\n // Parse JSON safely\n const text = await response.text();\n if (!text) {\n // Empty response - eventual consistency, retry with backoff\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n continue;\n }\n\n const json = JSON.parse(text);\n return json.data;\n } catch (error) {\n lastError = error as Error;\n // Exponential backoff before retry\n if (attempt < maxRetries - 1) {\n await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt)));\n }\n }\n }\n\n // After all retries, throw NonRetriableError to prevent Inngest function-level retry\n throw new NonRetriableError(`Failed to get runs after ${maxRetries} attempts: ${lastError?.message}`);\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\n return new Promise<any>((resolve, reject) => {\n let resolved = false;\n let unsubscribe: (() => void) | null = null;\n let pollTimeoutId: NodeJS.Timeout | null = null;\n\n const cleanup = () => {\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch {\n // Ignore unsubscribe errors\n }\n }\n if (pollTimeoutId) {\n clearTimeout(pollTimeoutId);\n }\n };\n\n const handleResult = (result: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve(result);\n }\n };\n\n const handleError = (error: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(error);\n }\n };\n\n // Start realtime subscription for workflow-finish event\n let realtimeStreamPromise: ReturnType<typeof subscribe> | null = null;\n\n const startRealtimeSubscription = async () => {\n try {\n realtimeStreamPromise = subscribe(\n {\n channel: `workflow:${this.workflowId}:${this.runId}`,\n topics: ['watch'],\n app: this.inngest,\n },\n async (message: any) => {\n if (resolved) return;\n\n const event = message.data;\n\n if (event?.type === 'workflow-finish') {\n // Got the finish event - load snapshot and resolve\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot?.context) {\n snapshot.context = hydrateSerializedStepErrors(snapshot.context);\n }\n\n const result = {\n output: {\n result: {\n steps: snapshot?.context,\n status: event.payload.status,\n result: event.payload.result,\n error: event.payload.error\n ? getErrorFromUnknown(event.payload.error, { serializeStack: false })\n : undefined,\n },\n },\n };\n\n handleResult(result, 'realtime');\n }\n },\n );\n\n // Set unsubscribe immediately so cleanup can cancel even before await resolves\n unsubscribe = () => {\n realtimeStreamPromise?.then(stream => stream.cancel().catch(() => {})).catch(() => {});\n };\n\n await realtimeStreamPromise;\n } catch {\n // Realtime subscription failed - polling will still work as fallback\n }\n };\n\n // Start polling as fallback\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 runs = await this.getRuns(eventId);\n const run = runs?.find((r: { event_id: string }) => r.event_id === eventId);\n\n if (run?.status === 'Completed') {\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 handleResult({ output: { result: { steps: snapshot?.context, status: 'success' } } }, 'polling');\n return;\n }\n\n if (run?.status === 'Failed') {\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 handleResult(\n {\n output: {\n result: {\n steps: snapshot?.context,\n status: 'failed',\n error: getErrorFromUnknown(run?.output?.cause?.error, { serializeStack: false }),\n },\n },\n },\n 'polling-failed',\n );\n return;\n }\n\n if (run?.status === 'Cancelled') {\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 handleResult(\n { output: { result: { steps: snapshot?.context, status: 'canceled' } } },\n 'polling-cancelled',\n );\n return;\n }\n\n // Schedule next poll with jitter\n pollTimeoutId = setTimeout(poll, 200 + Math.random() * 200);\n } catch (error) {\n if (error instanceof NonRetriableError) {\n handleError(error, 'polling-non-retriable');\n return;\n }\n handleError(\n new NonRetriableError(\n `Failed to poll workflow status: ${error instanceof Error ? error.message : String(error)}`,\n ),\n 'polling-error',\n );\n }\n };\n\n // Start first poll\n void poll();\n };\n\n // Start both in parallel\n void startRealtimeSubscription();\n void startPolling();\n });\n }\n\n async cancel() {\n const storage = this.#mastra?.getStorage();\n\n await this.inngest.send({\n name: `cancel.workflow.${this.workflowId}`,\n data: {\n runId: this.runId,\n },\n });\n\n const workflowsStore = await storage?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot) {\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n ...snapshot,\n status: 'canceled' as any,\n value: snapshot.value,\n },\n });\n }\n }\n\n async start(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext;\n outputWriter?: OutputWriter;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n return this._start(args);\n }\n\n /**\n * Starts the workflow execution without waiting for completion (fire-and-forget).\n * Returns immediately with the runId after sending the event to Inngest.\n * The workflow executes independently in Inngest.\n * Use this when you don't need to wait for the result or want to avoid polling failures.\n */\n async startAsync(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<{ runId: string }> {\n // Persist initial snapshot\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n // Validate inputs\n const inputDataToUse = await this._validateInput(args.inputData);\n const initialStateToUse = await this._validateInitialState(args.initialState ?? ({} as TState));\n\n // Send event to Inngest (fire-and-forget)\n const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions: args.outputOptions,\n tracingOptions: args.tracingOptions,\n requestContext: args.requestContext ? Object.fromEntries(args.requestContext.entries()) : {},\n 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 perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext;\n initialState?: TState;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n format?: 'legacy' | 'vnext' | undefined;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n const inputDataToUse = await this._validateInput(inputData);\n const initialStateToUse = await this._validateInitialState(initialState ?? ({} as TState));\n\n const eventName = `workflow.${this.workflowId}`;\n\n const eventOutput = await this.inngest.send({\n name: eventName,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions,\n tracingOptions,\n format,\n requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {},\n 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 if (result.status !== 'suspended') {\n this.cleanup?.();\n }\n return result;\n }\n\n async resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n 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 async _resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const storage = this.#mastra?.getStorage();\n\n const workflowsStore = await storage?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n // Support label-based resume: look up step from resumeLabels\n const snapshotResumeLabel = params.label ? snapshot?.resumeLabels?.[params.label] : undefined;\n const stepParam = snapshotResumeLabel?.stepId ?? params.step;\n\n let steps: string[] = [];\n if (stepParam) {\n if (typeof stepParam === 'string') {\n steps = stepParam.split('.');\n } else {\n steps = (Array.isArray(stepParam) ? stepParam : [stepParam]).map(step =>\n typeof step === 'string' ? step : step?.id,\n );\n }\n }\n\n const suspendedStep = this.workflowSteps[steps?.[0] ?? ''];\n\n const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);\n\n // Merge persisted requestContext from snapshot with any new values from params\n const persistedRequestContext = (snapshot as any)?.requestContext ?? {};\n const newRequestContext = params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {};\n const mergedRequestContext = { ...persistedRequestContext, ...newRequestContext };\n\n const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: resumeDataToUse,\n initialState: snapshot?.value ?? {},\n runId: this.runId,\n workflowId: this.workflowId,\n stepResults: snapshot?.context as any,\n resume: {\n steps,\n stepResults: snapshot?.context as any,\n resumePayload: resumeDataToUse,\n resumePath: steps?.[0] ? (snapshot?.suspendedPaths?.[steps?.[0]] as any) : undefined,\n },\n requestContext: mergedRequestContext,\n perStep: params.perStep,\n },\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 return result;\n }\n\n async timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const p = this._timeTravel(params).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n this.executionResults = p;\n return p;\n }\n\n async _timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n 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\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n if (!snapshot) {\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: 'pending',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\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 const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n initialState: timeTravelData.state,\n runId: this.runId,\n workflowId: this.workflowId,\n stepResults: timeTravelData.stepResults,\n timeTravel: timeTravelData,\n tracingOptions: params.tracingOptions,\n outputOptions: params.outputOptions,\n requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {},\n perStep: params.perStep,\n },\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 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({ inputData, requestContext }: { inputData?: TInput; requestContext?: RequestContext } = {}): {\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, 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 tracingOptions,\n closeOnSuspend = true,\n initialState,\n outputOptions,\n perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n closeOnSuspend?: boolean;\n initialState?: TState;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n } = {}): WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n if (this.closeStreamAction && this.streamOutput) {\n return this.streamOutput;\n }\n\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n // TODO: fix this, watch doesn't have a type\n const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n await controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n\n const executionResultsPromise = self._start({\n inputData,\n requestContext,\n // 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 // tracingContext,\n tracingOptions,\n outputOptions,\n perStep,\n }: {\n inputData?: TTravelInput;\n initialState?: TState;\n resumeData?: any;\n step:\n | Step<string, any, any, any, any, any, TEngineType>\n | [...Step<string, any, any, any, any, any, TEngineType>[], Step<string, any, any, any, any, any, TEngineType>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }) {\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n // TODO: fix this, watch doesn't have a type\n const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n const executionResultsPromise = self._timeTravel({\n inputData,\n step,\n context,\n nestedStepsContext,\n resumeData,\n initialState,\n requestContext,\n 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 { RequestContext } from '@mastra/core/di';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { SpanType, EntityType } from '@mastra/core/observability';\nimport type { WorkflowRuns } from '@mastra/core/storage';\nimport { Workflow } from '@mastra/core/workflows';\nimport type {\n Step,\n StepResult,\n WorkflowConfig,\n StepFlowEntry,\n WorkflowResult,\n WorkflowRunState,\n WorkflowStreamEvent,\n Run,\n} from '@mastra/core/workflows';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport { InngestExecutionEngine } from './execution-engine';\nimport { InngestPubSub } from './pubsub';\nimport { InngestRun } from './run';\nimport type {\n InngestEngineType,\n InngestFlowControlConfig,\n InngestFlowCronConfig,\n InngestWorkflowConfig,\n} from './types';\n\nexport class InngestWorkflow<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType\n >[],\n TWorkflowId extends string = string,\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TPrevSchema = TInput,\n> extends Workflow<TEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrevSchema> {\n #mastra: Mastra;\n public inngest: Inngest;\n\n private function: ReturnType<Inngest['createFunction']> | undefined;\n private cronFunction: ReturnType<Inngest['createFunction']> | undefined;\n private readonly flowControlConfig?: InngestFlowControlConfig;\n private readonly cronConfig?: InngestFlowCronConfig<TInput, TState>;\n\n constructor(\n params: InngestWorkflowConfig<\n TWorkflowId,\n TState,\n TInput,\n TOutput,\n TSteps & Step<string, any, any, any, any, any, InngestEngineType>[]\n >,\n inngest: Inngest,\n ) {\n const { concurrency, rateLimit, throttle, debounce, priority, cron, inputData, initialState, ...workflowParams } =\n params;\n\n super(workflowParams as WorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps>);\n\n this.engineType = 'inngest';\n\n const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(\n ([_, value]) => value !== undefined,\n );\n\n this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : undefined;\n\n this.#mastra = params.mastra!;\n this.inngest = inngest;\n\n if (cron) {\n this.cronConfig = { cron, inputData, initialState };\n }\n }\n\n async listWorkflowRuns(args?: {\n fromDate?: Date;\n toDate?: Date;\n perPage?: number | false;\n page?: number;\n resourceId?: string;\n }) {\n const storage = this.#mastra?.getStorage();\n if (!storage) {\n this.logger.debug('Cannot get workflow runs. Mastra engine is not initialized');\n return { runs: [], total: 0 };\n }\n\n const workflowsStore = await storage.getStore('workflows');\n if (!workflowsStore) {\n return { runs: [], total: 0 };\n }\n return workflowsStore.listWorkflowRuns({ workflowName: this.id, ...(args ?? {}) }) as unknown as WorkflowRuns;\n }\n\n __registerMastra(mastra: Mastra) {\n super.__registerMastra(mastra);\n this.#mastra = mastra;\n this.executionEngine.__registerMastra(mastra);\n const updateNested = (step: StepFlowEntry) => {\n if (\n (step.type === 'step' || step.type === 'loop' || step.type === 'foreach') &&\n step.step instanceof InngestWorkflow\n ) {\n step.step.__registerMastra(mastra);\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n for (const subStep of step.steps) {\n updateNested(subStep);\n }\n }\n };\n\n if (this.executionGraph.steps.length) {\n for (const step of this.executionGraph.steps) {\n updateNested(step);\n }\n }\n }\n\n async createRun(options?: {\n runId?: string;\n resourceId?: string;\n }): Promise<Run<TEngineType, TSteps, TState, TInput, TOutput>> {\n const runIdToUse = options?.runId || randomUUID();\n\n // Return a new Run instance with object parameters\n const existingInMemoryRun = this.runs.get(runIdToUse);\n const newRun = new InngestRun<TEngineType, TSteps, TState, TInput, TOutput>(\n {\n workflowId: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n executionEngine: this.executionEngine,\n executionGraph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n mastra: this.#mastra,\n retryConfig: this.retryConfig,\n cleanup: () => this.runs.delete(runIdToUse),\n workflowSteps: this.steps,\n workflowEngineType: this.engineType,\n validateInputs: this.options.validateInputs,\n },\n this.inngest,\n );\n const run = (existingInMemoryRun ?? newRun) as Run<TEngineType, TSteps, TState, TInput, TOutput>;\n\n this.runs.set(runIdToUse, run);\n\n const shouldPersistSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: run.workflowRunStatus,\n stepResults: {},\n });\n\n const existingStoredRun = await this.getWorkflowRunById(runIdToUse, {\n withNestedWorkflows: false,\n });\n\n // Check if run exists in persistent storage (not just in-memory)\n const existsInStorage = existingStoredRun && !existingStoredRun.isFromInMemory;\n\n if (!existsInStorage && shouldPersistSnapshot) {\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n snapshot: {\n runId: runIdToUse,\n status: 'pending',\n value: {},\n context: {},\n activePaths: [],\n activeStepsPath: {},\n waitingPaths: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: {},\n resumeLabels: {},\n result: undefined,\n error: undefined,\n timestamp: Date.now(),\n },\n });\n }\n\n return run;\n }\n\n //createCronFunction is only called if cronConfig.cron is defined.\n private createCronFunction() {\n if (this.cronFunction) {\n return this.cronFunction;\n }\n this.cronFunction = this.inngest.createFunction(\n {\n id: `workflow.${this.id}.cron`,\n retries: 0,\n cancelOn: [{ event: `cancel.workflow.${this.id}` }],\n ...this.flowControlConfig,\n },\n { cron: this.cronConfig?.cron ?? '' },\n async () => {\n const run = await this.createRun();\n // @ts-expect-error - cron inputData type mismatch\n const result = await run.start({\n inputData: this.cronConfig?.inputData,\n initialState: this.cronConfig?.initialState,\n });\n return { result, runId: run.runId };\n },\n );\n return this.cronFunction;\n }\n\n getFunction() {\n if (this.function) {\n return this.function;\n }\n\n // Always set function-level retries to 0, since retries are handled at the step level via executeStepWithRetry\n // which uses either step.retries or retryConfig.attempts (step.retries takes precedence).\n // step.retries is not accessible at function level, so we handle retries manually in executeStepWithRetry.\n // This is why we set retries to 0 here.\n this.function = this.inngest.createFunction(\n {\n id: `workflow.${this.id}`,\n retries: 0,\n cancelOn: [{ event: `cancel.workflow.${this.id}` }],\n // Spread flow control configuration\n ...this.flowControlConfig,\n },\n { event: `workflow.${this.id}` },\n async ({ event, step, attempt, publish }) => {\n let {\n inputData,\n initialState,\n runId,\n resourceId,\n resume,\n outputOptions,\n format,\n timeTravel,\n perStep,\n tracingOptions,\n } = event.data;\n\n if (!runId) {\n runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {\n return randomUUID();\n });\n }\n\n // Create InngestPubSub instance with the publish function from Inngest context\n const pubsub = new InngestPubSub(this.inngest, this.id, publish);\n\n // Create requestContext before execute so we can reuse it in finalize\n const requestContext: RequestContext = new RequestContext(Object.entries(event.data.requestContext ?? {}));\n\n // Store mastra reference for use in proxy closure\n const mastra = this.#mastra;\n const tracingPolicy = this.options.tracingPolicy;\n\n // Create the workflow root span durably - exports SPAN_STARTED immediately on first execution\n // On replay, returns memoized ExportedSpan data without re-creating the span\n const workflowSpanData = await step.run(`workflow.${this.id}.span.start`, async () => {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (!observability) return undefined;\n\n const span = observability.startSpan({\n type: SpanType.WORKFLOW_RUN,\n name: `workflow run: '${this.id}'`,\n entityType: EntityType.WORKFLOW_RUN,\n entityId: this.id,\n entityName: this.id,\n input: inputData,\n metadata: {\n resourceId,\n runId,\n },\n tracingPolicy,\n tracingOptions,\n requestContext,\n });\n\n return span?.exportSpan();\n });\n\n const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);\n\n let result: WorkflowResult<TState, TInput, TOutput, TSteps>;\n try {\n result = await engine.execute<TState, TInput, WorkflowResult<TState, TInput, TOutput, TSteps>>({\n workflowId: this.id,\n runId,\n resourceId,\n graph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n input: inputData,\n initialState,\n pubsub,\n retryConfig: this.retryConfig,\n requestContext,\n resume,\n timeTravel,\n perStep,\n format,\n abortController: new AbortController(),\n // For Inngest, we don't pass workflowSpan - step spans use tracingIds instead\n workflowSpan: undefined,\n // Pass tracing IDs for durable span operations\n tracingIds: workflowSpanData\n ? {\n traceId: workflowSpanData.traceId,\n workflowSpanId: workflowSpanData.id,\n }\n : undefined,\n outputOptions,\n outputWriter: async (chunk: WorkflowStreamEvent) => {\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: chunk,\n });\n } catch (err) {\n this.logger.debug?.('Failed to publish watch event:', err);\n }\n },\n });\n } catch (error) {\n // Re-throw - span will be ended in finalize if we reach it\n throw error;\n }\n\n // Final step to invoke lifecycle callbacks and end workflow span.\n // This step is memoized by step.run.\n let finalizeError: unknown;\n let finalizeErrored = false;\n try {\n await step.run(`workflow.${this.id}.finalize`, async () => {\n if (result.status !== 'paused') {\n // Invoke lifecycle callbacks (onFinish and onError)\n await engine.invokeLifecycleCallbacksInternal({\n status: result.status,\n result: 'result' in result ? result.result : undefined,\n error: 'error' in result ? result.error : undefined,\n steps: result.steps,\n tripwire: 'tripwire' in result ? result.tripwire : undefined,\n runId,\n workflowId: this.id,\n resourceId,\n input: inputData,\n requestContext,\n state: result.state ?? initialState ?? {},\n });\n }\n\n // End the workflow span with appropriate status\n // The workflow span was already created and SPAN_STARTED was exported in the span.start step\n if (workflowSpanData) {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n // Rebuild the span from cached data to call end/error\n const workflowSpan = observability.rebuildSpan(workflowSpanData);\n\n if (result.status === 'failed') {\n workflowSpan.error({\n error: result.error instanceof Error ? result.error : new Error(String(result.error)),\n attributes: { status: 'failed' },\n });\n } else {\n workflowSpan.end({\n output: result.status === 'success' ? result.result : undefined,\n attributes: { status: result.status },\n });\n }\n }\n }\n\n // Ensure final snapshot is persisted BEFORE publishing workflow-finish\n // This fixes a race condition where getRunOutput reads the snapshot before it's fully written\n const shouldPersistFinalSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: result.status,\n stepResults: result.steps,\n });\n if (shouldPersistFinalSnapshot) {\n const workflowsStore = await mastra?.getStorage()?.getStore('workflows');\n if (workflowsStore) {\n // For suspended workflows, read existing snapshot to preserve suspendedPaths and resumeLabels\n // which were set correctly by the handlers during execution\n let existingSnapshot:\n | { suspendedPaths?: Record<string, number[]>; resumeLabels?: Record<string, any> }\n | undefined;\n if (result.status === 'suspended') {\n existingSnapshot =\n (await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.id,\n runId,\n })) ?? undefined;\n }\n\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.id,\n runId,\n resourceId,\n snapshot: {\n runId,\n status: result.status,\n value: result.state ?? initialState ?? {},\n context: toSnapshotContext(result.steps),\n activePaths: [],\n activeStepsPath: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: existingSnapshot?.suspendedPaths ?? {},\n waitingPaths: {},\n resumeLabels: existingSnapshot?.resumeLabels ?? result.resumeLabels ?? {},\n result: result.status === 'success' ? toSnapshotResult(result.result) : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n timestamp: Date.now(),\n },\n });\n }\n }\n\n // Publish workflow-finish event for realtime subscribers (best-effort)\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: {\n type: 'workflow-finish',\n payload: {\n status: result.status,\n result: result.status === 'success' ? result.result : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n },\n },\n });\n } catch (publishError) {\n this.logger.debug?.('Failed to publish workflow-finish event:', publishError);\n }\n\n // Throw after span ended for failed workflows\n if (result.status === 'failed') {\n throw new NonRetriableError(`Workflow failed`, {\n cause: result,\n });\n }\n\n return result;\n });\n } catch (error) {\n finalizeErrored = true;\n finalizeError = error;\n } finally {\n // Keep this outside step.run memoization, but guaranteed on all paths.\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n try {\n await observability.flush();\n } catch (flushError) {\n this.logger.debug?.('Failed to flush observability:', flushError);\n }\n }\n }\n\n if (finalizeErrored) {\n throw finalizeError;\n }\n\n return { result, runId };\n },\n );\n return this.function;\n }\n\n getNestedFunctions(steps: StepFlowEntry[]): ReturnType<Inngest['createFunction']>[] {\n return steps.flatMap(step => {\n if (step.type === 'step' || step.type === 'loop' || step.type === 'foreach') {\n if (step.step instanceof InngestWorkflow) {\n return [step.step.getFunction(), ...step.step.getNestedFunctions(step.step.executionGraph.steps)];\n }\n return [];\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n return this.getNestedFunctions(step.steps);\n }\n\n return [];\n });\n }\n\n getFunctions() {\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 { Inngest, InngestFunction, RegisterOptions } from 'inngest';\nimport { serve as inngestServeHono } from 'inngest/hono';\nimport { InngestWorkflow } from './workflow';\n\n/**\n * Options for serve functions\n */\nexport interface MastraServeOptions {\n mastra: Mastra;\n inngest: Inngest;\n /**\n * Optional array of additional functions to serve and register with Inngest.\n */\n functions?: InngestFunction.Like[];\n registerOptions?: RegisterOptions;\n}\n\n/**\n * Type for inngest serve adapters (e.g., from inngest/hono, inngest/express, etc.)\n * Inferred from the inngest serve function signatures.\n */\nexport type InngestServeAdapter<THandler> = (options: {\n client: Inngest;\n functions: InngestFunction.Like[];\n [key: string]: unknown;\n}) => THandler;\n\n/**\n * Collects workflow functions from Mastra and prepares serve options for inngest.\n * This is the shared logic used by all serve functions.\n */\nfunction prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }: MastraServeOptions) {\n const wfs = mastra.listWorkflows();\n const workflowFunctions = Array.from(\n new Set(\n Object.values(wfs).flatMap(wf => {\n if (wf instanceof InngestWorkflow) {\n wf.__registerMastra(mastra);\n return wf.getFunctions();\n }\n return [];\n }),\n ),\n );\n\n return {\n ...registerOptions,\n client: inngest,\n functions: [...workflowFunctions, ...userFunctions],\n };\n}\n\n/**\n * Factory function to create a serve function with any inngest adapter.\n * Use this to integrate Mastra workflows with any framework supported by inngest.\n *\n * @example Express\n * ```ts\n * import { createServe } from '@mastra/inngest';\n * import { serve } from 'inngest/express';\n *\n * const serveExpress = createServe(serve);\n * app.use('/api/inngest', serveExpress({ mastra, inngest }));\n * ```\n *\n * @example Fastify\n * ```ts\n * import { createServe } from '@mastra/inngest';\n * import { serve } from 'inngest/fastify';\n *\n * const serveFastify = createServe(serve);\n * fastify.route({\n * method: ['GET', 'POST', 'PUT'],\n * handler: serveFastify({ mastra, inngest }),\n * url: '/api/inngest',\n * });\n * ```\n *\n * @example Next.js\n * ```ts\n * import { createServe } from '@mastra/inngest';\n * import { serve } from 'inngest/next';\n *\n * const serveNext = createServe(serve);\n * export const { GET, POST, PUT } = serveNext({ mastra, inngest });\n * ```\n */\nexport function createServe<THandler>(\n adapter: InngestServeAdapter<THandler>,\n): (options: MastraServeOptions) => THandler {\n return (options: MastraServeOptions): THandler => {\n const serveOptions = prepareServeOptions(options);\n return adapter(serveOptions);\n };\n}\n\n/**\n * Serve Mastra workflows with Hono (default).\n *\n * For other frameworks, use `createServe` with the appropriate inngest adapter.\n *\n * @example\n * ```ts\n * import { serve } from '@mastra/inngest';\n *\n * app.use('/api/inngest', async (c) => {\n * return serve({ mastra, inngest })(c);\n * });\n * ```\n */\nexport const serve: (options: MastraServeOptions) => ReturnType<typeof inngestServeHono> =\n createServe(inngestServeHono);\n","import type { Step, WorkflowConfig } from '@mastra/core/workflows';\nimport type { Inngest, InngestFunction } from 'inngest';\n\n// Extract Inngest's native flow control configuration types\nexport type InngestCreateFunctionConfig = Parameters<Inngest['createFunction']>[0];\nexport type InngestCreateFunctionEventConfig = InngestFunction.Trigger<string>;\n\n// Extract specific flow control properties (excluding batching)\nexport type InngestFlowControlConfig = Pick<\n InngestCreateFunctionConfig,\n 'concurrency' | 'rateLimit' | 'throttle' | 'debounce' | 'priority'\n>;\n\nexport type InngestFlowCronConfig<TInputData, TInitialState> = Pick<InngestCreateFunctionEventConfig, 'cron'> & {\n inputData?: TInputData;\n initialState?: TInitialState;\n};\n\n// Union type for Inngest workflows with flow control\nexport type InngestWorkflowConfig<\n TWorkflowId extends string,\n TState,\n TInput,\n TOutput,\n TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[],\n> = WorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps> &\n InngestFlowControlConfig &\n InngestFlowCronConfig<TInput, TState>;\n\n// Compile-time compatibility assertion\nexport type _AssertInngestCompatibility =\n InngestFlowControlConfig extends Pick<Parameters<Inngest['createFunction']>[0], keyof InngestFlowControlConfig>\n ? true\n : never;\nexport const _compatibilityCheck: _AssertInngestCompatibility = true;\n\nexport type InngestEngineType = {\n step: any;\n};\n","import type { ReadableStream } from 'node:stream/web';\nimport { Agent, MessageList, TripWire } from '@mastra/core/agent';\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { MastraScorers } from '@mastra/core/evals';\nimport type { CoreMessage } from '@mastra/core/llm';\nimport type { TracingContext } from '@mastra/core/observability';\nimport { EntityType, SpanType } from '@mastra/core/observability';\nimport type { Processor, ProcessorStepOutput, ProcessorStepInputSchema, OutputResult } from '@mastra/core/processors';\nimport { ProcessorRunner, ProcessorStepOutputSchema, ProcessorStepSchema } from '@mastra/core/processors';\nimport type { InferPublicSchema, PublicSchema, StandardSchemaWithJSON } from '@mastra/core/schema';\nimport { toStandardSchema } from '@mastra/core/schema';\nimport type { ChunkType, LanguageModelUsage } from '@mastra/core/stream';\nimport type { ToolExecutionContext } from '@mastra/core/tools';\nimport { Tool, createTool } from '@mastra/core/tools';\nimport type { DynamicArgument } from '@mastra/core/types';\nimport type { Step, AgentStepOptions, StepParams, ToolStep, StepMetadata } from '@mastra/core/workflows';\nimport { Workflow } from '@mastra/core/workflows';\nimport { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';\nimport type { Inngest } from 'inngest';\nimport { z } from 'zod';\nimport type { InngestEngineType, InngestWorkflowConfig } from './types';\nimport { InngestWorkflow } from './workflow';\n\nexport * from './workflow';\nexport * from './execution-engine';\nexport * from './pubsub';\nexport * from './run';\nexport * from './serve';\nexport * from './types';\n\n// ============================================\n// Type Guards\n// ============================================\n\nfunction isInngestWorkflow(input: unknown): input is InngestWorkflow<any, any, any, any, any, any, any> {\n return input instanceof InngestWorkflow;\n}\n\nfunction isAgent<TStepId extends string>(input: unknown): input is Agent<TStepId, any> {\n return input instanceof Agent;\n}\n\nfunction isToolStep(input: unknown): input is ToolStep<any, any, any, any, any> {\n return input instanceof Tool;\n}\n\nfunction isStepParams(input: unknown): input is StepParams<any, any, any, any, any, any> {\n return (\n input !== null &&\n typeof input === 'object' &&\n 'id' in input &&\n 'execute' in input &&\n !(input instanceof Agent) &&\n !(input instanceof Tool) &&\n !(input instanceof InngestWorkflow)\n );\n}\n\n/**\n * Type guard to check if an object is a Processor.\n * A Processor must have an 'id' property and at least one processor method.\n */\nfunction isProcessor(obj: unknown): obj is Processor {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n 'id' in obj &&\n typeof (obj as any).id === 'string' &&\n !(obj instanceof Agent) &&\n !(obj instanceof Tool) &&\n !(obj instanceof InngestWorkflow) &&\n (typeof (obj as any).processInput === 'function' ||\n typeof (obj as any).processInputStep === 'function' ||\n typeof (obj as any).processOutputStream === 'function' ||\n typeof (obj as any).processOutputResult === 'function' ||\n typeof (obj as any).processOutputStep === 'function')\n );\n}\n\n// ============================================\n// Overloads (Public API - clean types for consumers)\n// ============================================\n\n/**\n * Creates a step from explicit params (IMPORTANT: FIRST overload for best error messages when using .then in workflows)\n * @param params Configuration parameters for the step\n * @param params.id Unique identifier for the step\n * @param params.description Optional description of what the step does\n * @param params.inputSchema Zod schema defining the input structure\n * @param params.outputSchema Zod schema defining the output structure\n * @param params.execute Function that performs the step's operations\n * @returns A Step object that can be added to the workflow\n */\nexport function createStep<\n TStepId extends string,\n TStateSchema extends PublicSchema | undefined,\n TInputSchema extends PublicSchema,\n TOutputSchema extends PublicSchema,\n TResumeSchema extends PublicSchema | undefined = undefined,\n TSuspendSchema extends PublicSchema | undefined = undefined,\n>(\n params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>,\n): Step<\n TStepId,\n TStateSchema extends PublicSchema ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n>;\n\n/**\n * Creates a step from an agent with structured output\n */\nexport function createStep<TStepId extends string, TStepOutput>(\n agent: Agent<TStepId, any>,\n agentOptions: AgentStepOptions<TStepOutput> & {\n structuredOutput: { schema: StandardSchemaWithJSON<TStepOutput> };\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n metadata?: StepMetadata;\n },\n): Step<TStepId, unknown, { prompt: string }, TStepOutput, unknown, unknown, InngestEngineType>;\n\n/**\n * Creates a step from an agent (defaults to { text: string } output)\n */\nexport function createStep<\n TStepId extends string,\n TStepInput extends { prompt: string },\n TStepOutput extends { text: string },\n TResume,\n TSuspend,\n>(\n agent: Agent<TStepId, any>,\n agentOptions?: AgentStepOptions<TStepOutput> & {\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n },\n): Step<TStepId, unknown, TStepInput, TStepOutput, TResume, TSuspend, InngestEngineType>;\n\n/**\n * Creates a step from a tool\n */\nexport function createStep<\n TSchemaIn,\n TSchemaOut,\n TSuspend,\n TResume,\n TContext extends ToolExecutionContext<TSuspend, TResume, any> = ToolExecutionContext<TSuspend, TResume>,\n TId extends string = string,\n TRequestContext extends Record<string, any> | unknown = unknown,\n>(\n tool: Tool<TSchemaIn, TSchemaOut, TSuspend, TResume, TContext, TId, TRequestContext>,\n toolOptions?: { retries?: number; scorers?: DynamicArgument<MastraScorers>; metadata?: StepMetadata },\n): Step<TId, unknown, TSchemaIn, TSchemaOut, TSuspend, TResume, InngestEngineType>;\n\n/**\n * Creates a step from a Processor - wraps a Processor as a workflow step\n * Note: We require at least one processor method to distinguish from StepParams\n */\nexport function createStep<TProcessorId extends string>(\n processor:\n | (Processor<TProcessorId> & { processInput: Function })\n | (Processor<TProcessorId> & { processInputStream: Function })\n | (Processor<TProcessorId> & { processInputStep: Function })\n | (Processor<TProcessorId> & { processOutputStream: Function })\n | (Processor<TProcessorId> & { processOutputResult: Function })\n | (Processor<TProcessorId> & { processOutputStep: Function }),\n): Step<\n `processor:${TProcessorId}`,\n unknown,\n InferPublicSchema<typeof ProcessorStepInputSchema>,\n InferPublicSchema<typeof ProcessorStepOutputSchema>,\n unknown,\n unknown,\n InngestEngineType\n>;\n\n/**\n * IMPORTANT: Fallback overload - provides better error messages when StepParams doesn't match\n * This should be LAST and will show clearer errors about what's wrong\n * This is a copy of first one, KEEP THIS IN SYNC!\n */\nexport function createStep<\n TStepId extends string,\n TStateSchema extends PublicSchema | undefined,\n TInputSchema extends PublicSchema,\n TOutputSchema extends PublicSchema,\n TResumeSchema extends PublicSchema | undefined = undefined,\n TSuspendSchema extends PublicSchema | undefined = undefined,\n>(\n params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>,\n): Step<\n TStepId,\n TStateSchema extends PublicSchema ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n>;\n\n// ============================================\n// Implementation (uses type guards for clean logic)\n// ============================================\n\nexport function createStep(params: any, agentOrToolOptions?: any): Step<any, any, any, any, any, any, any> {\n // Type assertions are needed because each branch returns a different Step type,\n // but the overloads ensure type safety for consumers\n\n // Issue #9965: Preserve InngestWorkflow identity when passed to createStep\n // This ensures nested workflows in foreach are properly detected by isNestedWorkflowStep()\n if (isInngestWorkflow(params)) {\n return params;\n }\n\n if (isAgent(params)) {\n return createStepFromAgent(params, agentOrToolOptions);\n }\n\n if (isToolStep(params)) {\n return createStepFromTool(params, agentOrToolOptions);\n }\n\n // StepParams check must come before isProcessor since both have 'id'\n // StepParams always has 'execute', while Processor has processor methods\n if (isStepParams(params)) {\n return createStepFromParams(params);\n }\n\n if (isProcessor(params)) {\n return createStepFromProcessor(params);\n }\n\n throw new Error('Invalid input: expected StepParams, Agent, ToolStep, Processor, or InngestWorkflow');\n}\n\n// ============================================\n// Internal Implementations\n// ============================================\n\nfunction createStepFromParams<\n TStepId extends string,\n TStateSchema extends PublicSchema<any> | undefined,\n TInputSchema extends PublicSchema<any>,\n TOutputSchema extends PublicSchema<any>,\n TResumeSchema extends PublicSchema<any> | undefined = undefined,\n TSuspendSchema extends PublicSchema<any> | undefined = undefined,\n>(\n params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>,\n): Step<\n TStepId,\n TStateSchema extends PublicSchema<any> ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema<any> ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema<any> ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n> {\n // Type assertion needed because toStandardSchema returns StandardSchemaWithJSON<unknown>\n // but we need it to match the inferred generic types. The public overloads ensure\n // type safety for consumers.\n return {\n id: params.id,\n description: params.description,\n inputSchema: toStandardSchema(params.inputSchema),\n stateSchema: params.stateSchema ? toStandardSchema(params.stateSchema) : undefined,\n outputSchema: toStandardSchema(params.outputSchema),\n resumeSchema: params.resumeSchema ? toStandardSchema(params.resumeSchema) : undefined,\n suspendSchema: params.suspendSchema ? toStandardSchema(params.suspendSchema) : undefined,\n scorers: params.scorers,\n retries: params.retries,\n metadata: params.metadata,\n execute: params.execute.bind(params) as Step<\n TStepId,\n TStateSchema extends PublicSchema<any> ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema<any> ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema<any> ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n >['execute'],\n };\n}\n\nfunction createStepFromAgent<TStepId extends string, TStepOutput>(\n params: Agent<TStepId, any>,\n agentOrToolOptions?: Record<string, unknown>,\n): Step<TStepId, any, any, TStepOutput, unknown, unknown, InngestEngineType> {\n const options = (agentOrToolOptions ?? {}) as\n | (AgentStepOptions<TStepOutput> & {\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n metadata?: StepMetadata;\n })\n | undefined;\n // Determine output schema based on structuredOutput option\n const outputSchema = (options?.structuredOutput?.schema ??\n z.object({ text: z.string() })) as unknown as PublicSchema<TStepOutput>;\n const { retries, scorers, metadata, ...agentOptions } =\n options ??\n ({} as AgentStepOptions<TStepOutput> & {\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n metadata?: StepMetadata;\n });\n\n return {\n id: params.name as TStepId,\n description: params.getDescription(),\n inputSchema: toStandardSchema(\n z.object({\n prompt: z.string(),\n }),\n ),\n outputSchema: toStandardSchema(outputSchema),\n retries,\n scorers,\n metadata,\n execute: async ({\n inputData,\n runId,\n [PUBSUB_SYMBOL]: pubsub,\n [STREAM_FORMAT_SYMBOL]: streamFormat,\n requestContext,\n tracingContext,\n abortSignal,\n abort,\n writer,\n }) => {\n let streamPromise = {} as {\n promise: Promise<string>;\n resolve: (value: string) => void;\n reject: (reason?: any) => void;\n };\n\n streamPromise.promise = new Promise((resolve, reject) => {\n streamPromise.resolve = resolve;\n streamPromise.reject = reject;\n });\n\n // Track structured output result\n let structuredResult: any = null;\n\n const toolData = {\n name: params.name,\n args: inputData,\n };\n\n let stream: ReadableStream<any>;\n\n if ((await params.getModel()).specificationVersion === 'v1') {\n const { fullStream } = await params.streamLegacy((inputData as { prompt: string }).prompt, {\n ...(agentOptions ?? {}),\n requestContext,\n tracingContext,\n onFinish: result => {\n // Capture structured output if available\n const resultWithObject = result as typeof result & { object?: unknown };\n if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {\n structuredResult = resultWithObject.object;\n }\n streamPromise.resolve(result.text);\n void agentOptions?.onFinish?.(result);\n },\n abortSignal,\n });\n stream = fullStream as any;\n } else {\n const { structuredOutput, ...restAgentOptions } = agentOptions ?? {};\n const baseOptions = {\n ...restAgentOptions,\n requestContext,\n tracingContext,\n onFinish: (result: any) => {\n // Capture structured output if available\n const resultWithObject = result as typeof result & { object?: unknown };\n if (structuredOutput?.schema && resultWithObject.object) {\n structuredResult = resultWithObject.object;\n }\n streamPromise.resolve(result.text);\n void agentOptions?.onFinish?.(result);\n },\n abortSignal,\n };\n\n const modelOutput = structuredOutput\n ? await params.stream<any>((inputData as { prompt: string }).prompt, {\n ...baseOptions,\n structuredOutput,\n } as any)\n : await params.stream<any>((inputData as { prompt: string }).prompt, baseOptions as any);\n\n stream = modelOutput.fullStream;\n }\n\n if (streamFormat === 'legacy') {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: { type: 'tool-call-streaming-start', ...(toolData ?? {}) },\n });\n for await (const chunk of stream) {\n if (chunk.type === 'text-delta') {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: { type: 'tool-call-delta', ...(toolData ?? {}), argsTextDelta: chunk.textDelta },\n });\n }\n }\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: { type: 'tool-call-streaming-finish', ...(toolData ?? {}) },\n });\n } else {\n for await (const chunk of stream) {\n await writer.write(chunk as any);\n }\n }\n\n if (abortSignal.aborted) {\n return abort() as TStepOutput;\n }\n\n // Return structured output if available, otherwise default text\n if (structuredResult !== null) {\n return structuredResult;\n }\n return {\n text: await streamPromise.promise,\n } as TStepOutput;\n },\n component: params.component,\n };\n}\n\nfunction createStepFromTool<TStepInput, TSuspend, TResume, TStepOutput>(\n params: ToolStep<TStepInput, TSuspend, TResume, TStepOutput, any>,\n agentOrToolOptions?: Record<string, unknown>,\n): Step<string, any, TStepInput, TStepOutput, TResume, TSuspend, InngestEngineType> {\n const toolOpts = agentOrToolOptions as\n | { retries?: number; scorers?: DynamicArgument<MastraScorers>; metadata?: StepMetadata }\n | undefined;\n if (!params.inputSchema || !params.outputSchema) {\n throw new Error('Tool must have input and output schemas defined');\n }\n\n return {\n id: params.id,\n description: params.description,\n inputSchema: params.inputSchema,\n outputSchema: params.outputSchema,\n resumeSchema: params.resumeSchema,\n suspendSchema: params.suspendSchema,\n retries: toolOpts?.retries,\n scorers: toolOpts?.scorers,\n metadata: toolOpts?.metadata,\n execute: async ({\n inputData,\n mastra,\n requestContext,\n tracingContext,\n suspend,\n resumeData,\n runId,\n workflowId,\n state,\n setState,\n }) => {\n // BREAKING CHANGE v1.0: Pass raw input as first arg, context as second\n const toolContext = {\n mastra,\n requestContext,\n tracingContext,\n workflow: {\n runId,\n resumeData,\n suspend,\n workflowId,\n state,\n setState,\n },\n };\n return params.execute(inputData, toolContext) as TStepOutput;\n },\n component: 'TOOL',\n };\n}\n\nfunction createStepFromProcessor<TProcessorId extends string>(\n processor: Processor<TProcessorId>,\n): Step<`processor:${TProcessorId}`, unknown, any, any, unknown, unknown, InngestEngineType> {\n // Helper to map phase to entity type\n const getProcessorEntityType = (phase: string): EntityType => {\n switch (phase) {\n case 'input':\n return EntityType.INPUT_PROCESSOR;\n case 'inputStep':\n return EntityType.INPUT_STEP_PROCESSOR;\n case 'outputStream':\n case 'outputResult':\n return EntityType.OUTPUT_PROCESSOR;\n case 'outputStep':\n return EntityType.OUTPUT_STEP_PROCESSOR;\n default:\n return EntityType.OUTPUT_PROCESSOR;\n }\n };\n\n // Helper to get span name prefix\n const getSpanNamePrefix = (phase: string): string => {\n switch (phase) {\n case 'input':\n return 'input processor';\n case 'inputStep':\n return 'input step processor';\n case 'outputStream':\n return 'output stream processor';\n case 'outputResult':\n return 'output processor';\n case 'outputStep':\n return 'output step processor';\n default:\n return 'processor';\n }\n };\n\n // Helper to check if processor implements a phase\n const hasPhaseMethod = (phase: string): boolean => {\n switch (phase) {\n case 'input':\n return !!processor.processInput;\n case 'inputStep':\n return !!processor.processInputStep;\n case 'outputStream':\n return !!processor.processOutputStream;\n case 'outputResult':\n return !!processor.processOutputResult;\n case 'outputStep':\n return !!processor.processOutputStep;\n default:\n return false;\n }\n };\n\n return {\n id: `processor:${processor.id}`,\n description: processor.name ?? `Processor ${processor.id}`,\n inputSchema: ProcessorStepSchema,\n outputSchema: ProcessorStepOutputSchema,\n execute: async ({ inputData, requestContext, tracingContext }) => {\n // Cast to output type for easier property access - the discriminated union\n // ensures type safety at the schema level, but inside the execute function\n // we need access to all possible properties\n const input = inputData as ProcessorStepOutput;\n const {\n phase,\n messages,\n messageList,\n stepNumber,\n systemMessages,\n part,\n streamParts,\n state,\n result,\n finishReason,\n toolCalls,\n text,\n retryCount,\n // inputStep phase fields for model/tools configuration\n model,\n tools,\n toolChoice,\n activeTools,\n providerOptions,\n modelSettings,\n structuredOutput,\n steps,\n usage,\n } = input;\n\n // Create a minimal abort function that throws TripWire\n const abort = (reason?: string, options?: { retry?: boolean; metadata?: unknown }): never => {\n throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n };\n\n // Early return if processor doesn't implement this phase - no span created\n // This prevents empty spans for phases the processor doesn't handle\n if (!hasPhaseMethod(phase)) {\n return input;\n }\n\n // Create processor span for non-stream phases\n // outputStream phase doesn't need its own span (stream chunks are already tracked)\n const currentSpan = tracingContext?.currentSpan;\n\n // Find appropriate parent span:\n // - For input/outputResult: find AGENT_RUN (processor runs once at start/end)\n // - For inputStep/outputStep: find MODEL_STEP (processor runs per LLM call)\n // When workflow is executed, currentSpan is WORKFLOW_STEP, so we walk up the parent chain\n const parentSpan =\n phase === 'inputStep' || phase === 'outputStep'\n ? currentSpan?.findParent(SpanType.MODEL_STEP) || currentSpan\n : currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan;\n\n const processorSpan =\n phase !== 'outputStream'\n ? parentSpan?.createChildSpan({\n type: SpanType.PROCESSOR_RUN,\n name: `${getSpanNamePrefix(phase)}: ${processor.id}`,\n entityType: getProcessorEntityType(phase),\n entityId: processor.id,\n entityName: processor.name ?? processor.id,\n input: { phase, messageCount: messages?.length },\n attributes: {\n processorExecutor: 'workflow',\n // Read processorIndex from processor (set in combineProcessorsIntoWorkflow)\n processorIndex: processor.processorIndex,\n },\n })\n : undefined;\n\n // Create tracing context with processor span so internal agent calls nest correctly\n const processorTracingContext: TracingContext | undefined = processorSpan\n ? { currentSpan: processorSpan }\n : tracingContext;\n\n // Base context for all processor methods - includes requestContext for memory processors\n // and tracingContext for proper span nesting when processors call internal agents\n const baseContext = {\n abort,\n retryCount: retryCount ?? 0,\n requestContext,\n tracingContext: processorTracingContext,\n };\n\n // Pass-through data that should flow to the next processor in a chain\n // This enables processor workflows to use .then(), .parallel(), .branch(), etc.\n const passThrough = {\n phase,\n // Auto-create MessageList from messages if not provided\n // This enables running processor workflows from the UI where messageList can't be serialized\n messageList:\n messageList ??\n (Array.isArray(messages)\n ? new MessageList()\n .add(messages as MastraDBMessage[], 'input')\n .addSystem((systemMessages ?? []) as CoreMessage[])\n : undefined),\n stepNumber,\n systemMessages,\n streamParts,\n state,\n result,\n finishReason,\n toolCalls,\n text,\n retryCount,\n // inputStep phase fields for model/tools configuration\n model,\n tools,\n toolChoice,\n activeTools,\n providerOptions,\n modelSettings,\n structuredOutput,\n steps,\n usage,\n };\n\n // Helper to execute phase with proper span lifecycle management\n const executePhaseWithSpan = async <T>(fn: () => Promise<T>): Promise<T> => {\n try {\n const result = await fn();\n processorSpan?.end({ output: result });\n return result;\n } catch (error) {\n // TripWire errors should end span but bubble up to halt the workflow\n if (error instanceof TripWire) {\n processorSpan?.end({ output: { tripwire: error.message } });\n } else {\n processorSpan?.error({ error: error as Error, endSpan: true });\n }\n throw error;\n }\n };\n\n // Execute the phase with span lifecycle management\n return executePhaseWithSpan(async () => {\n switch (phase) {\n case 'input': {\n if (processor.processInput) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processInput phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const result = await processor.processInput({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n systemMessages: (systemMessages ?? []) as CoreMessage[],\n state: {},\n });\n\n if (result instanceof MessageList) {\n // Validate same instance\n if (result !== passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`,\n });\n }\n return {\n ...passThrough,\n messages: result.get.all.db(),\n systemMessages: result.getAllSystemMessages(),\n };\n } else if (Array.isArray(result)) {\n // Processor returned an array of messages\n ProcessorRunner.applyMessagesToMessageList(\n result as MastraDBMessage[],\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'input',\n );\n return { ...passThrough, messages: result };\n } else if (result && 'messages' in result && 'systemMessages' in result) {\n // Processor returned { messages, systemMessages }\n const typedResult = result as { messages: MastraDBMessage[]; systemMessages: CoreMessage[] };\n ProcessorRunner.applyMessagesToMessageList(\n typedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'input',\n );\n passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);\n return {\n ...passThrough,\n messages: typedResult.messages,\n systemMessages: typedResult.systemMessages,\n };\n }\n return { ...passThrough, messages };\n }\n return { ...passThrough, messages };\n }\n\n case 'inputStep': {\n if (processor.processInputStep) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processInputStep phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const result = await processor.processInputStep({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n stepNumber: stepNumber ?? 0,\n systemMessages: (systemMessages ?? []) as CoreMessage[],\n // Pass model/tools configuration fields - types match ProcessInputStepArgs\n model: model!,\n tools,\n toolChoice,\n activeTools,\n providerOptions,\n modelSettings,\n structuredOutput,\n steps: steps ?? [],\n state: {},\n });\n\n const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {\n messageList: passThrough.messageList,\n processor,\n stepNumber: stepNumber ?? 0,\n });\n\n if (validatedResult.messages) {\n ProcessorRunner.applyMessagesToMessageList(\n validatedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n );\n }\n\n if (validatedResult.systemMessages) {\n passThrough.messageList!.replaceAllSystemMessages(validatedResult.systemMessages as CoreMessage[]);\n }\n\n // Preserve messages in return - passThrough doesn't include messages,\n // so we must explicitly include it to avoid losing it for subsequent steps\n return { ...passThrough, messages, ...validatedResult };\n }\n return { ...passThrough, messages };\n }\n\n case 'outputStream': {\n if (processor.processOutputStream) {\n // Manage per-processor span lifecycle across stream chunks\n // Use unique key to store span on shared state object\n const spanKey = `__outputStreamSpan_${processor.id}`;\n const mutableState = (state ?? {}) as Record<string, unknown>;\n let processorSpan = mutableState[spanKey] as\n | ReturnType<NonNullable<typeof parentSpan>['createChildSpan']>\n | undefined;\n\n if (!processorSpan && parentSpan) {\n // First chunk - create span for this processor\n processorSpan = parentSpan.createChildSpan({\n type: SpanType.PROCESSOR_RUN,\n name: `output stream processor: ${processor.id}`,\n entityType: EntityType.OUTPUT_PROCESSOR,\n entityId: processor.id,\n entityName: processor.name ?? processor.id,\n input: { phase, streamParts: [] },\n attributes: {\n processorExecutor: 'workflow',\n processorIndex: processor.processorIndex,\n },\n });\n mutableState[spanKey] = processorSpan;\n }\n\n // Update span with current chunk data\n if (processorSpan) {\n processorSpan.input = {\n phase,\n streamParts: streamParts ?? [],\n totalChunks: (streamParts ?? []).length,\n };\n }\n\n // Create tracing context with processor span for internal agent calls\n const processorTracingContext = processorSpan\n ? { currentSpan: processorSpan }\n : baseContext.tracingContext;\n\n // Handle outputStream span lifecycle explicitly (not via executePhaseWithSpan)\n // because outputStream uses a per-processor span stored in mutableState\n let result: ChunkType | null | undefined;\n try {\n result = await processor.processOutputStream({\n ...baseContext,\n tracingContext: processorTracingContext,\n part: part as ChunkType,\n streamParts: (streamParts ?? []) as ChunkType[],\n state: mutableState,\n messageList: passThrough.messageList, // Optional for stream processing\n });\n\n // End span on finish chunk\n if (part && (part as ChunkType).type === 'finish') {\n processorSpan?.end({ output: result });\n delete mutableState[spanKey];\n }\n } catch (error) {\n // End span with error and clean up state\n if (error instanceof TripWire) {\n processorSpan?.end({ output: { tripwire: error.message } });\n } else {\n processorSpan?.error({ error: error as Error, endSpan: true });\n }\n delete mutableState[spanKey];\n throw error;\n }\n\n return { ...passThrough, state: mutableState, part: result };\n }\n return { ...passThrough, part };\n }\n\n case 'outputResult': {\n if (processor.processOutputResult) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processOutputResult phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const outputResult = (passThrough.result as OutputResult | undefined) ?? {\n text: '',\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n };\n\n const processResult = await processor.processOutputResult({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n state: passThrough.state ?? {},\n result: outputResult,\n });\n\n if (processResult instanceof MessageList) {\n // Validate same instance\n if (processResult !== passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`,\n });\n }\n return {\n ...passThrough,\n messages: processResult.get.all.db(),\n systemMessages: processResult.getAllSystemMessages(),\n };\n } else if (Array.isArray(processResult)) {\n // Processor returned an array of messages\n ProcessorRunner.applyMessagesToMessageList(\n processResult as MastraDBMessage[],\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n return { ...passThrough, messages: processResult };\n } else if (processResult && 'messages' in processResult && 'systemMessages' in processResult) {\n // Processor returned { messages, systemMessages }\n const typedResult = processResult as { messages: MastraDBMessage[]; systemMessages: CoreMessage[] };\n ProcessorRunner.applyMessagesToMessageList(\n typedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);\n return {\n ...passThrough,\n messages: typedResult.messages,\n systemMessages: typedResult.systemMessages,\n };\n }\n return { ...passThrough, messages };\n }\n return { ...passThrough, messages };\n }\n\n case 'outputStep': {\n if (processor.processOutputStep) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processOutputStep phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const defaultUsage: LanguageModelUsage = {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n const result = await processor.processOutputStep({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n stepNumber: stepNumber ?? 0,\n finishReason,\n toolCalls: toolCalls as any,\n text,\n usage: (usage as LanguageModelUsage) ?? defaultUsage,\n systemMessages: (systemMessages ?? []) as CoreMessage[],\n steps: steps ?? [],\n state: {},\n });\n\n if (result instanceof MessageList) {\n // Validate same instance\n if (result !== passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`,\n });\n }\n return {\n ...passThrough,\n messages: result.get.all.db(),\n systemMessages: result.getAllSystemMessages(),\n };\n } else if (Array.isArray(result)) {\n // Processor returned an array of messages\n ProcessorRunner.applyMessagesToMessageList(\n result as MastraDBMessage[],\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n return { ...passThrough, messages: result };\n } else if (result && 'messages' in result && 'systemMessages' in result) {\n // Processor returned { messages, systemMessages }\n const typedResult = result as { messages: MastraDBMessage[]; systemMessages: CoreMessage[] };\n ProcessorRunner.applyMessagesToMessageList(\n typedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);\n return {\n ...passThrough,\n messages: typedResult.messages,\n systemMessages: typedResult.systemMessages,\n };\n }\n return { ...passThrough, messages };\n }\n return { ...passThrough, messages };\n }\n\n default:\n return { ...passThrough, messages };\n }\n });\n },\n component: 'PROCESSOR',\n };\n}\n\nexport function init(inngest: Inngest) {\n return {\n createTool,\n createWorkflow<\n TWorkflowId extends string = string,\n TState = any,\n TInput = any,\n TOutput = any,\n TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[] = Step<\n string,\n any,\n any,\n any,\n any,\n any,\n InngestEngineType\n >[],\n >(params: InngestWorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps>) {\n return new InngestWorkflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TInput>(\n params,\n inngest,\n );\n },\n createStep,\n cloneStep<TStepId extends string>(\n step: Step<TStepId, any, any, any, any, any, InngestEngineType>,\n opts: { id: TStepId },\n ): Step<TStepId, any, any, any, any, any, InngestEngineType> {\n return {\n id: opts.id,\n description: step.description,\n inputSchema: step.inputSchema,\n outputSchema: step.outputSchema,\n resumeSchema: step.resumeSchema,\n suspendSchema: step.suspendSchema,\n stateSchema: step.stateSchema,\n metadata: step.metadata,\n execute: step.execute,\n retries: step.retries,\n scorers: step.scorers,\n component: step.component,\n };\n },\n cloneWorkflow<\n TWorkflowId extends string = string,\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[] = Step<\n string,\n any,\n any,\n any,\n any,\n any,\n InngestEngineType\n >[],\n TPrev = TInput,\n >(\n workflow: Workflow<InngestEngineType, TSteps, string, TState, TInput, TOutput, TPrev>,\n opts: { id: TWorkflowId },\n ): Workflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrev> {\n const wf: Workflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrev> = new Workflow({\n id: opts.id,\n inputSchema: workflow.inputSchema,\n outputSchema: workflow.outputSchema,\n steps: workflow.stepDefs,\n mastra: workflow.mastra,\n options: workflow.options,\n });\n\n wf.setStepFlow(workflow.stepGraph);\n wf.commit();\n return wf;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/execution-engine.ts","../src/pubsub.ts","../src/run.ts","../src/workflow.ts","../src/serve.ts","../src/types.ts","../src/durable-agent/create-inngest-agentic-workflow.ts","../src/durable-agent/create-inngest-agent.ts","../src/index.ts"],"names":["otelContext","subscribe","getErrorFromUnknown","createTimeTravelExecutionParams","randomUUID","NonRetriableError","inngestServeHono","SpanType","EntityType","emitErrorEvent","z","PUBSUB_SYMBOL","result","processorSpan","processorTracingContext","Workflow"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBO,IAAM,sBAAA,GAAN,cAAqC,sBAAA,CAAuB;AAAA,EACzD,WAAA;AAAA,EACA,eAAA;AAAA,EAER,WAAA,CACE,MAAA,EACA,WAAA,EACA,eAAA,GAA0B,GAC1B,OAAA,EACA;AACA,IAAA,KAAA,CAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,CAAA;AACzB,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AACnB,IAAA,IAAA,CAAK,eAAA,GAAkB,eAAA;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUU,iBAAA,CACR,OACA,UAAA,EACiB;AACjB,IAAA,MAAM,cAAe,UAAA,EAAgD,KAAA;AACrE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cesContent":["import { randomUUID } from 'node:crypto';\nimport type { RequestContext } from '@mastra/core/di';\nimport { getErrorFromUnknown } from '@mastra/core/error';\nimport type { SerializedError } from '@mastra/core/error';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { EntityType } from '@mastra/core/observability';\nimport { DefaultExecutionEngine, createTimeTravelExecutionParams } from '@mastra/core/workflows';\nimport type {\n ExecutionContext,\n Step,\n StepResult,\n StepFailure,\n ExecutionEngineOptions,\n TimeTravelExecutionParams,\n WorkflowResult,\n} from '@mastra/core/workflows';\nimport type { Inngest, BaseContext } from 'inngest';\nimport { InngestWorkflow } from './workflow';\n\nexport class InngestExecutionEngine extends DefaultExecutionEngine {\n private inngestStep: BaseContext<Inngest>['step'];\n private inngestAttempts: number;\n\n constructor(\n mastra: Mastra,\n inngestStep: BaseContext<Inngest>['step'],\n inngestAttempts: number = 0,\n options: ExecutionEngineOptions,\n ) {\n super({ mastra, options });\n this.inngestStep = inngestStep;\n this.inngestAttempts = inngestAttempts;\n }\n\n // =============================================================================\n // Hook Overrides\n // =============================================================================\n\n /**\n * Format errors while preserving Error instances and their custom properties.\n * Uses getErrorFromUnknown to ensure all error properties are preserved.\n */\n protected formatResultError(\n error: Error | string | undefined,\n lastOutput: StepResult<any, any, any, any>,\n ): SerializedError {\n const outputError = (lastOutput as StepFailure<any, any, any, any>)?.error;\n const errorSource = error || outputError;\n const errorInstance = getErrorFromUnknown(errorSource, {\n serializeStack: true, // Include stack in JSON for better debugging in Inngest\n fallbackMessage: 'Unknown workflow error',\n });\n return errorInstance.toJSON();\n }\n\n /**\n * Detect InngestWorkflow instances for special nested workflow handling\n */\n isNestedWorkflowStep(step: Step<any, any, any>): boolean {\n return step instanceof InngestWorkflow;\n }\n\n /**\n * Inngest requires requestContext serialization for memoization.\n * When steps are replayed, the original function doesn't re-execute,\n * so requestContext modifications must be captured and restored.\n */\n requiresDurableContextSerialization(): boolean {\n return true;\n }\n\n /**\n * Execute a step with retry logic for Inngest.\n * Retries are handled via step-level retry (RetryAfterError thrown INSIDE step.run()).\n * After retries exhausted, error propagates here and we return a failed result.\n */\n async executeStepWithRetry<T>(\n stepId: string,\n runStep: () => Promise<T>,\n params: {\n retries: number;\n delay: number;\n stepSpan?: any;\n workflowId: string;\n runId: string;\n },\n ): Promise<{ ok: true; result: T } | { ok: false; error: { status: 'failed'; error: Error; endedAt: number } }> {\n for (let i = 0; i < params.retries + 1; i++) {\n if (i > 0 && params.delay) {\n await new Promise(resolve => setTimeout(resolve, params.delay));\n }\n try {\n //removed retry config with RetryAfterError from wrapDurableOperation, since we're manually handling retries here\n const result = await this.wrapDurableOperation(stepId, runStep);\n return { ok: true, result };\n } catch (e) {\n if (i === params.retries) {\n // After step-level retries exhausted, extract failure from error cause\n const cause = (e as any)?.cause;\n if (cause?.status === 'failed') {\n params.stepSpan?.error({\n error: e,\n attributes: { status: 'failed' },\n });\n // Ensure cause.error is an Error instance\n if (cause.error && !(cause.error instanceof Error)) {\n cause.error = getErrorFromUnknown(cause.error, { serializeStack: false });\n }\n return { ok: false, error: cause };\n }\n\n // Fallback for other errors - preserve the original error instance\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n params.stepSpan?.error({\n error: errorInstance,\n attributes: { status: 'failed' },\n });\n return {\n ok: false,\n error: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n },\n };\n }\n }\n }\n // Should never reach here, but TypeScript needs it\n return { ok: false, error: { status: 'failed', error: new Error('Unknown error'), endedAt: Date.now() } };\n }\n\n /**\n * Use Inngest's sleep primitive for durability\n */\n async executeSleepDuration(duration: number, sleepId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleep(`workflow.${workflowId}.sleep.${sleepId}`, duration < 0 ? 0 : duration);\n }\n\n /**\n * Use Inngest's sleepUntil primitive for durability\n */\n async executeSleepUntilDate(date: Date, sleepUntilId: string, workflowId: string): Promise<void> {\n await this.inngestStep.sleepUntil(`workflow.${workflowId}.sleepUntil.${sleepUntilId}`, date);\n }\n\n /**\n * Wrap durable operations in Inngest step.run() for durability.\n *\n * IMPORTANT: Errors are wrapped with a cause structure before throwing.\n * This is necessary because Inngest's error serialization (serialize-error-cjs)\n * only captures standard Error properties (message, name, stack, code, cause).\n * Custom properties like statusCode, responseHeaders from AI SDK errors would\n * be lost. By putting our serialized error (via getErrorFromUnknown with toJSON())\n * in the cause property, we ensure custom properties survive serialization.\n * The cause property is in serialize-error-cjs's allowlist, and when the cause\n * object is finally JSON.stringify'd, our error's toJSON() is called.\n */\n async wrapDurableOperation<T>(operationId: string, operationFn: () => Promise<T>): Promise<T> {\n const result = await this.inngestStep.run(operationId, async () => {\n try {\n const fnResult = await operationFn();\n return fnResult;\n } catch (e) {\n const errorInstance = getErrorFromUnknown(e, {\n serializeStack: false,\n fallbackMessage: 'Unknown step execution error',\n });\n throw new Error(errorInstance.message, {\n cause: {\n status: 'failed',\n error: errorInstance,\n endedAt: Date.now(),\n },\n });\n }\n });\n return result as T;\n }\n\n /**\n * Provide Inngest step primitive in engine context\n */\n getEngineContext(): Record<string, any> {\n return { step: this.inngestStep };\n }\n\n /**\n * For Inngest, lifecycle callbacks are invoked in the workflow's finalize step\n * (wrapped in step.run for durability), not in execute(). Override to skip.\n */\n public async invokeLifecycleCallbacks(_result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n // No-op: Inngest handles callbacks in workflow.ts finalize step\n }\n\n /**\n * Actually invoke the lifecycle callbacks. Called from workflow.ts finalize step.\n */\n public async invokeLifecycleCallbacksInternal(result: {\n status: any;\n result?: any;\n error?: any;\n steps: Record<string, any>;\n tripwire?: any;\n runId: string;\n workflowId: string;\n resourceId?: string;\n input?: any;\n requestContext: RequestContext;\n state: Record<string, any>;\n }): Promise<void> {\n return super.invokeLifecycleCallbacks(result);\n }\n\n // =============================================================================\n // Durable Span Lifecycle Hooks\n // =============================================================================\n\n /**\n * Create a step span durably - on first execution, creates and exports span.\n * On replay, returns cached span data without re-creating.\n */\n async createStepSpan(params: {\n parentSpan: any;\n stepId: string;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n entityType?: string;\n entityId?: string;\n tracingPolicy?: any;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided (e.g., for steps inside control-flow),\n // otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n entityType: options.entityType as EntityType | undefined,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a step span durably.\n */\n async endStepSpan(params: {\n span: any;\n operationId: string;\n endOptions: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on step span durably.\n */\n async errorStepSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Create a generic child span durably (for control-flow operations).\n * On first execution, creates and exports span. On replay, returns cached span data.\n */\n async createChildSpan(params: {\n parentSpan: any;\n operationId: string;\n options: {\n name: string;\n type: any;\n input?: unknown;\n attributes?: Record<string, unknown>;\n };\n executionContext: ExecutionContext;\n }): Promise<any> {\n const { executionContext, operationId, options, parentSpan } = params;\n\n // Use the actual parent span's ID if provided, otherwise fall back to workflow span\n const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;\n\n // Use wrapDurableOperation to memoize span creation\n const exportedSpan = await this.wrapDurableOperation(operationId, async () => {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n if (!observability) return undefined;\n\n // Create span using tracingIds for traceId, and actual parent span for parentSpanId\n const span = observability.startSpan({\n ...options,\n traceId: executionContext.tracingIds?.traceId,\n parentSpanId,\n tracingPolicy: this.options?.tracingPolicy,\n });\n\n // Return serializable form\n return span?.exportSpan();\n });\n\n // Return a rebuilt span that can have .end()/.error() called later\n if (exportedSpan) {\n const observability = this.mastra?.observability?.getSelectedInstance({});\n return observability?.rebuildSpan(exportedSpan);\n }\n\n return undefined;\n }\n\n /**\n * End a generic child span durably (for control-flow operations).\n */\n async endChildSpan(params: {\n span: any;\n operationId: string;\n endOptions?: {\n output?: unknown;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, endOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.end(endOptions);\n });\n }\n\n /**\n * Record error on a generic child span durably (for control-flow operations).\n */\n async errorChildSpan(params: {\n span: any;\n operationId: string;\n errorOptions: {\n error: Error;\n attributes?: Record<string, unknown>;\n };\n }): Promise<void> {\n const { span, operationId, errorOptions } = params;\n if (!span) return;\n\n await this.wrapDurableOperation(operationId, async () => {\n span.error(errorOptions);\n });\n }\n\n /**\n * Execute nested InngestWorkflow using inngestStep.invoke() for durability.\n * This MUST be called directly (not inside step.run()) due to Inngest constraints.\n */\n async executeWorkflowStep(params: {\n step: Step<string, any, any>;\n stepResults: Record<string, StepResult<any, any, any, any>>;\n executionContext: ExecutionContext;\n resume?: {\n steps: string[];\n resumePayload: any;\n runId?: string;\n };\n timeTravel?: TimeTravelExecutionParams;\n prevOutput: any;\n inputData: any;\n pubsub: PubSub;\n startedAt: number;\n perStep?: boolean;\n stepSpan?: any;\n }): 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 } = params;\n\n // Build trace context to propagate to nested workflow\n const nestedTracingContext = executionContext.tracingIds?.traceId\n ? {\n traceId: executionContext.tracingIds.traceId,\n parentSpanId: stepSpan?.id,\n }\n : undefined;\n\n const isResume = !!resume?.steps?.length;\n let result: WorkflowResult<any, any, any, any>;\n let runId: string;\n\n const isTimeTravel = !!(timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === step.id);\n\n try {\n if (isResume) {\n runId = stepResults[resume?.steps?.[0] ?? '']?.suspendPayload?.__workflow_meta?.runId ?? randomUUID();\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: runId,\n });\n\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n initialState: executionContext.state ?? snapshot?.value ?? {},\n runId: runId,\n resume: {\n runId: runId,\n steps: resume.steps.slice(1),\n stepResults: snapshot?.context as any,\n resumePayload: resume.resumePayload,\n resumePath: resume.steps?.[1] ? (snapshot?.suspendedPaths?.[resume.steps?.[1]] as any) : undefined,\n },\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else if (isTimeTravel) {\n const workflowsStoreForTimeTravel = await this.mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = (await workflowsStoreForTimeTravel?.loadWorkflowSnapshot({\n workflowName: step.id,\n runId: executionContext.runId,\n })) ?? { context: {} };\n const timeTravelParams = createTimeTravelExecutionParams({\n steps: timeTravel.steps.slice(1),\n inputData: timeTravel.inputData,\n resumeData: timeTravel.resumeData,\n context: (timeTravel.nestedStepResults?.[step.id] ?? {}) as any,\n nestedStepsContext: (timeTravel.nestedStepResults ?? {}) as any,\n snapshot,\n graph: step.buildExecutionGraph(),\n });\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n timeTravel: timeTravelParams,\n initialState: executionContext.state ?? {},\n runId: executionContext.runId,\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n } else {\n const invokeResp = (await this.inngestStep.invoke(`workflow.${executionContext.workflowId}.step.${step.id}`, {\n function: step.getFunction(),\n data: {\n inputData,\n initialState: executionContext.state ?? {},\n outputOptions: { includeState: true },\n perStep,\n tracingOptions: nestedTracingContext,\n },\n })) as any;\n result = invokeResp.result;\n runId = invokeResp.runId;\n executionContext.state = invokeResp.result.state;\n }\n } catch (e) {\n // Nested workflow threw an error (likely from finalization step)\n // The error cause should contain the workflow result with runId\n const errorCause = (e as any)?.cause;\n\n // Try to extract runId from error cause or generate new one\n if (errorCause && typeof errorCause === 'object') {\n result = errorCause as WorkflowResult<any, any, any, any>;\n // The runId might be in the result's steps metadata\n runId = errorCause.runId || randomUUID();\n } else {\n // Fallback: if we can't get the result from error, construct a basic failed result\n runId = randomUUID();\n result = {\n status: 'failed',\n error: e instanceof Error ? e : new Error(String(e)),\n steps: {},\n input: inputData,\n } as WorkflowResult<any, any, any, any>;\n }\n }\n\n const res = await this.inngestStep.run(\n `workflow.${executionContext.workflowId}.step.${step.id}.nestedwf-results`,\n async () => {\n if (result.status === 'failed') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'failed',\n error: result?.error,\n payload: prevOutput,\n },\n },\n });\n\n return { executionContext, result: { status: 'failed', error: result?.error, endedAt: Date.now() } };\n } else if (result.status === 'suspended') {\n const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {\n const stepRes: StepResult<any, any, any, any> = stepResult as StepResult<any, any, any, any>;\n return stepRes?.status === 'suspended';\n });\n\n for (const [stepName, stepResult] of suspendedSteps) {\n const suspendPath: string[] = [stepName, ...(stepResult?.suspendPayload?.__workflow_meta?.path ?? [])];\n executionContext.suspendedPaths[step.id] = executionContext.executionPath;\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-suspended',\n payload: {\n id: step.id,\n status: 'suspended',\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: stepResult.payload,\n suspendPayload: {\n ...(stepResult as any)?.suspendPayload,\n __workflow_meta: { runId: runId, path: suspendPath },\n },\n },\n };\n }\n\n return {\n executionContext,\n result: {\n status: 'suspended',\n suspendedAt: Date.now(),\n payload: {},\n },\n };\n } else if (result.status === 'tripwire') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'tripwire',\n error: result?.tripwire?.reason,\n payload: prevOutput,\n },\n },\n });\n\n return {\n executionContext,\n result: {\n status: 'tripwire',\n tripwire: result?.tripwire,\n endedAt: Date.now(),\n },\n };\n } else if (perStep || result.status === 'paused') {\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'paused',\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n return { executionContext, result: { status: 'paused' } };\n }\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-result',\n payload: {\n id: step.id,\n status: 'success',\n output: result?.result,\n },\n },\n });\n\n await pubsub.publish(`workflow.events.v2.${executionContext.runId}`, {\n type: 'watch',\n runId: executionContext.runId,\n data: {\n type: 'workflow-step-finish',\n payload: {\n id: step.id,\n metadata: {},\n },\n },\n });\n\n return { executionContext, result: { status: 'success', output: result?.result, endedAt: Date.now() } };\n },\n );\n\n Object.assign(executionContext, res.executionContext);\n return {\n ...res.result,\n startedAt,\n payload: inputData,\n resumedAt: resume?.steps[0] === step.id ? startedAt : undefined,\n resumePayload: resume?.steps[0] === step.id ? resume?.resumePayload : undefined,\n } as StepResult<any, any, any, any>;\n }\n}\n","import { subscribe } from '@inngest/realtime';\nimport { PubSub } from '@mastra/core/events';\nimport type { Event } from '@mastra/core/events';\nimport type { Inngest } from 'inngest';\n\n/**\n * Type for Inngest's publish function, available inside Inngest function context.\n */\nexport type InngestPublishFn = (opts: { channel: string; topic: string; data: any }) => Promise<void>;\n\n/**\n * Parse a topic string and extract the runId and topic type.\n *\n * Supported formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * - \"agent.stream.{runId}\" - agent stream events\n *\n * @returns { runId, topicType } or null if not a recognized format\n */\nfunction parseTopic(topic: string): { runId: string; topicType: 'workflow' | 'agent' } | null {\n // Try workflow format first\n const workflowMatch = topic.match(/^workflow\\.events\\.v2\\.(.+)$/);\n if (workflowMatch && workflowMatch[1]) {\n return { runId: workflowMatch[1], topicType: 'workflow' };\n }\n\n // Try agent stream format\n const agentMatch = topic.match(/^agent\\.stream\\.(.+)$/);\n if (agentMatch && agentMatch[1]) {\n return { runId: agentMatch[1], topicType: 'agent' };\n }\n\n return null;\n}\n\n/**\n * PubSub implementation for Inngest workflows.\n *\n * This bridges the PubSub abstract class interface with Inngest's realtime system:\n * - publish() uses Inngest's publish function (only available in function context)\n * - subscribe() uses @inngest/realtime subscribe for real-time streaming\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * - \"agent.stream.{runId}\" - agent stream events (for InngestAgent)\n *\n * Both map to Inngest channel: \"workflow:{workflowId}:{runId}\"\n */\nexport class InngestPubSub extends PubSub {\n private inngest: Inngest;\n private workflowId: string;\n private publishFn?: InngestPublishFn;\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, publishFn?: InngestPublishFn) {\n super();\n this.inngest = inngest;\n this.workflowId = workflowId;\n this.publishFn = publishFn;\n }\n\n /**\n * Publish an event to Inngest's realtime system.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events\n * -> channel: \"agent:{runId}\", topic: \"agent-stream\"\n * (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)\n */\n async publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>): Promise<void> {\n if (!this.publishFn) {\n // Silently ignore if no publish function (e.g., outside Inngest context)\n return;\n }\n\n const parsed = parseTopic(topic);\n if (!parsed) {\n return; // Ignore unrecognized topic formats\n }\n\n const { runId, topicType } = parsed;\n\n // Use different Inngest topics and channels for different event types\n // Agent stream events use a runId-only channel so nested workflows publish to the same channel\n const inngestTopic = topicType === 'agent' ? 'agent-stream' : 'watch';\n const channel = topicType === 'agent' ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;\n\n try {\n // For agent stream events, send the full event structure so subscribers can access type/runId/data\n // For workflow events, send just the data (existing behavior)\n const dataToSend = topicType === 'agent' ? event : event.data;\n await this.publishFn({\n channel,\n topic: inngestTopic,\n data: dataToSend,\n });\n } catch (err: any) {\n // For agent stream terminal events, rethrow — losing a finish/error event\n // causes the client stream to hang indefinitely\n if (topicType === 'agent' && (event.type === 'finish' || event.type === 'error')) {\n throw err;\n }\n // Non-terminal events: log but don't throw\n console.error('InngestPubSub publish error:', err?.message ?? err);\n }\n }\n\n /**\n * Subscribe to events from Inngest's realtime system.\n *\n * Supported topic formats:\n * - \"workflow.events.v2.{runId}\" - workflow events\n * -> channel: \"workflow:{workflowId}:{runId}\", topic: \"watch\"\n * - \"agent.stream.{runId}\" - agent stream events\n * -> channel: \"agent:{runId}\", topic: \"agent-stream\"\n * (Note: agent stream uses runId-only channel so nested workflows can publish to same channel)\n */\n async subscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const parsed = parseTopic(topic);\n if (!parsed) {\n return; // Ignore unrecognized topic formats\n }\n\n const { runId, topicType } = parsed;\n\n // Check if we already have a subscription for this topic\n if (this.subscriptions.has(topic)) {\n this.subscriptions.get(topic)!.callbacks.add(cb);\n return;\n }\n\n const callbacks = new Set<(event: Event, ack?: () => Promise<void>) => void>([cb]);\n\n // Use different Inngest topics and channels for different event types\n // Agent stream events use a runId-only channel so nested workflows publish to the same channel\n const inngestTopic = topicType === 'agent' ? 'agent-stream' : 'watch';\n const channel = topicType === 'agent' ? `agent:${runId}` : `workflow:${this.workflowId}:${runId}`;\n\n // Await the subscribe call to ensure the WebSocket connection is established\n // before we consider the subscription \"ready\". This prevents race conditions\n // where the workflow triggers before the subscription can receive events.\n const stream = await subscribe(\n {\n channel,\n topics: [inngestTopic],\n app: this.inngest,\n },\n (message: any) => {\n // For agent stream events, message.data is the full AgentStreamEvent structure (type, runId, data)\n // For workflow events, wrap message.data in a PubSub Event format\n // IMPORTANT: Always generate a unique `id` and `createdAt` for every event.\n // CachingPubSub deduplicates events by `id` — without a unique id, all events\n // after the first would be filtered out (since undefined === undefined in the seen set).\n let event: Event;\n if (topicType === 'agent' && message.data?.type && message.data?.runId) {\n // Agent stream event - spread the AgentStreamEvent data and add required Event fields\n event = {\n id: crypto.randomUUID(),\n createdAt: new Date(),\n ...message.data,\n } as unknown as Event;\n } else {\n // Workflow event or fallback - wrap in standard Event format\n event = {\n id: crypto.randomUUID(),\n type: inngestTopic,\n runId,\n data: message.data,\n createdAt: new Date(),\n };\n }\n\n for (const callback of callbacks) {\n callback(event);\n }\n },\n );\n\n this.subscriptions.set(topic, {\n unsubscribe: () => {\n try {\n void stream.cancel();\n } catch (err) {\n console.error('InngestPubSub unsubscribe error:', err);\n }\n },\n callbacks,\n });\n }\n\n /**\n * Unsubscribe a callback from a topic.\n * If no callbacks remain, the underlying Inngest subscription is cancelled.\n */\n async unsubscribe(topic: string, cb: (event: Event, ack?: () => Promise<void>) => void): Promise<void> {\n const sub = this.subscriptions.get(topic);\n if (!sub) {\n return;\n }\n\n sub.callbacks.delete(cb);\n\n // If no more callbacks, cancel the subscription\n if (sub.callbacks.size === 0) {\n sub.unsubscribe();\n this.subscriptions.delete(topic);\n }\n }\n\n /**\n * Flush any pending operations. No-op for Inngest.\n */\n async flush(): Promise<void> {\n // No-op for Inngest\n }\n\n /**\n * Clean up all subscriptions during graceful shutdown.\n */\n async close(): Promise<void> {\n for (const [, sub] of this.subscriptions) {\n sub.unsubscribe();\n }\n this.subscriptions.clear();\n }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport { subscribe } from '@inngest/realtime';\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 { context as otelContext } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport type { InngestEngineType } from './types';\n\nexport class InngestRun<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType\n >[],\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n> extends Run<TEngineType, TSteps, TState, TInput, TOutput> {\n private inngest: Inngest;\n serializedStepGraph: SerializedStepFlowEntry[];\n #mastra: Mastra;\n\n constructor(\n params: {\n workflowId: string;\n runId: string;\n resourceId?: string;\n executionEngine: ExecutionEngine;\n executionGraph: ExecutionGraph;\n serializedStepGraph: SerializedStepFlowEntry[];\n mastra?: Mastra;\n retryConfig?: {\n attempts?: number;\n delay?: number;\n };\n cleanup?: () => void;\n workflowSteps: Record<string, StepWithComponent>;\n workflowEngineType: WorkflowEngineType;\n validateInputs?: boolean;\n },\n inngest: Inngest,\n ) {\n super(params);\n this.inngest = inngest;\n this.serializedStepGraph = params.serializedStepGraph;\n this.#mastra = params.mastra!;\n }\n\n async getRuns(eventId: string) {\n const maxRetries = 3;\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n // Suppress OTel auto-instrumentation on polling fetch calls to avoid\n // excessive trace noise (see https://github.com/mastra-ai/mastra/issues/13892)\n const response = await otelContext.with(suppressTracing(otelContext.active()), () =>\n fetch(`${this.inngest.apiBaseUrl ?? 'https://api.inngest.com'}/v1/events/${eventId}/runs`, {\n headers: {\n Authorization: `Bearer ${process.env.INNGEST_SIGNING_KEY}`,\n },\n }),\n );\n\n // Handle rate limiting with retry\n if (response.status === 429) {\n const retryAfter = parseInt(response.headers.get('retry-after') || '2', 10);\n await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));\n continue;\n }\n\n // Non-OK responses\n if (!response.ok) {\n throw new Error(`Inngest API error: ${response.status} ${response.statusText}`);\n }\n\n // Parse JSON safely\n const text = await response.text();\n if (!text) {\n // Empty response - eventual consistency, retry with backoff\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n continue;\n }\n\n const json = JSON.parse(text);\n return json.data;\n } catch (error) {\n lastError = error as Error;\n // Exponential backoff before retry\n if (attempt < maxRetries - 1) {\n await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt)));\n }\n }\n }\n\n // After all retries, throw NonRetriableError to prevent Inngest function-level retry\n throw new NonRetriableError(`Failed to get runs after ${maxRetries} attempts: ${lastError?.message}`);\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\n return new Promise<any>((resolve, reject) => {\n let resolved = false;\n let unsubscribe: (() => void) | null = null;\n let pollTimeoutId: NodeJS.Timeout | null = null;\n\n const cleanup = () => {\n if (unsubscribe) {\n try {\n unsubscribe();\n } catch {\n // Ignore unsubscribe errors\n }\n }\n if (pollTimeoutId) {\n clearTimeout(pollTimeoutId);\n }\n };\n\n const handleResult = (result: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n resolve(result);\n }\n };\n\n const handleError = (error: any, _source: string) => {\n if (!resolved) {\n resolved = true;\n cleanup();\n reject(error);\n }\n };\n\n // Start realtime subscription for workflow-finish event\n let realtimeStreamPromise: ReturnType<typeof subscribe> | null = null;\n\n const startRealtimeSubscription = async () => {\n try {\n realtimeStreamPromise = subscribe(\n {\n channel: `workflow:${this.workflowId}:${this.runId}`,\n topics: ['watch'],\n app: this.inngest,\n },\n async (message: any) => {\n if (resolved) return;\n\n const event = message.data;\n\n if (event?.type === 'workflow-finish') {\n // Got the finish event - load snapshot and resolve\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot?.context) {\n snapshot.context = hydrateSerializedStepErrors(snapshot.context);\n }\n\n const result = {\n output: {\n result: {\n steps: snapshot?.context,\n status: event.payload.status,\n result: event.payload.result,\n error: event.payload.error\n ? getErrorFromUnknown(event.payload.error, { serializeStack: false })\n : undefined,\n },\n },\n };\n\n handleResult(result, 'realtime');\n }\n },\n );\n\n // Set unsubscribe immediately so cleanup can cancel even before await resolves\n unsubscribe = () => {\n realtimeStreamPromise?.then(stream => stream.cancel().catch(() => {})).catch(() => {});\n };\n\n await realtimeStreamPromise;\n } catch {\n // Realtime subscription failed - polling will still work as fallback\n }\n };\n\n // Start polling as fallback\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 runs = await this.getRuns(eventId);\n const run = runs?.find((r: { event_id: string }) => r.event_id === eventId);\n\n if (run?.status === 'Completed') {\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 handleResult({ output: { result: { steps: snapshot?.context, status: 'success' } } }, 'polling');\n return;\n }\n\n if (run?.status === 'Failed') {\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 handleResult(\n {\n output: {\n result: {\n steps: snapshot?.context,\n status: 'failed',\n error: getErrorFromUnknown(run?.output?.cause?.error, { serializeStack: false }),\n },\n },\n },\n 'polling-failed',\n );\n return;\n }\n\n if (run?.status === 'Cancelled') {\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 handleResult(\n { output: { result: { steps: snapshot?.context, status: 'canceled' } } },\n 'polling-cancelled',\n );\n return;\n }\n\n // Schedule next poll with jitter\n pollTimeoutId = setTimeout(poll, 200 + Math.random() * 200);\n } catch (error) {\n if (error instanceof NonRetriableError) {\n handleError(error, 'polling-non-retriable');\n return;\n }\n handleError(\n new NonRetriableError(\n `Failed to poll workflow status: ${error instanceof Error ? error.message : String(error)}`,\n ),\n 'polling-error',\n );\n }\n };\n\n // Start first poll\n void poll();\n };\n\n // Start both in parallel\n void startRealtimeSubscription();\n void startPolling();\n });\n }\n\n async cancel() {\n const storage = this.#mastra?.getStorage();\n\n await this.inngest.send({\n name: `cancel.workflow.${this.workflowId}`,\n data: {\n runId: this.runId,\n },\n });\n\n const workflowsStore = await storage?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n if (snapshot) {\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n ...snapshot,\n status: 'canceled' as any,\n value: snapshot.value,\n },\n });\n }\n }\n\n async start(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext;\n outputWriter?: OutputWriter;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n return this._start(args);\n }\n\n /**\n * Starts the workflow execution without waiting for completion (fire-and-forget).\n * Returns immediately with the runId after sending the event to Inngest.\n * The workflow executes independently in Inngest.\n * Use this when you don't need to wait for the result or want to avoid polling failures.\n */\n async startAsync(\n args: (TInput extends unknown\n ? {\n inputData?: TInput;\n }\n : {\n inputData: TInput;\n }) &\n (TState extends unknown\n ? {\n initialState?: TState;\n }\n : {\n initialState: TState;\n }) & {\n requestContext?: RequestContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n },\n ): Promise<{ runId: string }> {\n // Persist initial snapshot\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n // Validate inputs\n const inputDataToUse = await this._validateInput(args.inputData);\n const initialStateToUse = await this._validateInitialState(args.initialState ?? ({} as TState));\n\n // Send event to Inngest (fire-and-forget)\n const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions: args.outputOptions,\n tracingOptions: args.tracingOptions,\n requestContext: args.requestContext ? Object.fromEntries(args.requestContext.entries()) : {},\n 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 perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext;\n initialState?: TState;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n format?: 'legacy' | 'vnext' | undefined;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n resourceId: this.resourceId,\n snapshot: {\n runId: this.runId,\n serializedStepGraph: this.serializedStepGraph,\n status: 'running',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\n\n const inputDataToUse = await this._validateInput(inputData);\n const initialStateToUse = await this._validateInitialState(initialState ?? ({} as TState));\n\n const eventName = `workflow.${this.workflowId}`;\n\n const eventOutput = await this.inngest.send({\n name: eventName,\n data: {\n inputData: inputDataToUse,\n initialState: initialStateToUse,\n runId: this.runId,\n resourceId: this.resourceId,\n outputOptions,\n tracingOptions,\n format,\n requestContext: requestContext ? Object.fromEntries(requestContext.entries()) : {},\n 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 if (result.status !== 'suspended') {\n this.cleanup?.();\n }\n return result;\n }\n\n async resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n 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 async _resume<TResume>(params: {\n resumeData?: TResume;\n step?:\n | Step<string, any, any, TResume, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, any, TResume, any>]\n | string\n | string[];\n label?: string;\n requestContext?: RequestContext;\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const storage = this.#mastra?.getStorage();\n\n const workflowsStore = await storage?.getStore('workflows');\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n // Support label-based resume: look up step from resumeLabels\n const snapshotResumeLabel = params.label ? snapshot?.resumeLabels?.[params.label] : undefined;\n const stepParam = snapshotResumeLabel?.stepId ?? params.step;\n\n let steps: string[] = [];\n if (stepParam) {\n if (typeof stepParam === 'string') {\n steps = stepParam.split('.');\n } else {\n steps = (Array.isArray(stepParam) ? stepParam : [stepParam]).map(step =>\n typeof step === 'string' ? step : step?.id,\n );\n }\n }\n\n const suspendedStep = this.workflowSteps[steps?.[0] ?? ''];\n\n const resumeDataToUse = await this._validateResumeData(params.resumeData, suspendedStep);\n\n // Merge persisted requestContext from snapshot with any new values from params\n const persistedRequestContext = (snapshot as any)?.requestContext ?? {};\n const newRequestContext = params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {};\n const mergedRequestContext = { ...persistedRequestContext, ...newRequestContext };\n\n const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n inputData: resumeDataToUse,\n initialState: snapshot?.value ?? {},\n runId: this.runId,\n workflowId: this.workflowId,\n stepResults: snapshot?.context as any,\n resume: {\n steps,\n stepResults: snapshot?.context as any,\n resumePayload: resumeDataToUse,\n resumePath: steps?.[0] ? (snapshot?.suspendedPaths?.[steps?.[0]] as any) : undefined,\n },\n requestContext: mergedRequestContext,\n perStep: params.perStep,\n },\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 return result;\n }\n\n async timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }): Promise<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n const p = this._timeTravel(params).then(result => {\n if (result.status !== 'suspended') {\n this.closeStreamAction?.().catch(() => {});\n }\n\n return result;\n });\n\n this.executionResults = p;\n return p;\n }\n\n async _timeTravel<TInput>(params: {\n inputData?: TInput;\n resumeData?: any;\n initialState?: TState;\n step:\n | Step<string, any, TInput, any, any>\n | [...Step<string, any, any, any, any>[], Step<string, any, TInput, any, any>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n 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\n const snapshot = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: this.workflowId,\n runId: this.runId,\n });\n\n if (!snapshot) {\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: 'pending',\n value: {},\n context: {} as any,\n activePaths: [],\n suspendedPaths: {},\n activeStepsPath: {},\n resumeLabels: {},\n waitingPaths: {},\n timestamp: Date.now(),\n },\n });\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 const eventOutput = await this.inngest.send({\n name: `workflow.${this.workflowId}`,\n data: {\n initialState: timeTravelData.state,\n runId: this.runId,\n workflowId: this.workflowId,\n stepResults: timeTravelData.stepResults,\n timeTravel: timeTravelData,\n tracingOptions: params.tracingOptions,\n outputOptions: params.outputOptions,\n requestContext: params.requestContext ? Object.fromEntries(params.requestContext.entries()) : {},\n perStep: params.perStep,\n },\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 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({ inputData, requestContext }: { inputData?: TInput; requestContext?: RequestContext } = {}): {\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, 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 tracingOptions,\n closeOnSuspend = true,\n initialState,\n outputOptions,\n perStep,\n }: {\n inputData?: TInput;\n requestContext?: RequestContext;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n closeOnSuspend?: boolean;\n initialState?: TState;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n } = {}): WorkflowRunOutput<WorkflowResult<TState, TInput, TOutput, TSteps>> {\n if (this.closeStreamAction && this.streamOutput) {\n return this.streamOutput;\n }\n\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n // TODO: fix this, watch doesn't have a type\n const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n await controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n\n const executionResultsPromise = self._start({\n inputData,\n requestContext,\n // 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 // tracingContext,\n tracingOptions,\n outputOptions,\n perStep,\n }: {\n inputData?: TTravelInput;\n initialState?: TState;\n resumeData?: any;\n step:\n | Step<string, any, any, any, any, any, TEngineType>\n | [...Step<string, any, any, any, any, any, TEngineType>[], Step<string, any, any, any, any, any, TEngineType>]\n | string\n | string[];\n context?: TimeTravelContext<any, any, any, any>;\n nestedStepsContext?: Record<string, TimeTravelContext<any, any, any, any>>;\n requestContext?: RequestContext;\n tracingContext?: TracingContext;\n tracingOptions?: TracingOptions;\n outputOptions?: {\n includeState?: boolean;\n includeResumeLabels?: boolean;\n };\n perStep?: boolean;\n }) {\n this.closeStreamAction = async () => {};\n\n const self = this;\n const stream = new ReadableStream<WorkflowStreamEvent>({\n async start(controller) {\n // TODO: fix this, watch doesn't have a type\n const unwatch = self.watch(async ({ type, from = ChunkFrom.WORKFLOW, payload }) => {\n controller.enqueue({\n type,\n runId: self.runId,\n from,\n payload: {\n stepName: (payload as unknown as { id: string })?.id,\n ...payload,\n },\n } as WorkflowStreamEvent);\n });\n\n self.closeStreamAction = async () => {\n unwatch();\n\n try {\n controller.close();\n } catch (err) {\n console.error('Error closing stream:', err);\n }\n };\n const executionResultsPromise = self._timeTravel({\n inputData,\n step,\n context,\n nestedStepsContext,\n resumeData,\n initialState,\n requestContext,\n 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 { Mastra } from '@mastra/core/mastra';\nimport { SpanType, EntityType } from '@mastra/core/observability';\nimport type { WorkflowRuns } from '@mastra/core/storage';\nimport { Workflow } from '@mastra/core/workflows';\nimport type {\n Step,\n StepResult,\n WorkflowConfig,\n StepFlowEntry,\n WorkflowResult,\n WorkflowRunState,\n WorkflowStreamEvent,\n Run,\n} from '@mastra/core/workflows';\nimport { NonRetriableError } from 'inngest';\nimport type { Inngest } from 'inngest';\nimport { InngestExecutionEngine } from './execution-engine';\nimport { InngestPubSub } from './pubsub';\nimport { InngestRun } from './run';\nimport type {\n InngestEngineType,\n InngestFlowControlConfig,\n InngestFlowCronConfig,\n InngestWorkflowConfig,\n} from './types';\n\nexport class InngestWorkflow<\n TEngineType = InngestEngineType,\n TSteps extends Step<string, any, any, any, any, any, TEngineType>[] = Step<\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n TEngineType\n >[],\n TWorkflowId extends string = string,\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TPrevSchema = TInput,\n> extends Workflow<TEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrevSchema> {\n #mastra: Mastra;\n public inngest: Inngest;\n\n private function: ReturnType<Inngest['createFunction']> | undefined;\n private cronFunction: ReturnType<Inngest['createFunction']> | undefined;\n private readonly flowControlConfig?: InngestFlowControlConfig;\n private readonly cronConfig?: InngestFlowCronConfig<TInput, TState>;\n\n constructor(\n params: InngestWorkflowConfig<\n TWorkflowId,\n TState,\n TInput,\n TOutput,\n TSteps & Step<string, any, any, any, any, any, InngestEngineType>[]\n >,\n inngest: Inngest,\n ) {\n const { concurrency, rateLimit, throttle, debounce, priority, cron, inputData, initialState, ...workflowParams } =\n params;\n\n super(workflowParams as WorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps>);\n\n this.engineType = 'inngest';\n\n const flowControlEntries = Object.entries({ concurrency, rateLimit, throttle, debounce, priority }).filter(\n ([_, value]) => value !== undefined,\n );\n\n this.flowControlConfig = flowControlEntries.length > 0 ? Object.fromEntries(flowControlEntries) : undefined;\n\n this.#mastra = params.mastra!;\n this.inngest = inngest;\n\n if (cron) {\n this.cronConfig = { cron, inputData, initialState };\n }\n }\n\n async listWorkflowRuns(args?: {\n fromDate?: Date;\n toDate?: Date;\n perPage?: number | false;\n page?: number;\n resourceId?: string;\n }) {\n const storage = this.#mastra?.getStorage();\n if (!storage) {\n this.logger.debug('Cannot get workflow runs. Mastra engine is not initialized');\n return { runs: [], total: 0 };\n }\n\n const workflowsStore = await storage.getStore('workflows');\n if (!workflowsStore) {\n return { runs: [], total: 0 };\n }\n return workflowsStore.listWorkflowRuns({ workflowName: this.id, ...(args ?? {}) }) as unknown as WorkflowRuns;\n }\n\n __registerMastra(mastra: Mastra) {\n super.__registerMastra(mastra);\n this.#mastra = mastra;\n this.executionEngine.__registerMastra(mastra);\n const updateNested = (step: StepFlowEntry) => {\n if (\n (step.type === 'step' || step.type === 'loop' || step.type === 'foreach') &&\n step.step instanceof InngestWorkflow\n ) {\n step.step.__registerMastra(mastra);\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n for (const subStep of step.steps) {\n updateNested(subStep);\n }\n }\n };\n\n if (this.executionGraph.steps.length) {\n for (const step of this.executionGraph.steps) {\n updateNested(step);\n }\n }\n }\n\n async createRun(options?: {\n runId?: string;\n resourceId?: string;\n }): Promise<Run<TEngineType, TSteps, TState, TInput, TOutput>> {\n const runIdToUse = options?.runId || randomUUID();\n\n // Return a new Run instance with object parameters\n const existingInMemoryRun = this.runs.get(runIdToUse);\n const newRun = new InngestRun<TEngineType, TSteps, TState, TInput, TOutput>(\n {\n workflowId: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n executionEngine: this.executionEngine,\n executionGraph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n mastra: this.#mastra,\n retryConfig: this.retryConfig,\n cleanup: () => this.runs.delete(runIdToUse),\n workflowSteps: this.steps,\n workflowEngineType: this.engineType,\n validateInputs: this.options.validateInputs,\n },\n this.inngest,\n );\n const run = (existingInMemoryRun ?? newRun) as Run<TEngineType, TSteps, TState, TInput, TOutput>;\n\n this.runs.set(runIdToUse, run);\n\n const shouldPersistSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: run.workflowRunStatus,\n stepResults: {},\n });\n\n const existingStoredRun = await this.getWorkflowRunById(runIdToUse, {\n withNestedWorkflows: false,\n });\n\n // Check if run exists in persistent storage (not just in-memory)\n const existsInStorage = existingStoredRun && !existingStoredRun.isFromInMemory;\n\n if (!existsInStorage && shouldPersistSnapshot) {\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n await workflowsStore?.persistWorkflowSnapshot({\n workflowName: this.id,\n runId: runIdToUse,\n resourceId: options?.resourceId,\n snapshot: {\n runId: runIdToUse,\n status: 'pending',\n value: {},\n context: {},\n activePaths: [],\n activeStepsPath: {},\n waitingPaths: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: {},\n resumeLabels: {},\n result: undefined,\n error: undefined,\n timestamp: Date.now(),\n },\n });\n }\n\n return run;\n }\n\n //createCronFunction is only called if cronConfig.cron is defined.\n private createCronFunction() {\n if (this.cronFunction) {\n return this.cronFunction;\n }\n this.cronFunction = this.inngest.createFunction(\n {\n id: `workflow.${this.id}.cron`,\n retries: 0,\n cancelOn: [{ event: `cancel.workflow.${this.id}` }],\n ...this.flowControlConfig,\n },\n { cron: this.cronConfig?.cron ?? '' },\n async () => {\n const run = await this.createRun();\n // @ts-expect-error - cron inputData type mismatch\n const result = await run.start({\n inputData: this.cronConfig?.inputData,\n initialState: this.cronConfig?.initialState,\n });\n return { result, runId: run.runId };\n },\n );\n return this.cronFunction;\n }\n\n getFunction() {\n if (this.function) {\n return this.function;\n }\n\n // Always set function-level retries to 0, since retries are handled at the step level via executeStepWithRetry\n // which uses either step.retries or retryConfig.attempts (step.retries takes precedence).\n // step.retries is not accessible at function level, so we handle retries manually in executeStepWithRetry.\n // This is why we set retries to 0 here.\n this.function = this.inngest.createFunction(\n {\n id: `workflow.${this.id}`,\n retries: 0,\n cancelOn: [{ event: `cancel.workflow.${this.id}` }],\n // Spread flow control configuration\n ...this.flowControlConfig,\n },\n { event: `workflow.${this.id}` },\n async ({ event, step, attempt, publish }) => {\n let {\n inputData,\n initialState,\n runId,\n resourceId,\n resume,\n outputOptions,\n format,\n timeTravel,\n perStep,\n tracingOptions,\n } = event.data;\n\n if (!runId) {\n runId = await step.run(`workflow.${this.id}.runIdGen`, async () => {\n return randomUUID();\n });\n }\n\n // Create InngestPubSub instance with the publish function from Inngest context\n const pubsub = new InngestPubSub(this.inngest, this.id, publish);\n\n // Create requestContext before execute so we can reuse it in finalize\n const requestContext: RequestContext = new RequestContext(Object.entries(event.data.requestContext ?? {}));\n\n // Store mastra reference for use in proxy closure\n const mastra = this.#mastra;\n const tracingPolicy = this.options.tracingPolicy;\n\n // Create the workflow root span durably - exports SPAN_STARTED immediately on first execution\n // On replay, returns memoized ExportedSpan data without re-creating the span\n const workflowSpanData = await step.run(`workflow.${this.id}.span.start`, async () => {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (!observability) return undefined;\n\n const span = observability.startSpan({\n type: SpanType.WORKFLOW_RUN,\n name: `workflow run: '${this.id}'`,\n entityType: EntityType.WORKFLOW_RUN,\n entityId: this.id,\n entityName: this.id,\n input: inputData,\n metadata: {\n resourceId,\n runId,\n },\n tracingPolicy,\n tracingOptions,\n requestContext,\n });\n\n return span?.exportSpan();\n });\n\n const engine = new InngestExecutionEngine(this.#mastra, step, attempt, this.options);\n\n let result: WorkflowResult<TState, TInput, TOutput, TSteps>;\n try {\n result = await engine.execute<TState, TInput, WorkflowResult<TState, TInput, TOutput, TSteps>>({\n workflowId: this.id,\n runId,\n resourceId,\n graph: this.executionGraph,\n serializedStepGraph: this.serializedStepGraph,\n input: inputData,\n initialState,\n pubsub,\n retryConfig: this.retryConfig,\n requestContext,\n resume,\n timeTravel,\n perStep,\n format,\n abortController: new AbortController(),\n // For Inngest, we don't pass workflowSpan - step spans use tracingIds instead\n workflowSpan: undefined,\n // Pass tracing IDs for durable span operations\n tracingIds: workflowSpanData\n ? {\n traceId: workflowSpanData.traceId,\n workflowSpanId: workflowSpanData.id,\n }\n : undefined,\n outputOptions,\n outputWriter: async (chunk: WorkflowStreamEvent) => {\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: chunk,\n });\n } catch (err) {\n this.logger.debug?.('Failed to publish watch event:', err);\n }\n },\n });\n } catch (executionError) {\n // Execution threw an exception (not just returned failed status)\n // Create a failed result to pass to finalize\n result = {\n status: 'failed',\n steps: {},\n state: initialState ?? {},\n error: executionError instanceof Error ? executionError : new Error(String(executionError)),\n } as WorkflowResult<TState, TInput, TOutput, TSteps>;\n }\n\n // Final step to invoke lifecycle callbacks and end workflow span.\n // This step is memoized by step.run.\n let finalizeError: unknown;\n let finalizeErrored = false;\n try {\n await step.run(`workflow.${this.id}.finalize`, async () => {\n // For durable agent workflows, emit error event on failure so the\n // client's stream can receive the error and close properly.\n if (result.status === 'failed' && inputData?.__workflowKind === 'durable-agent' && inputData?.runId) {\n const error = result.error instanceof Error ? result.error : new Error(String(result.error));\n try {\n await emitErrorEvent(pubsub, inputData.runId, error);\n } catch (e) {\n this.logger.debug?.('Failed to emit error event:', e);\n }\n }\n\n if (result.status !== 'paused') {\n // Invoke lifecycle callbacks (onFinish and onError)\n await engine.invokeLifecycleCallbacksInternal({\n status: result.status,\n result: 'result' in result ? result.result : undefined,\n error: 'error' in result ? result.error : undefined,\n steps: result.steps,\n tripwire: 'tripwire' in result ? result.tripwire : undefined,\n runId,\n workflowId: this.id,\n resourceId,\n input: inputData,\n requestContext,\n state: result.state ?? initialState ?? {},\n });\n }\n\n // End the workflow span with appropriate status\n // The workflow span was already created and SPAN_STARTED was exported in the span.start step\n if (workflowSpanData) {\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n // Rebuild the span from cached data to call end/error\n const workflowSpan = observability.rebuildSpan(workflowSpanData);\n\n if (result.status === 'failed') {\n workflowSpan.error({\n error: result.error instanceof Error ? result.error : new Error(String(result.error)),\n attributes: { status: 'failed' },\n });\n } else {\n workflowSpan.end({\n output: result.status === 'success' ? result.result : undefined,\n attributes: { status: result.status },\n });\n }\n }\n }\n\n // Ensure final snapshot is persisted BEFORE publishing workflow-finish\n // This fixes a race condition where getRunOutput reads the snapshot before it's fully written\n const shouldPersistFinalSnapshot = this.options.shouldPersistSnapshot({\n workflowStatus: result.status,\n stepResults: result.steps,\n });\n if (shouldPersistFinalSnapshot) {\n const workflowsStore = await mastra?.getStorage()?.getStore('workflows');\n if (workflowsStore) {\n // For suspended workflows, read existing snapshot to preserve suspendedPaths and resumeLabels\n // which were set correctly by the handlers during execution\n let existingSnapshot:\n | { suspendedPaths?: Record<string, number[]>; resumeLabels?: Record<string, any> }\n | undefined;\n if (result.status === 'suspended') {\n existingSnapshot =\n (await workflowsStore.loadWorkflowSnapshot({\n workflowName: this.id,\n runId,\n })) ?? undefined;\n }\n\n await workflowsStore.persistWorkflowSnapshot({\n workflowName: this.id,\n runId,\n resourceId,\n snapshot: {\n runId,\n status: result.status,\n value: result.state ?? initialState ?? {},\n context: toSnapshotContext(result.steps),\n activePaths: [],\n activeStepsPath: {},\n serializedStepGraph: this.serializedStepGraph,\n suspendedPaths: existingSnapshot?.suspendedPaths ?? {},\n waitingPaths: {},\n resumeLabels: existingSnapshot?.resumeLabels ?? result.resumeLabels ?? {},\n result: result.status === 'success' ? toSnapshotResult(result.result) : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n timestamp: Date.now(),\n },\n });\n }\n }\n\n // Publish workflow-finish event for realtime subscribers (best-effort)\n try {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: {\n type: 'workflow-finish',\n payload: {\n status: result.status,\n result: result.status === 'success' ? result.result : undefined,\n error: result.status === 'failed' ? result.error : undefined,\n },\n },\n });\n } catch (publishError) {\n this.logger.debug?.('Failed to publish workflow-finish event:', publishError);\n }\n\n // Throw after span ended for failed workflows\n if (result.status === 'failed') {\n throw new NonRetriableError(`Workflow failed`, {\n cause: result,\n });\n }\n\n return result;\n });\n } catch (error) {\n finalizeErrored = true;\n finalizeError = error;\n } finally {\n // Keep this outside step.run memoization, but guaranteed on all paths.\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n if (observability) {\n try {\n await observability.flush();\n } catch (flushError) {\n this.logger.debug?.('Failed to flush observability:', flushError);\n }\n }\n }\n\n if (finalizeErrored) {\n throw finalizeError;\n }\n\n return { result, runId };\n },\n );\n return this.function;\n }\n\n getNestedFunctions(steps: StepFlowEntry[]): ReturnType<Inngest['createFunction']>[] {\n return steps.flatMap(step => {\n if (step.type === 'step' || step.type === 'loop' || step.type === 'foreach') {\n if (step.step instanceof InngestWorkflow) {\n return [step.step.getFunction(), ...step.step.getNestedFunctions(step.step.executionGraph.steps)];\n }\n return [];\n } else if (step.type === 'parallel' || step.type === 'conditional') {\n return this.getNestedFunctions(step.steps);\n }\n\n return [];\n });\n }\n\n getFunctions() {\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 { Inngest, InngestFunction, RegisterOptions } from 'inngest';\nimport { serve as inngestServeHono } from 'inngest/hono';\nimport { InngestWorkflow } from './workflow';\n\n/**\n * Options for serve functions\n */\nexport interface MastraServeOptions {\n mastra: Mastra;\n inngest: Inngest;\n /**\n * Optional array of additional functions to serve and register with Inngest.\n */\n functions?: InngestFunction.Like[];\n registerOptions?: RegisterOptions;\n}\n\n/**\n * Type for inngest serve adapters (e.g., from inngest/hono, inngest/express, etc.)\n * Inferred from the inngest serve function signatures.\n */\nexport type InngestServeAdapter<THandler> = (options: {\n client: Inngest;\n functions: InngestFunction.Like[];\n [key: string]: unknown;\n}) => THandler;\n\n/**\n * Collects workflow functions from Mastra and prepares serve options for inngest.\n * This is the shared logic used by all serve functions.\n */\nfunction prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }: MastraServeOptions) {\n const wfs = mastra.listWorkflows();\n\n const workflowFunctions = Array.from(\n new Set(\n Object.values(wfs).flatMap(wf => {\n if (wf instanceof InngestWorkflow) {\n wf.__registerMastra(mastra);\n return wf.getFunctions();\n }\n return [];\n }),\n ),\n );\n\n return {\n ...registerOptions,\n client: inngest,\n functions: [...workflowFunctions, ...userFunctions],\n };\n}\n\n/**\n * Factory function to create a serve function with any inngest adapter.\n * Use this to integrate Mastra workflows with any framework supported by inngest.\n *\n * @example Express\n * ```ts\n * import { createServe } from '@mastra/inngest';\n * import { serve } from 'inngest/express';\n *\n * const serveExpress = createServe(serve);\n * app.use('/api/inngest', serveExpress({ mastra, inngest }));\n * ```\n *\n * @example Fastify\n * ```ts\n * import { createServe } from '@mastra/inngest';\n * import { serve } from 'inngest/fastify';\n *\n * const serveFastify = createServe(serve);\n * fastify.route({\n * method: ['GET', 'POST', 'PUT'],\n * handler: serveFastify({ mastra, inngest }),\n * url: '/api/inngest',\n * });\n * ```\n *\n * @example Next.js\n * ```ts\n * import { createServe } from '@mastra/inngest';\n * import { serve } from 'inngest/next';\n *\n * const serveNext = createServe(serve);\n * export const { GET, POST, PUT } = serveNext({ mastra, inngest });\n * ```\n */\nexport function createServe<THandler>(\n adapter: InngestServeAdapter<THandler>,\n): (options: MastraServeOptions) => THandler {\n return (options: MastraServeOptions): THandler => {\n const serveOptions = prepareServeOptions(options);\n return adapter(serveOptions);\n };\n}\n\n/**\n * Serve Mastra workflows with Hono (default).\n *\n * For other frameworks, use `createServe` with the appropriate inngest adapter.\n *\n * @example\n * ```ts\n * import { serve } from '@mastra/inngest';\n *\n * app.use('/api/inngest', async (c) => {\n * return serve({ mastra, inngest })(c);\n * });\n * ```\n */\nexport const serve: (options: MastraServeOptions) => ReturnType<typeof inngestServeHono> =\n createServe(inngestServeHono);\n","import type { Step, WorkflowConfig } from '@mastra/core/workflows';\nimport type { Inngest, InngestFunction } from 'inngest';\n\n// Extract Inngest's native flow control configuration types\nexport type InngestCreateFunctionConfig = Parameters<Inngest['createFunction']>[0];\nexport type InngestCreateFunctionEventConfig = InngestFunction.Trigger<string>;\n\n// Extract specific flow control properties (excluding batching)\nexport type InngestFlowControlConfig = Pick<\n InngestCreateFunctionConfig,\n 'concurrency' | 'rateLimit' | 'throttle' | 'debounce' | 'priority'\n>;\n\nexport type InngestFlowCronConfig<TInputData, TInitialState> = Pick<InngestCreateFunctionEventConfig, 'cron'> & {\n inputData?: TInputData;\n initialState?: TInitialState;\n};\n\n// Union type for Inngest workflows with flow control\nexport type InngestWorkflowConfig<\n TWorkflowId extends string,\n TState,\n TInput,\n TOutput,\n TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[],\n> = WorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps> &\n InngestFlowControlConfig &\n InngestFlowCronConfig<TInput, TState>;\n\n// Compile-time compatibility assertion\nexport type _AssertInngestCompatibility =\n InngestFlowControlConfig extends Pick<Parameters<Inngest['createFunction']>[0], keyof InngestFlowControlConfig>\n ? true\n : never;\nexport const _compatibilityCheck: _AssertInngestCompatibility = true;\n\nexport type InngestEngineType = {\n step: any;\n};\n","import {\n createDurableBackgroundTaskCheckStep,\n createDurableLLMExecutionStep,\n createDurableLLMMappingStep,\n createDurableToolCallStep,\n DurableAgentDefaults,\n DurableStepIds,\n emitFinishEvent,\n modelConfigSchema,\n durableAgenticOutputSchema,\n baseIterationStateSchema,\n createBaseIterationStateUpdate,\n} from '@mastra/core/agent/durable';\nimport type {\n DurableAgenticExecutionOutput,\n DurableAgenticWorkflowInput,\n DurableLLMStepOutput,\n DurableToolCallOutput,\n DurableToolCallInput,\n} from '@mastra/core/agent/durable';\nimport type { PubSub } from '@mastra/core/events';\nimport { SpanType, EntityType, InternalSpans } from '@mastra/core/observability';\nimport type { ExportedSpan } from '@mastra/core/observability';\nimport { PUBSUB_SYMBOL } from '@mastra/core/workflows/_constants';\nimport type { Inngest } from 'inngest';\nimport { z } from 'zod';\n\nimport { init } from '../index';\n\n/**\n * Input schema for the durable agentic workflow.\n * Extends base with observability fields for Inngest.\n */\nconst durableAgenticInputSchema = z.object({\n runId: z.string(),\n agentId: z.string(),\n agentName: z.string().optional(),\n messageListState: z.any(),\n toolsMetadata: z.array(z.any()),\n modelConfig: modelConfigSchema,\n options: z.any(),\n state: z.any(),\n messageId: z.string(),\n // Observability fields (Inngest-specific)\n agentSpanData: z.any().optional(),\n modelSpanData: z.any().optional(),\n stepIndex: z.number().optional(),\n});\n\n// Output schema imported from shared (durableAgenticOutputSchema)\n\n/**\n * Options for creating an Inngest durable agentic workflow\n */\nexport interface InngestDurableAgenticWorkflowOptions {\n /** Inngest client instance */\n inngest: Inngest;\n /** Maximum number of agentic loop iterations */\n maxSteps?: number;\n}\n\n/**\n * Iteration state schema - extends base with observability fields.\n */\nconst iterationStateSchema = baseIterationStateSchema.extend({\n // Observability - exported span data for agent run\n agentSpanData: z.any().optional(),\n // Observability - exported span data for model generation (ONE span for entire run)\n modelSpanData: z.any().optional(),\n // Step index for continuation across iterations (maintains step: 0, 1, 2, ...)\n stepIndex: z.number(),\n});\n\ntype IterationState = z.infer<typeof iterationStateSchema> & {\n agentSpanData?: ExportedSpan<SpanType.AGENT_RUN>;\n modelSpanData?: ExportedSpan<SpanType.MODEL_GENERATION>;\n};\n\n/**\n * Create a durable agentic workflow using Inngest.\n *\n * This workflow implements the agentic loop pattern in a durable way using\n * Inngest's execution engine:\n *\n * 1. LLM Execution Step - Calls the LLM and gets response/tool calls\n * 2. Tool Call Steps (foreach) - Executes each tool call individually with suspend support\n * 3. LLM Mapping Step - Merges tool results back into state\n * 4. Loop - Continues if more tool calls are needed (dowhile)\n *\n * All state flows through workflow input/output, making it durable across\n * process restarts and execution engine replays.\n *\n * @param options - Configuration options\n * @returns An InngestWorkflow instance that implements the agentic loop\n */\n/** Prefix for Inngest engine workflow IDs to avoid collision with other engines */\nconst INNGEST_ENGINE_PREFIX = 'inngest';\n\n/** Inngest-prefixed workflow IDs */\nexport const InngestDurableStepIds = {\n AGENTIC_EXECUTION: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_EXECUTION}`,\n AGENTIC_LOOP: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_LOOP}`,\n} as const;\n\nexport function createInngestDurableAgenticWorkflow(options: InngestDurableAgenticWorkflowOptions) {\n const { inngest, maxSteps = DurableAgentDefaults.MAX_STEPS } = options;\n const { createWorkflow } = init(inngest);\n\n // Create the LLM execution step - tools and model are resolved from Mastra at runtime\n const llmExecutionStep = createDurableLLMExecutionStep();\n\n // Create the tool call step - each tool call runs as its own step with suspend support\n const toolCallStep = createDurableToolCallStep();\n\n // Create the LLM mapping step - reuse from core\n const llmMappingStep = createDurableLLMMappingStep();\n\n // Create the background task check step\n const backgroundTaskCheckStep = createDurableBackgroundTaskCheckStep();\n\n // Create the single iteration workflow (LLM -> Tool Calls -> Mapping)\n const singleIterationWorkflow = createWorkflow({\n id: InngestDurableStepIds.AGENTIC_EXECUTION,\n inputSchema: iterationStateSchema,\n outputSchema: iterationStateSchema,\n options: {\n tracingPolicy: {\n // Mark all workflow spans as internal so they're hidden in traces\n // This makes the trace structure match regular agents (agent_run -> model_generation -> tool_call)\n internal: InternalSpans.WORKFLOW,\n },\n shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === 'suspended',\n validateInputs: false,\n },\n steps: [],\n })\n // Step 0: Convert iteration state to LLM input format\n .map(\n async ({ inputData }) => {\n const state = inputData as IterationState;\n return {\n runId: state.runId,\n agentId: state.agentId,\n agentName: state.agentName,\n messageListState: state.messageListState,\n toolsMetadata: state.toolsMetadata,\n modelConfig: state.modelConfig,\n options: state.options,\n state: state.state,\n messageId: state.messageId,\n // Pass agent span data so model spans can use it as parent\n agentSpanData: state.agentSpanData,\n // Pass model span data (ONE span for entire agent run)\n modelSpanData: state.modelSpanData,\n // Pass step index for continuation (step: 0, 1, 2, ...)\n stepIndex: state.stepIndex,\n };\n },\n { id: 'map-to-llm-input' },\n )\n // Step 1: Execute LLM\n .then(llmExecutionStep)\n // Step 2: Extract tool calls as array for foreach\n .map(\n async ({ inputData }) => {\n const llmOutput = inputData as DurableLLMStepOutput;\n return (llmOutput.toolCalls ?? []) as DurableToolCallInput[];\n },\n { id: 'extract-tool-calls' },\n )\n // Step 3: Execute each tool call individually (with suspend support)\n // Tool result/error PubSub emission is handled by createDurableToolCallStep\n .foreach(toolCallStep)\n // Step 4: Collect tool results, create observability spans, and bundle for mapping\n .map(\n async ({ inputData, getStepResult, getInitData, mastra }) => {\n const toolResults = inputData as DurableToolCallOutput[];\n const llmOutput = getStepResult(llmExecutionStep.id) as DurableLLMStepOutput;\n const initData = getInitData() as IterationState;\n\n // Create observability spans retroactively for each tool result\n // In the foreach pattern, individual tool calls don't have access to\n // the observability context, so we create spans here in the collection step\n const observability = mastra?.observability?.getSelectedInstance({});\n\n const modelSpanData = (llmOutput as any)?.modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION> | undefined;\n const stepSpanData = (llmOutput as any)?.stepSpanData as ExportedSpan<SpanType.MODEL_STEP> | undefined;\n\n const modelSpan = modelSpanData ? observability?.rebuildSpan(modelSpanData) : undefined;\n const stepSpan = stepSpanData ? observability?.rebuildSpan(stepSpanData) : undefined;\n const agentSpan = initData.agentSpanData ? observability?.rebuildSpan(initData.agentSpanData) : undefined;\n const toolParentSpan = stepSpan ?? modelSpan ?? agentSpan;\n\n // Create tool call + tool result spans for each tool result\n for (const tr of toolResults) {\n const toolSpan = toolParentSpan?.createChildSpan({\n type: SpanType.TOOL_CALL,\n name: `tool: '${tr.toolName}'`,\n entityType: EntityType.TOOL,\n entityId: tr.toolName,\n entityName: tr.toolName,\n input: tr.args,\n });\n\n if (tr.error) {\n toolSpan?.error({ error: new Error(tr.error.message) });\n } else {\n toolSpan?.end({ output: tr.result });\n }\n\n // Create tool-result chunk span as child of model_step\n if (!tr.error) {\n stepSpan?.createEventSpan({\n type: SpanType.MODEL_CHUNK,\n name: `chunk: 'tool-result'`,\n output: {\n toolCallId: tr.toolCallId,\n toolName: tr.toolName,\n result: tr.result,\n },\n });\n }\n }\n\n // End step span (children before parent)\n // NOTE: We do NOT close the model span here - it stays open for the entire agent run\n // and is closed in map-final-output after the agentic loop completes\n const toolCalls = (llmOutput?.toolCalls ?? []) as DurableToolCallInput[];\n if (stepSpan) {\n const stepFinishPayload = (llmOutput as any).stepFinishPayload as any;\n stepSpan.end({\n output: {\n toolCalls: toolCalls.map(tc => ({\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n args: tc.args,\n })),\n toolResults: toolResults.map((tr: DurableToolCallOutput) => ({\n toolCallId: tr.toolCallId,\n toolName: tr.toolName,\n result: tr.result,\n error: tr.error,\n })),\n },\n attributes: {\n usage: stepFinishPayload?.output?.usage,\n finishReason: stepFinishPayload?.stepResult?.reason,\n isContinued: stepFinishPayload?.stepResult?.isContinued,\n },\n });\n }\n\n return {\n llmOutput,\n toolResults,\n runId: initData.runId,\n agentId: initData.agentId,\n messageId: initData.messageId,\n state: llmOutput?.state ?? initData.state,\n };\n },\n { id: 'collect-tool-results' },\n )\n // Step 5: Map tool results back to state\n .then(llmMappingStep)\n // Step 6: Check for pending background tasks\n .then(backgroundTaskCheckStep)\n // Step 7: Map back to iteration state format using shared function\n .map(\n async ({ inputData, getInitData }) => {\n const executionOutput = inputData as DurableAgenticExecutionOutput;\n const initData = getInitData() as IterationState;\n\n // Use shared function for base state update\n const baseUpdate = createBaseIterationStateUpdate({\n currentState: initData,\n executionOutput,\n });\n\n // Extend with Inngest-specific observability fields\n const newIterationState: IterationState = {\n ...baseUpdate,\n // Preserve agent span data for observability\n agentSpanData: initData.agentSpanData,\n // Preserve model span data (ONE span for entire agent run)\n modelSpanData: initData.modelSpanData,\n // Increment step index for next iteration (step: 0 → 1 → 2 → ...)\n stepIndex: initData.stepIndex + 1,\n };\n\n return newIterationState;\n },\n { id: 'update-iteration-state' },\n )\n .commit();\n\n // Create the main agentic loop workflow with dowhile\n return (\n createWorkflow({\n id: InngestDurableStepIds.AGENTIC_LOOP,\n inputSchema: durableAgenticInputSchema,\n outputSchema: durableAgenticOutputSchema,\n options: {\n tracingPolicy: {\n // Mark all workflow spans as internal so they're hidden in traces\n // This makes the trace structure match regular agents (agent_run -> model_generation -> tool_call)\n internal: InternalSpans.WORKFLOW,\n },\n shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === 'suspended',\n validateInputs: false,\n },\n steps: [],\n })\n // Initialize iteration state from input\n // The AGENT_RUN span is created BEFORE the workflow starts (in InngestAgent.stream)\n // and passed via input.agentSpanData so the agent_run is the root of the trace\n .map(\n async ({ inputData }) => {\n const input = inputData as DurableAgenticWorkflowInput;\n\n // Use the agent span data passed from InngestAgent.stream()\n // This span was created before the workflow started, making it the trace root\n const agentSpanData = input.agentSpanData as ExportedSpan<SpanType.AGENT_RUN> | undefined;\n // Use the model span data passed from InngestAgent.stream()\n // This ensures ONE model_generation span contains all steps (like regular agents)\n const modelSpanData = input.modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION> | undefined;\n\n const iterationState: IterationState = {\n ...input,\n iterationCount: 0,\n accumulatedSteps: [],\n accumulatedUsage: {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n },\n lastStepResult: undefined,\n agentSpanData,\n modelSpanData,\n stepIndex: input.stepIndex ?? 0,\n };\n return iterationState;\n },\n { id: 'init-iteration-state' },\n )\n // Run the agentic loop with dowhile\n .dowhile(singleIterationWorkflow, async ({ inputData }) => {\n const state = inputData as IterationState;\n\n // Check if we should continue\n const shouldContinue = state.lastStepResult?.isContinued === true;\n // Use maxSteps from options (per-request), falling back to workflow-level default\n const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;\n const underMaxSteps = state.iterationCount < effectiveMaxSteps;\n\n return shouldContinue && underMaxSteps;\n })\n // Map final state to output format, close agent span, and emit finish event\n .map(\n async params => {\n const { inputData, mastra } = params;\n const state = inputData as IterationState;\n\n // Access pubsub via symbol to emit finish event\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n\n // Extract final text from last step\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n const finalText = lastStep?.text;\n\n const finalOutput = {\n messageListState: state.messageListState,\n messageId: state.messageId,\n stepResult: state.lastStepResult || {\n reason: 'stop',\n warnings: [],\n isContinued: false,\n },\n output: {\n text: finalText,\n usage: state.accumulatedUsage,\n steps: state.accumulatedSteps,\n },\n state: state.state,\n };\n\n // End MODEL_GENERATION span with final output (children before parent)\n // This span was created BEFORE the workflow started and stayed open for all iterations\n const observability = mastra?.observability?.getSelectedInstance({});\n if (state.modelSpanData) {\n const modelSpan = observability?.rebuildSpan(state.modelSpanData);\n modelSpan?.end({\n output: {\n text: finalText,\n usage: state.accumulatedUsage,\n },\n attributes: {\n finishReason: state.lastStepResult?.reason || 'stop',\n },\n });\n }\n\n // End AGENT_RUN span with final output\n if (state.agentSpanData) {\n const agentSpan = observability?.rebuildSpan(state.agentSpanData);\n agentSpan?.end({\n output: finalOutput.output,\n });\n }\n\n // Emit finish event via pubsub\n if (pubsub) {\n await emitFinishEvent(pubsub, state.runId, {\n output: finalOutput.output,\n stepResult: finalOutput.stepResult,\n });\n }\n\n return finalOutput;\n },\n { id: 'map-final-output' },\n )\n .commit()\n );\n}\n","/**\n * Factory function to create an Inngest-powered durable agent.\n *\n * This provides a clean API for wrapping a Mastra Agent with Inngest's\n * durable execution engine. The returned object can be registered with\n * Mastra like any other agent, and the required workflow is automatically\n * registered when added to Mastra.\n *\n * @example\n * ```typescript\n * import { Agent } from '@mastra/core/agent';\n * import { createInngestAgent } from '@mastra/inngest';\n * import { Inngest } from 'inngest';\n * import { realtimeMiddleware } from '@inngest/realtime/middleware';\n *\n * const inngest = new Inngest({\n * id: 'my-app',\n * middleware: [realtimeMiddleware()],\n * });\n *\n * const agent = new Agent({\n * id: 'my-agent',\n * name: 'My Agent',\n * instructions: 'You are a helpful assistant',\n * model: openai('gpt-4'),\n * });\n *\n * const durableAgent = createInngestAgent({ agent, inngest });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: durableAgent },\n * });\n *\n * // Use the agent\n * const { output, cleanup } = await durableAgent.stream('Hello!');\n * const text = await output.text;\n * cleanup();\n * ```\n */\n\nimport type { Agent, AgentExecutionOptions } from '@mastra/core/agent';\nimport { prepareForDurableExecution, createDurableAgentStream, emitErrorEvent } from '@mastra/core/agent/durable';\nimport type {\n AgentFinishEventData,\n AgentStepFinishEventData,\n AgentSuspendedEventData,\n} from '@mastra/core/agent/durable';\nimport type { MessageListInput } from '@mastra/core/agent/message-list';\nimport type { MastraServerCache } from '@mastra/core/cache';\nimport { CachingPubSub } from '@mastra/core/events';\nimport type { PubSub } from '@mastra/core/events';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { SpanType, EntityType } from '@mastra/core/observability';\nimport type { MastraModelOutput, ChunkType } from '@mastra/core/stream';\nimport type { Workflow } from '@mastra/core/workflows';\nimport type { Inngest } from 'inngest';\n\nimport { InngestPubSub } from '../pubsub';\nimport { createInngestDurableAgenticWorkflow, InngestDurableStepIds } from './create-inngest-agentic-workflow';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Options for createInngestAgent factory function.\n */\nexport interface CreateInngestAgentOptions {\n /** The Mastra Agent to wrap with durable execution */\n agent: Agent<any, any, any>;\n /** Inngest client instance */\n inngest: Inngest;\n /** Optional ID override (defaults to agent.id) */\n id?: string;\n /** Optional name override (defaults to agent.name) */\n name?: string;\n /** Optional PubSub override (defaults to InngestPubSub) */\n pubsub?: PubSub;\n /**\n * Cache instance for storing stream events.\n * Enables resumable streams - clients can disconnect and reconnect\n * without missing events.\n *\n * When provided, the pubsub is wrapped with CachingPubSub.\n */\n cache?: MastraServerCache;\n /** Mastra instance for observability (optional, set automatically when registered with Mastra) */\n mastra?: Mastra;\n}\n\n/**\n * Options for InngestAgent.stream()\n */\nexport interface InngestAgentStreamOptions<OUTPUT = undefined> {\n /** Custom instructions that override the agent's default instructions */\n instructions?: AgentExecutionOptions<OUTPUT>['instructions'];\n /** Additional context messages */\n context?: AgentExecutionOptions<OUTPUT>['context'];\n /** Memory configuration */\n memory?: AgentExecutionOptions<OUTPUT>['memory'];\n /** Unique identifier for this execution run */\n runId?: string;\n /** Request Context */\n requestContext?: AgentExecutionOptions<OUTPUT>['requestContext'];\n /** Maximum number of steps */\n maxSteps?: number;\n /** Additional tool sets */\n toolsets?: AgentExecutionOptions<OUTPUT>['toolsets'];\n /** Client-side tools */\n clientTools?: AgentExecutionOptions<OUTPUT>['clientTools'];\n /** Tool selection strategy */\n toolChoice?: AgentExecutionOptions<OUTPUT>['toolChoice'];\n /** Model settings */\n modelSettings?: AgentExecutionOptions<OUTPUT>['modelSettings'];\n /** Require approval for all tool calls */\n requireToolApproval?: boolean;\n /** Automatically resume suspended tools */\n autoResumeSuspendedTools?: boolean;\n /** Maximum concurrent tool calls */\n toolCallConcurrency?: number;\n /** Include raw chunks in output */\n includeRawChunks?: boolean;\n /** Maximum processor retries */\n maxProcessorRetries?: number;\n /** Callback when chunk is received */\n onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;\n /** Callback when step finishes */\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n /** Callback when execution finishes */\n onFinish?: (result: AgentFinishEventData) => void | Promise<void>;\n /** Callback on error */\n onError?: (error: Error) => void | Promise<void>;\n /** Callback when workflow suspends */\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n}\n\n/**\n * Result from InngestAgent.stream()\n */\nexport interface InngestAgentStreamResult<OUTPUT = undefined> {\n /** The streaming output */\n output: MastraModelOutput<OUTPUT>;\n /** The full stream - delegates to output.fullStream for server compatibility */\n readonly fullStream: ReadableStream<any>;\n /** The unique run ID */\n runId: string;\n /** Thread ID if using memory */\n threadId?: string;\n /** Resource ID if using memory */\n resourceId?: string;\n /** Cleanup function */\n cleanup: () => void;\n}\n\n/**\n * An Inngest-powered durable agent.\n *\n * This interface represents an agent that uses Inngest's durable execution engine.\n * It can be registered with Mastra like a regular Agent, and the required workflow\n * is automatically registered.\n *\n * At runtime, a Proxy forwards all Agent method calls (e.g., `generate()`, `listTools()`,\n * `getMemory()`) to the underlying agent. The index signature below reflects this:\n * any property not explicitly declared here is available via the Proxy.\n */\nexport interface InngestAgent<TOutput = undefined> {\n /** Agent ID */\n readonly id: string;\n /** Agent name */\n readonly name: string;\n /** The underlying Mastra Agent (for Mastra registration) */\n readonly agent: Agent<any, any, TOutput>;\n /** The Inngest client */\n readonly inngest: Inngest;\n /** The cache instance if resumable streams are enabled */\n readonly cache?: MastraServerCache;\n\n /**\n * The PubSub instance used for streaming events.\n * Returns the CachingPubSub wrapper if caching is enabled.\n * @internal Used by the server's observe endpoint to subscribe to the correct PubSub instance.\n */\n readonly pubsub: PubSub;\n\n /**\n * Stream a response using Inngest's durable execution.\n */\n stream(\n messages: MessageListInput,\n options?: InngestAgentStreamOptions<TOutput>,\n ): Promise<InngestAgentStreamResult<TOutput>>;\n\n /**\n * Resume a suspended workflow execution.\n */\n resume(\n runId: string,\n resumeData: unknown,\n options?: {\n threadId?: string;\n resourceId?: string;\n onChunk?: (chunk: ChunkType<TOutput>) => void | Promise<void>;\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n onFinish?: (result: AgentFinishEventData) => void | Promise<void>;\n onError?: (error: Error) => void | Promise<void>;\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n },\n ): Promise<InngestAgentStreamResult<TOutput>>;\n\n /**\n * Prepare for durable execution without starting it.\n */\n prepare(\n messages: MessageListInput,\n options?: AgentExecutionOptions<TOutput>,\n ): Promise<{\n runId: string;\n messageId: string;\n workflowInput: any;\n threadId?: string;\n resourceId?: string;\n }>;\n\n /**\n * Observe (reconnect to) an existing stream.\n * Use this to resume receiving events after a disconnection.\n *\n * @param runId - The run ID to observe\n * @param options.offset - Resume from this event index (0-based). If omitted, replays all events.\n */\n observe(\n runId: string,\n options?: {\n offset?: number;\n onChunk?: (chunk: ChunkType<TOutput>) => void | Promise<void>;\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n onFinish?: (result: AgentFinishEventData) => void | Promise<void>;\n onError?: (error: Error) => void | Promise<void>;\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n },\n ): Promise<Omit<InngestAgentStreamResult<TOutput>, 'threadId' | 'resourceId'> & { runId: string }>;\n\n /**\n * Get the durable workflows required by this agent.\n * Called by Mastra during agent registration.\n * @internal\n */\n getDurableWorkflows(): Workflow<any, any, any, any, any, any, any>[];\n\n /**\n * Set the Mastra instance for observability.\n * Called by Mastra during agent registration.\n * @internal\n */\n __setMastra(mastra: Mastra): void;\n\n // ---------------------------------------------------------------------------\n // Agent methods forwarded via Proxy to the underlying Agent at runtime.\n // Declared here so TypeScript can see them without the Proxy indirection.\n // ---------------------------------------------------------------------------\n\n /** Generate a non-streaming response. Forwarded to the underlying Agent. */\n generate(messages: MessageListInput, options?: AgentExecutionOptions<any>): Promise<any>;\n /** Get the agent's description. Forwarded to the underlying Agent. */\n getDescription(): string;\n /** Get the agent's instructions. Forwarded to the underlying Agent. */\n getInstructions(...args: any[]): any;\n /** List tools available to the agent. Forwarded to the underlying Agent. */\n listTools(...args: any[]): any;\n /** Get the agent's LLM configuration. Forwarded to the underlying Agent. */\n getLLM(...args: any[]): any;\n /** Get the agent's model. Forwarded to the underlying Agent. */\n getModel(...args: any[]): any;\n /** Get the agent's memory instance. Forwarded to the underlying Agent. */\n getMemory(...args: any[]): any;\n /** Check if agent has its own memory. Forwarded to the underlying Agent. */\n hasOwnMemory(): boolean;\n /** Get the agent's workspace. Forwarded to the underlying Agent. */\n getWorkspace(...args: any[]): any;\n /** List sub-agents. Forwarded to the underlying Agent. */\n listAgents(...args: any[]): any;\n /** List workflows. Forwarded to the underlying Agent. */\n listWorkflows(...args: any[]): any;\n /** Get default execution options. Forwarded to the underlying Agent. */\n getDefaultOptions(...args: any[]): any;\n /** Get legacy generate options. Forwarded to the underlying Agent. */\n getDefaultGenerateOptionsLegacy(...args: any[]): any;\n /** Get legacy stream options. Forwarded to the underlying Agent. */\n getDefaultStreamOptionsLegacy(...args: any[]): any;\n /** Get available models. Forwarded to the underlying Agent. */\n getModelList(...args: any[]): any;\n /** Get configured processor workflows. Forwarded to the underlying Agent. */\n getConfiguredProcessorWorkflows(...args: any[]): any;\n /** Get raw agent configuration. Forwarded to the underlying Agent. */\n toRawConfig(...args: any[]): any;\n /** Resume a streaming execution. Forwarded to the underlying Agent. */\n resumeStream(...args: any[]): any;\n /** Resume a generate execution. Forwarded to the underlying Agent. */\n resumeGenerate(...args: any[]): any;\n /** Approve a pending tool call. Forwarded to the underlying Agent. */\n approveToolCall(...args: any[]): any;\n /** @internal Update the agent's model. Forwarded to the underlying Agent. */\n __updateModel(...args: any[]): any;\n /** @internal Reset to original model. Forwarded to the underlying Agent. */\n __resetToOriginalModel(...args: any[]): any;\n /** @internal Set logger. Forwarded to the underlying Agent. */\n __setLogger(...args: any[]): any;\n /** @internal Register primitives. Forwarded to the underlying Agent. */\n __registerPrimitives(...args: any[]): any;\n /** @internal Register Mastra instance. Forwarded to the underlying Agent. */\n __registerMastra(...args: any[]): any;\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create an Inngest-powered durable agent from a Mastra Agent.\n *\n * This factory function wraps a regular Mastra Agent with Inngest's durable\n * execution capabilities. The returned InngestAgent can be registered with\n * Mastra, and the required workflow will be automatically registered.\n *\n * @param options - Configuration options\n * @returns An InngestAgent that can be registered with Mastra\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * id: 'my-agent',\n * instructions: 'You are helpful',\n * model: openai('gpt-4'),\n * });\n *\n * const durableAgent = createInngestAgent({ agent, inngest });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: durableAgent },\n * });\n * ```\n */\nexport function createInngestAgent<TOutput = undefined>(options: CreateInngestAgentOptions): InngestAgent<TOutput> {\n const {\n agent,\n inngest,\n id: idOverride,\n name: nameOverride,\n pubsub: customPubsub,\n cache,\n mastra: mastraOption,\n } = options;\n\n // Use provided id/name or fall back to agent.id/agent.name\n const agentId = idOverride ?? agent.id;\n const agentName = nameOverride ?? agent.name;\n\n // Track mastra instance - can be set later when registered with Mastra\n let mastra: Mastra | undefined = mastraOption;\n\n // Create the durable workflow for this agent\n // Mastra's addWorkflow handles deduplication, so creating multiple times is fine\n const workflow = createInngestDurableAgenticWorkflow({ inngest });\n\n // Track whether user provided a custom cache (if not, we'll inherit from mastra)\n let _customCache = cache;\n\n // Set up pubsub with lazy CachingPubSub creation\n // CachingPubSub is an internal implementation detail - users just configure cache and pubsub separately\n let innerPubsub: PubSub = customPubsub ?? new InngestPubSub(inngest, InngestDurableStepIds.AGENTIC_LOOP);\n let _cachingPubsub: PubSub | null = null;\n\n // Lazily create CachingPubSub - this allows inheriting cache from mastra if not provided\n function getPubsub(): PubSub {\n if (!_cachingPubsub) {\n // Resolve cache: user-provided > mastra's cache > no caching (just use inner pubsub)\n const resolvedCache = _customCache ?? mastra?.serverCache;\n if (resolvedCache) {\n _customCache = resolvedCache; // Store for the cache getter\n _cachingPubsub = new CachingPubSub(innerPubsub, resolvedCache);\n } else {\n _cachingPubsub = innerPubsub;\n }\n }\n return _cachingPubsub;\n }\n\n // Lazily resolve cache\n function getCache(): MastraServerCache | undefined {\n // Ensure pubsub is initialized (which resolves cache)\n getPubsub();\n return _customCache;\n }\n\n /**\n * Trigger the workflow via Inngest event\n */\n async function triggerWorkflow(\n runId: string,\n workflowInput: any,\n tracingOptions?: { traceId: string; parentSpanId: string },\n ): Promise<void> {\n const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;\n\n await inngest.send({\n name: eventName,\n data: {\n inputData: workflowInput,\n runId,\n resourceId: workflowInput.state?.resourceId,\n requestContext: {},\n tracingOptions,\n },\n });\n }\n\n /**\n * Emit an error event to pubsub\n */\n async function emitError(runId: string, error: Error): Promise<void> {\n await emitErrorEvent(getPubsub(), runId, error);\n }\n\n // Return the InngestAgent object (Agent methods are added by the Proxy below)\n const inngestAgent: Pick<\n InngestAgent<TOutput>,\n | 'id'\n | 'name'\n | 'agent'\n | 'inngest'\n | 'cache'\n | 'pubsub'\n | 'stream'\n | 'resume'\n | 'prepare'\n | 'observe'\n | 'getDurableWorkflows'\n | '__setMastra'\n > = {\n get id() {\n return agentId;\n },\n\n get name() {\n return agentName;\n },\n\n get agent() {\n return agent as Agent<any, any, TOutput>;\n },\n\n get inngest() {\n return inngest;\n },\n\n get cache() {\n return getCache();\n },\n\n get pubsub() {\n return getPubsub();\n },\n\n async stream(messages, streamOptions): Promise<InngestAgentStreamResult<TOutput>> {\n // 1. Prepare for durable execution\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: agent as Agent<string, any, TOutput>,\n messages,\n options: streamOptions as AgentExecutionOptions<TOutput>,\n runId: streamOptions?.runId,\n requestContext: streamOptions?.requestContext,\n });\n\n const { runId, messageId, workflowInput, threadId, resourceId } = preparation;\n\n // Override agentId and agentName in workflowInput with the durable agent's values\n workflowInput.agentId = agentId;\n workflowInput.agentName = agentName;\n\n // 2. Create AGENT_RUN span BEFORE the workflow starts\n // This ensures the agent_run is the root of the trace, not the workflow\n const observability = mastra?.observability?.getSelectedInstance({\n requestContext: streamOptions?.requestContext,\n });\n const agentSpan = observability?.startSpan({\n type: SpanType.AGENT_RUN,\n name: `agent run: '${agentId}'`,\n entityType: EntityType.AGENT,\n entityId: agentId,\n entityName: agentName,\n input: workflowInput.messageListState,\n metadata: {\n runId,\n threadId,\n resourceId,\n },\n });\n // Export span data so it can be passed to the workflow\n const agentSpanData = agentSpan?.exportSpan();\n\n // 3. Create MODEL_GENERATION span BEFORE the workflow starts\n // This ensures ONE model_generation span contains all steps (like regular agents)\n const modelSpan = agentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n name: `llm: '${workflowInput.modelConfig.modelId}'`,\n input: { messages: workflowInput.messageListState },\n attributes: {\n model: workflowInput.modelConfig.modelId,\n provider: workflowInput.modelConfig.provider,\n streaming: true,\n parameters: {\n temperature: workflowInput.options?.temperature,\n },\n },\n });\n const modelSpanData = modelSpan?.exportSpan();\n\n // Add span data to workflow input\n workflowInput.agentSpanData = agentSpanData;\n workflowInput.modelSpanData = modelSpanData;\n workflowInput.stepIndex = 0;\n\n // 2. Create the durable agent stream (subscribes to pubsub)\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: getPubsub(),\n runId,\n messageId,\n model: {\n modelId: workflowInput.modelConfig.modelId,\n provider: workflowInput.modelConfig.provider,\n version: 'v3',\n },\n threadId,\n resourceId,\n onChunk: streamOptions?.onChunk,\n onStepFinish: streamOptions?.onStepFinish,\n onFinish: streamOptions?.onFinish,\n onError: streamOptions?.onError,\n onSuspended: streamOptions?.onSuspended,\n });\n\n // 3. Wait for subscription to be established, then trigger workflow\n // Pass tracing options so workflow spans are children of the agent span\n const tracingOptions = agentSpanData\n ? { traceId: agentSpanData.traceId, parentSpanId: agentSpanData.id }\n : undefined;\n\n // Wait for subscription to be ready before triggering workflow\n // This prevents race conditions where events are published before subscription\n ready\n .then(() => triggerWorkflow(runId, workflowInput, tracingOptions))\n .catch(error => {\n void emitError(runId, error);\n });\n\n // 4. Return stream result - attach extra properties to output for compatibility\n // This allows both destructuring { output, runId, cleanup } AND direct access to fullStream\n const result = {\n output,\n runId,\n threadId,\n resourceId,\n cleanup: streamCleanup,\n // Also expose fullStream directly for server compatibility\n get fullStream() {\n return output.fullStream;\n },\n };\n\n return result as InngestAgentStreamResult<TOutput>;\n },\n\n async resume(runId, resumeData, resumeOptions): Promise<InngestAgentStreamResult<TOutput>> {\n // Re-subscribe to the stream\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: getPubsub(),\n runId,\n messageId: crypto.randomUUID(),\n model: {\n modelId: undefined,\n provider: undefined,\n version: 'v3',\n },\n threadId: resumeOptions?.threadId,\n resourceId: resumeOptions?.resourceId,\n onChunk: resumeOptions?.onChunk,\n onStepFinish: resumeOptions?.onStepFinish,\n onFinish: resumeOptions?.onFinish,\n onError: resumeOptions?.onError,\n onSuspended: resumeOptions?.onSuspended,\n });\n\n // Load the workflow snapshot to build proper resume data\n // This mirrors InngestRun._resume() which loads the snapshot, finds the suspended step,\n // and sends an event to the same trigger name (not a .resume suffix)\n const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;\n\n ready\n .then(async () => {\n const workflowsStore = await mastra?.getStorage()?.getStore('workflows');\n const snapshot: any = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: InngestDurableStepIds.AGENTIC_LOOP,\n runId,\n });\n\n // Find the suspended step from the snapshot\n const suspendedStepIds = snapshot?.suspendedPaths ? Object.keys(snapshot.suspendedPaths) : [];\n const steps = suspendedStepIds.length > 0 ? suspendedStepIds : [];\n\n await inngest.send({\n name: eventName,\n data: {\n inputData: resumeData,\n initialState: snapshot?.value ?? {},\n runId,\n resourceId: resumeOptions?.resourceId,\n requestContext: {},\n stepResults: snapshot?.context,\n resume: {\n steps,\n stepResults: snapshot?.context,\n resumePayload: resumeData,\n resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : undefined,\n },\n },\n });\n })\n .catch(error => {\n void emitError(runId, error);\n });\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId: resumeOptions?.threadId,\n resourceId: resumeOptions?.resourceId,\n cleanup: streamCleanup,\n };\n },\n\n async prepare(messages, prepareOptions) {\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: agent as Agent<string, any, TOutput>,\n messages,\n options: prepareOptions,\n requestContext: prepareOptions?.requestContext,\n });\n\n // Override with durable agent's id/name\n preparation.workflowInput.agentId = agentId;\n preparation.workflowInput.agentName = agentName;\n\n return {\n runId: preparation.runId,\n messageId: preparation.messageId,\n workflowInput: preparation.workflowInput,\n threadId: preparation.threadId,\n resourceId: preparation.resourceId,\n };\n },\n\n async observe(runId, observeOptions) {\n // Create the stream subscription with offset support\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: getPubsub(),\n runId,\n messageId: crypto.randomUUID(),\n model: {\n modelId: undefined,\n provider: undefined,\n version: 'v3',\n },\n offset: observeOptions?.offset,\n onChunk: observeOptions?.onChunk,\n onStepFinish: observeOptions?.onStepFinish,\n onFinish: observeOptions?.onFinish,\n onError: observeOptions?.onError,\n onSuspended: observeOptions?.onSuspended,\n });\n\n await ready;\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n cleanup: streamCleanup,\n };\n },\n\n getDurableWorkflows() {\n return [workflow];\n },\n\n __setMastra(mastraInstance: Mastra) {\n mastra = mastraInstance;\n\n // NOTE: Unlike core DurableAgent, we do NOT replace innerPubsub with mastra.pubsub.\n // InngestAgent uses InngestPubSub which handles both publishing (inside Inngest\n // functions via the realtime publishFn) and subscribing (via @inngest/realtime).\n // Replacing it with mastra's EventEmitterPubSub would break streaming because\n // the subscriber would be on a different transport than the publisher.\n },\n };\n\n // Use a Proxy to forward any unknown property/method calls to the underlying agent\n // This ensures the InngestAgent has all Agent methods (getMemory, etc.) while\n // overriding stream() to use durable execution\n return new Proxy(inngestAgent, {\n get(target, prop, receiver) {\n // First check if the property exists on our InngestAgent object\n if (prop in target) {\n return Reflect.get(target, prop, receiver);\n }\n // Otherwise, forward to the underlying agent\n const agentValue = (agent as any)[prop];\n if (typeof agentValue === 'function') {\n return agentValue.bind(agent);\n }\n return agentValue;\n },\n has(target, prop) {\n return prop in target || prop in agent;\n },\n }) as InngestAgent<TOutput>;\n}\n\n// =============================================================================\n// Type Guard\n// =============================================================================\n\n/**\n * Check if an object is an InngestAgent\n */\nexport function isInngestAgent(obj: any): obj is InngestAgent {\n if (!obj) return false;\n return (\n typeof obj.id === 'string' &&\n typeof obj.name === 'string' &&\n 'agent' in obj &&\n 'inngest' in obj &&\n typeof obj.stream === 'function' &&\n typeof obj.getDurableWorkflows === 'function'\n );\n}\n","import type { ReadableStream } from 'node:stream/web';\nimport { Agent, MessageList, TripWire } from '@mastra/core/agent';\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type { MastraScorers } from '@mastra/core/evals';\nimport type { CoreMessage } from '@mastra/core/llm';\nimport type { TracingContext } from '@mastra/core/observability';\nimport { EntityType, SpanType } from '@mastra/core/observability';\nimport type { Processor, ProcessorStepOutput, ProcessorStepInputSchema, OutputResult } from '@mastra/core/processors';\nimport { ProcessorRunner, ProcessorStepOutputSchema, ProcessorStepSchema } from '@mastra/core/processors';\nimport type { InferPublicSchema, PublicSchema, StandardSchemaWithJSON } from '@mastra/core/schema';\nimport { toStandardSchema } from '@mastra/core/schema';\nimport type { ChunkType, LanguageModelUsage } from '@mastra/core/stream';\nimport type { ToolExecutionContext } from '@mastra/core/tools';\nimport { Tool, createTool } from '@mastra/core/tools';\nimport type { DynamicArgument } from '@mastra/core/types';\nimport type { Step, AgentStepOptions, StepParams, ToolStep, StepMetadata } from '@mastra/core/workflows';\nimport { Workflow } from '@mastra/core/workflows';\nimport { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '@mastra/core/workflows/_constants';\nimport type { Inngest } from 'inngest';\nimport { z } from 'zod';\nimport type { InngestEngineType, InngestWorkflowConfig } from './types';\nimport { InngestWorkflow } from './workflow';\n\nexport * from './workflow';\nexport * from './execution-engine';\nexport * from './pubsub';\nexport * from './run';\nexport * from './serve';\nexport * from './types';\nexport * from './durable-agent';\n\n// ============================================\n// Type Guards\n// ============================================\n\nfunction isInngestWorkflow(input: unknown): input is InngestWorkflow<any, any, any, any, any, any, any> {\n return input instanceof InngestWorkflow;\n}\n\nfunction isAgent<TStepId extends string>(input: unknown): input is Agent<TStepId, any> {\n return input instanceof Agent;\n}\n\nfunction isToolStep(input: unknown): input is ToolStep<any, any, any, any, any> {\n return input instanceof Tool;\n}\n\nfunction isStepParams(input: unknown): input is StepParams<any, any, any, any, any, any> {\n return (\n input !== null &&\n typeof input === 'object' &&\n 'id' in input &&\n 'execute' in input &&\n !(input instanceof Agent) &&\n !(input instanceof Tool) &&\n !(input instanceof InngestWorkflow)\n );\n}\n\n/**\n * Type guard to check if an object is a Processor.\n * A Processor must have an 'id' property and at least one processor method.\n */\nfunction isProcessor(obj: unknown): obj is Processor {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n 'id' in obj &&\n typeof (obj as any).id === 'string' &&\n !(obj instanceof Agent) &&\n !(obj instanceof Tool) &&\n !(obj instanceof InngestWorkflow) &&\n (typeof (obj as any).processInput === 'function' ||\n typeof (obj as any).processInputStep === 'function' ||\n typeof (obj as any).processOutputStream === 'function' ||\n typeof (obj as any).processOutputResult === 'function' ||\n typeof (obj as any).processOutputStep === 'function')\n );\n}\n\n// ============================================\n// Overloads (Public API - clean types for consumers)\n// ============================================\n\n/**\n * Creates a step from explicit params (IMPORTANT: FIRST overload for best error messages when using .then in workflows)\n * @param params Configuration parameters for the step\n * @param params.id Unique identifier for the step\n * @param params.description Optional description of what the step does\n * @param params.inputSchema Zod schema defining the input structure\n * @param params.outputSchema Zod schema defining the output structure\n * @param params.execute Function that performs the step's operations\n * @returns A Step object that can be added to the workflow\n */\nexport function createStep<\n TStepId extends string,\n TStateSchema extends PublicSchema | undefined,\n TInputSchema extends PublicSchema,\n TOutputSchema extends PublicSchema,\n TResumeSchema extends PublicSchema | undefined = undefined,\n TSuspendSchema extends PublicSchema | undefined = undefined,\n>(\n params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>,\n): Step<\n TStepId,\n TStateSchema extends PublicSchema ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n>;\n\n/**\n * Creates a step from an agent with structured output\n */\nexport function createStep<TStepId extends string, TStepOutput>(\n agent: Agent<TStepId, any>,\n agentOptions: AgentStepOptions<TStepOutput> & {\n structuredOutput: { schema: StandardSchemaWithJSON<TStepOutput> };\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n metadata?: StepMetadata;\n },\n): Step<TStepId, unknown, { prompt: string }, TStepOutput, unknown, unknown, InngestEngineType>;\n\n/**\n * Creates a step from an agent (defaults to { text: string } output)\n */\nexport function createStep<\n TStepId extends string,\n TStepInput extends { prompt: string },\n TStepOutput extends { text: string },\n TResume,\n TSuspend,\n>(\n agent: Agent<TStepId, any>,\n agentOptions?: AgentStepOptions<TStepOutput> & {\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n },\n): Step<TStepId, unknown, TStepInput, TStepOutput, TResume, TSuspend, InngestEngineType>;\n\n/**\n * Creates a step from a tool\n */\nexport function createStep<\n TSchemaIn,\n TSchemaOut,\n TSuspend,\n TResume,\n TContext extends ToolExecutionContext<TSuspend, TResume, any> = ToolExecutionContext<TSuspend, TResume>,\n TId extends string = string,\n TRequestContext extends Record<string, any> | unknown = unknown,\n>(\n tool: Tool<TSchemaIn, TSchemaOut, TSuspend, TResume, TContext, TId, TRequestContext>,\n toolOptions?: { retries?: number; scorers?: DynamicArgument<MastraScorers>; metadata?: StepMetadata },\n): Step<TId, unknown, TSchemaIn, TSchemaOut, TSuspend, TResume, InngestEngineType>;\n\n/**\n * Creates a step from a Processor - wraps a Processor as a workflow step\n * Note: We require at least one processor method to distinguish from StepParams\n */\nexport function createStep<TProcessorId extends string>(\n processor:\n | (Processor<TProcessorId> & { processInput: Function })\n | (Processor<TProcessorId> & { processInputStream: Function })\n | (Processor<TProcessorId> & { processInputStep: Function })\n | (Processor<TProcessorId> & { processOutputStream: Function })\n | (Processor<TProcessorId> & { processOutputResult: Function })\n | (Processor<TProcessorId> & { processOutputStep: Function }),\n): Step<\n `processor:${TProcessorId}`,\n unknown,\n InferPublicSchema<typeof ProcessorStepInputSchema>,\n InferPublicSchema<typeof ProcessorStepOutputSchema>,\n unknown,\n unknown,\n InngestEngineType\n>;\n\n/**\n * IMPORTANT: Fallback overload - provides better error messages when StepParams doesn't match\n * This should be LAST and will show clearer errors about what's wrong\n * This is a copy of first one, KEEP THIS IN SYNC!\n */\nexport function createStep<\n TStepId extends string,\n TStateSchema extends PublicSchema | undefined,\n TInputSchema extends PublicSchema,\n TOutputSchema extends PublicSchema,\n TResumeSchema extends PublicSchema | undefined = undefined,\n TSuspendSchema extends PublicSchema | undefined = undefined,\n>(\n params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>,\n): Step<\n TStepId,\n TStateSchema extends PublicSchema ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n>;\n\n// ============================================\n// Implementation (uses type guards for clean logic)\n// ============================================\n\nexport function createStep(params: any, agentOrToolOptions?: any): Step<any, any, any, any, any, any, any> {\n // Type assertions are needed because each branch returns a different Step type,\n // but the overloads ensure type safety for consumers\n\n // Issue #9965: Preserve InngestWorkflow identity when passed to createStep\n // This ensures nested workflows in foreach are properly detected by isNestedWorkflowStep()\n if (isInngestWorkflow(params)) {\n return params;\n }\n\n if (isAgent(params)) {\n return createStepFromAgent(params, agentOrToolOptions);\n }\n\n if (isToolStep(params)) {\n return createStepFromTool(params, agentOrToolOptions);\n }\n\n // StepParams check must come before isProcessor since both have 'id'\n // StepParams always has 'execute', while Processor has processor methods\n if (isStepParams(params)) {\n return createStepFromParams(params);\n }\n\n if (isProcessor(params)) {\n return createStepFromProcessor(params);\n }\n\n throw new Error('Invalid input: expected StepParams, Agent, ToolStep, Processor, or InngestWorkflow');\n}\n\n// ============================================\n// Internal Implementations\n// ============================================\n\nfunction createStepFromParams<\n TStepId extends string,\n TStateSchema extends PublicSchema<any> | undefined,\n TInputSchema extends PublicSchema<any>,\n TOutputSchema extends PublicSchema<any>,\n TResumeSchema extends PublicSchema<any> | undefined = undefined,\n TSuspendSchema extends PublicSchema<any> | undefined = undefined,\n>(\n params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>,\n): Step<\n TStepId,\n TStateSchema extends PublicSchema<any> ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema<any> ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema<any> ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n> {\n // Type assertion needed because toStandardSchema returns StandardSchemaWithJSON<unknown>\n // but we need it to match the inferred generic types. The public overloads ensure\n // type safety for consumers.\n return {\n id: params.id,\n description: params.description,\n inputSchema: toStandardSchema(params.inputSchema),\n stateSchema: params.stateSchema ? toStandardSchema(params.stateSchema) : undefined,\n outputSchema: toStandardSchema(params.outputSchema),\n resumeSchema: params.resumeSchema ? toStandardSchema(params.resumeSchema) : undefined,\n suspendSchema: params.suspendSchema ? toStandardSchema(params.suspendSchema) : undefined,\n scorers: params.scorers,\n retries: params.retries,\n metadata: params.metadata,\n execute: params.execute.bind(params) as Step<\n TStepId,\n TStateSchema extends PublicSchema<any> ? InferPublicSchema<TStateSchema> : unknown,\n InferPublicSchema<TInputSchema>,\n InferPublicSchema<TOutputSchema>,\n TResumeSchema extends PublicSchema<any> ? InferPublicSchema<TResumeSchema> : unknown,\n TSuspendSchema extends PublicSchema<any> ? InferPublicSchema<TSuspendSchema> : unknown,\n InngestEngineType\n >['execute'],\n };\n}\n\nfunction createStepFromAgent<TStepId extends string, TStepOutput>(\n params: Agent<TStepId, any>,\n agentOrToolOptions?: Record<string, unknown>,\n): Step<TStepId, any, any, TStepOutput, unknown, unknown, InngestEngineType> {\n const options = (agentOrToolOptions ?? {}) as\n | (AgentStepOptions<TStepOutput> & {\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n metadata?: StepMetadata;\n })\n | undefined;\n // Determine output schema based on structuredOutput option\n const outputSchema = (options?.structuredOutput?.schema ??\n z.object({ text: z.string() })) as unknown as PublicSchema<TStepOutput>;\n const { retries, scorers, metadata, ...agentOptions } =\n options ??\n ({} as AgentStepOptions<TStepOutput> & {\n retries?: number;\n scorers?: DynamicArgument<MastraScorers>;\n metadata?: StepMetadata;\n });\n\n return {\n id: params.name as TStepId,\n description: params.getDescription(),\n inputSchema: toStandardSchema(\n z.object({\n prompt: z.string(),\n }),\n ),\n outputSchema: toStandardSchema(outputSchema),\n retries,\n scorers,\n metadata,\n execute: async ({\n inputData,\n runId,\n [PUBSUB_SYMBOL]: pubsub,\n [STREAM_FORMAT_SYMBOL]: streamFormat,\n requestContext,\n tracingContext,\n abortSignal,\n abort,\n writer,\n }) => {\n let streamPromise = {} as {\n promise: Promise<string>;\n resolve: (value: string) => void;\n reject: (reason?: any) => void;\n };\n\n streamPromise.promise = new Promise((resolve, reject) => {\n streamPromise.resolve = resolve;\n streamPromise.reject = reject;\n });\n\n // Track structured output result\n let structuredResult: any = null;\n\n const toolData = {\n name: params.name,\n args: inputData,\n };\n\n let stream: ReadableStream<any>;\n\n if ((await params.getModel()).specificationVersion === 'v1') {\n const { fullStream } = await params.streamLegacy((inputData as { prompt: string }).prompt, {\n ...(agentOptions ?? {}),\n requestContext,\n tracingContext,\n onFinish: result => {\n // Capture structured output if available\n const resultWithObject = result as typeof result & { object?: unknown };\n if (agentOptions?.structuredOutput?.schema && resultWithObject.object) {\n structuredResult = resultWithObject.object;\n }\n streamPromise.resolve(result.text);\n void agentOptions?.onFinish?.(result);\n },\n abortSignal,\n });\n stream = fullStream as any;\n } else {\n const { structuredOutput, ...restAgentOptions } = agentOptions ?? {};\n const baseOptions = {\n ...restAgentOptions,\n requestContext,\n tracingContext,\n onFinish: (result: any) => {\n // Capture structured output if available\n const resultWithObject = result as typeof result & { object?: unknown };\n if (structuredOutput?.schema && resultWithObject.object) {\n structuredResult = resultWithObject.object;\n }\n streamPromise.resolve(result.text);\n void agentOptions?.onFinish?.(result);\n },\n abortSignal,\n };\n\n const modelOutput = structuredOutput\n ? await params.stream<any>((inputData as { prompt: string }).prompt, {\n ...baseOptions,\n structuredOutput,\n } as any)\n : await params.stream<any>((inputData as { prompt: string }).prompt, baseOptions as any);\n\n stream = modelOutput.fullStream;\n }\n\n if (streamFormat === 'legacy') {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: { type: 'tool-call-streaming-start', ...(toolData ?? {}) },\n });\n for await (const chunk of stream) {\n if (chunk.type === 'text-delta') {\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: { type: 'tool-call-delta', ...(toolData ?? {}), argsTextDelta: chunk.textDelta },\n });\n }\n }\n await pubsub.publish(`workflow.events.v2.${runId}`, {\n type: 'watch',\n runId,\n data: { type: 'tool-call-streaming-finish', ...(toolData ?? {}) },\n });\n } else {\n for await (const chunk of stream) {\n await writer.write(chunk as any);\n }\n }\n\n if (abortSignal.aborted) {\n return abort() as TStepOutput;\n }\n\n // Return structured output if available, otherwise default text\n if (structuredResult !== null) {\n return structuredResult;\n }\n return {\n text: await streamPromise.promise,\n } as TStepOutput;\n },\n component: params.component,\n };\n}\n\nfunction createStepFromTool<TStepInput, TSuspend, TResume, TStepOutput>(\n params: ToolStep<TStepInput, TSuspend, TResume, TStepOutput, any>,\n agentOrToolOptions?: Record<string, unknown>,\n): Step<string, any, TStepInput, TStepOutput, TResume, TSuspend, InngestEngineType> {\n const toolOpts = agentOrToolOptions as\n | { retries?: number; scorers?: DynamicArgument<MastraScorers>; metadata?: StepMetadata }\n | undefined;\n if (!params.inputSchema || !params.outputSchema) {\n throw new Error('Tool must have input and output schemas defined');\n }\n\n return {\n id: params.id,\n description: params.description,\n inputSchema: params.inputSchema,\n outputSchema: params.outputSchema,\n resumeSchema: params.resumeSchema,\n suspendSchema: params.suspendSchema,\n retries: toolOpts?.retries,\n scorers: toolOpts?.scorers,\n metadata: toolOpts?.metadata,\n execute: async ({\n inputData,\n mastra,\n requestContext,\n tracingContext,\n suspend,\n resumeData,\n runId,\n workflowId,\n state,\n setState,\n }) => {\n // BREAKING CHANGE v1.0: Pass raw input as first arg, context as second\n const toolContext = {\n mastra,\n requestContext,\n tracingContext,\n workflow: {\n runId,\n resumeData,\n suspend,\n workflowId,\n state,\n setState,\n },\n };\n return params.execute(inputData, toolContext) as TStepOutput;\n },\n component: 'TOOL',\n };\n}\n\nfunction createStepFromProcessor<TProcessorId extends string>(\n processor: Processor<TProcessorId>,\n): Step<`processor:${TProcessorId}`, unknown, any, any, unknown, unknown, InngestEngineType> {\n // Helper to map phase to entity type\n const getProcessorEntityType = (phase: string): EntityType => {\n switch (phase) {\n case 'input':\n return EntityType.INPUT_PROCESSOR;\n case 'inputStep':\n return EntityType.INPUT_STEP_PROCESSOR;\n case 'outputStream':\n case 'outputResult':\n return EntityType.OUTPUT_PROCESSOR;\n case 'outputStep':\n return EntityType.OUTPUT_STEP_PROCESSOR;\n default:\n return EntityType.OUTPUT_PROCESSOR;\n }\n };\n\n // Helper to get span name prefix\n const getSpanNamePrefix = (phase: string): string => {\n switch (phase) {\n case 'input':\n return 'input processor';\n case 'inputStep':\n return 'input step processor';\n case 'outputStream':\n return 'output stream processor';\n case 'outputResult':\n return 'output processor';\n case 'outputStep':\n return 'output step processor';\n default:\n return 'processor';\n }\n };\n\n // Helper to check if processor implements a phase\n const hasPhaseMethod = (phase: string): boolean => {\n switch (phase) {\n case 'input':\n return !!processor.processInput;\n case 'inputStep':\n return !!processor.processInputStep;\n case 'outputStream':\n return !!processor.processOutputStream;\n case 'outputResult':\n return !!processor.processOutputResult;\n case 'outputStep':\n return !!processor.processOutputStep;\n default:\n return false;\n }\n };\n\n return {\n id: `processor:${processor.id}`,\n description: processor.name ?? `Processor ${processor.id}`,\n inputSchema: ProcessorStepSchema,\n outputSchema: ProcessorStepOutputSchema,\n execute: async ({ inputData, requestContext, tracingContext }) => {\n // Cast to output type for easier property access - the discriminated union\n // ensures type safety at the schema level, but inside the execute function\n // we need access to all possible properties\n const input = inputData as ProcessorStepOutput;\n const {\n phase,\n messages,\n messageList,\n stepNumber,\n systemMessages,\n part,\n streamParts,\n state,\n result,\n finishReason,\n toolCalls,\n text,\n retryCount,\n // inputStep phase fields for model/tools configuration\n model,\n tools,\n toolChoice,\n activeTools,\n providerOptions,\n modelSettings,\n structuredOutput,\n steps,\n usage,\n } = input;\n\n // Create a minimal abort function that throws TripWire\n const abort = (reason?: string, options?: { retry?: boolean; metadata?: unknown }): never => {\n throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n };\n\n // Early return if processor doesn't implement this phase - no span created\n // This prevents empty spans for phases the processor doesn't handle\n if (!hasPhaseMethod(phase)) {\n return input;\n }\n\n // Create processor span for non-stream phases\n // outputStream phase doesn't need its own span (stream chunks are already tracked)\n const currentSpan = tracingContext?.currentSpan;\n\n // Find appropriate parent span:\n // - For input/outputResult: find AGENT_RUN (processor runs once at start/end)\n // - For inputStep/outputStep: find MODEL_STEP (processor runs per LLM call)\n // When workflow is executed, currentSpan is WORKFLOW_STEP, so we walk up the parent chain\n const parentSpan =\n phase === 'inputStep' || phase === 'outputStep'\n ? currentSpan?.findParent(SpanType.MODEL_STEP) || currentSpan\n : currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan;\n\n const processorSpan =\n phase !== 'outputStream'\n ? parentSpan?.createChildSpan({\n type: SpanType.PROCESSOR_RUN,\n name: `${getSpanNamePrefix(phase)}: ${processor.id}`,\n entityType: getProcessorEntityType(phase),\n entityId: processor.id,\n entityName: processor.name ?? processor.id,\n input: { phase, messageCount: messages?.length },\n attributes: {\n processorExecutor: 'workflow',\n // Read processorIndex from processor (set in combineProcessorsIntoWorkflow)\n processorIndex: processor.processorIndex,\n },\n })\n : undefined;\n\n // Create tracing context with processor span so internal agent calls nest correctly\n const processorTracingContext: TracingContext | undefined = processorSpan\n ? { currentSpan: processorSpan }\n : tracingContext;\n\n // Base context for all processor methods - includes requestContext for memory processors\n // and tracingContext for proper span nesting when processors call internal agents\n const baseContext = {\n abort,\n retryCount: retryCount ?? 0,\n requestContext,\n tracingContext: processorTracingContext,\n };\n\n // Pass-through data that should flow to the next processor in a chain\n // This enables processor workflows to use .then(), .parallel(), .branch(), etc.\n const passThrough = {\n phase,\n // Auto-create MessageList from messages if not provided\n // This enables running processor workflows from the UI where messageList can't be serialized\n messageList:\n messageList ??\n (Array.isArray(messages)\n ? new MessageList()\n .add(messages as MastraDBMessage[], 'input')\n .addSystem((systemMessages ?? []) as CoreMessage[])\n : undefined),\n stepNumber,\n systemMessages,\n streamParts,\n state,\n result,\n finishReason,\n toolCalls,\n text,\n retryCount,\n // inputStep phase fields for model/tools configuration\n model,\n tools,\n toolChoice,\n activeTools,\n providerOptions,\n modelSettings,\n structuredOutput,\n steps,\n usage,\n };\n\n // Helper to execute phase with proper span lifecycle management\n const executePhaseWithSpan = async <T>(fn: () => Promise<T>): Promise<T> => {\n try {\n const result = await fn();\n processorSpan?.end({ output: result });\n return result;\n } catch (error) {\n // TripWire errors should end span but bubble up to halt the workflow\n if (error instanceof TripWire) {\n processorSpan?.end({ output: { tripwire: error.message } });\n } else {\n processorSpan?.error({ error: error as Error, endSpan: true });\n }\n throw error;\n }\n };\n\n // Execute the phase with span lifecycle management\n return executePhaseWithSpan(async () => {\n switch (phase) {\n case 'input': {\n if (processor.processInput) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processInput phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const result = await processor.processInput({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n systemMessages: (systemMessages ?? []) as CoreMessage[],\n state: {},\n });\n\n if (result instanceof MessageList) {\n // Validate same instance\n if (result !== passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`,\n });\n }\n return {\n ...passThrough,\n messages: result.get.all.db(),\n systemMessages: result.getAllSystemMessages(),\n };\n } else if (Array.isArray(result)) {\n // Processor returned an array of messages\n ProcessorRunner.applyMessagesToMessageList(\n result as MastraDBMessage[],\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'input',\n );\n return { ...passThrough, messages: result };\n } else if (result && 'messages' in result && 'systemMessages' in result) {\n // Processor returned { messages, systemMessages }\n const typedResult = result as { messages: MastraDBMessage[]; systemMessages: CoreMessage[] };\n ProcessorRunner.applyMessagesToMessageList(\n typedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'input',\n );\n passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);\n return {\n ...passThrough,\n messages: typedResult.messages,\n systemMessages: typedResult.systemMessages,\n };\n }\n return { ...passThrough, messages };\n }\n return { ...passThrough, messages };\n }\n\n case 'inputStep': {\n if (processor.processInputStep) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processInputStep phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const result = await processor.processInputStep({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n stepNumber: stepNumber ?? 0,\n systemMessages: (systemMessages ?? []) as CoreMessage[],\n // Pass model/tools configuration fields - types match ProcessInputStepArgs\n model: model!,\n tools,\n toolChoice,\n activeTools,\n providerOptions,\n modelSettings,\n structuredOutput,\n steps: steps ?? [],\n state: {},\n });\n\n const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {\n messageList: passThrough.messageList,\n processor,\n stepNumber: stepNumber ?? 0,\n });\n\n if (validatedResult.messages) {\n ProcessorRunner.applyMessagesToMessageList(\n validatedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n );\n }\n\n if (validatedResult.systemMessages) {\n passThrough.messageList!.replaceAllSystemMessages(validatedResult.systemMessages as CoreMessage[]);\n }\n\n // Preserve messages in return - passThrough doesn't include messages,\n // so we must explicitly include it to avoid losing it for subsequent steps\n return { ...passThrough, messages, ...validatedResult };\n }\n return { ...passThrough, messages };\n }\n\n case 'outputStream': {\n if (processor.processOutputStream) {\n // Manage per-processor span lifecycle across stream chunks\n // Use unique key to store span on shared state object\n const spanKey = `__outputStreamSpan_${processor.id}`;\n const mutableState = (state ?? {}) as Record<string, unknown>;\n let processorSpan = mutableState[spanKey] as\n | ReturnType<NonNullable<typeof parentSpan>['createChildSpan']>\n | undefined;\n\n if (!processorSpan && parentSpan) {\n // First chunk - create span for this processor\n processorSpan = parentSpan.createChildSpan({\n type: SpanType.PROCESSOR_RUN,\n name: `output stream processor: ${processor.id}`,\n entityType: EntityType.OUTPUT_PROCESSOR,\n entityId: processor.id,\n entityName: processor.name ?? processor.id,\n input: { phase, streamParts: [] },\n attributes: {\n processorExecutor: 'workflow',\n processorIndex: processor.processorIndex,\n },\n });\n mutableState[spanKey] = processorSpan;\n }\n\n // Update span with current chunk data\n if (processorSpan) {\n processorSpan.input = {\n phase,\n streamParts: streamParts ?? [],\n totalChunks: (streamParts ?? []).length,\n };\n }\n\n // Create tracing context with processor span for internal agent calls\n const processorTracingContext = processorSpan\n ? { currentSpan: processorSpan }\n : baseContext.tracingContext;\n\n // Handle outputStream span lifecycle explicitly (not via executePhaseWithSpan)\n // because outputStream uses a per-processor span stored in mutableState\n let result: ChunkType | null | undefined;\n try {\n result = await processor.processOutputStream({\n ...baseContext,\n tracingContext: processorTracingContext,\n part: part as ChunkType,\n streamParts: (streamParts ?? []) as ChunkType[],\n state: mutableState,\n messageList: passThrough.messageList, // Optional for stream processing\n });\n\n // End span on finish chunk\n if (part && (part as ChunkType).type === 'finish') {\n processorSpan?.end({ output: result });\n delete mutableState[spanKey];\n }\n } catch (error) {\n // End span with error and clean up state\n if (error instanceof TripWire) {\n processorSpan?.end({ output: { tripwire: error.message } });\n } else {\n processorSpan?.error({ error: error as Error, endSpan: true });\n }\n delete mutableState[spanKey];\n throw error;\n }\n\n return { ...passThrough, state: mutableState, part: result };\n }\n return { ...passThrough, part };\n }\n\n case 'outputResult': {\n if (processor.processOutputResult) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processOutputResult phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const outputResult = (passThrough.result as OutputResult | undefined) ?? {\n text: '',\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n finishReason: 'unknown',\n steps: [],\n };\n\n const processResult = await processor.processOutputResult({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n state: passThrough.state ?? {},\n result: outputResult,\n });\n\n if (processResult instanceof MessageList) {\n // Validate same instance\n if (processResult !== passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`,\n });\n }\n return {\n ...passThrough,\n messages: processResult.get.all.db(),\n systemMessages: processResult.getAllSystemMessages(),\n };\n } else if (Array.isArray(processResult)) {\n // Processor returned an array of messages\n ProcessorRunner.applyMessagesToMessageList(\n processResult as MastraDBMessage[],\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n return { ...passThrough, messages: processResult };\n } else if (processResult && 'messages' in processResult && 'systemMessages' in processResult) {\n // Processor returned { messages, systemMessages }\n const typedResult = processResult as { messages: MastraDBMessage[]; systemMessages: CoreMessage[] };\n ProcessorRunner.applyMessagesToMessageList(\n typedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);\n return {\n ...passThrough,\n messages: typedResult.messages,\n systemMessages: typedResult.systemMessages,\n };\n }\n return { ...passThrough, messages };\n }\n return { ...passThrough, messages };\n }\n\n case 'outputStep': {\n if (processor.processOutputStep) {\n if (!passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_MISSING_MESSAGE_LIST',\n text: `Processor ${processor.id} requires messageList or messages for processOutputStep phase`,\n });\n }\n\n // Create source checker before processing to preserve message sources\n const idsBeforeProcessing = (messages as MastraDBMessage[]).map(m => m.id);\n const check = passThrough.messageList.makeMessageSourceChecker();\n\n const defaultUsage: LanguageModelUsage = {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n const result = await processor.processOutputStep({\n ...baseContext,\n messages: messages as MastraDBMessage[],\n messageList: passThrough.messageList,\n stepNumber: stepNumber ?? 0,\n finishReason,\n toolCalls: toolCalls as any,\n text,\n usage: (usage as LanguageModelUsage) ?? defaultUsage,\n systemMessages: (systemMessages ?? []) as CoreMessage[],\n steps: steps ?? [],\n state: {},\n });\n\n if (result instanceof MessageList) {\n // Validate same instance\n if (result !== passThrough.messageList) {\n throw new MastraError({\n category: ErrorCategory.USER,\n domain: ErrorDomain.MASTRA_WORKFLOW,\n id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`,\n });\n }\n return {\n ...passThrough,\n messages: result.get.all.db(),\n systemMessages: result.getAllSystemMessages(),\n };\n } else if (Array.isArray(result)) {\n // Processor returned an array of messages\n ProcessorRunner.applyMessagesToMessageList(\n result as MastraDBMessage[],\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n return { ...passThrough, messages: result };\n } else if (result && 'messages' in result && 'systemMessages' in result) {\n // Processor returned { messages, systemMessages }\n const typedResult = result as { messages: MastraDBMessage[]; systemMessages: CoreMessage[] };\n ProcessorRunner.applyMessagesToMessageList(\n typedResult.messages,\n passThrough.messageList,\n idsBeforeProcessing,\n check,\n 'response',\n );\n passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);\n return {\n ...passThrough,\n messages: typedResult.messages,\n systemMessages: typedResult.systemMessages,\n };\n }\n return { ...passThrough, messages };\n }\n return { ...passThrough, messages };\n }\n\n default:\n return { ...passThrough, messages };\n }\n });\n },\n component: 'PROCESSOR',\n };\n}\n\nexport function init(inngest: Inngest) {\n return {\n createTool,\n createWorkflow<\n TWorkflowId extends string = string,\n TState = any,\n TInput = any,\n TOutput = any,\n TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[] = Step<\n string,\n any,\n any,\n any,\n any,\n any,\n InngestEngineType\n >[],\n >(params: InngestWorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps>) {\n return new InngestWorkflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TInput>(\n params,\n inngest,\n );\n },\n createStep,\n cloneStep<TStepId extends string>(\n step: Step<TStepId, any, any, any, any, any, InngestEngineType>,\n opts: { id: TStepId },\n ): Step<TStepId, any, any, any, any, any, InngestEngineType> {\n return {\n id: opts.id,\n description: step.description,\n inputSchema: step.inputSchema,\n outputSchema: step.outputSchema,\n resumeSchema: step.resumeSchema,\n suspendSchema: step.suspendSchema,\n stateSchema: step.stateSchema,\n metadata: step.metadata,\n execute: step.execute,\n retries: step.retries,\n scorers: step.scorers,\n component: step.component,\n };\n },\n cloneWorkflow<\n TWorkflowId extends string = string,\n TState = unknown,\n TInput = unknown,\n TOutput = unknown,\n TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[] = Step<\n string,\n any,\n any,\n any,\n any,\n any,\n InngestEngineType\n >[],\n TPrev = TInput,\n >(\n workflow: Workflow<InngestEngineType, TSteps, string, TState, TInput, TOutput, TPrev>,\n opts: { id: TWorkflowId },\n ): Workflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrev> {\n const wf: Workflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrev> = new Workflow({\n id: opts.id,\n inputSchema: workflow.inputSchema,\n outputSchema: workflow.outputSchema,\n steps: workflow.stepDefs,\n mastra: workflow.mastra,\n options: workflow.options,\n });\n\n wf.setStepFlow(workflow.stepGraph);\n wf.commit();\n return wf;\n },\n };\n}\n"]}
|