@mastra/inngest 1.6.0 → 1.7.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 +36 -0
- package/dist/durable-agent/create-inngest-agent.d.ts +12 -0
- package/dist/durable-agent/create-inngest-agent.d.ts.map +1 -1
- package/dist/index.cjs +15 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +16 -4
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../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":["collectInngestFunctions","inngestServeHono","z","modelConfigSchema","baseIterationStateSchema","DurableStepIds","DurableAgentDefaults","createDurableLLMExecutionStep","createDurableToolCallStep","createDurableLLMMappingStep","createDurableBackgroundTaskCheckStep","InternalSpans","observability","SpanType","EntityType","createBaseIterationStateUpdate","durableAgenticOutputSchema","PUBSUB_SYMBOL","emitFinishEvent","InngestPubSub","CachingPubSub","emitErrorEvent","prepareForDurableExecution","createDurableAgentStream","InngestWorkflow","Tool","Agent","toStandardSchema","STREAM_FORMAT_SYMBOL","ProcessorStepSchema","ProcessorStepOutputSchema","TripWire","MessageList","result","MastraError","ErrorCategory","ErrorDomain","ProcessorRunner","processorSpan","processorTracingContext","createTool","Workflow"],"mappings":";;;;;;;;;;;;;;;;AA+BA,SAAS,mBAAA,CAAoB,EAAE,MAAA,EAAQ,OAAA,EAAS,WAAW,aAAA,GAAgB,EAAC,EAAG,eAAA,EAAgB,EAAuB;AACpH,EAAA,OAAO;AAAA,IACL,GAAG,eAAA;AAAA,IACH,MAAA,EAAQ,OAAA;AAAA,IACR,WAAWA,yCAAA,CAAwB,EAAE,MAAA,EAAQ,SAAA,EAAW,eAAe;AAAA,GACzE;AACF;AAsCO,SAAS,YACd,OAAA,EAC2C;AA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,IAAA,CAAK,WAAA;AAAA,QAClB,aAAa,IAAA,CAAK,WAAA;AAAA,QAClB,cAAc,IAAA,CAAK,YAAA;AAAA,QACnB,cAAc,IAAA,CAAK,YAAA;AAAA,QACnB,eAAe,IAAA,CAAK,aAAA;AAAA,QACpB,aAAa,IAAA,CAAK,WAAA;AAAA,QAClB,UAAU,IAAA,CAAK,QAAA;AAAA,QACf,SAAS,IAAA,CAAK,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,IAAIiB,kBAAA,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.cjs","sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport type { Inngest, InngestFunction, RegisterOptions } from 'inngest';\nimport { serve as inngestServeHono } from 'inngest/hono';\nimport { collectInngestFunctions } from './functions';\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 */\nfunction prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }: MastraServeOptions) {\n return {\n ...registerOptions,\n client: inngest,\n functions: collectInngestFunctions({ mastra, functions: 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('/inngest/api', 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: '/inngest/api',\n * });\n * ```\n *\n * @example Next.js\n * ```ts\n * // app/inngest/api/route.ts — file path determines the route URL\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('/inngest/api', 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 } from 'inngest';\n\n// Extract Inngest's native flow control configuration types from createFunction first argument\nexport type InngestCreateFunctionConfig = Parameters<Inngest['createFunction']>[0];\n\n// Extract specific flow control properties (excluding batching)\nexport type InngestFlowControlConfig = Pick<\n InngestCreateFunctionConfig,\n 'concurrency' | 'rateLimit' | 'throttle' | 'debounce' | 'priority'\n>;\n\n// Cron config for scheduled workflows\nexport type InngestFlowCronConfig<TInputData, TInitialState> = {\n cron?: string;\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 *\n * const inngest = new Inngest({\n * id: 'my-app',\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 (via\n // `inngest.realtime.publish()` in SDK v4) 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 './connect';\nexport * from './types';\nexport * from './durable-agent';\n\ntype InngestSubAgent<TId extends string = string> = {\n id: TId;\n name?: string;\n getDescription: () => string;\n getModel: () => Promise<{ specificationVersion: string }> | { specificationVersion: string };\n generate: (...args: any[]) => Promise<any>;\n stream: (...args: any[]) => Promise<{ fullStream: ReadableStream<any> }>;\n streamLegacy?: (...args: any[]) => Promise<{ fullStream: ReadableStream<any> }>;\n};\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\n/**\n * copied from @mastra/core/agent/subagent.ts for compatible\n */\nfunction isAgentCompatible<TId extends string>(input: unknown): input is InngestSubAgent<TId> {\n return (\n typeof input === 'object' &&\n input !== null &&\n 'generate' in input &&\n typeof input.generate === 'function' &&\n 'stream' in input &&\n typeof input.stream === 'function' &&\n 'getDescription' in input &&\n typeof input.getDescription === 'function' &&\n 'getModel' in input &&\n typeof input.getModel === 'function'\n );\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: InngestSubAgent<TStepId> | 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: InngestSubAgent<TStepId> | 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 (isAgentCompatible(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: InngestSubAgent<TStepId> | 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.id,\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 ?? params.id,\n args: inputData,\n };\n\n let stream: ReadableStream<any>;\n\n if ((await params.getModel()).specificationVersion === 'v1') {\n if (typeof params.streamLegacy !== 'function') {\n throw new Error(`Agent step ${params.id} returned a v1 model but does not implement streamLegacy`);\n }\n const modelOutput = await params.streamLegacy((inputData as { prompt: string }).prompt, {\n ...(agentOptions ?? {}),\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 (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 if ('text' in modelOutput) {\n void (modelOutput as { text: Promise<string> }).text.then(streamPromise.resolve, streamPromise.reject);\n }\n stream = modelOutput.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((inputData as { prompt: string }).prompt, {\n ...baseOptions,\n structuredOutput,\n } as any)\n : await params.stream((inputData as { prompt: string }).prompt, baseOptions as any);\n\n stream = modelOutput.fullStream as ReadableStream<any>;\n void (modelOutput as { text: Promise<string> }).text.then(streamPromise.resolve, streamPromise.reject);\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: 'AGENT',\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.getSystemMessages(),\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: passThrough.messageList.getSystemMessages(),\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 {\n ...passThrough,\n messages,\n ...validatedResult,\n systemMessages: passThrough.messageList!.getSystemMessages(),\n };\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.getSystemMessages(),\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: passThrough.messageList.getSystemMessages(),\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.getSystemMessages(),\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: passThrough.messageList.getSystemMessages(),\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/serve.ts","../src/types.ts","../src/durable-agent/create-inngest-agentic-workflow.ts","../src/durable-agent/create-inngest-agent.ts","../src/index.ts"],"names":["collectInngestFunctions","inngestServeHono","z","modelConfigSchema","baseIterationStateSchema","DurableStepIds","DurableAgentDefaults","createDurableLLMExecutionStep","createDurableToolCallStep","createDurableLLMMappingStep","createDurableBackgroundTaskCheckStep","InternalSpans","observability","SpanType","EntityType","createBaseIterationStateUpdate","durableAgenticOutputSchema","PUBSUB_SYMBOL","emitFinishEvent","InngestPubSub","CachingPubSub","emitErrorEvent","runDurableStreamUntilIdle","prepareForDurableExecution","createDurableAgentStream","result","InngestWorkflow","Tool","Agent","toStandardSchema","STREAM_FORMAT_SYMBOL","ProcessorStepSchema","ProcessorStepOutputSchema","TripWire","MessageList","MastraError","ErrorCategory","ErrorDomain","ProcessorRunner","processorSpan","processorTracingContext","createTool","Workflow"],"mappings":";;;;;;;;;;;;;;;;AA+BA,SAAS,mBAAA,CAAoB,EAAE,MAAA,EAAQ,OAAA,EAAS,WAAW,aAAA,GAAgB,EAAC,EAAG,eAAA,EAAgB,EAAuB;AACpH,EAAA,OAAO;AAAA,IACL,GAAG,eAAA;AAAA,IACH,MAAA,EAAQ,OAAA;AAAA,IACR,WAAWA,yCAAA,CAAwB,EAAE,MAAA,EAAQ,SAAA,EAAW,eAAe;AAAA,GACzE;AACF;AAsCO,SAAS,YACd,OAAA,EAC2C;AAC3C,EAAA,OAAO,CAAC,OAAA,KAA0C;AAChD,IAAA,MAAM,YAAA,GAAe,oBAAoB,OAAO,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AA,CAAG,MAAA,EAAO;AACV,MAAA,OAAO,EAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport type { Inngest, InngestFunction, RegisterOptions } from 'inngest';\nimport { serve as inngestServeHono } from 'inngest/hono';\nimport { collectInngestFunctions } from './functions';\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 */\nfunction prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }: MastraServeOptions) {\n return {\n ...registerOptions,\n client: inngest,\n functions: collectInngestFunctions({ mastra, functions: 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('/inngest/api', 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: '/inngest/api',\n * });\n * ```\n *\n * @example Next.js\n * ```ts\n * // app/inngest/api/route.ts — file path determines the route URL\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('/inngest/api', 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 } from 'inngest';\n\n// Extract Inngest's native flow control configuration types from createFunction first argument\nexport type InngestCreateFunctionConfig = Parameters<Inngest['createFunction']>[0];\n\n// Extract specific flow control properties (excluding batching)\nexport type InngestFlowControlConfig = Pick<\n InngestCreateFunctionConfig,\n 'concurrency' | 'rateLimit' | 'throttle' | 'debounce' | 'priority'\n>;\n\n// Cron config for scheduled workflows\nexport type InngestFlowCronConfig<TInputData, TInitialState> = {\n cron?: string;\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 *\n * const inngest = new Inngest({\n * id: 'my-app',\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 {\n prepareForDurableExecution,\n createDurableAgentStream,\n emitErrorEvent,\n runDurableStreamUntilIdle,\n} 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 * When set, `stream()` delegates to the idle-loop wrapper that keeps the\n * outer stream open across background-task continuations.\n *\n * Pass `true` for default idle timeout (5 min), or `{ maxIdleMs }` to\n * customise.\n */\n untilIdle?: boolean | { maxIdleMs?: number };\n /** @internal */\n _skipBgTaskWait?: boolean;\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 // Active untilIdle wrappers keyed by scope (threadId|resourceId)\n const activeStreamUntilIdle = new Map<string, () => void>();\n\n // Late-bound reference to the proxy so stream() can pass it to runDurableStreamUntilIdle\n let proxyRef: InngestAgent<TOutput> | undefined;\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 // Delegate to the idle-loop wrapper when `untilIdle` is set.\n if (streamOptions?.untilIdle) {\n const { untilIdle, ...rest } = streamOptions;\n const maxIdleMs = typeof untilIdle === 'object' ? untilIdle.maxIdleMs : undefined;\n return runDurableStreamUntilIdle<TOutput>(proxyRef as any, messages, { ...rest, maxIdleMs } as any, {\n activeStreams: activeStreamUntilIdle,\n bgManager: mastra?.backgroundTaskManager,\n }) as Promise<InngestAgentStreamResult<TOutput>>;\n }\n\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 (via\n // `inngest.realtime.publish()` in SDK v4) 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 const result = 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 // Assign the late-bound reference so stream()'s untilIdle path can use it\n proxyRef = result;\n return result;\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 './connect';\nexport * from './types';\nexport * from './durable-agent';\n\ntype InngestSubAgent<TId extends string = string> = {\n id: TId;\n name?: string;\n getDescription: () => string;\n getModel: () => Promise<{ specificationVersion: string }> | { specificationVersion: string };\n generate: (...args: any[]) => Promise<any>;\n stream: (...args: any[]) => Promise<{ fullStream: ReadableStream<any> }>;\n streamLegacy?: (...args: any[]) => Promise<{ fullStream: ReadableStream<any> }>;\n};\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\n/**\n * copied from @mastra/core/agent/subagent.ts for compatible\n */\nfunction isAgentCompatible<TId extends string>(input: unknown): input is InngestSubAgent<TId> {\n return (\n typeof input === 'object' &&\n input !== null &&\n 'generate' in input &&\n typeof input.generate === 'function' &&\n 'stream' in input &&\n typeof input.stream === 'function' &&\n 'getDescription' in input &&\n typeof input.getDescription === 'function' &&\n 'getModel' in input &&\n typeof input.getModel === 'function'\n );\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: InngestSubAgent<TStepId> | 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: InngestSubAgent<TStepId> | 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 (isAgentCompatible(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: InngestSubAgent<TStepId> | 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.id,\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 ?? params.id,\n args: inputData,\n };\n\n let stream: ReadableStream<any>;\n\n if ((await params.getModel()).specificationVersion === 'v1') {\n if (typeof params.streamLegacy !== 'function') {\n throw new Error(`Agent step ${params.id} returned a v1 model but does not implement streamLegacy`);\n }\n const modelOutput = await params.streamLegacy((inputData as { prompt: string }).prompt, {\n ...(agentOptions ?? {}),\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 (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 if ('text' in modelOutput) {\n void (modelOutput as { text: Promise<string> }).text.then(streamPromise.resolve, streamPromise.reject);\n }\n stream = modelOutput.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((inputData as { prompt: string }).prompt, {\n ...baseOptions,\n structuredOutput,\n } as any)\n : await params.stream((inputData as { prompt: string }).prompt, baseOptions as any);\n\n stream = modelOutput.fullStream as ReadableStream<any>;\n void (modelOutput as { text: Promise<string> }).text.then(streamPromise.resolve, streamPromise.reject);\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: 'AGENT',\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.getSystemMessages(),\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: passThrough.messageList.getSystemMessages(),\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 {\n ...passThrough,\n messages,\n ...validatedResult,\n systemMessages: passThrough.messageList!.getSystemMessages(),\n };\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.getSystemMessages(),\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: passThrough.messageList.getSystemMessages(),\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.getSystemMessages(),\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: passThrough.messageList.getSystemMessages(),\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"]}
|