@cchevli/inngest 1.8.1-walton.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 +3981 -0
- package/dist/__tests__/adapters/_utils.d.ts +18 -0
- package/dist/__tests__/adapters/_utils.d.ts.map +1 -0
- package/dist/__tests__/durable-agent.test.utils.d.ts +43 -0
- package/dist/__tests__/durable-agent.test.utils.d.ts.map +1 -0
- package/dist/chunk-MICZJLEE.cjs +1977 -0
- package/dist/chunk-MICZJLEE.cjs.map +1 -0
- package/dist/chunk-SE7QPBOX.js +1970 -0
- package/dist/chunk-SE7QPBOX.js.map +1 -0
- package/dist/connect.cjs +12 -0
- package/dist/connect.cjs.map +1 -0
- package/dist/connect.d.ts +43 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +3 -0
- package/dist/connect.js.map +1 -0
- package/dist/durable-agent/create-inngest-agent.d.ts +425 -0
- package/dist/durable-agent/create-inngest-agent.d.ts.map +1 -0
- package/dist/durable-agent/create-inngest-agentic-workflow.d.ts +56 -0
- package/dist/durable-agent/create-inngest-agentic-workflow.d.ts.map +1 -0
- package/dist/durable-agent/index.d.ts +48 -0
- package/dist/durable-agent/index.d.ts.map +1 -0
- package/dist/execution-engine.d.ts +209 -0
- package/dist/execution-engine.d.ts.map +1 -0
- package/dist/functions.d.ts +7 -0
- package/dist/functions.d.ts.map +1 -0
- package/dist/index.cjs +1576 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +117 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1548 -0
- package/dist/index.js.map +1 -0
- package/dist/nested-workflow-output.d.ts +21 -0
- package/dist/nested-workflow-output.d.ts.map +1 -0
- package/dist/pubsub.d.ts +60 -0
- package/dist/pubsub.d.ts.map +1 -0
- package/dist/run.d.ts +234 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/serve.d.ts +77 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/types.d.ts +16 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/workflow.d.ts +58 -0
- package/dist/workflow.d.ts.map +1 -0
- package/package.json +98 -0
|
@@ -0,0 +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","cache","InngestPubSub","InMemoryServerCache","CachingPubSub","emitErrorEvent","runDurableStreamUntilIdle","prepareForDurableExecution","globalRunRegistry","createDurableAgentStream","result","runResumeDurableStreamUntilIdle","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,CAAA;AAChD,IAAA,OAAO,QAAQ,YAAY,CAAA;AAAA,EAC7B,CAAA;AACF;AAgBO,IAAM,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,MAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,UAAA;AAAA,IACA,SAAA,CACE,MACA,IAAA,EAC2D;AAC3D,MAAA,OAAO;AAAA,QACL,IAAI,IAAA,CAAK,EAAA;AAAA,QACT,aAAa,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,IAAIgB,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 {\n prepareForDurableExecution,\n createDurableAgentStream,\n emitErrorEvent,\n runDurableStreamUntilIdle,\n runResumeDurableStreamUntilIdle,\n globalRunRegistry,\n} from '@mastra/core/agent/durable';\nimport type { AgentStepFinishEventData, AgentSuspendedEventData } from '@mastra/core/agent/durable';\nimport type { MessageListInput } from '@mastra/core/agent/message-list';\nimport { InMemoryServerCache } from '@mastra/core/cache';\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, FullOutput, MastraOnFinishCallback } from '@mastra/core/stream';\nimport type { Workflow } from '@mastra/core/workflows';\nimport type { Inngest } from 'inngest';\n\nimport { InngestPubSub } from '../pubsub';\nimport type { InngestWorkflow } from '../workflow';\nimport { createInngestDurableAgenticWorkflow, InngestDurableStepIds } from './create-inngest-agentic-workflow';\n\n/**\n * Internal sentinel used by {@link InngestAgent.generate} and\n * {@link InngestAgent.resumeGenerate} to ask the underlying `stream()` /\n * `resume()` implementation to close the consumer stream on a SUSPENDED\n * event, so `getFullOutput()` resolves promptly with `finishReason:\n * 'suspended'` instead of waiting for FINISH/ERROR.\n *\n * Modelled on `CLOSE_ON_SUSPEND` in core `DurableAgent`.\n */\nconst CLOSE_ON_SUSPEND = Symbol('mastra.durable.inngest.closeOnSuspend');\n\n/**\n * Internal symbol used by `generate()` / `resumeGenerate()` to tear down the\n * pubsub subscription on suspend without removing the run-registry entry.\n * The public `cleanup()` does both; this lets the generate wrappers keep the\n * registry alive across `suspend` → `resumeGenerate()` while still releasing\n * the local stream subscription.\n */\nconst STREAM_CLEANUP = Symbol('mastra.durable.inngest.streamCleanup');\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 *\n * Mirrors `DurableAgentStreamOptions` from `@mastra/core/agent/durable` so that\n * Inngest-backed durable agents accept the same execution surface as the\n * in-memory `DurableAgent`. Most options flow straight through\n * `prepareForDurableExecution` and onto the shared workflow steps; see\n * `.context/durable-agent-parity.md` for the per-option durability matrix.\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 /**\n * Stop condition(s) for the agentic loop. Data-shaped conditions are\n * serialized into the workflow snapshot; function-form conditions are stored\n * on the in-process run registry and degrade to \"no extra stop\" on a\n * cross-worker resume (same as core DurableAgent).\n */\n stopWhen?: AgentExecutionOptions<OUTPUT>['stopWhen'];\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 /** Tool names enabled for this execution */\n activeTools?: AgentExecutionOptions<OUTPUT>['activeTools'];\n /** Model settings */\n modelSettings?: AgentExecutionOptions<OUTPUT>['modelSettings'];\n /** Require approval for tool calls. Boolean (gate all / none) or a per-call function policy. */\n requireToolApproval?: AgentExecutionOptions<OUTPUT>['requireToolApproval'];\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 /** Structured output configuration */\n structuredOutput?: AgentExecutionOptions<OUTPUT>['structuredOutput'];\n /** Version overrides for sub-agent delegation */\n versions?: AgentExecutionOptions<OUTPUT>['versions'];\n /** Additional system message appended after context but before user messages. */\n system?: AgentExecutionOptions<OUTPUT>['system'];\n /** When true, background tasks are disabled for this run. */\n disableBackgroundTasks?: AgentExecutionOptions<OUTPUT>['disableBackgroundTasks'];\n /** Tracing options forwarded to the agent/model spans. */\n tracingOptions?: AgentExecutionOptions<OUTPUT>['tracingOptions'];\n /** Per-call actor signal forwarded to FGA checks and tool execution. */\n actor?: AgentExecutionOptions<OUTPUT>['actor'];\n /**\n * Tool payload transform policy. `targets` is JSON-safe and persisted in the\n * workflow snapshot; `transformToolPayload` is a closure on the run registry\n * and degrades on cross-worker resume.\n */\n transform?: AgentExecutionOptions<OUTPUT>['transform'];\n /**\n * Per-step preparation hook. Stored on the run registry and applied via a\n * processor in the durable LLM step. Closure — degrades on cross-worker\n * resume.\n */\n prepareStep?: AgentExecutionOptions<OUTPUT>['prepareStep'];\n /**\n * Optional completion config (scorers + onComplete + suppressFeedback).\n * JSON-safe parts are serialized; the `onComplete` callback lives on the run\n * registry and degrades on cross-worker resume.\n */\n isTaskComplete?: AgentExecutionOptions<OUTPUT>['isTaskComplete'];\n /**\n * Sub-agent delegation hooks. Forwarded into `convertTools` at prepare time\n * and baked into the sub-agent tool wrappers stored on the run registry.\n * Cross-worker resume on a fresh worker loses the callbacks and degrades to\n * the agent's default delegation.\n */\n delegation?: AgentExecutionOptions<OUTPUT>['delegation'];\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?: MastraOnFinishCallback<OUTPUT>;\n /** Callback on error */\n onError?: ({ error }: { error: Error | string }) => void | Promise<void>;\n /** Callback when workflow suspends */\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n /** Callback when execution is aborted via abortSignal or `result.abort()` */\n onAbort?: AgentExecutionOptions<OUTPUT>['onAbort'];\n /** Callback fired after each agentic-loop iteration (observation only) */\n onIterationComplete?: AgentExecutionOptions<OUTPUT>['onIterationComplete'];\n /**\n * Optional external abort signal. Forwarded onto an internal AbortController\n * stored on the run registry. Either the external signal or\n * `result.abort()` will cancel the stream and emit an ABORT event over\n * pubsub.\n */\n abortSignal?: AbortSignal;\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 * Abort this run. Flips the internal AbortController for this stream so the\n * durable LLM step short-circuits (when the step worker shares the same\n * process) and emits an ABORT event over pubsub so the consumer stream\n * closes. Safe to call after the run has already finished.\n */\n abort: (reason?: unknown) => void;\n}\n\n/**\n * Options for InngestAgent.resume(). Mirrors core DurableAgent.resume().\n */\nexport interface InngestAgentResumeOptions<OUTPUT = undefined> {\n threadId?: string;\n resourceId?: string;\n onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n onFinish?: MastraOnFinishCallback<OUTPUT>;\n onError?: ({ error }: { error: Error | string }) => void | Promise<void>;\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n /** Callback when execution is aborted via abortSignal or `result.abort()` */\n onAbort?: AgentExecutionOptions<OUTPUT>['onAbort'];\n /**\n * Optional abort signal scoped to the resumed segment. Forwarded onto a\n * fresh internal controller installed on the run's registry entry, so\n * `result.abort()` and the external signal can both cancel the resumed\n * iterations.\n */\n abortSignal?: AbortSignal;\n /**\n * When set, keep the resumed segment open after the workflow's initial\n * resume turn finishes and continue streaming follow-up turns until the\n * agent goes idle (no in-flight background tasks for the same memory\n * scope). Same semantics as `stream({ untilIdle })`. Pass an object to\n * tune `maxIdleMs`.\n */\n untilIdle?: boolean | { maxIdleMs?: number };\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?: InngestAgentResumeOptions<TOutput>,\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?: MastraOnFinishCallback<TOutput>;\n onError?: ({ error }: { error: Error | string }) => 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 * Drain a durable run to a single {@link FullOutput}. Mirrors\n * {@link DurableAgent.generate}: kicks off the same Inngest durable\n * workflow as {@link InngestAgent.stream}, but threads\n * `methodType: 'generate'` into preparation (so tool/preparation paths\n * that branch on method behave consistently with non-durable\n * `Agent.generate`) and awaits `output.getFullOutput()`.\n *\n * If the run suspends (e.g. tool approval), the returned output's\n * `finishReason` is `'suspended'` — use {@link InngestAgent.resumeGenerate}\n * to continue. The run registry entry is intentionally not cleaned up on\n * suspend so resume can pick it up.\n */\n generate(messages: MessageListInput, options?: InngestAgentStreamOptions<TOutput>): Promise<FullOutput<TOutput>>;\n\n /**\n * Resume a suspended durable run and drain it to a single\n * {@link FullOutput}. Mirrors {@link DurableAgent.resumeGenerate} on top\n * of {@link InngestAgent.resume}.\n */\n resumeGenerate(\n runId: string,\n resumeData: unknown,\n options?: InngestAgentResumeOptions<TOutput>,\n ): Promise<FullOutput<TOutput>>;\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 /** 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 /** 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 // Resolve the cache that backs CachingPubSub history.\n //\n // Resolution order: user-provided > mastra's serverCache > InMemoryServerCache fallback.\n // The fallback gives single-process observe replay parity with the in-memory durable agent.\n // Cross-process observe still requires a shared cache backend (Redis, etc.) supplied via\n // `cache` or `mastra.serverCache`.\n function resolveCache(): MastraServerCache {\n const resolved = _customCache ?? mastra?.serverCache ?? new InMemoryServerCache();\n _customCache = resolved;\n return resolved;\n }\n\n // Lazily create CachingPubSub for the agent.\n //\n // We always wrap the inner pubsub with CachingPubSub (mirroring the in-memory DurableAgent\n // at packages/core/src/agent/durable/durable-agent.ts#ensurePubsubInitialized). Without it,\n // `observe()` would only see live events: the bare InngestPubSub.subscribe streams from the\n // current point in the realtime channel, with no history replay, so reconnects and late\n // observers miss everything emitted before they attached.\n //\n // If the inner pubsub is already a CachingPubSub (e.g. a user passed `new Mastra({ pubsub })`\n // with their own caching layer), we reuse it instead of double-wrapping (issue #18148).\n function getPubsub(): PubSub {\n if (!_cachingPubsub) {\n if (innerPubsub instanceof CachingPubSub) {\n _cachingPubsub = innerPubsub;\n _customCache = _customCache ?? mastra?.serverCache;\n } else {\n _cachingPubsub = new CachingPubSub(innerPubsub, resolveCache());\n }\n }\n return _cachingPubsub;\n }\n\n // Route workflow event publishes through a CachingPubSub backed by the same cache\n // as the agent's pubsub. Each InngestWorkflow function (including nested ones)\n // passes its own workflow-local InngestPubSub as `defaultPubsub`, which we wrap.\n // This keeps per-workflow event channels (`workflow:<workflowId>:<runId>`)\n // workflow-local while sharing the cache that `observe()` reads from for\n // agent-stream replay.\n // The chained `.commit()` builder loses the InngestWorkflow subtype, so cast back.\n (workflow as unknown as InngestWorkflow).__setPubsubFactory(defaultPubsub => {\n // If the caller already supplied a CachingPubSub upstream, defer to it.\n if (defaultPubsub instanceof CachingPubSub) return defaultPubsub;\n // Ensure the agent's CachingPubSub (and its cache) is resolved so workflow\n // events and agent.stream events share the same history backend.\n getPubsub();\n return new CachingPubSub(defaultPubsub, resolveCache());\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: workflowInput.requestContextEntries ?? {},\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 | 'generate'\n | 'resumeGenerate'\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 methodType: (streamOptions as any)?.__methodType ?? 'stream',\n });\n\n const { runId, messageId, workflowInput, registryEntry, 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 // 1a. Install abort controller for this run. The controller is owned by\n // this InngestAgent instance; `result.abort()` flips it, the durable\n // LLM-execution step reads `abortSignal` off the global run registry\n // (when running in the same process) and the consumer stream closes via\n // an ABORT pubsub event when the inner catch detects the signal. If the\n // caller supplied an external signal, forward it onto the internal\n // controller so either source can cancel the run.\n const abortController = new AbortController();\n if (streamOptions?.abortSignal) {\n const external = streamOptions.abortSignal;\n if (external.aborted) {\n abortController.abort((external as AbortSignal & { reason?: unknown }).reason);\n } else {\n external.addEventListener(\n 'abort',\n () => abortController.abort((external as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n registryEntry.abortController = abortController;\n registryEntry.abortSignal = abortController.signal;\n\n // 1b. Register non-serializable state on the global run registry so\n // workflow steps running in the same process can recover it.\n globalRunRegistry.set(runId, registryEntry);\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?.modelSettings?.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 // Track cleanup state and global registry entry lifecycle.\n let cleanedUp = false;\n const finalizeGlobalRegistry = () => {\n if (cleanedUp) return;\n cleanedUp = true;\n globalRunRegistry.delete(runId);\n };\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: async result => {\n try {\n await streamOptions?.onFinish?.(result);\n } finally {\n finalizeGlobalRegistry();\n }\n },\n onError: async errorArg => {\n try {\n await streamOptions?.onError?.(errorArg);\n } finally {\n finalizeGlobalRegistry();\n }\n },\n onSuspended: streamOptions?.onSuspended,\n onAbort: async data => {\n try {\n await (streamOptions?.onAbort as ((event: any) => void | Promise<void>) | undefined)?.(data);\n } finally {\n finalizeGlobalRegistry();\n }\n },\n onIterationComplete: streamOptions?.onIterationComplete\n ? async data => {\n await (streamOptions.onIterationComplete as (ctx: any) => void | Promise<void>)?.(data);\n }\n : undefined,\n closeOnSuspend: (streamOptions as any)?.[CLOSE_ON_SUSPEND] === true,\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 // Track the trigger promise on the registry so generate() can await suspend\n // snapshot persistence before returning.\n const workflowExecution = ready\n .then(() => triggerWorkflow(runId, workflowInput, tracingOptions))\n .catch(error => {\n void emitError(runId, error);\n });\n const trackedEntry = globalRunRegistry.get(runId);\n if (trackedEntry) {\n trackedEntry.workflowExecution = workflowExecution;\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 cleanup = () => {\n streamCleanup();\n finalizeGlobalRegistry();\n };\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n const result = {\n output,\n runId,\n threadId,\n resourceId,\n cleanup,\n abort,\n // Also expose fullStream directly for server compatibility\n get fullStream() {\n return output.fullStream;\n },\n // Internal: stream-only cleanup for generate()/resumeGenerate() to\n // release the subscription on suspend without dropping the registry.\n [STREAM_CLEANUP]: streamCleanup,\n };\n\n return result as InngestAgentStreamResult<TOutput>;\n },\n\n async resume(runId, resumeData, resumeOptions): Promise<InngestAgentStreamResult<TOutput>> {\n // Delegate to the resume idle-loop wrapper when `untilIdle` is set.\n // After the resumed segment completes, the wrapper runs\n // `agent.stream([], ...)` continuations against the same thread until\n // pending background tasks settle.\n if (resumeOptions?.untilIdle) {\n const { untilIdle, ...rest } = resumeOptions;\n const maxIdleMs = typeof untilIdle === 'object' ? untilIdle.maxIdleMs : undefined;\n return runResumeDurableStreamUntilIdle<TOutput>(\n proxyRef as any,\n runId,\n resumeData,\n { ...rest, maxIdleMs } as any,\n {\n activeStreams: activeStreamUntilIdle,\n bgManager: mastra?.backgroundTaskManager,\n },\n ) as Promise<InngestAgentStreamResult<TOutput>>;\n }\n\n // Install a fresh abort controller scoped to the resumed segment and\n // attach it to the run-registry entry so the durable LLM step (when\n // co-located) can react. The previous run's controller is no longer\n // relevant.\n const abortController = new AbortController();\n if (resumeOptions?.abortSignal) {\n const external = resumeOptions.abortSignal;\n if (external.aborted) {\n abortController.abort((external as AbortSignal & { reason?: unknown }).reason);\n } else {\n external.addEventListener(\n 'abort',\n () => abortController.abort((external as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n // Ensure a registry entry exists for this resumed segment. On Inngest,\n // a resume frequently runs in a fresh process where no prior stream()\n // entry is in memory — without this, the abort controller would be\n // silently dropped and the durable LLM step (when co-located) would\n // have nothing to react to.\n let existingEntry = globalRunRegistry.get(runId);\n if (!existingEntry) {\n existingEntry = {\n // Minimal placeholder fields. The durable LLM step recreates tools\n // and model from the workflow input; this slot exists primarily to\n // carry the abort controller across the resumed segment.\n tools: {},\n model: undefined as any,\n };\n globalRunRegistry.set(runId, existingEntry);\n }\n existingEntry.abortController = abortController;\n existingEntry.abortSignal = abortController.signal;\n\n // Track cleanup state for the resumed segment so terminal events\n // (finish/error/abort/cleanup) always tear down the registry entry.\n let resumeCleanedUp = false;\n const finalizeResumeRegistry = () => {\n if (resumeCleanedUp) return;\n resumeCleanedUp = true;\n globalRunRegistry.delete(runId);\n };\n\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: async result => {\n try {\n await resumeOptions?.onFinish?.(result);\n } finally {\n finalizeResumeRegistry();\n }\n },\n onError: async errorArg => {\n try {\n await resumeOptions?.onError?.(errorArg);\n } finally {\n finalizeResumeRegistry();\n }\n },\n onSuspended: resumeOptions?.onSuspended,\n onAbort: async data => {\n try {\n await (resumeOptions?.onAbort as ((event: any) => void | Promise<void>) | undefined)?.(data);\n } finally {\n finalizeResumeRegistry();\n }\n },\n closeOnSuspend: (resumeOptions as any)?.[CLOSE_ON_SUSPEND] === true,\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 const workflowExecution = 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: snapshot?.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 existingEntry.workflowExecution = workflowExecution;\n\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n const cleanup = () => {\n streamCleanup();\n finalizeResumeRegistry();\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,\n abort,\n // Internal: stream-only cleanup for resumeGenerate() to release the\n // subscription on suspend without dropping the resumed registry entry.\n [STREAM_CLEANUP]: streamCleanup,\n } as InngestAgentStreamResult<TOutput>;\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 // `observe()` is a read-only re-subscription — it does not own the run\n // so it cannot abort the underlying workflow. We still expose `abort()`\n // on the result for type parity with stream()/resume(); calling it\n // closes the local subscription via cleanup but is a no-op against the\n // running workflow.\n const abort = (_reason?: unknown) => {\n streamCleanup();\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n cleanup: streamCleanup,\n abort,\n };\n },\n\n async generate(messages, generateOptions): Promise<FullOutput<TOutput>> {\n // Delegate to stream() with `methodType: 'generate'` and `closeOnSuspend`\n // so that getFullOutput() resolves promptly on suspend (mirroring\n // DurableAgent.generate). We do NOT pass `untilIdle` through — generate\n // is a one-shot drain, not an idle loop.\n const { untilIdle, ...rest } = generateOptions ?? {};\n void untilIdle;\n const streamOpts = {\n ...rest,\n [CLOSE_ON_SUSPEND]: true,\n __methodType: 'generate',\n } as InngestAgentStreamOptions<TOutput>;\n const result = await proxyRef!.stream(messages, streamOpts);\n\n let suspended = false;\n try {\n const fullOutput = (await result.output.getFullOutput()) as FullOutput<TOutput>;\n if (fullOutput.error) {\n throw fullOutput.error;\n }\n suspended = fullOutput.finishReason === 'suspended';\n // On suspend, wait for the workflow trigger promise so the suspend\n // snapshot has landed before returning — otherwise a follow-up\n // resumeGenerate() may race the storage write.\n if (suspended) {\n await globalRunRegistry.get(result.runId)?.workflowExecution;\n }\n if (!fullOutput.runId) {\n (fullOutput as { runId?: string }).runId = result.runId;\n }\n return fullOutput;\n } finally {\n // Always release the local stream subscription. On suspend, keep the\n // registry entry alive so resumeGenerate() can pick it up; other\n // outcomes run the full public cleanup (which also finalizes the\n // registry).\n if (suspended) {\n const streamOnlyCleanup = (result as unknown as { [STREAM_CLEANUP]?: () => void })[STREAM_CLEANUP];\n streamOnlyCleanup?.();\n } else {\n result.cleanup();\n }\n }\n },\n\n async resumeGenerate(runId, resumeData, resumeOptions): Promise<FullOutput<TOutput>> {\n // `resumeGenerate` is a one-shot drain; strip `untilIdle` so the\n // underlying resume() never delegates to the idle-loop wrapper.\n const { untilIdle, ...rest } = resumeOptions ?? {};\n void untilIdle;\n const result = await proxyRef!.resume(runId, resumeData, {\n ...rest,\n [CLOSE_ON_SUSPEND]: true,\n } as InngestAgentResumeOptions<TOutput>);\n\n let suspended = false;\n try {\n const fullOutput = (await result.output.getFullOutput()) as FullOutput<TOutput>;\n if (fullOutput.error) {\n throw fullOutput.error;\n }\n suspended = fullOutput.finishReason === 'suspended';\n if (suspended) {\n await globalRunRegistry.get(result.runId)?.workflowExecution;\n }\n if (!fullOutput.runId) {\n (fullOutput as { runId?: string }).runId = result.runId;\n }\n return fullOutput;\n } finally {\n if (suspended) {\n const streamOnlyCleanup = (result as unknown as { [STREAM_CLEANUP]?: () => void })[STREAM_CLEANUP];\n streamOnlyCleanup?.();\n } else {\n result.cleanup();\n }\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"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { ReadableStream } from 'node:stream/web';
|
|
2
|
+
import { Agent } from '@mastra/core/agent';
|
|
3
|
+
import type { MastraScorers } from '@mastra/core/evals';
|
|
4
|
+
import type { Processor, ProcessorStepInputSchema } from '@mastra/core/processors';
|
|
5
|
+
import { ProcessorStepOutputSchema } from '@mastra/core/processors';
|
|
6
|
+
import type { InferPublicSchema, PublicSchema, StandardSchemaWithJSON } from '@mastra/core/schema';
|
|
7
|
+
import type { ToolExecutionContext } from '@mastra/core/tools';
|
|
8
|
+
import { Tool, createTool } from '@mastra/core/tools';
|
|
9
|
+
import type { DynamicArgument } from '@mastra/core/types';
|
|
10
|
+
import type { Step, AgentStepOptions, StepParams, StepMetadata } from '@mastra/core/workflows';
|
|
11
|
+
import { Workflow } from '@mastra/core/workflows';
|
|
12
|
+
import type { Inngest } from 'inngest';
|
|
13
|
+
import type { InngestEngineType, InngestWorkflowConfig } from './types.js';
|
|
14
|
+
import { InngestWorkflow } from './workflow.js';
|
|
15
|
+
export * from './workflow.js';
|
|
16
|
+
export * from './execution-engine.js';
|
|
17
|
+
export * from './pubsub.js';
|
|
18
|
+
export * from './run.js';
|
|
19
|
+
export * from './serve.js';
|
|
20
|
+
export * from './connect.js';
|
|
21
|
+
export * from './types.js';
|
|
22
|
+
export * from './durable-agent/index.js';
|
|
23
|
+
type InngestSubAgent<TId extends string = string> = {
|
|
24
|
+
id: TId;
|
|
25
|
+
name?: string;
|
|
26
|
+
getDescription: () => string;
|
|
27
|
+
getModel: () => Promise<{
|
|
28
|
+
specificationVersion: string;
|
|
29
|
+
}> | {
|
|
30
|
+
specificationVersion: string;
|
|
31
|
+
};
|
|
32
|
+
generate: (...args: any[]) => Promise<any>;
|
|
33
|
+
stream: (...args: any[]) => Promise<{
|
|
34
|
+
fullStream: ReadableStream<any>;
|
|
35
|
+
}>;
|
|
36
|
+
streamLegacy?: (...args: any[]) => Promise<{
|
|
37
|
+
fullStream: ReadableStream<any>;
|
|
38
|
+
}>;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Creates a step from explicit params (IMPORTANT: FIRST overload for best error messages when using .then in workflows)
|
|
42
|
+
* @param params Configuration parameters for the step
|
|
43
|
+
* @param params.id Unique identifier for the step
|
|
44
|
+
* @param params.description Optional description of what the step does
|
|
45
|
+
* @param params.inputSchema Zod schema defining the input structure
|
|
46
|
+
* @param params.outputSchema Zod schema defining the output structure
|
|
47
|
+
* @param params.execute Function that performs the step's operations
|
|
48
|
+
* @returns A Step object that can be added to the workflow
|
|
49
|
+
*/
|
|
50
|
+
export declare function createStep<TStepId extends string, TStateSchema extends PublicSchema | undefined, TInputSchema extends PublicSchema, TOutputSchema extends PublicSchema, TResumeSchema extends PublicSchema | undefined = undefined, TSuspendSchema extends PublicSchema | undefined = undefined>(params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>): Step<TStepId, TStateSchema extends PublicSchema ? InferPublicSchema<TStateSchema> : unknown, InferPublicSchema<TInputSchema>, InferPublicSchema<TOutputSchema>, TResumeSchema extends PublicSchema ? InferPublicSchema<TResumeSchema> : unknown, TSuspendSchema extends PublicSchema ? InferPublicSchema<TSuspendSchema> : unknown, InngestEngineType>;
|
|
51
|
+
/**
|
|
52
|
+
* Creates a step from an agent with structured output
|
|
53
|
+
*/
|
|
54
|
+
export declare function createStep<TStepId extends string, TStepOutput>(agent: InngestSubAgent<TStepId> | Agent<TStepId, any>, agentOptions: AgentStepOptions<TStepOutput> & {
|
|
55
|
+
structuredOutput: {
|
|
56
|
+
schema: StandardSchemaWithJSON<TStepOutput>;
|
|
57
|
+
};
|
|
58
|
+
retries?: number;
|
|
59
|
+
scorers?: DynamicArgument<MastraScorers>;
|
|
60
|
+
metadata?: StepMetadata;
|
|
61
|
+
}): Step<TStepId, unknown, {
|
|
62
|
+
prompt: string;
|
|
63
|
+
}, TStepOutput, unknown, unknown, InngestEngineType>;
|
|
64
|
+
/**
|
|
65
|
+
* Creates a step from an agent (defaults to { text: string } output)
|
|
66
|
+
*/
|
|
67
|
+
export declare function createStep<TStepId extends string, TStepInput extends {
|
|
68
|
+
prompt: string;
|
|
69
|
+
}, TStepOutput extends {
|
|
70
|
+
text: string;
|
|
71
|
+
}, TResume, TSuspend>(agent: InngestSubAgent<TStepId> | Agent<TStepId, any>, agentOptions?: AgentStepOptions<TStepOutput> & {
|
|
72
|
+
retries?: number;
|
|
73
|
+
scorers?: DynamicArgument<MastraScorers>;
|
|
74
|
+
}): Step<TStepId, unknown, TStepInput, TStepOutput, TResume, TSuspend, InngestEngineType>;
|
|
75
|
+
/**
|
|
76
|
+
* Creates a step from a tool
|
|
77
|
+
*/
|
|
78
|
+
export declare function createStep<TSchemaIn, TSchemaOut, TSuspend, TResume, TContext extends ToolExecutionContext<TSuspend, TResume, any> = ToolExecutionContext<TSuspend, TResume>, TId extends string = string, TRequestContext extends Record<string, any> | unknown = unknown>(tool: Tool<TSchemaIn, TSchemaOut, TSuspend, TResume, TContext, TId, TRequestContext>, toolOptions?: {
|
|
79
|
+
retries?: number;
|
|
80
|
+
scorers?: DynamicArgument<MastraScorers>;
|
|
81
|
+
metadata?: StepMetadata;
|
|
82
|
+
}): Step<TId, unknown, TSchemaIn, TSchemaOut, TSuspend, TResume, InngestEngineType>;
|
|
83
|
+
/**
|
|
84
|
+
* Creates a step from a Processor - wraps a Processor as a workflow step
|
|
85
|
+
* Note: We require at least one processor method to distinguish from StepParams
|
|
86
|
+
*/
|
|
87
|
+
export declare function createStep<TProcessorId extends string>(processor: (Processor<TProcessorId> & {
|
|
88
|
+
processInput: Function;
|
|
89
|
+
}) | (Processor<TProcessorId> & {
|
|
90
|
+
processInputStream: Function;
|
|
91
|
+
}) | (Processor<TProcessorId> & {
|
|
92
|
+
processInputStep: Function;
|
|
93
|
+
}) | (Processor<TProcessorId> & {
|
|
94
|
+
processOutputStream: Function;
|
|
95
|
+
}) | (Processor<TProcessorId> & {
|
|
96
|
+
processOutputResult: Function;
|
|
97
|
+
}) | (Processor<TProcessorId> & {
|
|
98
|
+
processOutputStep: Function;
|
|
99
|
+
})): Step<`processor:${TProcessorId}`, unknown, InferPublicSchema<typeof ProcessorStepInputSchema>, InferPublicSchema<typeof ProcessorStepOutputSchema>, unknown, unknown, InngestEngineType>;
|
|
100
|
+
/**
|
|
101
|
+
* IMPORTANT: Fallback overload - provides better error messages when StepParams doesn't match
|
|
102
|
+
* This should be LAST and will show clearer errors about what's wrong
|
|
103
|
+
* This is a copy of first one, KEEP THIS IN SYNC!
|
|
104
|
+
*/
|
|
105
|
+
export declare function createStep<TStepId extends string, TStateSchema extends PublicSchema | undefined, TInputSchema extends PublicSchema, TOutputSchema extends PublicSchema, TResumeSchema extends PublicSchema | undefined = undefined, TSuspendSchema extends PublicSchema | undefined = undefined>(params: StepParams<TStepId, TStateSchema, TInputSchema, TOutputSchema, TResumeSchema, TSuspendSchema>): Step<TStepId, TStateSchema extends PublicSchema ? InferPublicSchema<TStateSchema> : unknown, InferPublicSchema<TInputSchema>, InferPublicSchema<TOutputSchema>, TResumeSchema extends PublicSchema ? InferPublicSchema<TResumeSchema> : unknown, TSuspendSchema extends PublicSchema ? InferPublicSchema<TSuspendSchema> : unknown, InngestEngineType>;
|
|
106
|
+
export declare function init(inngest: Inngest): {
|
|
107
|
+
createTool: typeof createTool;
|
|
108
|
+
createWorkflow<TWorkflowId extends string = string, TState = any, TInput = any, TOutput = any, TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[] = Step<string, any, any, any, any, any, InngestEngineType, unknown>[]>(params: InngestWorkflowConfig<TWorkflowId, TState, TInput, TOutput, TSteps>): InngestWorkflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TInput>;
|
|
109
|
+
createStep: typeof createStep;
|
|
110
|
+
cloneStep<TStepId extends string>(step: Step<TStepId, any, any, any, any, any, InngestEngineType>, opts: {
|
|
111
|
+
id: TStepId;
|
|
112
|
+
}): Step<TStepId, any, any, any, any, any, InngestEngineType>;
|
|
113
|
+
cloneWorkflow<TWorkflowId extends string = string, TState = unknown, TInput = unknown, TOutput = unknown, TSteps extends Step<string, any, any, any, any, any, InngestEngineType>[] = Step<string, any, any, any, any, any, InngestEngineType, unknown>[], TPrev = TInput>(workflow: Workflow<InngestEngineType, TSteps, string, TState, TInput, TOutput, TPrev>, opts: {
|
|
114
|
+
id: TWorkflowId;
|
|
115
|
+
}): Workflow<InngestEngineType, TSteps, TWorkflowId, TState, TInput, TOutput, TPrev>;
|
|
116
|
+
};
|
|
117
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,KAAK,EAAyB,MAAM,oBAAoB,CAAC;AAGlE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAIxD,OAAO,KAAK,EAAE,SAAS,EAAuB,wBAAwB,EAAgB,MAAM,yBAAyB,CAAC;AACtH,OAAO,EAAmB,yBAAyB,EAAuB,MAAM,yBAAyB,CAAC;AAC1G,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,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