@mastra/core 1.55.0-alpha.2 → 1.55.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 +86 -0
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/durable/index.cjs +1 -1
- package/dist/agent/durable/index.js +1 -1
- package/dist/agent/index.cjs +2 -2
- package/dist/agent/index.js +2 -2
- package/dist/{agent-BvRfRKIt.js → agent-0y2cApTZ.js} +57 -82
- package/dist/agent-0y2cApTZ.js.map +1 -0
- package/dist/agent-builder/ee/index.cjs +1 -1
- package/dist/agent-builder/ee/index.js +1 -1
- package/dist/agent-controller/index.cjs +1 -1
- package/dist/agent-controller/index.js +1 -1
- package/dist/{agent-controller-CM6tQSMj.js → agent-controller-ByW51eCC.js} +5 -5
- package/dist/{agent-controller-CM6tQSMj.js.map → agent-controller-ByW51eCC.js.map} +1 -1
- package/dist/{agent-controller-C75dc544.cjs → agent-controller-DahKlMET.cjs} +5 -5
- package/dist/{agent-controller-C75dc544.cjs.map → agent-controller-DahKlMET.cjs.map} +1 -1
- package/dist/{agent-CwUYflGG.cjs → agent-um2LJs-0.cjs} +57 -82
- package/dist/agent-um2LJs-0.cjs.map +1 -0
- package/dist/background-tasks/index.cjs +1 -1
- package/dist/background-tasks/index.js +1 -1
- package/dist/{background-tasks-AKlv5tIo.js → background-tasks-CM94BIj8.js} +2 -2
- package/dist/{background-tasks-AKlv5tIo.js.map → background-tasks-CM94BIj8.js.map} +1 -1
- package/dist/{background-tasks-Chpan7PB.cjs → background-tasks-CobPW4Z3.cjs} +2 -2
- package/dist/{background-tasks-Chpan7PB.cjs.map → background-tasks-CobPW4Z3.cjs.map} +1 -1
- package/dist/browser/index.cjs +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/channels/index.cjs +2 -2
- package/dist/channels/index.js +2 -2
- package/dist/{channels-BW52ccH_.cjs → channels-BgbloDjB.cjs} +2 -2
- package/dist/{channels-BW52ccH_.cjs.map → channels-BgbloDjB.cjs.map} +1 -1
- package/dist/{channels-Da9lEAi1.js → channels-MegO_4KL.js} +2 -2
- package/dist/{channels-Da9lEAi1.js.map → channels-MegO_4KL.js.map} +1 -1
- package/dist/coding-agent/index.cjs +1 -1
- package/dist/coding-agent/index.js +1 -1
- package/dist/{create-durable-agent-DmTTvoGi.cjs → create-durable-agent-ChmjQwzE.cjs} +8 -8
- package/dist/{create-durable-agent-DmTTvoGi.cjs.map → create-durable-agent-ChmjQwzE.cjs.map} +1 -1
- package/dist/{create-durable-agent-Bd4Bm5FV.js → create-durable-agent-DH_dWTMR.js} +8 -8
- package/dist/{create-durable-agent-Bd4Bm5FV.js.map → create-durable-agent-DH_dWTMR.js.map} +1 -1
- package/dist/datasets/index.cjs +1 -1
- package/dist/datasets/index.js +1 -1
- package/dist/{dist-C077BlAN.js → dist-BZBxELZo.js} +2 -2
- package/dist/{dist-C077BlAN.js.map → dist-BZBxELZo.js.map} +1 -1
- package/dist/{dist-CsR_D1uk.cjs → dist-ftJxyNRx.cjs} +2 -2
- package/dist/{dist-CsR_D1uk.cjs.map → dist-ftJxyNRx.cjs.map} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/evals/index.cjs +1 -1
- package/dist/evals/index.js +1 -1
- package/dist/evals/scoreTraces/index.cjs +1 -1
- package/dist/evals/scoreTraces/index.js +1 -1
- package/dist/harness/index.cjs +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/llm/index.cjs +5 -5
- package/dist/llm/index.js +5 -5
- package/dist/{llm-DlVyw1cX.js → llm-DGuYy_Nx.js} +5 -5
- package/dist/{llm-DlVyw1cX.js.map → llm-DGuYy_Nx.js.map} +1 -1
- package/dist/{llm-Bjt2hZ3f.cjs → llm-DmAhSSgh.cjs} +5 -5
- package/dist/{llm-Bjt2hZ3f.cjs.map → llm-DmAhSSgh.cjs.map} +1 -1
- package/dist/loop/index.cjs +1 -1
- package/dist/loop/index.js +1 -1
- package/dist/{manager-CYGpXJfK.js → manager-DDRcONBK.js} +3 -3
- package/dist/{manager-CYGpXJfK.js.map → manager-DDRcONBK.js.map} +1 -1
- package/dist/{manager-BjrFnt_A.cjs → manager-DqHiikx1.cjs} +3 -3
- package/dist/{manager-BjrFnt_A.cjs.map → manager-DqHiikx1.cjs.map} +1 -1
- package/dist/mastra/index.cjs +1 -1
- package/dist/mastra/index.js +1 -1
- package/dist/{mastra-CVLF1dWt.js → mastra-B6CffFOC.js} +9 -9
- package/dist/{mastra-CVLF1dWt.js.map → mastra-B6CffFOC.js.map} +1 -1
- package/dist/{mastra-Bxx9WPf6.cjs → mastra-BlT9srQJ.cjs} +9 -9
- package/dist/{mastra-Bxx9WPf6.cjs.map → mastra-BlT9srQJ.cjs.map} +1 -1
- package/dist/memory/index.cjs +1 -1
- package/dist/memory/index.js +1 -1
- package/dist/{model-CA0WLISt.js → model-DQzxkQqM.js} +2 -2
- package/dist/{model-CA0WLISt.js.map → model-DQzxkQqM.js.map} +1 -1
- package/dist/{model-DMVq6nAS.cjs → model-Iow-mV9i.cjs} +2 -2
- package/dist/{model-DMVq6nAS.cjs.map → model-Iow-mV9i.cjs.map} +1 -1
- package/dist/{models-dev-Cbus1Uh2.js → models-dev-BFOUCgyS.js} +2 -2
- package/dist/{models-dev-Cbus1Uh2.js.map → models-dev-BFOUCgyS.js.map} +1 -1
- package/dist/{models-dev-D_X4VMSu.cjs → models-dev-BUEaCBxL.cjs} +2 -2
- package/dist/{models-dev-D_X4VMSu.cjs.map → models-dev-BUEaCBxL.cjs.map} +1 -1
- package/dist/{netlify-C-nnPVSj.js → netlify-7eHXUkln.js} +2 -2
- package/dist/{netlify-C-nnPVSj.js.map → netlify-7eHXUkln.js.map} +1 -1
- package/dist/{netlify-CUuCnmtd.cjs → netlify-Db5icdAJ.cjs} +2 -2
- package/dist/{netlify-CUuCnmtd.cjs.map → netlify-Db5icdAJ.cjs.map} +1 -1
- package/dist/processor-provider/index.cjs +1 -1
- package/dist/processor-provider/index.js +1 -1
- package/dist/processors/index.cjs +2 -2
- package/dist/processors/index.js +2 -2
- package/dist/processors/processors/index.d.ts +1 -1
- package/dist/processors/processors/index.d.ts.map +1 -1
- package/dist/processors/tool-result-reminder.d.ts +23 -0
- package/dist/processors/tool-result-reminder.d.ts.map +1 -1
- package/dist/{provider-registry-BFknh6Fu.cjs → provider-registry-DRJihW5_.cjs} +6 -6
- package/dist/{provider-registry-BFknh6Fu.cjs.map → provider-registry-DRJihW5_.cjs.map} +1 -1
- package/dist/{provider-registry-DIbls44Z.js → provider-registry-DzSSAz1R.js} +6 -6
- package/dist/{provider-registry-DIbls44Z.js.map → provider-registry-DzSSAz1R.js.map} +1 -1
- package/dist/relevance/index.cjs +2 -2
- package/dist/relevance/index.js +2 -2
- package/dist/stream/index.cjs +3 -3
- package/dist/stream/index.js +3 -3
- package/dist/{stream-tlVjYkAO.cjs → stream-D-cHV05r.cjs} +3 -3
- package/dist/{stream-tlVjYkAO.cjs.map → stream-D-cHV05r.cjs.map} +1 -1
- package/dist/{stream-Cd_isEZJ.js → stream-DJaosaeO.js} +3 -3
- package/dist/{stream-Cd_isEZJ.js.map → stream-DJaosaeO.js.map} +1 -1
- package/dist/test-utils/llm-mock.cjs +1 -1
- package/dist/test-utils/llm-mock.js +1 -1
- package/dist/tool-loop-agent/index.cjs +1 -1
- package/dist/tool-loop-agent/index.js +1 -1
- package/dist/{tool-loop-agent-th9L-ls9.cjs → tool-loop-agent-ByrutV2Q.cjs} +4 -4
- package/dist/{tool-loop-agent-th9L-ls9.cjs.map → tool-loop-agent-ByrutV2Q.cjs.map} +1 -1
- package/dist/{tool-loop-agent-CcT-TTcT.js → tool-loop-agent-BzHXZDL3.js} +4 -4
- package/dist/{tool-loop-agent-CcT-TTcT.js.map → tool-loop-agent-BzHXZDL3.js.map} +1 -1
- package/dist/{trip-wire-Cj0cJivR.js → trip-wire-DxpTS3jV.js} +2 -2
- package/dist/{trip-wire-Cj0cJivR.js.map → trip-wire-DxpTS3jV.js.map} +1 -1
- package/dist/{trip-wire-BNzxirr0.cjs → trip-wire-utCESgMt.cjs} +2 -2
- package/dist/{trip-wire-BNzxirr0.cjs.map → trip-wire-utCESgMt.cjs.map} +1 -1
- package/dist/{utils-BoQofieM.cjs → utils-CPUQn5dX.cjs} +2 -2
- package/dist/{utils-BoQofieM.cjs.map → utils-CPUQn5dX.cjs.map} +1 -1
- package/dist/{utils-DUfAZ4gr.js → utils-CrKEOVUo.js} +2 -2
- package/dist/{utils-DUfAZ4gr.js.map → utils-CrKEOVUo.js.map} +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.js +1 -1
- package/dist/worker/index.cjs +1 -1
- package/dist/worker/index.js +1 -1
- package/dist/{worker-DwlyX5l8.js → worker-Ciya6mfo.js} +3 -3
- package/dist/{worker-DwlyX5l8.js.map → worker-Ciya6mfo.js.map} +1 -1
- package/dist/{worker-CsbZPhWb.cjs → worker-YT_pMttZ.cjs} +3 -3
- package/dist/{worker-CsbZPhWb.cjs.map → worker-YT_pMttZ.cjs.map} +1 -1
- package/dist/{workflow-BR5D6ij_.cjs → workflow-DcS_0R0Z.cjs} +3 -3
- package/dist/{workflow-BR5D6ij_.cjs.map → workflow-DcS_0R0Z.cjs.map} +1 -1
- package/dist/{workflow-OjZRiiCG.js → workflow-k6s0ESOR.js} +3 -3
- package/dist/{workflow-OjZRiiCG.js.map → workflow-k6s0ESOR.js.map} +1 -1
- package/dist/workflows/evented/index.cjs +1 -1
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/index.cjs +1 -1
- package/dist/workflows/index.js +1 -1
- package/package.json +12 -12
- package/dist/agent-BvRfRKIt.js.map +0 -1
- package/dist/agent-CwUYflGG.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-durable-agent-Bd4Bm5FV.js","names":["#entries","#messageLists","#memoryInfo","ReadableStream","input","#wrappedAgent","#runRegistry","#maxSteps","#hasCustomPubsub","#cleanupTimeoutMs","#innerPubsub","#cacheConfig","#ensurePubsubInitialized","#resolvedCache","#cachingPubsub","#mastra","#resolveExecutionOptions","#activeStreamUntilIdle","#clearPubsubTopic","#getPubsubOffset","#workflow"],"sources":["../src/agent/durable/constants.ts","../src/agent/durable/durable-stream-until-idle.ts","../src/agent/durable/utils/serialize-state.ts","../src/agent/durable/preparation.ts","../src/agent/durable/run-registry.ts","../src/agent/durable/stream-adapter.ts","../src/agent/durable/workflows/shared/schemas.ts","../src/agent/durable/workflows/shared/iteration-state.ts","../src/agent/durable/workflows/shared/tool-call-concurrency.ts","../src/agent/durable/workflows/steps/background-task-check.ts","../src/agent/durable/utils/apply-tool-payload-transform.ts","../src/agent/durable/utils/resolve-runtime.ts","../src/agent/durable/workflows/steps/llm-execution.ts","../src/agent/durable/workflows/steps/tool-call.ts","../src/agent/durable/workflows/steps/llm-mapping.ts","../src/agent/durable/workflows/steps/is-task-complete.ts","../src/agent/durable/workflows/steps/goal.ts","../src/agent/durable/workflows/steps/signal-drain.ts","../src/agent/durable/workflows/create-durable-agentic-workflow.ts","../src/agent/durable/durable-agent.ts","../src/agent/durable/create-durable-agent.ts"],"sourcesContent":["/**\n * Constants for DurableAgent pubsub channels and event types\n */\n\n/**\n * Symbol for passing run registry to workflow steps\n * This allows steps to access the actual model/tool instances\n */\nexport const RUN_REGISTRY_SYMBOL = Symbol('run_registry');\n\n/**\n * Generate the pubsub topic name for agent streaming events\n * @param runId - The unique run identifier\n * @returns The topic name for subscribing/publishing agent stream events\n */\nexport const AGENT_STREAM_TOPIC = (runId: string): string => `agent.stream.${runId}`;\n\n/**\n * Event type constants for agent stream events\n */\nexport const AgentStreamEventTypes = {\n /** Chunk of streaming data (text, tool call, etc.) */\n CHUNK: 'chunk',\n /** Start of a new step in the agentic loop */\n STEP_START: 'step-start',\n /** End of a step in the agentic loop */\n STEP_FINISH: 'step-finish',\n /** Agent execution completed successfully */\n FINISH: 'finish',\n /** Error occurred during execution */\n ERROR: 'error',\n /** Workflow suspended (e.g., for tool approval) */\n SUSPENDED: 'suspended',\n /** Execution aborted by abortSignal */\n ABORT: 'abort',\n /** Single agentic-loop iteration completed (observability hook) */\n ITERATION_COMPLETE: 'iteration-complete',\n} as const;\n\n/**\n * Default values for durable agent execution\n */\nexport const DurableAgentDefaults = {\n /** Default maximum number of agentic loop iterations */\n MAX_STEPS: 5,\n /**\n * Default tool call concurrency.\n * Applied by `resolveDurableToolCallConcurrency` when a run doesn't\n * configure `toolCallConcurrency`. Approval / suspend-capable tool sets\n * always run sequentially (concurrency: 1) regardless of this value.\n */\n TOOL_CALL_CONCURRENCY: 10,\n} as const;\n\n/**\n * Step IDs used in the durable agentic workflow\n */\nexport const DurableStepIds = {\n /** LLM execution step */\n LLM_EXECUTION: 'durable-llm-execution',\n /** Tool call step */\n TOOL_CALL: 'durable-tool-call',\n /** LLM mapping step (combines results) */\n LLM_MAPPING: 'durable-llm-mapping',\n /** Agentic execution workflow (one iteration) */\n AGENTIC_EXECUTION: 'durable-agentic-execution',\n /** Full agentic loop workflow */\n AGENTIC_LOOP: 'durable-agentic-loop',\n /** Scorer execution step */\n SCORER_EXECUTION: 'durable-scorer-execution',\n /** isTaskComplete evaluation step */\n IS_TASK_COMPLETE: 'durable-is-task-complete',\n} as const;\n","/**\n * Implementation of `DurableAgent.streamUntilIdle` and\n * `DurableAgent.resume(..., { untilIdle })`. Mirrors the regular agent's\n * `stream-until-idle.ts` but adapted for durable execution:\n * - `DurableAgent.stream()` returns `DurableAgentStreamResult` (not `MastraModelOutput`)\n * - Each continuation starts a new durable workflow (new runId)\n * - Cleanup functions from each inner stream are tracked and called on close\n * - Inner `abort()` handles are fanned out so the outer `result.abort()`\n * cancels every active durable run\n *\n * Uses the shared `runIdleLoop` helper from `loop/shared/stream-until-idle-helpers`\n * with durable-specific hooks for cleanup/abort tracking.\n */\nimport type { BackgroundTaskManager } from '../../background-tasks/manager';\nimport { runIdleLoop } from '../../loop/shared/stream-until-idle-helpers';\nimport type { MessageListInput } from '../message-list';\n\nimport type { DurableAgent, DurableAgentStreamOptions, DurableAgentStreamResult } from './durable-agent';\n\nexport interface DurableStreamUntilIdleDeps {\n activeStreams: Map<string, () => void>;\n bgManager: BackgroundTaskManager | undefined;\n}\n\n/**\n * Run `DurableAgent.streamUntilIdle` (or `DurableAgent.stream({ untilIdle })`).\n * Initial turn invokes `agent.stream(messages, ...)`; continuations triggered\n * by background-task completions run as fresh `agent.stream([], ...)` calls\n * against the same memory thread.\n */\nexport async function runDurableStreamUntilIdle<OUTPUT = undefined>(\n agent: DurableAgent<any, any, OUTPUT>,\n messages: MessageListInput,\n streamOptions: (DurableAgentStreamOptions<OUTPUT> & { maxIdleMs?: number }) | undefined,\n deps: DurableStreamUntilIdleDeps,\n): Promise<DurableAgentStreamResult<OUTPUT>> {\n // Durable-specific: track cleanup/abort handles from each inner stream\n const innerCleanups: Array<() => void> = [];\n const innerAborts: Array<(reason?: unknown) => void> = [];\n\n return runIdleLoop<typeof agent, DurableAgentStreamResult<OUTPUT>, DurableAgentStreamResult<OUTPUT>>(\n agent,\n streamOptions,\n deps,\n opts => (agent as any).stream(messages, opts) as Promise<DurableAgentStreamResult<OUTPUT>>,\n opts => (agent as any).stream([], opts) as Promise<{ fullStream: ReadableStream<any> }>,\n (first, ctx) => {\n // No ctx means no bgManager / no memory — fall through without wrapping.\n if (!ctx) return first;\n\n return {\n output: new Proxy(first.output, {\n get(target, prop) {\n if (prop === 'fullStream') return ctx.combinedStream;\n const value = Reflect.get(target, prop, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n }) as any,\n get fullStream() {\n return ctx.combinedStream;\n },\n runId: first.runId,\n threadId: ctx.threadId,\n resourceId: ctx.resourceId,\n cleanup: ctx.forceClose,\n abort: (reason?: unknown) => {\n // Fan the abort out to every inner DurableAgent.stream() that has been\n // spawned by the idle loop so far. `forceClose` then unwinds the outer\n // stream + idle timer.\n for (const innerAbort of innerAborts) {\n try {\n innerAbort(reason);\n } catch {\n // ignore — best-effort abort across siblings\n }\n }\n ctx.forceClose();\n },\n };\n },\n {\n onInnerResult: (inner: any) => {\n if (typeof inner.cleanup === 'function') innerCleanups.push(inner.cleanup);\n if (typeof inner.abort === 'function') innerAborts.push(inner.abort);\n },\n onForceClose: () => {\n for (const fn of innerCleanups) {\n try {\n fn();\n } catch {\n // ignore\n }\n }\n },\n },\n );\n}\n\n/**\n * Run `DurableAgent.resume(..., { untilIdle })`. Same idle-loop semantics as\n * `runDurableStreamUntilIdle` — initial turn calls `agent.resume(runId,\n * resumeData, ...)` against the existing run snapshot, and subsequent\n * continuations triggered by background-task completions use\n * `agent.stream([], continuationOpts)` (a normal multi-turn agent stream)\n * since the resume completes and we're back in regular conversation flow.\n */\nexport async function runResumeDurableStreamUntilIdle<OUTPUT = undefined>(\n agent: DurableAgent<any, any, OUTPUT>,\n runId: string,\n resumeData: unknown,\n streamOptions: (DurableAgentStreamOptions<OUTPUT> & { maxIdleMs?: number }) | undefined,\n deps: DurableStreamUntilIdleDeps,\n): Promise<DurableAgentStreamResult<OUTPUT>> {\n const innerCleanups: Array<() => void> = [];\n const innerAborts: Array<(reason?: unknown) => void> = [];\n\n return runIdleLoop<typeof agent, DurableAgentStreamResult<OUTPUT>, DurableAgentStreamResult<OUTPUT>>(\n agent,\n streamOptions,\n deps,\n opts => (agent as any).resume(runId, resumeData, opts) as Promise<DurableAgentStreamResult<OUTPUT>>,\n opts => (agent as any).stream([], opts) as Promise<{ fullStream: ReadableStream<any> }>,\n (first, ctx) => {\n if (!ctx) return first;\n\n return {\n output: new Proxy(first.output, {\n get(target, prop) {\n if (prop === 'fullStream') return ctx.combinedStream;\n const value = Reflect.get(target, prop, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n }) as any,\n get fullStream() {\n return ctx.combinedStream;\n },\n runId: first.runId,\n threadId: ctx.threadId,\n resourceId: ctx.resourceId,\n cleanup: ctx.forceClose,\n abort: (reason?: unknown) => {\n for (const innerAbort of innerAborts) {\n try {\n innerAbort(reason);\n } catch {\n // ignore\n }\n }\n ctx.forceClose();\n },\n };\n },\n {\n onInnerResult: (inner: any) => {\n if (typeof inner.cleanup === 'function') innerCleanups.push(inner.cleanup);\n if (typeof inner.abort === 'function') innerAborts.push(inner.abort);\n },\n onForceClose: () => {\n for (const fn of innerCleanups) {\n try {\n fn();\n } catch {\n // ignore\n }\n }\n },\n },\n );\n}\n","import type { JSONSchema7 } from 'json-schema';\nimport type { MastraLanguageModel } from '../../../llm/model/shared.types';\nimport type { MemoryConfig } from '../../../memory/types';\nimport type { CoreTool } from '../../../tools/types';\nimport type { MessageList } from '../../message-list';\nimport type { AgentModelManagerConfig } from '../../types';\nimport type {\n SerializableToolMetadata,\n SerializableModelConfig,\n SerializableModelListEntry,\n SerializableDurableState,\n SerializableDurableOptions,\n SerializableModelSettings,\n SerializableScorersConfig,\n SerializableScorerEntry,\n DurableAgenticWorkflowInput,\n} from '../types';\n\n/**\n * Extract serializable metadata from a CoreTool\n * This strips out the execute function and converts the schema to JSON Schema\n */\nexport function serializeToolMetadata(name: string, tool: CoreTool): SerializableToolMetadata {\n // Extract JSON Schema from the parameters\n let inputSchema: JSONSchema7 = { type: 'object' };\n\n if (tool.parameters) {\n // If it's already a JSON Schema object\n if ('type' in tool.parameters && typeof tool.parameters.type === 'string') {\n inputSchema = tool.parameters as JSONSchema7;\n }\n // If it has a jsonSchema property (zod schema converted)\n else if ('jsonSchema' in tool.parameters) {\n inputSchema = (tool.parameters as any).jsonSchema as JSONSchema7;\n }\n // If it's a Zod schema with _def (try to extract)\n else if ('_def' in tool.parameters) {\n // We'll need to use zodToJsonSchema at runtime if available\n // For now, use a basic object schema\n inputSchema = { type: 'object' };\n }\n }\n\n return {\n id: 'id' in tool && typeof tool.id === 'string' ? tool.id : name,\n name,\n description: tool.description,\n inputSchema,\n requireApproval: (tool as any).requireApproval,\n hasSuspendSchema: (tool as any).hasSuspendSchema,\n };\n}\n\n/**\n * Extract serializable metadata from all tools\n */\nexport function serializeToolsMetadata(tools: Record<string, CoreTool>): SerializableToolMetadata[] {\n return Object.entries(tools).map(([name, tool]) => serializeToolMetadata(name, tool));\n}\n\n/**\n * Extract serializable model configuration\n */\nexport function serializeModelConfig(model: MastraLanguageModel): SerializableModelConfig {\n return {\n provider: model.provider,\n modelId: model.modelId,\n specificationVersion: model.specificationVersion,\n // Store the original config string for runtime resolution (e.g., 'openai/gpt-4o')\n originalConfig: `${model.provider}/${model.modelId}`,\n // Note: We don't serialize model settings here - they come from execution options\n };\n}\n\n/**\n * Extract serializable model list entry from AgentModelManagerConfig\n */\nexport function serializeModelListEntry(entry: AgentModelManagerConfig): SerializableModelListEntry {\n const model = entry.model;\n return {\n id: entry.id,\n config: {\n provider: model.provider,\n modelId: model.modelId,\n specificationVersion: model.specificationVersion,\n originalConfig: `${model.provider}/${model.modelId}`,\n providerOptions: entry.providerOptions,\n },\n maxRetries: entry.maxRetries,\n enabled: entry.enabled,\n };\n}\n\n/**\n * Serialize an array of model configs into a model list.\n * Filters out disabled models since they shouldn't be included in durable execution.\n */\nexport function serializeModelList(models: AgentModelManagerConfig[]): SerializableModelListEntry[] {\n return models.filter(m => m.enabled !== false).map(serializeModelListEntry);\n}\n\n/**\n * Serialize scorers configuration for durable execution.\n *\n * This extracts the scorer name (for resolution at runtime) and sampling config.\n * The actual scorer objects are resolved from Mastra at step execution time.\n *\n * @param scorers The agent's scorers configuration (from agent.scorers or options.scorers)\n * @returns Serializable scorer configuration\n */\nexport function serializeScorersConfig(\n scorers: Record<\n string,\n { scorer: { name: string } | string; sampling?: { type: 'none' } | { type: 'ratio'; rate: number } }\n >,\n): SerializableScorersConfig {\n const result: SerializableScorersConfig = {};\n\n for (const [key, entry] of Object.entries(scorers)) {\n // Get the scorer name - can be a string directly or from scorer.name\n const scorerName = typeof entry.scorer === 'string' ? entry.scorer : entry.scorer.name;\n\n const scorerEntry: SerializableScorerEntry = {\n scorerName,\n };\n\n // Include sampling if provided\n if (entry.sampling) {\n scorerEntry.sampling = entry.sampling;\n }\n\n result[key] = scorerEntry;\n }\n\n return result;\n}\n\n/**\n * Extract serializable state from _internal-like objects\n */\nexport function serializeDurableState(params: {\n memoryConfig?: MemoryConfig;\n threadId?: string;\n resourceId?: string;\n threadExists?: boolean;\n savePerStep?: boolean;\n observationalMemory?: boolean;\n}): SerializableDurableState {\n return {\n memoryConfig: params.memoryConfig,\n threadId: params.threadId,\n resourceId: params.resourceId,\n threadExists: params.threadExists,\n savePerStep: params.savePerStep,\n observationalMemory: params.observationalMemory,\n };\n}\n\n/**\n * Pick the JSON-safe call settings out of an arbitrary `modelSettings` input.\n * Drops any field that is not a primitive value of the expected type so that\n * non-serializable fields (functions, AbortSignal, etc.) never reach the\n * workflow input.\n */\nexport function serializeModelSettings(\n settings: SerializableModelSettings | Record<string, unknown> | undefined,\n): SerializableModelSettings | undefined {\n if (!settings || typeof settings !== 'object') return undefined;\n\n const source = settings as Record<string, unknown>;\n const out: SerializableModelSettings = {};\n const pickNumber = (key: keyof SerializableModelSettings) => {\n const value = source[key as string];\n if (typeof value === 'number' && Number.isFinite(value)) {\n (out as Record<string, unknown>)[key as string] = value;\n }\n };\n\n pickNumber('maxOutputTokens');\n pickNumber('temperature');\n pickNumber('topP');\n pickNumber('topK');\n pickNumber('presencePenalty');\n pickNumber('frequencyPenalty');\n pickNumber('seed');\n pickNumber('maxRetries');\n\n if (Array.isArray(source.stopSequences) && source.stopSequences.every(v => typeof v === 'string')) {\n out.stopSequences = source.stopSequences as string[];\n }\n\n // Headers are never serialized into the workflow input. They are stored\n // exclusively on the in-process RunRegistryEntry so they never reach\n // durable storage. The durable llm-execution step merges them back from\n // the registry at call time.\n // (Previously we had a denylist of \"sensitive\" header names, but any\n // header could carry credentials — the safest approach is to keep them\n // all off the wire.)\n\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Extract serializable options from agent execution options\n */\nexport function serializeDurableOptions(options: {\n maxSteps?: number;\n toolChoice?: any;\n activeTools?: string[];\n modelSettings?: SerializableModelSettings | Record<string, unknown>;\n requireToolApproval?: boolean;\n toolCallConcurrency?: number;\n autoResumeSuspendedTools?: boolean;\n maxProcessorRetries?: number;\n includeRawChunks?: boolean;\n returnScorerData?: boolean;\n hasErrorProcessors?: boolean;\n providerOptions?: SerializableDurableOptions['providerOptions'];\n structuredOutput?: SerializableDurableOptions['structuredOutput'];\n skipBgTaskWait?: boolean;\n disableBackgroundTasks?: boolean;\n tracingOptions?: SerializableDurableOptions['tracingOptions'];\n actor?: SerializableDurableOptions['actor'];\n instructionsOverride?: SerializableDurableOptions['instructionsOverride'];\n systemMessage?: SerializableDurableOptions['systemMessage'];\n transform?: SerializableDurableOptions['transform'];\n isTaskComplete?: SerializableDurableOptions['isTaskComplete'];\n}): SerializableDurableOptions {\n // Normalize toolChoice to serializable form\n let serializedToolChoice: SerializableDurableOptions['toolChoice'];\n if (options.toolChoice) {\n if (typeof options.toolChoice === 'string') {\n serializedToolChoice = options.toolChoice as 'auto' | 'none' | 'required';\n } else if (typeof options.toolChoice === 'object' && 'type' in options.toolChoice) {\n if (options.toolChoice.type === 'tool' && 'toolName' in options.toolChoice) {\n serializedToolChoice = {\n type: 'tool',\n toolName: options.toolChoice.toolName as string,\n };\n }\n }\n }\n\n return {\n maxSteps: options.maxSteps,\n toolChoice: serializedToolChoice,\n activeTools: options.activeTools,\n modelSettings: serializeModelSettings(options.modelSettings),\n requireToolApproval: options.requireToolApproval,\n toolCallConcurrency: options.toolCallConcurrency,\n autoResumeSuspendedTools: options.autoResumeSuspendedTools,\n maxProcessorRetries: options.maxProcessorRetries,\n includeRawChunks: options.includeRawChunks,\n returnScorerData: options.returnScorerData,\n hasErrorProcessors: options.hasErrorProcessors,\n providerOptions: options.providerOptions,\n structuredOutput: options.structuredOutput,\n skipBgTaskWait: options.skipBgTaskWait,\n disableBackgroundTasks: options.disableBackgroundTasks,\n tracingOptions: options.tracingOptions,\n actor: options.actor,\n instructionsOverride: options.instructionsOverride,\n systemMessage: options.systemMessage,\n transform: options.transform,\n isTaskComplete: options.isTaskComplete,\n };\n}\n\n/**\n * Create the full workflow input from all components\n */\nexport function createWorkflowInput(params: {\n runId: string;\n agentId: string;\n agentName?: string;\n messageList: MessageList;\n tools: Record<string, CoreTool>;\n model: MastraLanguageModel;\n modelList?: AgentModelManagerConfig[];\n scorers?: Parameters<typeof serializeScorersConfig>[0];\n options: Parameters<typeof serializeDurableOptions>[0];\n state: Parameters<typeof serializeDurableState>[0];\n messageId: string;\n agentSpanData?: unknown;\n modelSpanData?: unknown;\n requestContextEntries?: Record<string, unknown>;\n}): DurableAgenticWorkflowInput {\n return {\n __workflowKind: 'durable-agent',\n runId: params.runId,\n agentId: params.agentId,\n agentName: params.agentName,\n messageListState: params.messageList.serialize(),\n toolsMetadata: serializeToolsMetadata(params.tools),\n modelConfig: serializeModelConfig(params.model),\n modelList: params.modelList ? serializeModelList(params.modelList) : undefined,\n scorers: params.scorers ? serializeScorersConfig(params.scorers) : undefined,\n options: serializeDurableOptions(params.options),\n state: serializeDurableState(params.state),\n messageId: params.messageId,\n agentSpanData: params.agentSpanData,\n modelSpanData: params.modelSpanData,\n requestContextEntries: params.requestContextEntries,\n };\n}\n\n/**\n * Serialize an error for workflow state\n */\nexport function serializeError(error: unknown): { name: string; message: string; stack?: string } {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n }\n return {\n name: 'Error',\n message: String(error),\n };\n}\n\n/**\n * Serialize a Date to ISO string for workflow state\n */\nexport function serializeDate(date: Date | undefined): string | undefined {\n return date?.toISOString();\n}\n\n/**\n * Deserialize an ISO string back to Date\n */\nexport function deserializeDate(isoString: string | undefined): Date | undefined {\n return isoString ? new Date(isoString) : undefined;\n}\n","import type { AgentBackgroundConfig } from '../../background-tasks/types';\nimport type { MastraLanguageModel } from '../../llm/model/shared.types';\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { MastraMemory } from '../../memory/memory';\nimport type { MemoryConfig, MemoryConfig as _MemoryConfig, StorageThreadType } from '../../memory/types';\nimport { EntityType, SpanType, createObservabilityContext, getOrCreateSpan } from '../../observability';\nimport type { InputProcessorOrWorkflow, OutputProcessorOrWorkflow, ErrorProcessorOrWorkflow } from '../../processors';\nimport type { ProcessorState } from '../../processors/runner';\nimport { RequestContext, MASTRA_VERSIONS_KEY, mergeVersionOverrides } from '../../request-context';\nimport type { VersionOverrides } from '../../request-context';\nimport { toStandardSchema } from '../../schema';\nimport { normalizeToolPayloadTransformPolicy } from '../../tools/payload-transform';\nimport type { CoreTool, ToolHooks, ToolPayloadTransformPolicy } from '../../tools/types';\nimport { deepMerge } from '../../utils';\nimport type { Workspace } from '../../workspace';\nimport type { Agent } from '../agent';\nimport type { AgentExecutionOptions, DelegationConfig } from '../agent.types';\nimport { MessageList } from '../message-list';\nimport type { MessageListInput } from '../message-list';\nimport { SaveQueueManager } from '../save-queue';\nimport type { CreatedAgentSignal } from '../signals';\nimport { mastraDBMessageToSignal } from '../signals';\nimport { TripWire } from '../trip-wire';\nimport type {\n AgentInstructions,\n AgentMethodType,\n AgentModelManagerConfig,\n GoalConfig,\n ToolsetsInput,\n ToolsInput,\n} from '../types';\nimport type { DurableAgenticWorkflowInput, RunRegistryEntry, SerializableStructuredOutput } from './types';\nimport { createWorkflowInput } from './utils/serialize-state';\n\n/**\n * JSON-safe snapshot of `requestContext.entries()` so durable steps (e.g.\n * is-task-complete scorers) can see the same `customContext` the non-durable\n * path passes. Best-effort: entries that fail a JSON round-trip are skipped\n * so a single non-serializable value can't break the workflow input.\n */\nfunction snapshotRequestContextEntries(\n requestContext: RequestContext | undefined,\n): Record<string, unknown> | undefined {\n if (!requestContext) return undefined;\n const out: Record<string, unknown> = {};\n let any = false;\n for (const [key, value] of requestContext.entries()) {\n try {\n const cloned = JSON.parse(JSON.stringify(value));\n out[key as string] = cloned;\n any = true;\n } catch {\n // Skip non-serializable entries silently — they wouldn't survive the\n // wire on cross-process engines anyway.\n }\n }\n return any ? out : undefined;\n}\n\n/**\n * Mirror of Agent#convertInstructionsToString — used for the AGENT_RUN span\n * `attributes.instructions` field so durable runs publish the same shape as\n * non-durable runs. Kept local to avoid promoting the private method.\n */\nfunction convertInstructionsToString(instructions: AgentInstructions | undefined): string {\n if (!instructions) return '';\n if (typeof instructions === 'string') return instructions;\n if (Array.isArray(instructions)) {\n return instructions\n .map(msg => (typeof msg === 'string' ? msg : typeof msg.content === 'string' ? msg.content : ''))\n .filter(Boolean)\n .join('\\n\\n');\n }\n return typeof instructions.content === 'string' ? instructions.content : '';\n}\n\n/**\n * Extract signal messages already present in the messageList at run start\n * (from persisted history) so they can be echoed as data-signal stream parts\n * on the first LLM step. Mirrors `prepare-memory-step.ts#getInitialSignalEchoes`.\n */\nfunction getInitialSignalEchoes(messageList: MessageList): CreatedAgentSignal[] {\n const inputMessageIds = messageList.makeMessageSourceChecker().input;\n return messageList.get.all\n .db()\n .filter(message => message.role === 'signal' && inputMessageIds.has(message.id))\n .map(mastraDBMessageToSignal);\n}\n\n/**\n * Interface for the Agent methods needed during durable preparation.\n * This provides proper typing for the public Agent methods we call.\n */\ninterface DurablePreparationAgent {\n id: string;\n name?: string;\n getDefaultOptions(opts: { requestContext: RequestContext }): AgentExecutionOptions | Promise<AgentExecutionOptions>;\n getInstructions(opts: { requestContext: RequestContext }): AgentInstructions | Promise<AgentInstructions>;\n getModel(opts: { requestContext: RequestContext }): MastraLanguageModel | Promise<MastraLanguageModel>;\n getModelList(requestContext: RequestContext): Promise<AgentModelManagerConfig[] | null>;\n getMemory(opts: { requestContext: RequestContext }): Promise<MastraMemory | undefined>;\n getWorkspace(opts: { requestContext: RequestContext }): Promise<Workspace | undefined>;\n listScorers(opts: {\n requestContext: RequestContext;\n }): Promise<Record<string, { scorer: unknown; sampling?: unknown }> | undefined>;\n getToolsForExecution(opts: {\n toolsets?: ToolsetsInput;\n clientTools?: ToolsInput;\n threadId?: string;\n resourceId?: string;\n runId?: string;\n requestContext?: RequestContext;\n memoryConfig?: MemoryConfig;\n autoResumeSuspendedTools?: boolean;\n hooks?: ToolHooks;\n delegation?: DelegationConfig;\n methodType?: AgentMethodType;\n }): Promise<Record<string, CoreTool>>;\n listInputProcessors(requestContext?: RequestContext): Promise<InputProcessorOrWorkflow[]>;\n listOutputProcessors(requestContext?: RequestContext): Promise<OutputProcessorOrWorkflow[]>;\n listErrorProcessors(requestContext?: RequestContext): Promise<ErrorProcessorOrWorkflow[]>;\n getBackgroundTasksConfig(): AgentBackgroundConfig | undefined;\n getToolPayloadTransform?(): ToolPayloadTransformPolicy | undefined;\n __getDrainPendingSignals(): (runId: string, scope?: 'pending' | 'pre-run') => CreatedAgentSignal[];\n __getGoalConfig(): GoalConfig | undefined;\n __listLLMRequestProcessors(requestContext?: RequestContext): Promise<InputProcessorOrWorkflow[]>;\n}\n\n/**\n * Result from the preparation phase\n */\nexport interface PreparationResult<_OUTPUT = undefined> {\n /** Unique run identifier */\n runId: string;\n /** Message ID for this generation */\n messageId: string;\n /** Serialized workflow input */\n workflowInput: DurableAgenticWorkflowInput;\n /** Non-serializable state for the run registry */\n registryEntry: RunRegistryEntry;\n /** MessageList for callback access */\n messageList: MessageList;\n /** Thread ID if using memory */\n threadId?: string;\n /** Resource ID if using memory */\n resourceId?: string;\n}\n\n/**\n * Options for preparation phase\n */\nexport interface PreparationOptions<OUTPUT = undefined> {\n /** The agent instance (wrapped agent — used for config resolution: tools, model, instructions, memory) */\n agent: Agent<string, any, OUTPUT>;\n /** User messages to process */\n messages: MessageListInput;\n /** Execution options */\n options?: AgentExecutionOptions<OUTPUT>;\n /** Whether execution options already include the agent defaults. */\n optionsAreResolved?: boolean;\n /** Run ID (will be generated if not provided) */\n runId?: string;\n /** Request context */\n requestContext?: RequestContext;\n /** Logger */\n logger?: IMastraLogger;\n /** Mastra instance (for version overrides, background tasks, etc.) */\n mastra?: Mastra;\n /** Method type */\n methodType?: AgentMethodType;\n /**\n * The public-facing agent ID (the DurableAgent wrapper's ID).\n * Used for spans, background tasks, scorers, and all identification visible to Studio.\n * Falls back to `agent.id` if not provided.\n */\n durableAgentId?: string;\n /**\n * The public-facing agent name (the DurableAgent wrapper's name).\n * Used for spans, background tasks, scorers, and all identification visible to Studio.\n * Falls back to `agent.name` if not provided.\n */\n durableAgentName?: string;\n}\n\n/**\n * Prepare for durable agent execution.\n *\n * This function performs the non-durable preparation phase:\n * 1. Generates run ID and message ID\n * 2. Resolves thread/memory context\n * 3. Creates MessageList with instructions and messages\n * 4. Converts tools to CoreTool format\n * 5. Gets the model configuration\n * 6. Creates serialized workflow input\n * 7. Creates run registry entry for non-serializable state\n *\n * The result includes both the serialized workflow input (for the durable\n * workflow) and the run registry entry (for non-serializable state).\n */\nexport async function prepareForDurableExecution<OUTPUT = undefined>(\n options: PreparationOptions<OUTPUT>,\n): Promise<PreparationResult<OUTPUT>> {\n const {\n agent,\n messages,\n options: rawExecOptions,\n optionsAreResolved = false,\n runId: providedRunId,\n requestContext: providedRequestContext,\n logger,\n mastra,\n methodType = 'stream',\n durableAgentId,\n durableAgentName,\n } = options;\n\n // Public-facing identity: use the durable wrapper's ID/name for all\n // external-facing identification (spans, background tasks, scorers, Studio).\n // Fall back to the wrapped agent's ID/name when called outside the durable wrapper.\n const publicAgentId = durableAgentId ?? agent.id;\n const publicAgentName = durableAgentName ?? agent.name ?? agent.id;\n\n const typedAgent = agent as unknown as DurablePreparationAgent;\n\n // 1. Generate IDs\n const runId = providedRunId ?? crypto.randomUUID();\n const messageId = crypto.randomUUID();\n\n // 2. Get request context\n const requestContext = providedRequestContext ?? new RequestContext();\n\n // 2a. Snapshot caller-provided RequestContext entries *before* preparation\n // mutates the context (version overrides at step 3, MastraMemory at step 4).\n // The persisted `customContext` should reflect only what the caller passed in,\n // not internal-key state added during prep.\n const requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext);\n\n // 2b. Merge the wrapped agent's defaultOptions under the per-request options,\n // mirroring the non-durable Agent.stream()/generate() paths. Without this the\n // agent's configured defaults (maxSteps, providerOptions, etc.) are silently\n // dropped and durable runs fall back to DurableAgentDefaults.MAX_STEPS.\n const execOptions: AgentExecutionOptions<OUTPUT> = optionsAreResolved\n ? (rawExecOptions ?? ({} as AgentExecutionOptions<OUTPUT>))\n : (deepMerge(\n ((await typedAgent.getDefaultOptions({ requestContext })) ?? {}) as Record<string, unknown>,\n (rawExecOptions ?? {}) as Record<string, unknown>,\n ) as AgentExecutionOptions<OUTPUT>);\n\n // 3. Merge version overrides (Mastra defaults < requestContext < call-site)\n const requestVersions = requestContext.get(MASTRA_VERSIONS_KEY) as VersionOverrides | undefined;\n let mergedVersions = mergeVersionOverrides(mastra?.getVersionOverrides?.(), requestVersions);\n if ((execOptions as any)?.versions) {\n mergedVersions = mergeVersionOverrides(mergedVersions, (execOptions as any).versions);\n }\n if (mergedVersions) {\n requestContext.set(MASTRA_VERSIONS_KEY, mergedVersions);\n }\n\n // 4. Resolve thread/memory context\n const thread =\n typeof execOptions?.memory?.thread === 'string' ? { id: execOptions.memory.thread } : execOptions?.memory?.thread;\n const threadId = thread?.id;\n const resourceId = execOptions?.memory?.resource;\n let threadObject: StorageThreadType | undefined;\n let threadExists = false;\n\n // 5. Create MessageList\n const messageList = new MessageList({\n threadId,\n resourceId,\n });\n\n // Add agent instructions. Per-call `options.instructions` overrides the\n // agent's default instructions to mirror non-durable Agent.stream() behavior.\n const instructions = execOptions?.instructions || (await typedAgent.getInstructions({ requestContext }));\n if (instructions) {\n if (typeof instructions === 'string') {\n messageList.addSystem(instructions);\n } else if (Array.isArray(instructions)) {\n for (const inst of instructions) {\n messageList.addSystem(inst);\n }\n } else {\n messageList.addSystem(instructions);\n }\n }\n const workspace = await typedAgent.getWorkspace({ requestContext });\n\n // Durable preparation runs processInput processors below, but workspace\n // instructions are a processInputStep concern in the non-durable path.\n // Add them here once so durable runs get the same workspace context.\n if (workspace) {\n const hasFs =\n typeof workspace.hasFilesystemConfig === 'function' ? workspace.hasFilesystemConfig() : !!workspace.filesystem;\n const hasSb = typeof workspace.hasSandboxConfig === 'function' ? workspace.hasSandboxConfig() : !!workspace.sandbox;\n if (hasFs || hasSb) {\n const wsInstructions =\n typeof workspace.getInstructionsAsync === 'function'\n ? await workspace.getInstructionsAsync({ requestContext })\n : workspace.getInstructions({ requestContext });\n if (wsInstructions) {\n messageList.addSystem({ role: 'system', content: wsInstructions });\n }\n }\n }\n\n // Add context messages if provided\n if (execOptions?.context) {\n messageList.add(execOptions.context, 'context');\n }\n\n // Per-call `options.system` is appended as an additional system message after\n // context. Mirrors the non-durable Agent.stream() prepare-memory-step path.\n if (execOptions?.system) {\n const sys = execOptions.system;\n if (typeof sys === 'string') {\n messageList.addSystem(sys);\n } else if (Array.isArray(sys)) {\n for (const s of sys) {\n messageList.addSystem(s);\n }\n } else {\n messageList.addSystem(sys);\n }\n }\n\n // Add user messages\n messageList.add(messages, 'input');\n\n // 6. Establish the memory/thread context BEFORE resolving input processors.\n //\n // Memory.getInputProcessors() decides whether to add the working-memory\n // injector by reading requestContext.get('MastraMemory')?.memoryConfig. When\n // working memory is disabled in the constructor and enabled per-request (the\n // documented setup), that runtime config is the only signal that turns the\n // injector on. If we resolve processors before setting MastraMemory, the\n // per-request config is invisible, the chain falls back to the constructor\n // config, and the injector is silently omitted — so stored working memory is\n // saved by the update-working-memory tool but never read back into the prompt.\n // Setting the context first keeps read (inject) and write (tool) in sync.\n const memory = await typedAgent.getMemory({ requestContext });\n const memoryConfig = execOptions?.memory?.options;\n if (memory && threadId && resourceId) {\n const existingThread = await memory.getThreadById({ threadId });\n threadObject =\n existingThread ??\n (await memory.createThread({\n threadId,\n metadata: thread?.metadata,\n title: thread?.title,\n memoryConfig,\n resourceId,\n saveThread: true,\n }));\n threadExists = true;\n requestContext.set('MastraMemory', { thread: threadObject, resourceId, memoryConfig });\n } else {\n // This run has no complete per-request memory context. Clear any\n // MastraMemory inherited from a caller-provided requestContext (e.g. a\n // parent agent's context during sub-agent delegation) so processor\n // resolution can't pick up the working-memory injector from stale/parent\n // memory — that would both leak prior resource memory into this prompt and\n // break the \"no per-request memory options means no injection\" gate.\n requestContext.delete('MastraMemory');\n }\n\n // Resolve input processors now that the memory context is in place.\n const processorStates = new Map<string, ProcessorState>();\n let inputProcessors: InputProcessorOrWorkflow[] = [];\n let llmRequestInputProcessors: InputProcessorOrWorkflow[] = [];\n let outputProcessors: OutputProcessorOrWorkflow[] = [];\n let errorProcessors: ErrorProcessorOrWorkflow[] = [];\n\n try {\n inputProcessors = await typedAgent.listInputProcessors(requestContext);\n // Uncombined processors for processLLMRequest — combined (workflow-wrapped)\n // processors are skipped by ProcessorRunner.runProcessLLMRequest.\n llmRequestInputProcessors = await typedAgent.__listLLMRequestProcessors(requestContext);\n // Call-time outputProcessors replace constructor-level ones (parity with\n // Agent.listResolvedOutputProcessors which uses overrides-first semantics).\n outputProcessors = execOptions?.outputProcessors\n ? execOptions.outputProcessors\n : await typedAgent.listOutputProcessors(requestContext);\n errorProcessors = await typedAgent.listErrorProcessors(requestContext);\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error resolving processors: ${error}`);\n }\n\n // Open AGENT_RUN here so processor_run spans (and their MEMORY_OPERATION\n // children) parent to it. MODEL_GENERATION is opened later under it.\n //\n // Mirrors non-durable Agent.stream(): forward attributes (conversationId,\n // resolved instructions string, resolvedVersionId), metadata (entityVersionId),\n // and the agent-level tracingPolicy so durable runs land in the same span\n // shape as in-process runs.\n const rawConfig = typeof (agent as any).toRawConfig === 'function' ? (agent as any).toRawConfig() : undefined;\n const resolvedVersionId = rawConfig?.resolvedVersionId as string | undefined;\n const agentTracingPolicy =\n typeof (agent as any).getTracingPolicy === 'function' ? (agent as any).getTracingPolicy() : undefined;\n const agentSpan = getOrCreateSpan({\n type: SpanType.AGENT_RUN,\n name: `agent run: '${publicAgentId}'`,\n entityType: EntityType.AGENT,\n entityId: publicAgentId,\n entityName: publicAgentName,\n input: messages,\n attributes: {\n conversationId: threadId,\n instructions: convertInstructionsToString(instructions),\n // @deprecated — use entityVersionId (top-level span context field) instead.\n // Kept for backward compatibility during migration.\n ...(resolvedVersionId ? { resolvedVersionId } : {}),\n },\n metadata: {\n runId,\n resourceId,\n threadId,\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n tracingPolicy: agentTracingPolicy,\n tracingContext: execOptions?.tracingContext,\n tracingOptions: execOptions?.tracingOptions,\n requestContext,\n mastra,\n });\n // Run processInput (once, before execution) if we have any processors.\n // The MastraMemory context (thread + memoryConfig) was already established\n // above, before processor resolution, so processors that need it (working\n // memory, OM, message history) can access it here.\n let tripwireData: RunRegistryEntry['tripwire'];\n if (inputProcessors.length > 0) {\n try {\n const { ProcessorRunner } = await import('../../processors/runner');\n const runner = new ProcessorRunner({\n inputProcessors,\n outputProcessors,\n errorProcessors,\n logger: logger as any,\n agentName: publicAgentName,\n processorStates,\n });\n await runner.runInputProcessors(\n messageList,\n createObservabilityContext({ currentSpan: agentSpan }),\n requestContext,\n 0,\n );\n } catch (error) {\n if (error instanceof TripWire) {\n tripwireData = {\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n processorId: error.processorId,\n };\n logger?.warn?.('Input processor tripwire triggered', {\n agent: publicAgentName,\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n } else {\n logger?.warn?.(`[DurableAgent] Error running input processors: ${error}`);\n }\n }\n }\n\n // 7. Convert tools to CoreTool format for execution\n let tools: Record<string, CoreTool> = {};\n try {\n tools = await typedAgent.getToolsForExecution({\n toolsets: execOptions?.toolsets,\n clientTools: execOptions?.clientTools,\n threadId,\n resourceId,\n runId,\n requestContext,\n memoryConfig: execOptions?.memory?.options,\n autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,\n hooks: execOptions?.hooks,\n delegation: execOptions?.delegation,\n methodType,\n });\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error converting tools: ${error}`);\n }\n\n // 8. Get model (and model list if configured)\n const model = await typedAgent.getModel({ requestContext });\n if (!model) {\n throw new Error('Agent model not available');\n }\n\n const modelList = await typedAgent.getModelList(requestContext);\n\n // 8b. Get scorers configuration\n const overrideScorers = (execOptions as any)?.scorers;\n let scorers: Record<string, { scorer: any; sampling?: any }> | undefined;\n\n if (overrideScorers) {\n scorers = overrideScorers;\n } else {\n try {\n const agentScorers = await typedAgent.listScorers({ requestContext });\n if (agentScorers && Object.keys(agentScorers).length > 0) {\n scorers = agentScorers;\n }\n } catch (error) {\n logger?.debug?.(`[DurableAgent] Error getting scorers: ${error}`);\n }\n }\n\n // 9. Create SaveQueueManager (memory + memoryConfig were resolved in step 6)\n const saveQueueManager = memory\n ? new SaveQueueManager({\n logger,\n memory,\n })\n : undefined;\n\n // 10. Serialize structured output if provided\n let serializedStructuredOutput: SerializableStructuredOutput | undefined;\n if (execOptions?.structuredOutput) {\n const so = execOptions.structuredOutput as any;\n if (so.schema) {\n serializedStructuredOutput = {\n jsonPromptInjection: so.jsonPromptInjection,\n useAgent: so.useAgent,\n };\n // Convert Zod schema to JSON Schema if possible\n if (typeof so.schema === 'object' && 'type' in so.schema) {\n serializedStructuredOutput.schema = so.schema;\n } else if (typeof so.schema === 'object' && 'jsonSchema' in so.schema) {\n serializedStructuredOutput.schema = so.schema.jsonSchema;\n }\n }\n }\n\n // 11. Get background task config. When the caller opts out with\n // `disableBackgroundTasks: true`, drop the manager so the registry entry\n // signals \"no background tasks for this run\" to the check step.\n const backgroundTasksConfig = typedAgent.getBackgroundTasksConfig?.();\n const backgroundTaskManager = execOptions?.disableBackgroundTasks ? undefined : mastra?.backgroundTaskManager;\n\n // Resolve tool payload transform policy with the same precedence the\n // non-durable Agent uses: per-call > agent-level > mastra-level. The\n // resolved policy carries a closure, so it lives on the run registry; the\n // JSON-safe `targets` shadow is serialized into workflow input below.\n const toolPayloadTransform =\n normalizeToolPayloadTransformPolicy(execOptions?.transform) ??\n typedAgent.getToolPayloadTransform?.() ??\n normalizeToolPayloadTransformPolicy(\n mastra?.getToolPayloadTransform?.() ?? (mastra as any)?.getToolPayloadProjection?.(),\n );\n\n // 12. Resolve memory persistence flags\n const savePerStep = execOptions?.savePerStep;\n const observationalMemory = !!memoryConfig?.observationalMemory;\n\n // 12b. Open MODEL_GENERATION under the AGENT_RUN opened in step 6, and export both\n // into the workflow input so each durable step can rebuild them. No-ops when\n // observability is off.\n const modelSpan = agentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n name: `llm: '${model.modelId}'`,\n attributes: {\n model: model.modelId,\n provider: model.provider,\n streaming: true,\n },\n metadata: {\n runId,\n threadId,\n resourceId,\n },\n requestContext,\n });\n\n // 13. Create serialized workflow input\n const workflowInput = createWorkflowInput({\n runId,\n agentId: publicAgentId,\n agentName: publicAgentName,\n messageList,\n tools,\n model,\n modelList: modelList ?? undefined,\n scorers,\n options: {\n maxSteps: execOptions?.maxSteps,\n toolChoice: execOptions?.toolChoice as any,\n activeTools: execOptions?.activeTools,\n modelSettings: execOptions?.modelSettings as any,\n // Function-form approval policies are closures that can't ride on the\n // serialized workflow input — the live closure is parked on the run\n // registry below. This boolean shadow is the cross-process fallback:\n // function policies degrade to \"require approval for every tool call\"\n // when the registry slot is unavailable (e.g. Inngest after a worker\n // restart), which is the safe default.\n requireToolApproval:\n typeof execOptions?.requireToolApproval === 'function' ? true : execOptions?.requireToolApproval,\n toolCallConcurrency: execOptions?.toolCallConcurrency,\n autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,\n maxProcessorRetries: execOptions?.maxProcessorRetries,\n includeRawChunks: execOptions?.includeRawChunks,\n returnScorerData: (execOptions as any)?.returnScorerData,\n hasErrorProcessors: errorProcessors.length > 0,\n providerOptions: execOptions?.providerOptions,\n structuredOutput: serializedStructuredOutput,\n skipBgTaskWait: (execOptions as any)?._skipBgTaskWait,\n disableBackgroundTasks: execOptions?.disableBackgroundTasks,\n tracingOptions: execOptions?.tracingOptions,\n actor: execOptions?.actor,\n instructionsOverride: execOptions?.instructions,\n systemMessage: execOptions?.system,\n transform: toolPayloadTransform?.targets ? { targets: toolPayloadTransform.targets } : undefined,\n isTaskComplete: execOptions?.isTaskComplete\n ? {\n scorerNames: execOptions.isTaskComplete.scorers?.map(s => s.name).filter((n): n is string => !!n),\n strategy: execOptions.isTaskComplete.strategy,\n timeout: execOptions.isTaskComplete.timeout,\n parallel: execOptions.isTaskComplete.parallel,\n suppressFeedback: execOptions.isTaskComplete.suppressFeedback,\n }\n : undefined,\n },\n state: {\n memoryConfig,\n threadId,\n resourceId,\n threadExists,\n savePerStep,\n observationalMemory,\n },\n messageId,\n agentSpanData: agentSpan?.exportSpan(),\n modelSpanData: modelSpan?.exportSpan(),\n requestContextEntries: requestContextEntriesSnapshot,\n });\n\n // 14. Create registry entry for non-serializable state\n const registryEntry: RunRegistryEntry = {\n tools,\n saveQueueManager,\n memory,\n model,\n modelList: modelList\n ? modelList.map((entry: AgentModelManagerConfig) => ({\n id: entry.id,\n model: entry.model,\n maxRetries: entry.maxRetries ?? 0,\n enabled: entry.enabled ?? true,\n headers: entry.headers,\n }))\n : undefined,\n workspace,\n requestContext,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n backgroundTaskManager,\n backgroundTasksConfig,\n agentSpan,\n modelSpan,\n // Park the stopWhen predicate(s) on the registry so the durable agentic\n // loop can evaluate them on each iteration. The predicate is a closure and\n // cannot ride on the serialized workflow input; in-process engines read it\n // back via globalRunRegistry, cross-process engines degrade to maxSteps.\n stopWhen: execOptions?.stopWhen,\n onIterationComplete: execOptions?.onIterationComplete,\n prepareStep: execOptions?.prepareStep,\n toolPayloadTransform,\n isTaskComplete: execOptions?.isTaskComplete,\n // Park the per-call requireToolApproval policy on the registry so the\n // durable tool-call step can evaluate function-form policies with the\n // real (toolName, args) on each call. The boolean shadow on the\n // serialized workflow input is the cross-process fallback.\n requireToolApproval: execOptions?.requireToolApproval,\n // Signal drain — the closure reads from AgentThreadStreamRuntime's queues.\n // Non-serializable; cross-process engines lose it and signals go undelivered.\n drainPendingSignals: scope => typedAgent.__getDrainPendingSignals()(runId, scope),\n // Thread title generation — mirrors the non-durable `#executeOnFinish` branch,\n // which was never ported to the durable finish step (so `generateTitle` never\n // fired for durable/evented agents). Parked here because the agent instance is\n // in scope; the durable finish step invokes it after the run completes. No-op\n // when the merged config has no `generateTitle` or the thread already has a\n // title. Non-serializable — cross-process engines skip title generation.\n generateThreadTitle: memory\n ? async ({ threadId, resourceId, memoryConfig, messageListState, requestContext: rc, tracingContext }) => {\n // Re-read the thread so a title written mid-run isn't regenerated, and so we only\n // generate on the first turn (mirrors the non-durable `!thread.title` guard).\n const thread = await memory.getThreadById?.({ threadId });\n const mergedConfig = memory.getMergedThreadConfig?.(memoryConfig);\n const { shouldGenerate, model, instructions, minMessages } = agent.resolveTitleGenerationConfig(\n mergedConfig?.generateTitle as Parameters<typeof agent.resolveTitleGenerationConfig>[0],\n );\n if (!shouldGenerate || thread?.title) return;\n\n const titleMessageList = new MessageList().deserialize(messageListState);\n const uiMessages = titleMessageList.get.all.ui();\n const coreMessages = titleMessageList.get.all.core();\n if (coreMessages.length < (minMessages ?? 1)) return;\n\n const userMessage = agent.getMostRecentUserMessage(uiMessages);\n if (!userMessage) return;\n\n const title = await agent.genTitle(\n userMessage,\n rc ?? new RequestContext(),\n createObservabilityContext(tracingContext),\n model,\n instructions,\n uiMessages,\n );\n if (!title) return;\n\n // Title-only late write. Prefer updateThread when the thread record\n // already exists so its original createdAt is preserved (createThread\n // rebuilds the record with a fresh createdAt). Fall back to createThread\n // for the first-turn case where the record may not be persisted yet.\n if (thread) {\n await memory.updateThread({\n id: threadId,\n title,\n metadata: thread.metadata ?? {},\n memoryConfig,\n });\n } else {\n await memory.createThread({\n threadId,\n resourceId,\n memoryConfig,\n title,\n });\n }\n }\n : undefined,\n // Signal messages already in the messageList at run start (from persisted\n // history). Echoed as data-signal parts on the first LLM step so the client\n // sees them without refetching. Spliced once, never re-emitted.\n initialSignalEchoes: getInitialSignalEchoes(messageList),\n // Agent-level goal config (judge resolver, tools resolver, scorer).\n // Non-serializable — cross-process engines skip goal evaluation.\n goal: agent.__getGoalConfig(),\n // Tripwire from processInput (initial input processing). When an input\n // processor calls abort() during runInputProcessors, we store the tripwire\n // data here so the first llm-execution step can emit a tripwire chunk and\n // bail immediately without calling the model.\n tripwire: tripwireData,\n // Call-time headers from modelSettings.headers. Kept off the serialized\n // workflow input so they never reach durable storage; the durable\n // llm-execution step reads them from this registry slot instead.\n callTimeHeaders: extractCallTimeHeaders(execOptions?.modelSettings),\n // Call-time structured output config with the live schema. The schema is\n // non-serializable (Zod / standard-schema instance), so it lives on the\n // in-process registry. The durable stream adapter reads it to pipe LLM\n // text through `createObjectStreamTransformer`, producing `object-result`\n // chunks. Cross-process engines lose this slot and structured output\n // degrades to raw text.\n structuredOutput: execOptions?.structuredOutput?.schema\n ? {\n ...execOptions.structuredOutput,\n schema: toStandardSchema(execOptions.structuredOutput.schema),\n }\n : undefined,\n cleanup: () => {},\n };\n\n return {\n runId,\n messageId,\n workflowInput,\n registryEntry,\n messageList,\n threadId,\n resourceId,\n };\n}\n\n/**\n * Extract string-valued headers from `modelSettings.headers` for storage on the\n * in-process `RunRegistryEntry`. Returns `undefined` when no valid headers are\n * present so the registry slot stays empty rather than carrying an empty object.\n */\nfunction extractCallTimeHeaders(\n modelSettings: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n const raw = (modelSettings as Record<string, unknown> | undefined)?.headers;\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n\n const headers: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {\n if (typeof value === 'string') headers[key] = value;\n }\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n","import { TTLCache } from '@isaacs/ttlcache';\nimport type { MastraLanguageModel } from '../../llm/model/shared.types';\nimport type { CoreTool } from '../../tools/types';\nimport type { MessageList } from '../message-list';\nimport type { SaveQueueManager } from '../save-queue';\nimport type { RunRegistryEntry } from './types';\n\n/**\n * Global registry for accessing run entries from workflow steps.\n * This is necessary because workflow steps don't have direct access to\n * the DurableAgent instance's registry.\n *\n * Entries are keyed by runId (which are unique UUIDs).\n *\n * Uses TTLCache to prevent unbounded memory growth: entries auto-expire\n * after 10 minutes (refreshed on access) and the registry is hard-capped\n * at 1000 concurrent entries.\n */\nexport const globalRunRegistry = new TTLCache<string, RunRegistryEntry>({\n max: 1000,\n ttl: 10 * 60 * 1000,\n updateAgeOnGet: true,\n dispose: entry => {\n entry?.cleanup?.();\n },\n noDisposeOnSet: true,\n});\n\n/**\n * End a run's root spans (MODEL_GENERATION then AGENT_RUN) with an error so the trace\n * still exports — stores persist only span-end events. After a resume the fresh resume\n * spans are the active root, so prefer them. Ending an already-ended span is a no-op,\n * so the duplicate error paths (workflow failure + emitError) are safe. Never throws.\n */\nexport function endRunSpansWithError(runId: string, error: Error): void {\n try {\n const entry = globalRunRegistry.get(runId);\n (entry?.resumeModelSpan ?? entry?.modelSpan)?.error({ error, endSpan: true });\n (entry?.resumeAgentSpan ?? entry?.agentSpan)?.error({ error, endSpan: true });\n } catch {\n // Span bookkeeping must never break error reporting.\n }\n}\n\n/**\n * Registry for per-run non-serializable state.\n *\n * During durable execution, the DurableAgent needs to store non-serializable\n * objects (tools with execute functions, SaveQueueManager, etc.) that can't\n * flow through workflow state. This registry provides a way to store and\n * retrieve these objects keyed by runId.\n *\n * The registry is scoped to a single DurableAgent instance and entries are\n * cleaned up when a run completes.\n */\nexport class RunRegistry {\n #entries = new Map<string, RunRegistryEntry>();\n\n /**\n * Register non-serializable state for a run\n * @param runId - The unique run identifier\n * @param entry - The registry entry containing tools, saveQueueManager, etc.\n */\n register(runId: string, entry: RunRegistryEntry): void {\n // Clean up any existing entry first\n this.cleanup(runId);\n this.#entries.set(runId, entry);\n }\n\n /**\n * Get the registry entry for a run\n * @param runId - The unique run identifier\n * @returns The registry entry or undefined if not found\n */\n get(runId: string): RunRegistryEntry | undefined {\n return this.#entries.get(runId);\n }\n\n /**\n * Get tools for a specific run\n * @param runId - The unique run identifier\n * @returns The tools record or an empty object if not found\n */\n getTools(runId: string): Record<string, CoreTool> {\n return this.#entries.get(runId)?.tools ?? {};\n }\n\n /**\n * Get SaveQueueManager for a specific run\n * @param runId - The unique run identifier\n * @returns The SaveQueueManager or undefined if not found\n */\n getSaveQueueManager(runId: string): SaveQueueManager | undefined {\n return this.#entries.get(runId)?.saveQueueManager;\n }\n\n /**\n * Get the language model for a specific run\n * @param runId - The unique run identifier\n * @returns The MastraLanguageModel or undefined if not found\n */\n getModel(runId: string): MastraLanguageModel | undefined {\n return this.#entries.get(runId)?.model;\n }\n\n /**\n * Check if a run is registered\n * @param runId - The unique run identifier\n * @returns True if the run is registered\n */\n has(runId: string): boolean {\n return this.#entries.has(runId);\n }\n\n /**\n * Cleanup and remove a run's entry from the registry\n * @param runId - The unique run identifier\n */\n cleanup(runId: string): void {\n const entry = this.#entries.get(runId);\n if (entry) {\n // Call cleanup function if provided\n entry.cleanup?.();\n this.#entries.delete(runId);\n }\n }\n\n /**\n * Get the number of active runs in the registry\n */\n get size(): number {\n return this.#entries.size;\n }\n\n /**\n * Get all active run IDs\n */\n get runIds(): string[] {\n return Array.from(this.#entries.keys());\n }\n\n /**\n * Clear all entries from the registry\n * Calls cleanup on each entry before removing\n */\n clear(): void {\n for (const runId of this.#entries.keys()) {\n this.cleanup(runId);\n }\n }\n}\n\n/**\n * Extended registry entry that also stores the MessageList reference.\n * This is useful for accessing message state outside of workflow steps\n * (e.g., for callbacks that need to read messages).\n */\nexport interface ExtendedRunRegistryEntry extends RunRegistryEntry {\n /** MessageList reference for callback access */\n messageList?: MessageList;\n /** Thread ID for memory */\n threadId?: string;\n /** Resource ID for memory */\n resourceId?: string;\n}\n\n/**\n * Extended run registry that also stores MessageList references and memory info\n */\nexport class ExtendedRunRegistry extends RunRegistry {\n #messageLists = new Map<string, MessageList>();\n #memoryInfo = new Map<string, { threadId?: string; resourceId?: string }>();\n\n /**\n * Register non-serializable state for a run including MessageList\n */\n registerWithMessageList(\n runId: string,\n entry: RunRegistryEntry,\n messageList: MessageList,\n memoryInfo?: { threadId?: string; resourceId?: string },\n ): void {\n this.register(runId, entry);\n this.#messageLists.set(runId, messageList);\n if (memoryInfo) {\n this.#memoryInfo.set(runId, memoryInfo);\n }\n }\n\n /**\n * Get MessageList for a specific run\n */\n getMessageList(runId: string): MessageList | undefined {\n return this.#messageLists.get(runId);\n }\n\n /**\n * Get memory info for a specific run\n */\n getMemoryInfo(runId: string): { threadId?: string; resourceId?: string } | undefined {\n return this.#memoryInfo.get(runId);\n }\n\n /**\n * Override cleanup to also remove MessageList and memory info\n */\n override cleanup(runId: string): void {\n super.cleanup(runId);\n this.#messageLists.delete(runId);\n this.#memoryInfo.delete(runId);\n }\n\n /**\n * Override clear to also clear MessageLists and memory info\n */\n override clear(): void {\n super.clear();\n this.#messageLists.clear();\n this.#memoryInfo.clear();\n }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport type { PubSub } from '../../events/pubsub';\nimport type { Event } from '../../events/types';\nimport type { IMastraLogger } from '../../logger';\nimport type { OutputProcessorOrWorkflow } from '../../processors';\nimport { safeClose, safeEnqueue } from '../../stream/base';\nimport { MastraModelOutput } from '../../stream/base/output';\nimport type {\n ChunkType,\n MastraOnFinishCallback,\n MastraOnStepFinishCallback,\n MastraStreamTransformOptions,\n LanguageModelUsage,\n} from '../../stream/types';\nimport { MessageList } from '../message-list';\nimport type { StructuredOutputOptions } from '../types';\nimport { AGENT_STREAM_TOPIC, AgentStreamEventTypes } from './constants';\nimport type {\n AgentStreamEvent,\n AgentChunkEventData,\n AgentStepFinishEventData,\n AgentFinishEventData,\n AgentErrorEventData,\n AgentSuspendedEventData,\n AgentAbortEventData,\n AgentIterationCompleteEventData,\n} from './types';\n\n/**\n * Map workflow usage (which may use legacy promptTokens/completionTokens) to\n * the canonical LanguageModelUsage shape (inputTokens/outputTokens).\n */\nfunction normalizeUsage(raw?: Record<string, unknown>): LanguageModelUsage {\n if (!raw) {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n }\n const inputTokens = (raw.inputTokens as number) ?? (raw.promptTokens as number) ?? 0;\n const outputTokens = (raw.outputTokens as number) ?? (raw.completionTokens as number) ?? 0;\n const totalTokens = (raw.totalTokens as number) ?? inputTokens + outputTokens;\n return { inputTokens, outputTokens, totalTokens };\n}\n\n/**\n * Options for creating a durable agent stream\n */\nexport interface DurableAgentStreamOptions<OUTPUT = undefined> {\n /** Pubsub instance to subscribe to */\n pubsub: PubSub;\n /** Run identifier */\n runId: string;\n /** Message ID for this execution */\n messageId: string;\n /** Model information for the output */\n model: {\n modelId: string | undefined;\n provider: string | undefined;\n version: 'v2' | 'v3' | 'v4';\n };\n /** Thread ID for memory */\n threadId?: string;\n /** Resource ID for memory */\n resourceId?: string;\n /**\n * Start replay from this index (0-based).\n * If undefined, uses full replay (subscribeWithReplay).\n * If specified, uses efficient indexed replay (subscribeFromOffset).\n */\n offset?: number;\n /** Callback when chunk is received */\n onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;\n /** Callback when step finishes */\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n /** Callback when execution finishes — routed through MastraModelOutput for rich step data */\n onFinish?: MastraOnFinishCallback<OUTPUT>;\n /** Lifecycle hook called after the FINISH event closes the stream (for cleanup scheduling) */\n onStreamFinished?: () => void | Promise<void>;\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 */\n onAbort?: (data: AgentAbortEventData) => void | Promise<void>;\n /** Callback fired after each agentic-loop iteration */\n onIterationComplete?: (data: AgentIterationCompleteEventData) => void | Promise<void>;\n /** Optional logger for structured logging */\n logger?: IMastraLogger;\n /**\n * If true, close the underlying ReadableStream when a SUSPENDED event is\n * received. Used by `generate()` / `resumeGenerate()` so that\n * `getFullOutput()` resolves on suspend instead of hanging. Streaming\n * callers leave this `false` so the stream stays open for a later resume.\n */\n closeOnSuspend?: boolean;\n /**\n * Structured output configuration with live schema. When provided,\n * `MastraModelOutput` pipes LLM text through `createObjectStreamTransformer`\n * to produce `object-result` chunks.\n */\n structuredOutput?: StructuredOutputOptions<OUTPUT>;\n /** Output processors to run in MastraModelOutput's stream pipeline */\n outputProcessors?: OutputProcessorOrWorkflow[];\n /** Experimental transforms applied whenever the returned full stream is consumed. */\n experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;\n /**\n * Optional external MessageList to use instead of creating a fresh empty one.\n * When provided (e.g. the registry's live MessageList), MastraModelOutput can\n * resolve step content from messages added during the workflow execution.\n */\n messageList?: MessageList;\n}\n\n/**\n * Result from creating a durable agent stream\n */\nexport interface DurableAgentStreamResult<OUTPUT = undefined> {\n /** The MastraModelOutput that streams from pubsub events */\n output: MastraModelOutput<OUTPUT>;\n /** Cleanup function to unsubscribe from pubsub */\n cleanup: () => void;\n /** Promise that resolves when subscription is established */\n ready: Promise<void>;\n}\n\n/**\n * Create a MastraModelOutput that streams from pubsub events.\n *\n * This adapter subscribes to the agent stream pubsub channel and converts\n * pubsub events into a ReadableStream that MastraModelOutput can consume.\n * Callbacks are invoked as events arrive.\n */\nexport function createDurableAgentStream<OUTPUT = undefined>(\n options: DurableAgentStreamOptions<OUTPUT>,\n): DurableAgentStreamResult<OUTPUT> {\n const {\n pubsub,\n runId,\n messageId,\n model,\n threadId,\n resourceId,\n offset,\n onChunk,\n onStepFinish,\n onFinish,\n onStreamFinished,\n onError,\n onSuspended,\n onAbort,\n onIterationComplete,\n logger,\n closeOnSuspend = false,\n structuredOutput,\n outputProcessors,\n experimentalTransform,\n messageList: externalMessageList,\n } = options;\n\n // Helper to log errors (uses logger if available, falls back to console)\n const logError = (message: string, error: unknown) => {\n if (logger) {\n logger.error(message, error);\n } else {\n console.error(message, error);\n }\n };\n\n // Use an external MessageList if provided (e.g. the live registry one that\n // llm-execution.ts keeps in sync), otherwise create a fresh empty one.\n // This lets MastraModelOutput resolve step content from the real assistant\n // messages added during the workflow execution.\n const messageList =\n externalMessageList ??\n new MessageList({\n threadId,\n resourceId,\n });\n\n // Track subscription state\n let isSubscribed = false;\n let cancelled = false;\n let controller: ReadableStreamDefaultController<ChunkType<OUTPUT>> | null = null;\n\n // Promise that resolves when subscription is established\n let resolveReady: () => void;\n let rejectReady: (error: Error) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n // Handler for pubsub events.\n //\n // All `controller.enqueue` / `controller.close` / `controller.error` calls\n // are wrapped in safe* helpers because pubsub events can arrive AFTER the\n // stream has already been closed (e.g. a stale background-task lifecycle\n // event published after the agent's FINISH chunk closed the controller).\n // Without the guards, those late events surface as\n // `TypeError: Invalid state: Controller is already closed` from the\n // controller, which the outer try/catch logs but which floods the\n // console and (in test runs) causes timeouts as event handlers retry.\n // Track the last error message seen in an 'error' chunk, so we can\n // surface it in onError when the FINISH event arrives with reason 'error'.\n let lastErrorMessage: string | undefined;\n\n const handleEvent = async (event: Event) => {\n if (!controller) return;\n\n // Parse the event data as AgentStreamEvent\n const streamEvent = event as unknown as AgentStreamEvent;\n\n try {\n switch (streamEvent.type) {\n case AgentStreamEventTypes.CHUNK: {\n const chunk = streamEvent.data as AgentChunkEventData;\n // Track error chunks for onError callback\n if ((chunk as any).type === 'error') {\n const errPayload = (chunk as any).payload;\n lastErrorMessage = errPayload?.error?.message || errPayload?.message || 'LLM execution error';\n }\n safeEnqueue(controller, chunk as ChunkType<OUTPUT>);\n await onChunk?.(chunk as ChunkType<OUTPUT>);\n break;\n }\n\n case AgentStreamEventTypes.STEP_START: {\n // Step start - enqueue if it's a chunk type\n const chunk = streamEvent.data as ChunkType<OUTPUT>;\n if (chunk && 'type' in chunk) {\n safeEnqueue(controller, chunk);\n }\n break;\n }\n\n case AgentStreamEventTypes.STEP_FINISH: {\n const data = streamEvent.data as AgentStepFinishEventData;\n await onStepFinish?.(data);\n break;\n }\n\n case AgentStreamEventTypes.FINISH: {\n const data = streamEvent.data as AgentFinishEventData;\n // Enqueue finish chunk and close stream even if callback throws\n const finishChunk = {\n type: 'finish' as const,\n payload: {\n output: data.output,\n stepResult: data.stepResult,\n },\n } as ChunkType<OUTPUT>;\n safeEnqueue(controller, finishChunk);\n safeClose(controller);\n\n // Build rich onFinish payload from finish event data.\n // The pubsub FINISH event carries output.text, output.steps, and\n // stepResult — enough to reconstruct the fields scenario tests expect\n // (text, steps, toolResults, finishReason, usage).\n if (onFinish) {\n try {\n const steps = (data.output?.steps ?? []) as any[];\n const allToolResults = steps.flatMap((s: any) => s?.toolResults ?? []);\n const allToolCalls = steps.flatMap((s: any) => s?.toolCalls ?? []);\n await onFinish({\n text: data.output?.text ?? '',\n steps,\n toolResults: allToolResults,\n toolCalls: allToolCalls,\n dynamicToolCalls: [],\n dynamicToolResults: [],\n staticToolCalls: [],\n staticToolResults: [],\n files: [],\n sources: [],\n reasoning: [],\n content: [],\n finishReason: data.stepResult?.reason ?? 'stop',\n usage: normalizeUsage(data.output?.usage),\n totalUsage: normalizeUsage(data.output?.usage),\n warnings: data.stepResult?.warnings ?? [],\n request: { body: undefined },\n response: {},\n reasoningText: undefined,\n providerMetadata: undefined,\n });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onFinish callback error:`, callbackError);\n }\n }\n\n // When the finish reason is 'abort', also fire onAbort so\n // consumers see it — the abort was handled gracefully (clean\n // return from llm-execution) rather than crashing the workflow,\n // so the separate ABORT event never fires.\n if (onAbort && (data.stepResult?.reason as string) === 'abort') {\n try {\n await onAbort({ steps: (data.output?.steps ?? []) as unknown[] });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onAbort (from FINISH) callback error:`, callbackError);\n }\n }\n\n // When the finish reason is 'error', also fire onError so\n // consumers see it — the error was handled gracefully (bail\n // response) rather than crashing the workflow, so the ERROR\n // event never fires.\n if (onError && data.stepResult?.reason === 'error') {\n try {\n await onError({ error: new Error(lastErrorMessage || 'LLM execution error') });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onError (from FINISH) callback error:`, callbackError);\n }\n }\n\n try {\n await onStreamFinished?.();\n } catch (callbackError) {\n logError(`[DurableAgentStream] onStreamFinished callback error:`, callbackError);\n }\n break;\n }\n\n case AgentStreamEventTypes.ERROR: {\n const data = streamEvent.data as AgentErrorEventData;\n const error = new Error(data.error.message);\n error.name = data.error.name;\n if (data.error.stack) {\n error.stack = data.error.stack;\n }\n // Enqueue an error chunk and close the stream normally (mirrors the\n // regular agent's deferred-error-chunk pattern). Using\n // controller.error() would error the base ReadableStream, which\n // MastraModelOutput.consumeStream swallows — leaving fullStream\n // hanging because no 'finish' event fires on the internal emitter.\n safeEnqueue(controller, {\n type: 'error',\n payload: { error },\n } as ChunkType<OUTPUT>);\n safeClose(controller);\n try {\n await onError?.({ error });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onError callback error:`, callbackError);\n }\n break;\n }\n\n case AgentStreamEventTypes.SUSPENDED: {\n const data = streamEvent.data as AgentSuspendedEventData;\n await onSuspended?.(data);\n // By default we leave the stream open on suspend so a later resume\n // can keep streaming chunks. `generate()`/`resumeGenerate()` opt\n // into closing here so `getFullOutput()` can resolve.\n if (closeOnSuspend) {\n safeClose(controller);\n }\n break;\n }\n\n case AgentStreamEventTypes.ABORT: {\n const data = streamEvent.data as AgentAbortEventData;\n try {\n await onAbort?.(data);\n } catch (callbackError) {\n logError(`[DurableAgentStream] onAbort callback error:`, callbackError);\n }\n // Abort closes the stream — the run will not continue.\n safeClose(controller);\n break;\n }\n\n case AgentStreamEventTypes.ITERATION_COMPLETE: {\n const data = streamEvent.data as AgentIterationCompleteEventData;\n try {\n await onIterationComplete?.(data);\n } catch (callbackError) {\n logError(`[DurableAgentStream] onIterationComplete callback error:`, callbackError);\n }\n break;\n }\n\n default:\n // Unknown event type - ignore\n break;\n }\n } catch (error) {\n // Intentional catch-and-continue: callback errors (onChunk, onStepFinish,\n // onSuspended) must not kill the stream. onFinish/onError have their own\n // inner try/catch and close/error the stream before invoking callbacks,\n // so they are not affected by this outer handler.\n logError(`[DurableAgentStream] Error handling event ${streamEvent.type}:`, error);\n }\n };\n\n // Create the readable stream\n const stream = new ReadableStream<ChunkType<OUTPUT>>({\n start(ctrl) {\n controller = ctrl;\n\n // Subscribe to pubsub with replay support for resumable streams\n // If offset is specified, use indexed replay for efficiency\n // Otherwise use full replay\n const topic = AGENT_STREAM_TOPIC(runId);\n const subscribePromise =\n offset !== undefined\n ? pubsub.subscribeFromOffset(topic, offset, handleEvent)\n : pubsub.subscribeWithReplay(topic, handleEvent);\n\n subscribePromise\n .then(() => {\n if (cancelled) {\n // cleanup() was called before subscribe resolved — unsubscribe now\n void pubsub.unsubscribe(topic, handleEvent).catch(error => {\n logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, error);\n });\n resolveReady();\n return;\n }\n isSubscribed = true;\n resolveReady();\n })\n .catch(error => {\n logError(`[DurableAgentStream] Failed to subscribe to ${topic}:`, error);\n rejectReady(error);\n ctrl.error(error);\n });\n },\n cancel() {\n cleanup();\n },\n });\n\n // Cleanup function - intentionally fire-and-forget for unsubscribe.\n // Sets cancelled=true so the subscribe .then() handler will unsubscribe\n // if cleanup runs before the subscription promise resolves.\n const cleanup = () => {\n cancelled = true;\n if (isSubscribed) {\n isSubscribed = false;\n const topic = AGENT_STREAM_TOPIC(runId);\n void pubsub.unsubscribe(topic, handleEvent).catch(error => {\n logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, error);\n });\n }\n controller = null;\n };\n\n // Create the MastraModelOutput.\n // onStepFinish is passed to MastraModelOutput so it fires during stream\n // consumption (the harness and user code iterate fullStream, which drives\n // consumeStream internally). The pubsub STEP_FINISH event is not emitted\n // by the durable workflow, so the pubsub handler alone is not sufficient.\n //\n // onFinish is called from the pubsub FINISH handler (above) with a\n // payload built from the event data. This ensures it fires even when\n // nobody iterates the stream (e.g. resume flows with delay-only waits).\n const output = new MastraModelOutput<OUTPUT>({\n model,\n stream,\n messageList,\n messageId,\n options: {\n runId,\n onStepFinish: onStepFinish as MastraOnStepFinishCallback<OUTPUT> | undefined,\n // For durable agents there is only one MastraModelOutput for the whole run.\n // isLLMExecutionStep must be true so output processors run per-chunk\n // (processOutputStream / processPart path) rather than the batch\n // runOutputProcessors path which only fires at finish. It also gates\n // createObjectStreamTransformer for structured output.\n // resolveFinalPromises forces text/finishReason promise resolution at\n // step-finish despite isLLMExecutionStep being true — durable agents have\n // no outer MastraModelOutput to resolve them.\n structuredOutput: structuredOutput as any,\n isLLMExecutionStep: true,\n resolveFinalPromises: true,\n outputProcessors,\n experimentalTransform,\n },\n });\n\n return {\n output,\n cleanup,\n ready,\n };\n}\n\n/**\n * Helper to emit a chunk event to pubsub\n */\nexport async function emitChunkEvent<OUTPUT = undefined>(\n pubsub: PubSub,\n runId: string,\n chunk: ChunkType<OUTPUT>,\n): Promise<void> {\n const topic = AGENT_STREAM_TOPIC(runId);\n await pubsub.publish(topic, {\n type: AgentStreamEventTypes.CHUNK,\n runId,\n data: chunk,\n });\n}\n\n/**\n * Helper to emit a step start event to pubsub.\n * The `data` payload must include `type: 'step-start'` so the stream-adapter\n * consumer recognises it as a `ChunkType` and enqueues it onto the client stream.\n */\nexport async function emitStepStartEvent(\n pubsub: PubSub,\n runId: string,\n data: { stepId?: string; request?: unknown; warnings?: unknown[] },\n): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.STEP_START,\n runId,\n data: { type: 'step-start', ...data },\n });\n}\n\n/**\n * Helper to emit a step finish event to pubsub\n */\nexport async function emitStepFinishEvent(\n pubsub: PubSub,\n runId: string,\n data: AgentStepFinishEventData,\n): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.STEP_FINISH,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit a finish event to pubsub\n */\nexport async function emitFinishEvent(pubsub: PubSub, runId: string, data: AgentFinishEventData): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.FINISH,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit an error event to pubsub\n */\nexport async function emitErrorEvent(pubsub: PubSub, runId: string, error: Error): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.ERROR,\n runId,\n data: {\n error: {\n name: error.name,\n message: error.message,\n // stack intentionally omitted — avoid leaking internals through external pubsub\n },\n },\n });\n}\n\n/**\n * Helper to emit a suspended event to pubsub\n */\nexport async function emitSuspendedEvent(pubsub: PubSub, runId: string, data: AgentSuspendedEventData): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.SUSPENDED,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit an abort event to pubsub\n */\nexport async function emitAbortEvent(pubsub: PubSub, runId: string, data: AgentAbortEventData): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.ABORT,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit an iteration-complete event to pubsub\n */\nexport async function emitIterationCompleteEvent(\n pubsub: PubSub,\n runId: string,\n data: AgentIterationCompleteEventData,\n): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.ITERATION_COMPLETE,\n runId,\n data,\n });\n}\n","import { z } from 'zod';\n\n/**\n * Shared Zod schemas for durable agentic workflows.\n *\n * These schemas are used by:\n * - Core DurableAgent workflow\n * - Inngest durable agent workflow\n * - Evented durable agent workflow (future)\n */\n\n/**\n * Schema for model configuration\n */\nexport const modelConfigSchema = z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n settings: z.record(z.string(), z.any()).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n});\n\n/**\n * Schema for model list entry (fallback support)\n */\nexport const modelListEntrySchema = z.object({\n id: z.string(),\n config: z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n originalConfig: z.union([z.string(), z.record(z.string(), z.any())]).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n }),\n maxRetries: z.number(),\n enabled: z.boolean(),\n});\n\n/**\n * Schema for accumulated usage across iterations\n */\nexport const accumulatedUsageSchema = z.object({\n inputTokens: z.number(),\n outputTokens: z.number(),\n totalTokens: z.number(),\n});\n\n/**\n * Schema for output from the durable agentic workflow\n */\nexport const durableAgenticOutputSchema = z.object({\n messageListState: z.any(),\n messageId: z.string(),\n stepResult: z.any(),\n output: z.object({\n text: z.string().optional(),\n usage: z.any(),\n steps: z.array(z.any()),\n }),\n state: z.any(),\n});\n\n/**\n * Base schema for durable agentic workflow input.\n * Implementations can extend this with additional fields.\n */\nexport const baseDurableAgenticInputSchema = 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});\n\n/**\n * Base schema for iteration state.\n * Implementations can extend this with additional fields.\n */\nexport const baseIterationStateSchema = z.object({\n // Original input fields\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: z.any(),\n options: z.any(),\n state: z.any(),\n messageId: z.string(),\n // Iteration tracking\n iterationCount: z.number(),\n accumulatedSteps: z.array(z.any()),\n accumulatedUsage: accumulatedUsageSchema,\n // Last step result for continuation check\n lastStepResult: z.any().optional(),\n // Background task tracking\n backgroundTaskPending: z.boolean().optional(),\n // Set when a delegation hook calls ctx.bail() — signals the loop to stop\n delegationBailed: z.boolean().optional(),\n // Set when onIterationComplete returns { continue: false, feedback } — allows\n // one more LLM turn with the feedback, then stops on the next predicate eval.\n pendingFeedbackStop: z.boolean().optional(),\n // Span data, carried unchanged so every iteration shares one trace\n agentSpanData: z.any().optional(),\n modelSpanData: z.any().optional(),\n});\n\n/**\n * Type for the base iteration state\n */\nexport type BaseIterationState = z.infer<typeof baseIterationStateSchema>;\n\n/**\n * Type for accumulated usage\n */\nexport type AccumulatedUsage = z.infer<typeof accumulatedUsageSchema>;\n","import type { DurableAgenticExecutionOutput } from '../../types';\nimport type { AccumulatedUsage, BaseIterationState } from './schemas';\n\n/**\n * Input for creating iteration state update\n */\nexport interface IterationStateUpdateInput {\n /** Current iteration state */\n currentState: BaseIterationState;\n /** Output from the current iteration's execution */\n executionOutput: DurableAgenticExecutionOutput;\n}\n\n/**\n * Step record for tracking iteration history\n */\nexport interface StepRecord {\n text?: string;\n toolCalls?: unknown[];\n toolResults?: unknown[];\n usage?: unknown;\n finishReason?: string;\n}\n\n/**\n * Calculate accumulated usage from current state and new execution output.\n */\nexport function calculateAccumulatedUsage(\n currentUsage: AccumulatedUsage,\n executionUsage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number },\n): AccumulatedUsage {\n return {\n inputTokens: currentUsage.inputTokens + (executionUsage?.inputTokens || 0),\n outputTokens: currentUsage.outputTokens + (executionUsage?.outputTokens || 0),\n totalTokens: currentUsage.totalTokens + (executionUsage?.totalTokens || 0),\n };\n}\n\n/**\n * Build a step record from execution output.\n */\nexport function buildStepRecord(executionOutput: DurableAgenticExecutionOutput): StepRecord {\n return {\n text: executionOutput.output.text,\n toolCalls: executionOutput.output.toolCalls,\n toolResults: executionOutput.toolResults,\n usage: executionOutput.output.usage,\n finishReason: executionOutput.stepResult.reason,\n };\n}\n\n/**\n * Create the base iteration state update.\n *\n * This returns the common fields for iteration state updates.\n * Implementations can extend this with their specific fields.\n *\n * @example\n * ```typescript\n * const baseUpdate = createBaseIterationStateUpdate({\n * currentState: initData,\n * executionOutput,\n * });\n *\n * // Core extends with modelList\n * const coreState = { ...baseUpdate, modelList: initData.modelList };\n *\n * // Inngest extends with observability\n * const inngestState = {\n * ...baseUpdate,\n * agentSpanData: initData.agentSpanData,\n * modelSpanData: initData.modelSpanData,\n * stepIndex: initData.stepIndex + 1,\n * };\n * ```\n */\nexport function createBaseIterationStateUpdate(input: IterationStateUpdateInput): BaseIterationState {\n const { currentState, executionOutput } = input;\n\n const newUsage = calculateAccumulatedUsage(currentState.accumulatedUsage, executionOutput.output.usage);\n const stepRecord = buildStepRecord(executionOutput);\n\n return {\n runId: currentState.runId,\n agentId: currentState.agentId,\n agentName: currentState.agentName,\n messageListState: executionOutput.messageListState,\n toolsMetadata: currentState.toolsMetadata,\n modelConfig: currentState.modelConfig,\n options: currentState.options,\n state: executionOutput.state,\n messageId: executionOutput.messageId,\n iterationCount: currentState.iterationCount + 1,\n accumulatedSteps: [...currentState.accumulatedSteps, stepRecord],\n accumulatedUsage: newUsage,\n lastStepResult: executionOutput.stepResult,\n backgroundTaskPending: executionOutput.backgroundTaskPending,\n delegationBailed: executionOutput.delegationBailed,\n // Preserve the two-phase stop flag set by the dowhile predicate's\n // onIterationComplete handler. The predicate mutates state on the\n // *output* of the previous iteration; createBaseIterationStateUpdate\n // rebuilds the state for the next iteration, so we must carry the\n // flag forward explicitly.\n pendingFeedbackStop: currentState.pendingFeedbackStop,\n // Carry span identity forward unchanged so every iteration shares one trace.\n agentSpanData: currentState.agentSpanData,\n modelSpanData: currentState.modelSpanData,\n };\n}\n","import { DurableAgentDefaults } from '../../constants';\nimport type { DurableToolCallInput, SerializableDurableOptions, SerializableToolMetadata } from '../../types';\n\n/**\n * Resolves the effective tool-call foreach concurrency for a durable agentic\n * workflow from the serialized workflow input (iteration state) and the\n * step's tool calls.\n *\n * Mirrors @mastra/core's non-durable loop semantics\n * (loop/workflows/agentic-execution/tool-call-concurrency.ts):\n * - Global `requireToolApproval` forces sequential execution. The serialized\n * boolean shadow is `true` for function-form policies, so those degrade\n * safely to sequential as well.\n * - Any tool in the step's *effective active tool set* with `requireApproval`\n * or `hasSuspendSchema` forces sequential execution so approval/suspension\n * flows never race with concurrent tool calls. The check is against the\n * active tool set, NOT the tools the model actually called: a registered\n * suspending/approval tool the model skipped this step must still force\n * sequential execution, since a concurrently-running sibling tool would\n * race the suspension.\n * - Otherwise the configured `toolCallConcurrency` applies\n * (default {@link DurableAgentDefaults.TOOL_CALL_CONCURRENCY}).\n *\n * The active tool set is the `activeTools` allowlist the LLM step stamps on\n * each tool call (processors may narrow or clear it; all calls in one step\n * share the value, `null` = restriction cleared → unrestricted). When the\n * calls carry no stamp, the run-level `activeTools` option applies.\n *\n * Designed to be called from a foreach concurrency resolver at execution\n * time, reading only serialized state — safe across durable-engine replays\n * and shared workflow instances.\n */\nexport function resolveDurableToolCallConcurrency({\n options,\n toolsMetadata,\n toolCalls,\n}: {\n options?: Pick<SerializableDurableOptions, 'requireToolApproval' | 'toolCallConcurrency' | 'activeTools'>;\n toolsMetadata?: SerializableToolMetadata[];\n toolCalls?: Pick<DurableToolCallInput, 'activeTools'>[];\n}): number {\n if (options?.requireToolApproval) {\n return 1;\n }\n\n const stamped = toolCalls?.find(tc => tc.activeTools !== undefined);\n const activeTools = stamped ? stamped.activeTools : options?.activeTools;\n const consideredTools =\n activeTools === undefined || activeTools === null\n ? (toolsMetadata ?? [])\n : (toolsMetadata ?? []).filter(tool => activeTools.includes(tool.name));\n\n if (consideredTools.some(tool => tool.hasSuspendSchema || tool.requireApproval)) {\n return 1;\n }\n\n const configured = options?.toolCallConcurrency;\n return typeof configured === 'number' && configured > 0 ? configured : DurableAgentDefaults.TOOL_CALL_CONCURRENCY;\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\nconst BG_CHECK_STEP_ID = `${DurableStepIds.AGENTIC_EXECUTION}-bg-task-check`;\n\n/**\n * The background task check step accepts the output of llmMappingStep\n * and passes it through, adding backgroundTaskPending if tasks are running.\n */\nconst bgCheckInputSchema = z.any();\nconst bgCheckOutputSchema = z.any();\n\n/**\n * Create a durable background task check step.\n *\n * Mirrors the regular agent's backgroundTaskCheckStep pattern:\n * - After tool calls complete, checks if any background tasks are still running\n * - If no running tasks: passes through unchanged\n * - If an explicit waitTimeoutMs is configured and retryCount === 0: returns\n * immediately with backgroundTaskPending=true (caller drives continuation)\n * - Otherwise: waits for the next task to complete using the configured\n * waitTimeoutMs or a 1 s default — this keeps the workflow (and its pubsub\n * subscription) alive so background-task tool-result chunks are delivered\n * - When a task completes: sets isContinued=true so the LLM processes the result\n */\nexport function createDurableBackgroundTaskCheckStep() {\n return createStep({\n id: BG_CHECK_STEP_ID,\n inputSchema: bgCheckInputSchema,\n outputSchema: bgCheckOutputSchema,\n execute: async params => {\n const { inputData, getInitData, retryCount } = params;\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const typedInput = inputData as Record<string, any>;\n\n const initData = getInitData<{\n runId: string;\n agentId: string;\n options?: { skipBgTaskWait?: boolean };\n state?: { threadId?: string; resourceId?: string };\n }>();\n const { runId, agentId } = initData;\n\n const registryEntry = globalRunRegistry.get(runId);\n const bgManager = registryEntry?.backgroundTaskManager;\n\n if (!bgManager) {\n return typedInput;\n }\n\n const runningResult = await bgManager.listTasks({\n agentId,\n status: 'running',\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n });\n const runningTasks = runningResult?.tasks;\n\n if (!runningTasks || runningTasks.length === 0) {\n return typedInput;\n }\n\n // When the outer caller drives continuation externally (e.g. streamUntilIdle),\n // skip the in-loop wait. We still mark pending so ownstream knows.\n if (initData.options?.skipBgTaskWait) {\n return { ...typedInput, backgroundTaskPending: true };\n }\n\n const taskIds = runningTasks.map(task => task.id);\n\n const bgConfig = registryEntry?.backgroundTasksConfig;\n const managerConfig = bgManager.config;\n const waitTimeoutMs = bgConfig?.waitTimeoutMs ?? managerConfig?.waitTimeoutMs;\n\n // The regular agent gates on `retryCount === 0 || !waitTimeoutMs`\n // and can afford to skip waiting because tool-result chunks from\n // background tasks are pushed directly into the ReadableStream\n // controller via safeEnqueue — that works even after this step\n // returns.\n //\n // The durable agent emits tool-result chunks via pubsub. The\n // pubsub subscription is torn down when the stream closes and the\n // consumer calls cleanup(). If this step returns without waiting,\n // the workflow finishes, FINISH fires, the stream closes, cleanup\n // runs, and the pubsub subscriber is gone before the background\n // task can deliver its result.\n //\n // Therefore the durable agent must always wait when background\n // tasks are running — using the configured waitTimeoutMs, or a\n // sensible 1 s default to keep the workflow (and pubsub) alive.\n\n // First invocation without explicit waitTimeoutMs — match the\n // regular agent's \"signal pending, don't block\" on retryCount 0,\n // but only when the caller provided an explicit timeout (meaning\n // they'll drive continuation externally).\n if (retryCount === 0 && waitTimeoutMs) {\n return { ...typedInput, backgroundTaskPending: true };\n }\n\n // Use configured timeout, or default to 1 s so the workflow stays\n // alive long enough for pubsub to deliver background-task results.\n const effectiveWaitMs = waitTimeoutMs ?? 1000;\n\n // Emit initial progress chunk\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, runId, {\n type: 'background-task-progress' as any,\n runId,\n from: ChunkFrom.AGENT,\n payload: { taskIds, runningCount: runningTasks.length, elapsedMs: 0 },\n });\n } catch {\n // PubSub may be closed\n }\n }\n\n // Wait for the next task to complete (or until timeout)\n try {\n await bgManager.waitForNextTask(taskIds, {\n timeoutMs: effectiveWaitMs,\n onProgress: (elapsedMs: number) => {\n if (!pubsub) return;\n void emitChunkEvent(pubsub, runId, {\n type: 'background-task-progress' as any,\n runId,\n from: ChunkFrom.AGENT,\n payload: { taskIds, runningCount: runningTasks.length, elapsedMs },\n }).catch(() => {});\n },\n progressIntervalMs: 3000,\n });\n } catch {\n // Timeout elapsed — no task completed. Return unchanged so the loop can end.\n // The tasks keep running in the background — results are picked up on\n // the next user message or stream.\n return typedInput;\n }\n\n // A task completed — force the loop to continue so the LLM processes the result\n if (typedInput.stepResult) {\n return {\n ...typedInput,\n backgroundTaskPending: true,\n stepResult: { ...typedInput.stepResult, isContinued: true },\n };\n }\n\n return { ...typedInput, backgroundTaskPending: true };\n },\n });\n}\n","import type { IMastraLogger } from '../../../logger';\nimport { transformToolPayloadForTargets, withToolPayloadTransformMetadata } from '../../../tools/payload-transform';\nimport type { CoreTool, ToolPayloadTransformPolicy } from '../../../tools/types';\n\n/**\n * Apply the in-process tool payload transform policy to a chunk before the\n * durable layer publishes it. Mirrors `addToolPayloadTransformToChunk` in the\n * non-durable agentic-execution layer, restricted to the chunk types that the\n * durable loop emits (`tool-call`, `tool-result`, `tool-error`).\n *\n * The transform policy is only available for in-process durable runs (it\n * carries a closure that cannot be serialized into the workflow input). When\n * the policy is missing or the chunk is not tool-shaped, the chunk is\n * returned unchanged.\n */\nexport async function applyToolPayloadTransformToChunk<TChunk extends { type: string; payload?: any }>(\n chunk: TChunk,\n opts: {\n policy?: ToolPayloadTransformPolicy;\n tools?: Record<string, CoreTool>;\n logger?: IMastraLogger;\n },\n): Promise<TChunk> {\n const { policy, tools, logger } = opts;\n if (!policy && !tools) {\n return chunk;\n }\n\n const payload = chunk.payload;\n if (!payload || typeof payload !== 'object') {\n return chunk;\n }\n\n const toolName = (payload as { toolName?: unknown }).toolName;\n const toolCallId = (payload as { toolCallId?: unknown }).toolCallId;\n if (typeof toolName !== 'string' || typeof toolCallId !== 'string') {\n return chunk;\n }\n\n const tool = tools?.[toolName];\n const source = {\n policy,\n toolTransform: (tool as { transform?: unknown } | undefined)?.transform as any,\n };\n\n let transformedChunk: TChunk = chunk;\n let transform;\n\n if (chunk.type === 'tool-call') {\n transform = await transformToolPayloadForTargets(\n {\n phase: 'input-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n );\n } else if (chunk.type === 'tool-result') {\n transformedChunk = withToolPayloadTransformMetadata(\n transformedChunk as any,\n await transformToolPayloadForTargets(\n {\n phase: 'input-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n ),\n ) as TChunk;\n transform = await transformToolPayloadForTargets(\n {\n phase: 'output-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n output: (payload as { result?: unknown }).result,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n );\n } else if (chunk.type === 'tool-error') {\n transformedChunk = withToolPayloadTransformMetadata(\n transformedChunk as any,\n await transformToolPayloadForTargets(\n {\n phase: 'input-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n ),\n ) as TChunk;\n transform = await transformToolPayloadForTargets(\n {\n phase: 'error',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n error: (payload as { error?: unknown }).error,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n );\n } else {\n return chunk;\n }\n\n return withToolPayloadTransformMetadata(transformedChunk as any, transform) as TChunk;\n}\n","import type { ToolSet } from '@internal/ai-sdk-v5';\nimport { resolveModelConfig } from '../../../llm/model/resolve-model';\nimport type { MastraLanguageModel } from '../../../llm/model/shared.types';\nimport type { StreamInternal } from '../../../loop/types';\nimport type { Mastra } from '../../../mastra';\nimport type { MastraMemory } from '../../../memory/memory';\nimport type {\n ProcessorState,\n ErrorProcessorOrWorkflow,\n InputProcessorOrWorkflow,\n OutputProcessorOrWorkflow,\n} from '../../../processors';\nimport { RequestContext } from '../../../request-context';\nimport { getNeedsApprovalFn } from '../../../tools/toolchecks';\nimport type { CoreTool, RequireToolApproval, ToolApprovalContext } from '../../../tools/types';\nimport type { Workspace } from '../../../workspace';\nimport { MessageList } from '../../message-list';\nimport { SaveQueueManager } from '../../save-queue';\nimport { globalRunRegistry } from '../run-registry';\nimport type {\n RunRegistryEntry,\n SerializableDurableState,\n SerializableDurableOptions,\n SerializableModelConfig,\n SerializableModelListEntry,\n SerializableToolMetadata,\n DurableAgenticWorkflowInput,\n RegistryModelListEntry,\n} from '../types';\n\n/**\n * Runtime dependencies that need to be resolved at step execution time.\n * These cannot be serialized and must be recreated from available context.\n */\nexport interface ResolvedRuntimeDependencies {\n /** Reconstructed _internal object for compatibility with existing code */\n _internal: StreamInternal;\n /** Resolved tools with execute functions */\n tools: Record<string, CoreTool>;\n /** Resolved language model */\n model: MastraLanguageModel;\n /** Resolved model list for fallback support (actual model instances) */\n modelList?: RegistryModelListEntry[];\n /** Deserialized MessageList */\n messageList: MessageList;\n /** Memory instance (if available) */\n memory?: MastraMemory;\n /** SaveQueueManager for message persistence */\n saveQueueManager?: SaveQueueManager;\n /** Workspace for file/sandbox operations */\n workspace?: Workspace;\n /** Resolved input processors (rebuilt from the agent when the registry is empty) */\n inputProcessors?: InputProcessorOrWorkflow[];\n /** Uncombined input processors for processLLMRequest */\n llmRequestInputProcessors?: InputProcessorOrWorkflow[];\n /** Resolved output processors */\n outputProcessors?: OutputProcessorOrWorkflow[];\n /** Resolved error processors */\n errorProcessors?: ErrorProcessorOrWorkflow[];\n /** Processor state map */\n processorStates?: Map<string, ProcessorState>;\n}\n\n/**\n * Build a SaveQueueManager for a run's memory, or `undefined` when no memory\n * is configured. Shared by `resolveRuntimeDependencies` and\n * `rebuildRunToolsFromMastra` so the construction lives in one place.\n */\nfunction makeSaveQueueManager(memory: MastraMemory | undefined, mastra?: Mastra): SaveQueueManager | undefined {\n if (!memory) return undefined;\n return new SaveQueueManager({ logger: mastra?.getLogger?.(), memory });\n}\n\n/**\n * Options for resolving runtime dependencies\n */\nexport interface ResolveRuntimeOptions {\n /** Mastra instance for accessing services */\n mastra?: Mastra;\n /** Run identifier */\n runId: string;\n /** Agent identifier */\n agentId: string;\n /** Workflow input containing serialized state */\n input: DurableAgenticWorkflowInput;\n /** Logger for debugging */\n logger?: { debug?: (...args: any[]) => void; error?: (...args: any[]) => void };\n}\n\n/**\n * Restore a RequestContext from the JSON-safe `requestContextEntries`\n * snapshot serialized onto the workflow input (see preparation.ts). Returns\n * an empty context when no snapshot is present.\n */\nfunction restoreRequestContext(entries?: Record<string, unknown>): RequestContext {\n return entries\n ? new RequestContext(Object.entries(entries) as Iterable<readonly [string, unknown]>)\n : new RequestContext();\n}\n\n/**\n * Thrown when the per-request processor pipeline cannot be rebuilt during\n * cross-process rehydration. Propagated (not swallowed) because continuing\n * without the rebuilt processors would silently drop skills / workspace\n * instructions — the exact failure mode this rebuild exists to fix.\n */\nexport class DurableProcessorRebuildError extends Error {\n constructor(agentId: string, cause: unknown) {\n super(\n `[DurableAgent:${agentId}] Failed to rebuild processor pipeline during cross-process rehydration: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n this.name = 'DurableProcessorRebuildError';\n this.cause = cause;\n }\n}\n\n/**\n * Resolve all runtime dependencies needed for durable step execution.\n *\n * This function reconstructs the non-serializable state needed to execute\n * agent steps from:\n * 1. The Mastra instance (for agent lookup, tools, model)\n * 2. The serialized workflow input (for MessageList, state)\n *\n * Unlike the registry-based approach, this reconstructs tools and model\n * from the agent registered with Mastra, making it truly durable across\n * process restarts.\n */\nexport async function resolveRuntimeDependencies(options: ResolveRuntimeOptions): Promise<ResolvedRuntimeDependencies> {\n const { mastra, runId, agentId, input, logger } = options;\n\n // 1. Deserialize MessageList\n // Reuse the existing MessageList from the registry if available so that\n // external consumers (e.g. the stream adapter) that hold a reference to it\n // see the updated state. Creating a new instance each iteration would\n // orphan those references (their newResponseMessages Set would point at\n // stale objects).\n const existingEntry = globalRunRegistry.get(runId);\n const messageList = existingEntry?.messageList\n ? existingEntry.messageList.deserialize(input.messageListState)\n : new MessageList({\n threadId: input.state.threadId,\n resourceId: input.state.resourceId,\n }).deserialize(input.messageListState);\n\n // 2. Check global registry first (for local/test execution).\n // This is necessary because workflow steps don't have direct access to\n // DurableAgent's registry.\n //\n // On a cross-process engine (e.g. the @mastra/inngest connect() worker) the\n // durable steps run in a DIFFERENT process than the one that prepared the run,\n // so this process's registry has either no entry or a minimal placeholder\n // (see @mastra/inngest resume(): `{ isPlaceholder: true, tools: {}, model:\n // undefined }`). In that case we MUST rebuild tools / processors / model from\n // the agent registered on the Mastra instance — otherwise per-request closure\n // tools (workspace/skill tools) and per-request processors (SkillsProcessor,\n // WorkspaceInstructions) silently drop cross-process.\n //\n // IMPORTANT: an empty `tools` map is NOT a placeholder signal — agents with\n // zero tools legitimately register `{ tools: {} }` in-process. Placeholders\n // are detected by the explicit `isPlaceholder` flag or by the absence of a\n // real model instance (every in-process seeding site stores the live model;\n // placeholders and metadata-only stubs do not).\n const globalEntry = globalRunRegistry.get(runId);\n const registryModel = globalEntry?.model as (MastraLanguageModel & { __metadataOnly?: boolean }) | undefined;\n const hasHydratedEntry =\n !!globalEntry && globalEntry.isPlaceholder !== true && !!registryModel && registryModel.__metadataOnly !== true;\n let tools: Record<string, CoreTool> = globalEntry?.tools ?? {};\n let model: MastraLanguageModel = globalEntry?.model as MastraLanguageModel;\n let modelList: RegistryModelListEntry[] | undefined = globalEntry?.modelList;\n let workspace: Workspace | undefined = globalEntry?.workspace;\n let memory: MastraMemory | undefined = globalEntry?.memory;\n let inputProcessors: InputProcessorOrWorkflow[] | undefined = globalEntry?.inputProcessors;\n let llmRequestInputProcessors: InputProcessorOrWorkflow[] | undefined = globalEntry?.llmRequestInputProcessors;\n let outputProcessors: OutputProcessorOrWorkflow[] | undefined = globalEntry?.outputProcessors;\n let errorProcessors: ErrorProcessorOrWorkflow[] | undefined = globalEntry?.errorProcessors;\n let processorStates: Map<string, ProcessorState> | undefined = globalEntry?.processorStates;\n let rehydratedFromMastra = false;\n\n // If the registry entry is a real (non-placeholder) in-process entry we\n // trust it wholesale (in-process / same-process resume). Otherwise fall\n // through and rebuild from the Mastra instance.\n if (hasHydratedEntry) {\n logger?.debug?.(`[DurableAgent:${agentId}] Using model and tools from global registry for run ${runId}`);\n } else if (mastra) {\n try {\n const agent = mastra.getAgentById(agentId);\n\n // Restore the caller's request context from the JSON-safe snapshot on\n // the workflow input (mirrors durable-agent.ts resume handling), so\n // request-scoped tools / workspace / memory / processors resolve with\n // the same configuration as the original call site.\n const resolveRequestContext = restoreRequestContext(input.requestContextEntries);\n\n tools = await agent.getToolsForExecution({\n runId,\n threadId: input.state.threadId,\n resourceId: input.state.resourceId,\n requestContext: resolveRequestContext,\n memoryConfig: input.state.memoryConfig,\n autoResumeSuspendedTools: input.options?.autoResumeSuspendedTools,\n });\n\n model =\n (await (agent as any).getModel?.({ requestContext: resolveRequestContext })) ??\n resolveModel(input.modelConfig, mastra);\n\n const rawModelList = await (agent as any).getModelList?.(resolveRequestContext);\n if (rawModelList && Array.isArray(rawModelList)) {\n modelList = rawModelList.map((entry: any) => ({\n id: entry.id,\n model: entry.model,\n maxRetries: entry.maxRetries ?? 0,\n enabled: entry.enabled ?? true,\n headers: entry.headers,\n }));\n }\n\n memory = await (agent as any).getMemory?.({ requestContext: resolveRequestContext });\n workspace = await (agent as any).getWorkspace?.({ requestContext: resolveRequestContext });\n\n // Rebuild the per-request processor pipeline. `listInputProcessors` /\n // `listOutputProcessors` already inject the SkillsProcessor and\n // WorkspaceInstructionsProcessor (see Agent.listInputProcessors), so this\n // restores the missing available-skills list + workspace instructions in\n // the cross-process system prompt. Mirrors preparation.ts.\n try {\n inputProcessors = await (agent as any).listInputProcessors?.(resolveRequestContext);\n llmRequestInputProcessors = await (agent as any).__listLLMRequestProcessors?.(resolveRequestContext);\n outputProcessors = await (agent as any).listOutputProcessors?.(resolveRequestContext);\n errorProcessors = await (agent as any).listErrorProcessors?.(resolveRequestContext);\n // A fresh processor-state map is correct here: on a cross-process worker\n // there is no prior state to carry, and processors are re-run per step.\n processorStates = globalEntry?.processorStates ?? new Map<string, ProcessorState>();\n } catch (processorError) {\n // Fail the step loudly rather than continuing (and writing back) an\n // incomplete pipeline: running without the rebuilt processors would\n // silently drop skills / workspace instructions.\n logger?.error?.(`[DurableAgent:${agentId}] Failed to rebuild processors from Mastra: ${processorError}`);\n throw new DurableProcessorRebuildError(agentId, processorError);\n }\n\n rehydratedFromMastra = true;\n } catch (error) {\n if (error instanceof DurableProcessorRebuildError) throw error;\n logger?.debug?.(`[DurableAgent:${agentId}] Failed to get agent from Mastra: ${error}`);\n model = resolveModel(input.modelConfig, mastra);\n }\n } else {\n logger?.debug?.(`[DurableAgent:${agentId}] No Mastra instance available, using fallback model`);\n model = resolveModel(input.modelConfig);\n }\n\n if (Object.keys(tools).length === 0) {\n logger?.debug?.(`[DurableAgent:${agentId}] No tools resolved for run ${runId}`);\n }\n\n // Write the rebuilt state back into the per-process registry so sibling\n // durable steps in THIS process (e.g. the tool-call step that runs after the\n // LLM step on the same worker) reuse it instead of rebuilding per call. Only\n // persist when we actually rehydrated from Mastra — never clobber a fully\n // populated in-process entry.\n if (rehydratedFromMastra) {\n const rebuilt: Partial<RunRegistryEntry> = {\n // The entry now carries real runtime state — drop the placeholder mark\n // so sibling steps in this process trust it instead of rebuilding.\n isPlaceholder: false,\n tools,\n model,\n modelList,\n workspace,\n memory,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n };\n if (globalEntry) {\n Object.assign(globalEntry, rebuilt);\n } else {\n globalRunRegistry.set(runId, rebuilt as RunRegistryEntry);\n }\n }\n\n // 3. Get or create SaveQueueManager\n const saveQueueManager = makeSaveQueueManager(memory, mastra);\n\n // 4. Reconstruct _internal for compatibility with existing code\n const _internal = resolveInternalState({\n state: input.state,\n memory,\n saveQueueManager,\n tools,\n });\n\n return {\n _internal,\n tools,\n model,\n modelList,\n messageList,\n memory,\n saveQueueManager,\n workspace,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n };\n}\n\n/**\n * Tool + workspace state rebuilt for the durable tool-call step.\n */\nexport interface RebuiltRunTools {\n tools: Record<string, CoreTool>;\n workspace?: Workspace;\n memory?: MastraMemory;\n saveQueueManager?: SaveQueueManager;\n}\n\n/**\n * Rebuild the run's tools (and workspace/memory) from the agent registered on\n * the Mastra instance, then write them back into the per-process run registry.\n *\n * The durable tool-call step runs as a SEPARATE step from the LLM-execution\n * step and, on a cross-process engine (e.g. the @mastra/inngest connect()\n * worker), can execute in a different process than the one that prepared the\n * run. In that process `globalRunRegistry.get(runId)` is empty (or a minimal\n * placeholder), so per-request closure tools (workspace/skill tools:\n * `skill`, `skill_read`, `skill_search`, `mastra_workspace_*`) are absent and\n * the model's tool call rejects with `ToolNotFoundError`.\n *\n * The LLM step already rebuilds the full toolset via\n * `resolveRuntimeDependencies` → `getToolsForExecution`; this helper gives the\n * tool-call step the same rebuild so tool resolution is symmetric cross-process.\n * The writeback means the first unresolved tool call rebuilds once and later\n * calls in the same process hit the registry.\n *\n * Returns `undefined` when no Mastra instance is available or the agent can't\n * be resolved — callers fall back to their existing `ToolNotFoundError`.\n */\nexport async function rebuildRunToolsFromMastra(options: {\n mastra?: Mastra;\n runId: string;\n agentId: string;\n state: SerializableDurableState;\n options?: SerializableDurableOptions;\n /** JSON-safe request-context snapshot from the workflow input (see preparation.ts). */\n requestContextEntries?: Record<string, unknown>;\n logger?: { debug?: (...args: any[]) => void };\n}): Promise<RebuiltRunTools | undefined> {\n const { mastra, runId, agentId, state, options: execOptions, requestContextEntries, logger } = options;\n if (!mastra) return undefined;\n\n try {\n const agent = mastra.getAgentById(agentId);\n // Restore the caller's request context so request-scoped tools, workspace\n // and memory resolve with the same configuration as the original call.\n const resolveRequestContext = restoreRequestContext(requestContextEntries);\n\n const tools = await agent.getToolsForExecution({\n runId,\n threadId: state.threadId,\n resourceId: state.resourceId,\n requestContext: resolveRequestContext,\n memoryConfig: state.memoryConfig,\n autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,\n });\n\n const memory = await (agent as any).getMemory?.({ requestContext: resolveRequestContext });\n const workspace = await (agent as any).getWorkspace?.({ requestContext: resolveRequestContext });\n const saveQueueManager = makeSaveQueueManager(memory, mastra);\n\n // Write back so sibling steps in this process reuse the rebuilt tools.\n const existing = globalRunRegistry.get(runId);\n const patch: Partial<RunRegistryEntry> = { tools, workspace, memory, saveQueueManager };\n if (existing) {\n // Only fill fields the entry is missing — never clobber a populated entry.\n if (Object.keys(existing.tools ?? {}).length === 0) existing.tools = tools;\n existing.workspace ??= workspace;\n existing.memory ??= memory;\n existing.saveQueueManager ??= saveQueueManager;\n } else {\n globalRunRegistry.set(runId, patch as RunRegistryEntry);\n }\n\n return { tools, workspace, memory, saveQueueManager };\n } catch (error) {\n logger?.debug?.(`[DurableAgent:${agentId}] Failed to rebuild tools from Mastra for run ${runId}: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Resolve the language model from serialized config.\n *\n * Note: This is a fallback when the model is not in the run registry.\n * The preferred approach is to store the actual model instance in the\n * run registry during preparation and retrieve it via runRegistry.getModel().\n *\n * This fallback returns a metadata-only stub that will fail the\n * isSupportedLanguageModel check with a descriptive error message.\n */\nexport function resolveModel(config: SerializableModelConfig, _mastra?: Mastra): MastraLanguageModel {\n const metadataError = () => {\n throw new Error(\n `Model ${config.provider}/${config.modelId} is a metadata-only stub. ` +\n `The actual model instance should be resolved from the run registry.`,\n );\n };\n\n return {\n provider: config.provider,\n modelId: config.modelId,\n specificationVersion: config.specificationVersion ?? 'v2',\n supportedUrls: {},\n doGenerate: metadataError,\n doStream: metadataError,\n __metadataOnly: true,\n } as MastraLanguageModel;\n}\n\n/**\n * Reconstruct the _internal (StreamInternal) object from available state\n */\nexport function resolveInternalState(options: {\n state: SerializableDurableState;\n memory?: MastraMemory;\n saveQueueManager?: SaveQueueManager;\n tools?: Record<string, CoreTool>;\n}): StreamInternal {\n const { state, memory, saveQueueManager, tools } = options;\n\n return {\n // Functions - create fresh\n now: () => Date.now(),\n generateId: () => crypto.randomUUID(),\n currentDate: () => new Date(),\n\n // Class instances - from resolved state\n saveQueueManager,\n memory,\n\n // Serializable state\n memoryConfig: state.memoryConfig,\n threadId: state.threadId,\n resourceId: state.resourceId,\n threadExists: state.threadExists,\n\n // Tools if provided - cast to ToolSet for compatibility\n // CoreTool and ToolSet are structurally compatible at runtime\n stepTools: tools as ToolSet | undefined,\n };\n}\n\n/**\n * Resolve a single tool by name from Mastra's global tool registry\n */\nexport function resolveTool(toolName: string, mastra?: Mastra): CoreTool | undefined {\n // Get from Mastra's global tool registry\n try {\n return mastra?.getTool?.(toolName as any) as CoreTool | undefined;\n } catch {\n // Tool not found in global registry\n return undefined;\n }\n}\n\n/**\n * Check if a tool requires human approval.\n *\n * Mirrors the non-durable precedence:\n * - Function-form global `requireToolApproval` is evaluated per call with\n * `(toolName, args, ...)`. Throwing defaults to \"require approval\" (safe).\n * - Boolean global / tool-level `requireApproval` seed the decision.\n * - A per-tool `needsApprovalFn` (e.g. skill tools) is authoritative when\n * present and overrides the seed.\n *\n * In durable execution the function form lives on the run registry, not on\n * the serialized workflow input — pass the resolved value from the caller.\n */\nexport async function toolRequiresApproval(\n tool: CoreTool,\n globalRequireApproval?: RequireToolApproval,\n args?: Record<string, unknown>,\n approvalContext?: Partial<ToolApprovalContext> & { toolName: string },\n): Promise<boolean> {\n let globalRequires: boolean;\n if (typeof globalRequireApproval === 'function') {\n try {\n globalRequires = !!(await globalRequireApproval({\n toolName: approvalContext?.toolName ?? '',\n args: args ?? {},\n requestContext: approvalContext?.requestContext,\n workspace: approvalContext?.workspace,\n }));\n } catch {\n // On error, default to requiring approval (safe default).\n globalRequires = true;\n }\n } else {\n globalRequires = !!globalRequireApproval;\n }\n\n let requires = globalRequires || !!(tool as any).requireApproval;\n\n // needsApprovalFn overrides all other flags (e.g., skill tools return false)\n const needsApprovalFn = getNeedsApprovalFn(tool);\n if (needsApprovalFn) {\n try {\n requires = !!(await needsApprovalFn(args ?? {}));\n } catch {\n // On error, default to requiring approval (safe default)\n requires = true;\n }\n }\n\n return requires;\n}\n\n/**\n * Extract tool metadata needed for LLM from resolved tools\n * This is useful when we need to pass tool info to the model\n */\nexport function extractToolsForModel(\n tools: Record<string, CoreTool>,\n _toolsMetadata: SerializableToolMetadata[],\n): Record<string, CoreTool> {\n // Return the tools as-is since they're already in CoreTool format\n // The metadata is just for reference/serialization\n return tools;\n}\n\n/**\n * Resolve a language model from a serialized model config.\n *\n * This is used during durable execution to reconstruct models from\n * serialized configuration. It uses the originalConfig string (e.g., 'openai/gpt-4o')\n * to resolve the model through the standard model resolution pipeline.\n *\n * @param config The serialized model configuration\n * @param mastra Optional Mastra instance for custom gateways\n * @returns Resolved language model\n */\nexport async function resolveModelFromConfig(\n config: SerializableModelConfig,\n mastra?: Mastra,\n): Promise<MastraLanguageModel> {\n const requestContext = new RequestContext();\n\n // Use originalConfig if available (e.g., 'openai/gpt-4o'), otherwise construct from provider/modelId\n const modelConfigString = config.originalConfig ?? `${config.provider}/${config.modelId}`;\n\n if (typeof modelConfigString === 'string') {\n return (await resolveModelConfig(modelConfigString, requestContext, mastra)) as MastraLanguageModel;\n }\n\n // If originalConfig is an object, pass it through\n return (await resolveModelConfig(\n modelConfigString as Parameters<typeof resolveModelConfig>[0],\n requestContext,\n mastra,\n )) as MastraLanguageModel;\n}\n\n/**\n * Resolve a model from a model list entry.\n *\n * @param entry The model list entry with config, maxRetries, enabled\n * @param mastra Optional Mastra instance\n * @returns Resolved language model\n */\nexport async function resolveModelFromListEntry(\n entry: SerializableModelListEntry,\n mastra?: Mastra,\n): Promise<MastraLanguageModel> {\n return resolveModelFromConfig(entry.config, mastra);\n}\n","import type { LanguageModelV2Prompt } from '@ai-sdk/provider-v5';\nimport type { ToolChoice, ToolSet } from '@internal/ai-sdk-v5';\nimport { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { mergeProviderOptions } from '../../../../llm/model/provider-options';\nimport type { SharedProviderOptions } from '../../../../llm/model/shared.types';\nimport { ConsoleLogger } from '../../../../logger';\nimport { applyAutoResumeSystemMessage } from '../../../../loop/shared/auto-resume-system-message';\nimport { buildLlmPromptArgs } from '../../../../loop/shared/build-llm-prompt-args';\nimport { composeStepInput } from '../../../../loop/shared/compose-step-input';\nimport { injectBackgroundTaskPrompt } from '../../../../loop/shared/inject-background-task-prompt';\nimport { buildMemoryHeaders, mergeLlmCallHeaders } from '../../../../loop/shared/merge-llm-call-headers';\nimport { buildMessagesFromChunks } from '../../../../loop/workflows/agentic-execution/build-messages-from-chunks';\nimport type { CollectedChunk } from '../../../../loop/workflows/agentic-execution/build-messages-from-chunks';\nimport type { Mastra } from '../../../../mastra';\nimport type {\n SpanType,\n AIModelGenerationSpan,\n ExportedSpan,\n IModelSpanTracker,\n AnySpan,\n} from '../../../../observability';\nimport { EntityType } from '../../../../observability';\nimport { getStepAvailableToolNames } from '../../../../observability/utils';\nimport type { CachedLLMStepResponse } from '../../../../processors';\nimport { PrepareStepProcessor } from '../../../../processors/processors/prepare-step';\nimport { ProcessorRunner } from '../../../../processors/runner';\nimport { execute } from '../../../../stream/aisdk/v5/execute';\nimport { MastraModelOutput } from '../../../../stream/base/output';\nimport type { ChunkType, TextDeltaPayload, ToolCallPayload } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { findProviderToolByName, inferProviderExecuted } from '../../../../tools/provider-tool-utils';\nimport type { ToolToConvert } from '../../../../tools/tool-builder/builder';\nimport { isMastraTool } from '../../../../tools/toolchecks';\nimport type { CoreTool } from '../../../../tools/types';\nimport { createMastraProxy, makeCoreTool } from '../../../../utils';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { TripWire } from '../../../trip-wire';\nimport { isSupportedLanguageModel } from '../../../utils';\nimport { DurableStepIds } from '../../constants';\nimport { endRunSpansWithError, globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent, emitStepStartEvent } from '../../stream-adapter';\nimport type { DurableAgenticWorkflowInput, DurableLLMStepOutput, DurableToolCallInput } from '../../types';\nimport { applyToolPayloadTransformToChunk } from '../../utils/apply-tool-payload-transform';\nimport { resolveRuntimeDependencies, resolveModelFromListEntry } from '../../utils/resolve-runtime';\n\n/**\n * Input schema for the durable LLM execution step\n */\nconst durableLLMInputSchema = z.object({\n runId: z.string(),\n agentId: z.string(),\n agentName: z.string().optional(),\n messageListState: z.any(), // SerializedMessageListState\n toolsMetadata: z.array(z.any()),\n modelConfig: z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n originalConfig: z.union([z.string(), z.record(z.string(), z.any())]).optional(),\n settings: z.record(z.string(), z.any()).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n }),\n // Model list for fallback support (when agent configured with array of models)\n modelList: z\n .array(\n z.object({\n id: z.string(),\n config: z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n originalConfig: z.union([z.string(), z.record(z.string(), z.any())]).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n }),\n maxRetries: z.number(),\n enabled: z.boolean(),\n }),\n )\n .optional(),\n options: z.any(),\n state: z.any(),\n messageId: z.string(),\n // Agent span data for model span parenting\n agentSpanData: z.any().optional(),\n // Model span data (ONE span for entire agent run, created before workflow)\n modelSpanData: z.any().optional(),\n // Step index for continuation (step: 0, 1, 2, ...)\n stepIndex: z.number().optional(),\n});\n\n/**\n * Output schema for the durable LLM execution step\n */\nconst durableLLMOutputSchema = z.object({\n messageListState: z.any(),\n text: z.string().optional(),\n toolCalls: z.array(\n z.object({\n toolCallId: z.string(),\n toolName: z.string(),\n args: z.record(z.string(), z.any()),\n providerMetadata: z.record(z.string(), z.any()).optional(),\n activeTools: z.array(z.string()).nullable().optional(),\n }),\n ),\n stepResult: z.object({\n reason: z.string(),\n warnings: z.array(z.any()),\n isContinued: z.boolean(),\n totalUsage: z.any().optional(),\n }),\n metadata: z.any(),\n processorRetryCount: z.number().optional(),\n processorRetryFeedback: z.string().optional(),\n state: z.any(),\n // Step index used in this execution (for tracking)\n stepIndex: z.number().optional(),\n // Exported span data forwarded to downstream steps for trace nesting/closing\n modelSpanData: z.any().optional(),\n stepSpanData: z.any().optional(),\n stepFinishPayload: z.any().optional(),\n});\n\n/**\n * Options for creating the durable LLM execution step\n */\nexport interface DurableLLMExecutionStepOptions {\n // No options needed - tools and model are resolved from Mastra at runtime\n}\n\n/**\n * Create a durable LLM execution step.\n *\n * This step:\n * 1. Deserializes the MessageList from workflow input\n * 2. Resolves tools and model from the runtime context\n * 3. Executes the LLM call\n * 4. Emits streaming chunks via pubsub\n * 5. Returns serialized state for the next step\n *\n * The key difference from the non-durable version is that all state\n * flows through the workflow input/output, and non-serializable\n * dependencies are resolved at execution time.\n */\nexport function createDurableLLMExecutionStep(_options?: DurableLLMExecutionStepOptions) {\n return createStep({\n id: DurableStepIds.LLM_EXECUTION,\n inputSchema: durableLLMInputSchema,\n outputSchema: durableLLMOutputSchema,\n execute: async params => {\n const { inputData, mastra, tracingContext, requestContext, abortSignal } = params;\n\n // Access pubsub via symbol\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n\n const typedInput = inputData as DurableAgenticWorkflowInput;\n const { agentId, messageId, options: execOptions } = typedInput;\n const runId = typedInput.runId;\n const logger = mastra?.getLogger?.();\n\n // 1. Resolve runtime dependencies (tools from Mastra)\n const resolved = await resolveRuntimeDependencies({\n mastra: mastra as Mastra,\n runId,\n agentId,\n input: typedInput,\n logger,\n });\n\n const {\n messageList,\n tools,\n model: resolvedModel,\n modelList: resolvedModelList,\n // Processors rebuilt from the agent when the per-process registry was\n // empty (cross-process worker). resolveRuntimeDependencies also writes\n // these back into globalRunRegistry, so `registryEntry?.inputProcessors`\n // below is populated too — these are the direct fallback if the entry is\n // evicted (TTL) or absent, restoring the SkillsProcessor /\n // WorkspaceInstructionsProcessor in the cross-process system prompt.\n inputProcessors: resolvedInputProcessors,\n llmRequestInputProcessors: resolvedLlmRequestInputProcessors,\n outputProcessors: resolvedOutputProcessors,\n } = resolved;\n\n // 1b. Check for abort signal before doing any work. If the signal is\n // already aborted (e.g. pre-aborted before the loop starts), return a\n // clean output so the dowhile predicate sees isContinued: false and\n // stops the loop. The FINISH event will be emitted by the finalization\n // block with stepResult.reason: 'abort' (set by the predicate's abort\n // guard). We intentionally do NOT emit an ABORT event here because\n // that would close the stream before the FINISH event arrives.\n const executionAbortSignalEarly = globalRunRegistry.get(runId)?.abortSignal ?? abortSignal;\n if (executionAbortSignalEarly?.aborted) {\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: {},\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n // 1c. Check for tripwire from processInput (initial input processing).\n // If an input processor called abort() during preparation, the tripwire\n // data is stored on the registry entry. Emit a tripwire chunk and bail\n // immediately — the model must never be called.\n const registryTripwire = globalRunRegistry.get(runId)?.tripwire;\n if (registryTripwire) {\n // Clear it so it doesn't fire again on a subsequent iteration (shouldn't\n // happen since the loop will stop, but belt-and-suspenders).\n const entry = globalRunRegistry.get(runId);\n if (entry) entry.tripwire = undefined;\n\n logger?.warn?.('Input processor tripwire triggered (from preparation)', {\n agent: agentId,\n reason: registryTripwire.reason,\n processorId: registryTripwire.processorId,\n retry: registryTripwire.retry,\n });\n\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n reason: registryTripwire.reason || '',\n retry: registryTripwire.retry,\n metadata: registryTripwire.metadata,\n processorId: registryTripwire.processorId,\n },\n });\n }\n\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings: [],\n isContinued: false,\n },\n metadata: {},\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n // 2. Determine if we have a model list for fallback support\n const hasModelList = typedInput.modelList && typedInput.modelList.length > 0;\n\n // 3. Build the model list - either from explicit list or single model\n // For single model case (no modelList), we use the resolved model directly\n // which supports mock models and directly-provided models\n const modelList = hasModelList\n ? typedInput.modelList!.filter(m => m.enabled)\n : [\n {\n id: `${typedInput.modelConfig.provider}/${typedInput.modelConfig.modelId}`,\n config: typedInput.modelConfig,\n maxRetries: 0,\n enabled: true,\n },\n ];\n\n if (modelList.length === 0) {\n throw new Error('No enabled models available for execution');\n }\n\n // 4. Execute with model fallback - try each model in the list with retries\n let lastError: Error | undefined;\n let processorRetryCount = 0;\n const maxProcessorRetries =\n typedInput.options?.maxProcessorRetries ??\n (globalRunRegistry.get(runId)?.errorProcessors?.length ? 10 : undefined);\n\n for (let modelIndex = 0; modelIndex < modelList.length; modelIndex++) {\n const modelEntry = modelList[modelIndex]!;\n const maxRetries = modelEntry.maxRetries || 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n // Resolve the model - for single model case (no modelList), use resolved model\n // For model list case, try registry first (works with mock models), then config resolution (for Inngest)\n const model = !hasModelList\n ? resolvedModel\n : (resolvedModelList?.find(m => m.id === modelEntry.id)?.model ??\n (await resolveModelFromListEntry(modelEntry, mastra as Mastra)));\n\n // Check if model is supported\n if (!isSupportedLanguageModel(model)) {\n const hint = (model as any).__metadataOnly\n ? ' The model could not be resolved from the run registry or Mastra instance.'\n : '';\n throw new Error(\n `Unsupported model version: ${(model as any).specificationVersion}. Model must implement doStream.${hint}`,\n );\n }\n\n let currentMessageId = messageId;\n\n // 5. Prepare tools - cast through unknown as CoreTool and ToolSet are structurally compatible at runtime\n let currentModel = model;\n let currentTools = tools as unknown as ToolSet;\n let currentToolChoice = execOptions.toolChoice as ToolChoice<ToolSet> | undefined;\n let currentActiveTools = execOptions.activeTools;\n let currentModelSettings: Record<string, unknown> = { ...(execOptions.modelSettings ?? {}) };\n let currentProviderOptions: SharedProviderOptions | undefined = mergeProviderOptions(\n execOptions.providerOptions,\n modelEntry.config.providerOptions,\n ) as SharedProviderOptions | undefined;\n\n // 6. Rebuild MODEL_GENERATION span from passed data\n // For durable execution, ONE model_generation span is created BEFORE the workflow starts\n // and passed through each iteration. This ensures all steps are children of the same span.\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n\n // modelSpanData is threaded through the iteration state (seeded in preparation.ts);\n // after a resume the registry override points steps at the resumed generation.\n const inputModelSpanData = (globalRunRegistry.get(runId)?.resumeModelSpanData ??\n (inputData as any).modelSpanData) as ExportedSpan<SpanType.MODEL_GENERATION> | undefined;\n const modelSpan = inputModelSpanData\n ? (observability?.rebuildSpan(inputModelSpanData) as AIModelGenerationSpan | undefined)\n : undefined;\n\n // Create model span tracker for MODEL_STEP and MODEL_CHUNK spans\n const modelSpanTracker: IModelSpanTracker | undefined = modelSpan?.createTracker();\n\n // Set the step index for continuation (step: 0, 1, 2, ...)\n // This ensures step numbering continues across agentic loop iterations\n const stepIndex = (inputData as any).stepIndex ?? 0;\n modelSpanTracker?.setStepIndex(stepIndex);\n\n // Build structured output for AI SDK if configured. Held in a `let`\n // because `composeStepInput` (driven by input processors / prepareStep)\n // is allowed to replace `structuredOutput` for this iteration.\n const structuredOutputConfig = execOptions.structuredOutput;\n let structuredOutput =\n structuredOutputConfig?.schema && !structuredOutputConfig?.structuringModelConfig\n ? {\n schema: structuredOutputConfig.schema,\n jsonPromptInjection: structuredOutputConfig.jsonPromptInjection,\n }\n : undefined;\n\n const registryEntry = globalRunRegistry.get(runId);\n const executionAbortSignal = registryEntry?.abortSignal ?? abortSignal;\n const baseInputProcessors = registryEntry?.inputProcessors ?? resolvedInputProcessors ?? [];\n // Output processors likewise fall back to the rebuilt list when the\n // per-process registry is empty (cross-process worker).\n const effectiveOutputProcessors = registryEntry?.outputProcessors ?? resolvedOutputProcessors ?? [];\n const stepInputProcessors = registryEntry?.prepareStep\n ? [...baseInputProcessors, new PrepareStepProcessor({ prepareStep: registryEntry.prepareStep })]\n : baseInputProcessors;\n if (stepInputProcessors.length) {\n const inputStepWriter = pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n const runner = new ProcessorRunner({\n inputProcessors: stepInputProcessors,\n outputProcessors: effectiveOutputProcessors,\n errorProcessors: registryEntry?.errorProcessors ?? [],\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry?.processorStates,\n });\n try {\n const processInputStepResult = await runner.runProcessInputStep({\n messageList,\n stepNumber: stepIndex,\n steps: (inputData as any).accumulatedSteps ?? [],\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n requestContext,\n memory: registryEntry?.memory,\n resourceId: typedInput.state?.resourceId,\n threadId: typedInput.state?.threadId,\n model: currentModel,\n messageId: currentMessageId,\n rotateResponseMessageId: () => {\n currentMessageId = crypto.randomUUID();\n return currentMessageId;\n },\n tools: currentTools,\n toolChoice: currentToolChoice,\n providerOptions: currentProviderOptions,\n activeTools: currentActiveTools,\n modelSettings: currentModelSettings,\n structuredOutput: structuredOutput as any,\n retryCount: (inputData as any).processorRetryCount ?? 0,\n abortSignal: executionAbortSignal,\n writer: inputStepWriter,\n });\n const merged = composeStepInput(\n {\n messageId: currentMessageId,\n model: currentModel,\n tools: currentTools,\n toolChoice: currentToolChoice,\n activeTools: currentActiveTools,\n providerOptions: currentProviderOptions,\n modelSettings: currentModelSettings,\n structuredOutput,\n },\n processInputStepResult,\n );\n currentMessageId = merged.messageId;\n currentModel = merged.model as typeof currentModel;\n currentTools = merged.tools as ToolSet;\n currentToolChoice = merged.toolChoice as ToolChoice<ToolSet> | undefined;\n currentActiveTools = merged.activeTools;\n currentProviderOptions = merged.providerOptions;\n currentModelSettings = merged.modelSettings ?? {};\n structuredOutput = merged.structuredOutput;\n\n // Processors (e.g. ToolSearchProcessor) can inject per-step meta-tools\n // like `search_tools` / `load_tool`. In the non-durable Agent the same\n // step that shows these tools to the model also executes them, so a\n // per-step tool map is enough. The DurableAgent instead runs tool calls\n // in a SEPARATE workflow step that resolves tools from the run registry\n // (see tool-call.ts). Without a write-back, those processor-injected\n // tools are missing there and the call fails with ToolNotFoundError\n // (issue #19571).\n //\n // Convert any raw Mastra tools the processor returned into CoreTool form\n // (mirroring the non-durable llm-execution-step) and merge them into the\n // run registry so the durable tool-call step can resolve and execute them.\n if (processInputStepResult.tools) {\n const boundLogger = logger || new ConsoleLogger({ level: 'error' });\n const convertedTools: Record<string, CoreTool> = {};\n for (const [name, tool] of Object.entries(currentTools as Record<string, unknown>)) {\n if (isMastraTool(tool)) {\n convertedTools[name] = makeCoreTool(\n tool as unknown as ToolToConvert,\n {\n name,\n runId,\n threadId: typedInput.state?.threadId,\n resourceId: typedInput.state?.resourceId,\n logger: boundLogger,\n mastra: mastra ? createMastraProxy({ mastra, logger: boundLogger }) : undefined,\n memory: registryEntry?.memory,\n agentName: typedInput.agentName ?? agentId,\n requestContext,\n workspace: registryEntry?.workspace,\n requireApproval: (tool as any).requireApproval,\n backgroundConfig: (tool as any).background,\n // Emit context.writer.write() / .custom() output through pubsub,\n // matching how the durable tool-call step builds its writer.\n outputWriter: pubsub\n ? async (chunk: any) => {\n await emitChunkEvent(pubsub, runId, chunk as ChunkType);\n }\n : undefined,\n },\n undefined,\n execOptions.autoResumeSuspendedTools,\n );\n } else {\n convertedTools[name] = tool as CoreTool;\n }\n }\n currentTools = convertedTools as unknown as ToolSet;\n if (registryEntry) {\n // Store the exact per-step snapshot rather than merging onto the\n // previous step's set. `currentTools` already starts from the full\n // toolset resolved at the top of this step, so a snapshot keeps the\n // static tools while dropping processor-injected tools the current\n // step no longer exposes (e.g. a ToolSearchProcessor entry that hit\n // its TTL). Merging would leave those stale tools executable by the\n // tool-call step even though the model was never shown them.\n registryEntry.tools = convertedTools;\n }\n }\n } catch (error) {\n // Handle TripWire from processInputStep — emit tripwire chunk and\n // bail the step, mirroring the regular agent's buildTripWireBailResponse.\n // Return a bail output with reason: 'tripwire' so the dowhile loop\n // stops gracefully and emits a proper finish event.\n if (error instanceof TripWire) {\n logger?.warn?.('Streaming input processor tripwire triggered', {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n processorId: error.processorId,\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n },\n });\n }\n // Return a bail response instead of throwing — the dowhile\n // predicate will see isContinued: false and stop the loop,\n // then emitFinishEvent will emit reason: 'tripwire'.\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings: [],\n isContinued: false,\n },\n metadata: {\n modelId: currentModel.modelId,\n },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processInputStep processors:', error);\n throw error;\n }\n }\n\n // ── Signal echo & pre-run drain ───────────────────────────────\n // Mirror the non-durable llm-execution-step:\n // 1. Echo initialSignalEchoes (signals that were part of the input\n // messages, e.g. from persisted memory) so the client sees them.\n // 2. Pre-run signals: if this is the first model request of the run\n // (stepIndex === 0), drain signals that were queued before the\n // run made its first request. These must be added to messageList\n // BEFORE inputMessages is materialized so the model sees them.\n if (pubsub) {\n const initialSignalEchoes = registryEntry?.initialSignalEchoes?.splice(0) ?? [];\n for (const initialSignal of initialSignalEchoes) {\n await emitChunkEvent(pubsub, runId, initialSignal.toDataPart() as any);\n }\n\n const isFirstModelRequest = stepIndex === 0;\n if (isFirstModelRequest && registryEntry?.drainPendingSignals) {\n const preRunSignals = registryEntry.drainPendingSignals('pre-run');\n if (preRunSignals.length > 0) {\n currentMessageId = mastra?.generateId?.() ?? crypto.randomUUID();\n }\n for (const preRunSignal of preRunSignals) {\n const signalForTranscript = messageList.addSignal(preRunSignal);\n await emitChunkEvent(pubsub, runId, signalForTranscript.toDataPart() as any);\n }\n }\n }\n\n // `downloadRetries` / `downloadConcurrency` are internal-only on the\n // non-durable path today (not exposed through AgentExecutionOptions),\n // so durable also relies on the MessageList defaults here. If those\n // ever become user-facing they should be plumbed in identically.\n const messageListPromptArgs = await buildLlmPromptArgs({\n model: currentModel,\n });\n const llmPromptForModel =\n currentModel.specificationVersion === 'v4'\n ? messageList.get.all.aiV7.llmPrompt\n : currentModel.specificationVersion === 'v3'\n ? messageList.get.all.aiV6.llmPrompt\n : messageList.get.all.aiV5.llmPrompt;\n let inputMessages = (await llmPromptForModel(messageListPromptArgs)) as LanguageModelV2Prompt;\n\n // Inject the auto-resume directive into the leading system message when\n // there are suspended tools waiting for resumption (parity with the\n // non-durable agentic-execution step).\n inputMessages = applyAutoResumeSystemMessage({\n autoResume: execOptions.autoResumeSuspendedTools,\n inputMessages,\n messages: messageList.get.all.db(),\n });\n\n // Tell the model about background-task capabilities when a\n // background-task manager is wired in. Mirrors the non-durable\n // agentic-execution step so background-enabled tools surface the\n // same `_background` guidance to the LLM.\n inputMessages = injectBackgroundTaskPrompt({\n inputMessages,\n backgroundTaskManager: registryEntry?.backgroundTaskManager,\n tools: currentTools as Record<string, { background?: any; description?: string }> | undefined,\n agentBackgroundConfig: registryEntry?.backgroundTasksConfig,\n });\n\n // Run `processLLMRequest` for any input processors that implement it.\n // This hook lets processors rewrite the outbound prompt transiently\n // without persisting changes back to the message list, or short-circuit\n // the call entirely by returning a cached response.\n // Mirrors loop/workflows/agentic-execution/llm-execution-step.ts.\n //\n // Use `llmRequestInputProcessors` (uncombined) because combined\n // (workflow-wrapped) processors are skipped by\n // `ProcessorRunner.runProcessLLMRequest`. Fall back to\n // `inputProcessors` for backward compatibility.\n let cachedResponse: CachedLLMStepResponse | undefined;\n const allInputProcessors =\n registryEntry?.llmRequestInputProcessors ??\n registryEntry?.inputProcessors ??\n resolvedLlmRequestInputProcessors ??\n resolvedInputProcessors ??\n [];\n // Create a single ProcessorRunner shared between processLLMRequest\n // and processLLMResponse so processor state (e.g. cache keys stashed\n // in the request hook) is available in the response hook.\n const requestStepRunner =\n allInputProcessors.length > 0\n ? new ProcessorRunner({\n inputProcessors: allInputProcessors,\n outputProcessors: [],\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry?.processorStates,\n })\n : undefined;\n const requestStepWriter = pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n if (requestStepRunner) {\n try {\n const requestStepResult = await requestStepRunner.runProcessLLMRequest({\n prompt: inputMessages,\n model: currentModel,\n stepNumber: (inputData as any).accumulatedSteps?.length ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n retryCount: (inputData as any).processorRetryCount ?? 0,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: requestStepWriter,\n abortSignal: executionAbortSignal,\n });\n inputMessages = requestStepResult.prompt;\n cachedResponse = requestStepResult.response;\n } catch (error) {\n if (error instanceof TripWire) {\n logger?.warn?.('Streaming request processor tripwire triggered', {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n // Emit a tripwire chunk and return a bail response so the\n // dowhile loop stops gracefully with reason: 'tripwire'.\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n processorId: error.processorId,\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n },\n });\n }\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings: [],\n isContinued: false,\n },\n metadata: {\n modelId: currentModel.modelId,\n },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processLLMRequest processors:', error);\n throw error;\n }\n }\n\n // Enable defer mode - step-finish won't auto-close the step span\n // This allows us to export the step span and close it later after tool execution\n modelSpanTracker?.setDeferStepClose(true);\n\n // 7. Track state during streaming\n let warnings: any[] = [];\n let request: any = {};\n let rawResponse: any = {};\n const textDeltas: string[] = [];\n const toolCalls: DurableToolCallInput[] = [];\n let finishReason: string = 'stop';\n let usage: any = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n let responseMetadata: any = {};\n\n // ── Client-tool observability + onInputStart / onInputDelta ──\n // Mirrors the regular agent's injectClientToolObservability / endClientToolObservabilitySpan\n // helpers. Creates CLIENT_TOOL_CALL spans for tools executed on the client side and\n // invokes the tool-level onInputStart / onInputDelta callbacks as chunks arrive.\n const clientToolArgsTextByToolCallId = new Map<string, string[]>();\n const clientToolObservabilityByToolCallId = new Map<\n string,\n { carrier: unknown; span: AnySpan; ended: boolean }\n >();\n // Cache resolved tool defs by toolCallId so `tool-call-delta` chunks\n // (which may carry only a toolCallId, no toolName) can still find the\n // tool resolved during the preceding `tool-call-input-streaming-start`.\n const resolvedToolByCallId = new Map<string, CoreTool>();\n const providerToolSpansByToolCallId = new Map<string, { span: AnySpan; ended: boolean }>();\n\n const resolveToolDef = (toolName: string): CoreTool | undefined => {\n const directTool = (currentTools as unknown as Record<string, CoreTool> | undefined)?.[toolName];\n if (directTool) return directTool;\n const registryTool = registryEntry?.tools?.[toolName];\n if (registryTool) return registryTool;\n // Resolve provider tools by model-facing name (e.g. 'web_search' → provider tool with id 'anthropic.web_search').\n // Check both currentTools and registryEntry.tools to match the durable tool-call step's resolution.\n const providerTool = findProviderToolByName(currentTools as any, toolName) as CoreTool | undefined;\n if (providerTool) return providerTool;\n return findProviderToolByName(registryEntry?.tools as any, toolName) as CoreTool | undefined;\n };\n\n const endClientToolObservabilitySpan = (toolCallId: string, args?: unknown): void => {\n const entry = clientToolObservabilityByToolCallId.get(toolCallId);\n if (!entry || entry.ended) {\n clientToolArgsTextByToolCallId.delete(toolCallId);\n return;\n }\n entry.span.end(args !== undefined ? { metadata: { args } } : undefined);\n entry.ended = true;\n clientToolArgsTextByToolCallId.delete(toolCallId);\n };\n\n const parseClientToolArgsFromDeltas = (toolCallId: string): unknown | undefined => {\n const deltas = clientToolArgsTextByToolCallId.get(toolCallId);\n if (!deltas?.length) return undefined;\n const input = deltas.join('');\n if (!input) return undefined;\n try {\n return JSON.parse(input);\n } catch {\n return undefined;\n }\n };\n\n const injectClientToolObservability = ({\n toolCallId,\n toolName,\n args,\n providerExecuted,\n payload,\n }: {\n toolCallId: string;\n toolName: string;\n args?: unknown;\n providerExecuted?: boolean;\n payload: Record<string, unknown> & { observability?: unknown };\n }): { toolDef: CoreTool | undefined } => {\n const toolDef = resolveToolDef(toolName);\n const inferredProviderExecuted = inferProviderExecuted(providerExecuted, toolDef);\n const isClientTool =\n !inferredProviderExecuted && !(toolDef as { execute?: unknown } | undefined)?.execute;\n\n if (!isClientTool || !mastra || !tracingContext?.currentSpan) {\n return { toolDef };\n }\n\n const existingCarrier = clientToolObservabilityByToolCallId.get(toolCallId);\n if (existingCarrier) {\n payload.observability = existingCarrier.carrier;\n if (args !== undefined) {\n endClientToolObservabilitySpan(toolCallId, args);\n }\n return { toolDef };\n }\n\n const proxy = (mastra as Mastra).observability?.getClientObservabilityProxy?.();\n if (!proxy) return { toolDef };\n\n try {\n const parentSpan =\n tracingContext.currentSpan.type === ('agent_run' as string)\n ? tracingContext.currentSpan\n : ((tracingContext.currentSpan as any).findParent?.('agent_run') ?? tracingContext.currentSpan);\n const clientToolSpan = (parentSpan as any).createChildSpan?.({\n type: 'client_tool_call',\n name: `client_tool: '${toolName}'`,\n entityType: EntityType.TOOL,\n entityId: toolName,\n entityName: toolName,\n attributes: {\n toolDescription: (toolDef as { description?: string } | undefined)?.description,\n toolType: 'client-tool',\n },\n ...(args !== undefined ? { input: args } : {}),\n });\n if (clientToolSpan) {\n const carrier = proxy.inject(clientToolSpan);\n const entry = { carrier, span: clientToolSpan as AnySpan, ended: false };\n clientToolObservabilityByToolCallId.set(toolCallId, entry);\n payload.observability = carrier;\n if (args !== undefined) {\n endClientToolObservabilitySpan(toolCallId, args);\n }\n }\n } catch (err) {\n logger?.warn?.('[ClientObservabilityProxy] failed to create CLIENT_TOOL_CALL span', {\n error: err instanceof Error ? err.message : String(err),\n toolName,\n });\n }\n\n return { toolDef };\n };\n\n const injectProviderToolObservability = ({\n toolCallId,\n toolName,\n args,\n providerExecuted,\n }: {\n toolCallId: string;\n toolName: string;\n args?: unknown;\n providerExecuted?: boolean;\n }) => {\n if (!tracingContext?.currentSpan) return;\n\n const toolDef = resolveToolDef(toolName);\n const inferredProviderExecuted = inferProviderExecuted(providerExecuted, toolDef);\n if (!inferredProviderExecuted) return;\n const existingEntry = providerToolSpansByToolCallId.get(toolCallId);\n if (existingEntry) {\n if (args !== undefined && existingEntry.span.input === undefined) {\n (existingEntry.span as any).update?.({ input: args });\n }\n return;\n }\n\n try {\n const parentSpan =\n tracingContext.currentSpan.type === ('agent_run' as string)\n ? tracingContext.currentSpan\n : ((tracingContext.currentSpan as any).findParent?.('agent_run') ?? tracingContext.currentSpan);\n\n const span = (parentSpan as any).createChildSpan?.({\n type: 'provider_tool_call',\n name: `provider_tool: '${toolName}'`,\n entityType: EntityType.TOOL,\n entityId: toolName,\n entityName: toolName,\n attributes: {\n toolType: 'provider-tool',\n toolDescription: (toolDef as { description?: string } | undefined)?.description,\n toolCallId,\n },\n metadata: { toolCallId },\n ...(args !== undefined ? { input: args } : {}),\n });\n\n if (span) {\n providerToolSpansByToolCallId.set(toolCallId, { span: span as AnySpan, ended: false });\n }\n } catch (err) {\n logger?.warn?.('[ProviderToolObservability] failed to create PROVIDER_TOOL_CALL span', {\n error: err instanceof Error ? err.message : String(err),\n toolName,\n });\n }\n };\n\n const cleanupToolObservabilitySpans = () => {\n for (const [toolCallId, entry] of clientToolObservabilityByToolCallId.entries()) {\n if (!entry.ended) {\n const parsedArgs = parseClientToolArgsFromDeltas(toolCallId);\n entry.span.end(parsedArgs !== undefined ? { metadata: { args: parsedArgs } } : undefined);\n entry.ended = true;\n }\n }\n clientToolArgsTextByToolCallId.clear();\n\n for (const [, entry] of providerToolSpansByToolCallId.entries()) {\n if (!entry.ended) {\n entry.span.end();\n entry.ended = true;\n }\n }\n providerToolSpansByToolCallId.clear();\n };\n\n // 8. Start MODEL_STEP span at the beginning of LLM execution\n modelSpanTracker?.startStep();\n\n // Apply post-processor request-side context to MODEL_INFERENCE then\n // open the inference span immediately before the model call so its\n // startTime excludes any input processor work and availableTools /\n // toolChoice reflect per-step mutations. responseFormat tracks the\n // actual structuredOutput payload sent to execute() — which is\n // undefined when structuringModelConfig routes through a separate\n // structuring step instead of asking the model for json_schema.\n modelSpanTracker?.setInferenceContext?.({\n parameters: currentModelSettings as Record<string, unknown> | undefined,\n providerOptions: currentProviderOptions as Record<string, unknown> | undefined,\n availableTools: getStepAvailableToolNames(\n currentTools as Record<string, unknown> | undefined,\n currentActiveTools,\n ),\n toolChoice: currentToolChoice,\n responseFormat: structuredOutput ? 'json_schema' : undefined,\n });\n modelSpanTracker?.startInference?.();\n\n // Collect chunks for post-stream message building (via\n // buildMessagesFromChunks) and for the processLLMResponse hook\n // (pairs with processLLMRequest — lets processors like\n // ResponseCache persist the model's response). Always populated\n // so reasoning/text/tool parts are reconstructed in stream order,\n // including empty reasoning spans that carry providerMetadata\n // (e.g. OpenAI itemId) required by subsequent turns (#19365).\n const collectedChunks: CollectedChunk[] = [];\n\n // 10. Execute LLM call (or replay cached response)\n let modelResult: ReturnType<typeof execute>;\n if (cachedResponse) {\n // Short-circuit: replay cached chunks instead of calling the model.\n // Output processors are skipped on cache hit because the cached\n // chunks already reflect their effects from the original call.\n warnings = cachedResponse.warnings ?? [];\n request = cachedResponse.request ?? {};\n rawResponse = cachedResponse.rawResponse;\n modelSpanTracker?.updateStep?.({\n request: request || {},\n inputMessages,\n warnings: warnings || [],\n messageId: currentMessageId,\n });\n const replayChunks = cachedResponse.chunks;\n modelResult = new ReadableStream({\n start(ctrl) {\n for (const chunk of replayChunks) {\n ctrl.enqueue({\n ...chunk,\n runId,\n from: ChunkFrom.AGENT,\n });\n }\n ctrl.close();\n },\n }) as unknown as ReturnType<typeof execute>;\n } else {\n modelResult = execute({\n runId,\n model: currentModel,\n providerOptions: currentProviderOptions,\n inputMessages,\n tools: currentTools,\n toolChoice: currentToolChoice,\n activeTools: currentActiveTools,\n options: { abortSignal: executionAbortSignal },\n headers: mergeLlmCallHeaders({\n memoryHeaders: buildMemoryHeaders({\n threadId: typedInput.state?.threadId,\n resourceId: typedInput.state?.resourceId,\n }),\n modelConfigHeaders: resolvedModelList?.find(m => m.id === modelEntry.id)?.headers,\n callTimeHeaders:\n registryEntry?.callTimeHeaders || currentModelSettings?.headers\n ? {\n ...(registryEntry?.callTimeHeaders as Record<string, string> | undefined),\n ...(currentModelSettings?.headers as Record<string, string> | undefined),\n }\n : undefined,\n }),\n modelSettings: {\n ...currentModelSettings,\n maxRetries: 0,\n },\n includeRawChunks: execOptions.includeRawChunks,\n methodType: 'stream',\n structuredOutput: structuredOutput as any,\n onResult: ({ warnings: w, request: r, rawResponse: rr }) => {\n warnings = w || [];\n request = r || {};\n rawResponse = rr || {};\n modelSpanTracker?.updateStep?.({ request, inputMessages, warnings, messageId: currentMessageId });\n },\n });\n }\n\n // 10. Create output stream to process chunks\n // Note: We cast through any to handle the web/node ReadableStream type mismatch\n const outputStream = new MastraModelOutput({\n model: {\n modelId: currentModel.modelId,\n provider: currentModel.provider,\n version: currentModel.specificationVersion,\n },\n stream: modelResult as any,\n messageList,\n messageId: currentMessageId,\n options: {\n runId,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n requestContext,\n },\n });\n\n // 11. Process the stream and emit chunks via pubsub.\n // The inner LLM stream emits 'finish' but never 'step-finish' (durable calls\n // `execute` directly). Rewrite 'finish' -> 'step-finish' before the tracker so\n // MODEL_STEP / MODEL_INFERENCE close and the client buffers the step.\n const baseStream = outputStream._getBaseStream();\n const stepBoundaryStream = (baseStream as ReadableStream<any>).pipeThrough(\n new TransformStream<any, any>({\n transform(chunk, controller) {\n if (chunk?.type === 'finish') {\n controller.enqueue({ ...chunk, type: 'step-finish' });\n } else {\n controller.enqueue(chunk);\n }\n },\n }),\n );\n // Wrap with ModelSpanTracker to create/close MODEL_STEP and MODEL_CHUNK spans\n const trackedStream = modelSpanTracker?.wrapStream(stepBoundaryStream) ?? stepBoundaryStream;\n\n let deferredStepFinishChunk: any = null;\n try {\n let stepStartEmitted = false;\n for await (const rawChunk of trackedStream) {\n if (!rawChunk) continue;\n\n // Mirror the regular agent: if the abort signal fired between\n // chunks, stop consuming the stream immediately so we don't\n // send additional data to the client after cancellation.\n if (executionAbortSignal?.aborted) break;\n\n // Emit step-start before the first stream chunk so the\n // ordering matches the regular agent: start → step-start → response-metadata → …\n // onResult has already fired by the time the first chunk arrives,\n // so `request` and `warnings` are populated.\n if (!stepStartEmitted && pubsub) {\n stepStartEmitted = true;\n await emitStepStartEvent(pubsub, runId, {\n stepId: DurableStepIds.LLM_EXECUTION,\n request,\n warnings,\n });\n }\n\n // Enrich tool-related chunks with the in-process payload transform\n // policy (mirrors the non-durable agentic-execution layer). The\n // policy lives on the run registry; serializable `targets` shadow\n // travels with the workflow input. No-op for non-tool chunks or\n // when no policy is configured for this run.\n //\n // IMPORTANT: the transformed chunk is only used for client-facing\n // emission. Internal tool-call state (args persisted into\n // `toolCalls`, downstream tool execution) MUST be built from the\n // untransformed `rawChunk` so display-layer redactions/rewrites\n // do not leak into actual tool inputs.\n //\n // Use the per-step `currentTools` (post-`prepareStep` and input\n // processors) rather than the registry-level tool list — that way\n // any tool-level `transformToolPayload` added or replaced for the\n // current step is honoured, instead of being silently skipped.\n const transformTools = currentTools as unknown as Record<string, CoreTool> | undefined;\n const clientChunk =\n registryEntry?.toolPayloadTransform || transformTools\n ? await applyToolPayloadTransformToChunk(rawChunk, {\n policy: registryEntry?.toolPayloadTransform,\n tools: transformTools,\n logger: logger as any,\n })\n : rawChunk;\n\n // ── Client-tool observability injection ──\n // For tool-call streaming chunks, inject CLIENT_TOOL_CALL spans\n // and collect deltas so the span can be ended with parsed args.\n //\n // IMPORTANT: inject into `clientChunk.payload` (the published\n // chunk), not `rawChunk.payload`. When a payload transform is\n // active, `clientChunk` is a new object — mutating `rawChunk`\n // would lose the observability carrier on the wire.\n let toolInputStartToolDef: CoreTool | undefined;\n if (rawChunk.type === 'tool-call-input-streaming-start') {\n ({ toolDef: toolInputStartToolDef } = injectClientToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n providerExecuted: rawChunk.payload.providerExecuted,\n payload: (clientChunk as any).payload as Record<string, unknown> & { observability?: unknown },\n }));\n // Cache the resolved tool so subsequent delta chunks (which may\n // carry only toolCallId, no toolName) can still find it.\n if (toolInputStartToolDef) {\n resolvedToolByCallId.set(rawChunk.payload.toolCallId, toolInputStartToolDef);\n }\n injectProviderToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n providerExecuted: rawChunk.payload.providerExecuted,\n });\n } else if (rawChunk.type === 'tool-call-delta') {\n const toolCallId = rawChunk.payload.toolCallId;\n if (toolCallId && rawChunk.payload.argsTextDelta) {\n const deltas = clientToolArgsTextByToolCallId.get(toolCallId) ?? [];\n deltas.push(rawChunk.payload.argsTextDelta);\n clientToolArgsTextByToolCallId.set(toolCallId, deltas);\n }\n } else if (rawChunk.type === 'tool-call-input-streaming-end') {\n const parsedArgs = parseClientToolArgsFromDeltas(rawChunk.payload.toolCallId);\n if (parsedArgs !== undefined) {\n endClientToolObservabilitySpan(rawChunk.payload.toolCallId, parsedArgs);\n }\n } else if (rawChunk.type === 'tool-call') {\n injectClientToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n args: rawChunk.payload.args,\n providerExecuted: rawChunk.payload.providerExecuted,\n payload: (clientChunk as any).payload as Record<string, unknown> & { observability?: unknown },\n });\n injectProviderToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n args: rawChunk.payload.args,\n providerExecuted: rawChunk.payload.providerExecuted,\n });\n }\n\n // Forward every chunk to the client ('finish' was rewritten to 'step-finish' above).\n // Skip 'error' chunks — they are handled internally by the retry/fallback\n // logic and must not be emitted to the client stream. When all models are\n // exhausted the fatal error is propagated via emitError (mirrors the regular\n // agent's deferredErrorChunk pattern).\n //\n // Defer 'step-finish': for intermediate steps (hasToolCalls) we save it\n // on the output so llm-mapping can emit it AFTER tool-result chunks,\n // matching the regular agent's ordering (tool-result → step-finish).\n // For final steps (no tool calls) we emit it after the assistant message\n // is added to messageList.\n if (pubsub && rawChunk.type !== 'error') {\n if (rawChunk.type === 'step-finish') {\n deferredStepFinishChunk = clientChunk;\n } else {\n await emitChunkEvent(pubsub, runId, clientChunk);\n }\n }\n\n // Collect every chunk for post-stream message building and the\n // processLLMResponse hook. Always collect — reasoning parts\n // (including empty spans with providerMetadata carrying\n // OpenAI itemIds) are required to correctly reconstruct the\n // assistant message and preserve pairing with subsequent\n // tool-calls (#19365).\n collectedChunks.push({\n type: rawChunk.type,\n payload: 'payload' in rawChunk ? rawChunk.payload : undefined,\n metadata: (rawChunk as { metadata?: Record<string, unknown> }).metadata,\n });\n\n // Process different chunk types — always from the raw chunk so\n // internal state (tool args, finish reason, usage, metadata) is\n // never affected by display-layer transforms.\n switch (rawChunk.type) {\n case 'text-delta': {\n const payload = rawChunk.payload as TextDeltaPayload;\n textDeltas.push(payload.text);\n break;\n }\n\n case 'tool-call-input-streaming-start': {\n const tool = toolInputStartToolDef || resolveToolDef(rawChunk.payload.toolName);\n if (tool && 'onInputStart' in tool) {\n try {\n // Pass the actual prompt sent to the model (post-processLLMRequest\n // rewrites) instead of rebuilding from messageList, which would\n // drop any transient prompt modifications made by input processors.\n await (tool as any).onInputStart?.({\n toolCallId: rawChunk.payload.toolCallId,\n messages: inputMessages,\n abortSignal: executionAbortSignal,\n });\n } catch (error) {\n logger?.error?.('Error calling onInputStart', error);\n }\n }\n break;\n }\n\n case 'tool-call-delta': {\n // Prefer the cached tool resolved during the preceding start chunk.\n // Fall back to toolName-based resolution for completeness.\n const tool =\n resolvedToolByCallId.get(rawChunk.payload.toolCallId) ??\n (rawChunk.payload.toolName ? resolveToolDef(rawChunk.payload.toolName) : undefined);\n if (tool && 'onInputDelta' in tool) {\n try {\n await (tool as any).onInputDelta?.({\n inputTextDelta: rawChunk.payload.argsTextDelta,\n toolCallId: rawChunk.payload.toolCallId,\n messages: inputMessages,\n abortSignal: executionAbortSignal,\n });\n } catch (error) {\n logger?.error?.('Error calling onInputDelta', error);\n }\n }\n break;\n }\n\n case 'tool-call': {\n const payload = rawChunk.payload as ToolCallPayload;\n toolCalls.push({\n toolCallId: payload.toolCallId,\n toolName: payload.toolName,\n args: payload.args || {},\n providerMetadata: payload.providerMetadata as Record<string, unknown> | undefined,\n providerExecuted: payload.providerExecuted,\n output: payload.output,\n activeTools: currentActiveTools ?? null,\n });\n break;\n }\n\n case 'tool-result': {\n const payload = rawChunk.payload as any;\n // Close PROVIDER_TOOL_CALL span if one was opened for this tool call\n const providerEntry = providerToolSpansByToolCallId.get(payload.toolCallId);\n if (providerEntry && !providerEntry.ended) {\n providerEntry.span.end({\n output: payload.result,\n attributes: { success: !payload.isError },\n });\n providerEntry.ended = true;\n } else if (!providerEntry && tracingContext?.currentSpan) {\n // Deferred result: no span was opened in this step invocation.\n // Only create a synthetic span if this is actually a provider-executed tool.\n const resultToolDef2 = resolveToolDef(payload.toolName);\n const isProviderExec = inferProviderExecuted(payload.providerExecuted, resultToolDef2);\n if (!isProviderExec) break;\n\n let spanInput = payload.args;\n if (spanInput === undefined) {\n // Fallback: find args from the tool-call already stored in messageList\n const allMessages = messageList.get.all.db();\n for (const msg of allMessages) {\n if (!msg.content?.parts) continue;\n for (const part of msg.content.parts) {\n if (\n part.type === 'tool-invocation' &&\n part.toolInvocation?.toolCallId === payload.toolCallId\n ) {\n spanInput = part.toolInvocation.args;\n break;\n }\n }\n if (spanInput !== undefined) break;\n }\n }\n injectProviderToolObservability({\n toolCallId: payload.toolCallId,\n toolName: payload.toolName,\n args: spanInput,\n providerExecuted: true,\n });\n const deferredEntry = providerToolSpansByToolCallId.get(payload.toolCallId);\n if (deferredEntry && !deferredEntry.ended) {\n deferredEntry.span.end({\n output: payload.result,\n attributes: { success: !payload.isError },\n });\n deferredEntry.ended = true;\n }\n }\n break;\n }\n\n case 'step-finish': {\n const payload = rawChunk.payload as any;\n // The terminal chunk (rewritten from 'finish' above) carries finishReason\n // in stepResult.reason and usage in output.usage.\n finishReason = payload.stepResult?.reason || payload.finishReason || 'stop';\n usage = payload.output?.usage || payload.usage || usage;\n break;\n }\n\n case 'response-metadata': {\n const payload = rawChunk.payload as any;\n responseMetadata = {\n id: payload.id,\n timestamp: payload.timestamp,\n modelId: payload.modelId,\n headers: payload.headers,\n };\n break;\n }\n\n case 'error': {\n const payload = rawChunk.payload as any;\n const errorMessage = payload?.error?.message || payload?.message || 'LLM execution error';\n const errorObj = new Error(errorMessage);\n // DON'T emit error event here - we might have fallback models to try\n // Error event will be emitted after all models are exhausted\n throw errorObj;\n }\n }\n }\n // Clean up any unclosed observability spans after successful stream completion\n cleanupToolObservabilitySpans();\n } catch (error) {\n cleanupToolObservabilitySpans();\n logger?.error?.('Error processing LLM stream', { error, runId });\n\n const errorObj = error instanceof Error ? error : new Error(String(error));\n if (modelSpanTracker) {\n modelSpanTracker.reportGenerationError({ error: errorObj });\n } else if (modelSpan) {\n modelSpan.error({ error: errorObj });\n }\n\n // If this error was triggered by abortSignal cancellation, surface an\n // abort event to the client so onAbort callbacks fire and bail out\n // of the entire fallback/retry flow — a confirmed abort should not\n // trigger retries on the same model nor fall through to other\n // models. We deliberately avoid matching on arbitrary error message\n // text (e.g. /abort/i) because that can fire for retryable provider\n // errors whose message happens to mention \"abort\"; we only trust\n // the canonical AbortError name or an actual aborted signal.\n const isAbort = executionAbortSignal?.aborted === true || errorObj.name === 'AbortError';\n if (isAbort) {\n // Return a clean output instead of throwing so the workflow\n // engine doesn't crash. The dowhile predicate will see\n // isContinued: false and stop the loop. The FINISH event\n // (emitted by the finalization block) will carry reason: 'abort'.\n return {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: currentModel.modelId },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n lastError = errorObj;\n\n // Try processAPIError before deciding retry/break\n const registryEntryInner = globalRunRegistry.get(runId);\n const canRetryErrorInner = maxProcessorRetries !== undefined && processorRetryCount < maxProcessorRetries;\n if (registryEntryInner?.errorProcessors?.length && canRetryErrorInner) {\n try {\n const runner = new ProcessorRunner({\n inputProcessors: registryEntryInner.inputProcessors ?? [],\n outputProcessors: registryEntryInner.outputProcessors ?? [],\n errorProcessors: registryEntryInner.errorProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntryInner.processorStates,\n });\n const currentMessageList = new MessageList();\n currentMessageList.deserialize(typedInput.messageListState);\n const { retry } = await runner.runProcessAPIError({\n error: lastError,\n messages: currentMessageList.get.all.db(),\n messageList: currentMessageList,\n stepNumber: (inputData as any).stepIndex ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n retryCount: processorRetryCount,\n requestContext,\n });\n if (retry) {\n processorRetryCount++;\n // Error processor retry should NOT consume a model retry attempt.\n // Decrement attempt so the `for` loop increment restores it.\n attempt--;\n continue;\n }\n } catch (processorError) {\n logger?.debug?.(`processAPIError handler failed: ${processorError}`, { runId });\n }\n }\n\n if (attempt < maxRetries) continue; // retry same model\n break; // exhausted retries, try next model\n }\n\n // Check if the stream captured an error (MastraModelOutput swallows errors internally)\n const streamError = outputStream.error;\n if (streamError) {\n const streamErrorObj = streamError instanceof Error ? streamError : new Error(String(streamError));\n logger?.error?.('Stream captured error', { error: streamErrorObj, runId });\n\n if (modelSpanTracker) {\n modelSpanTracker.reportGenerationError({ error: streamErrorObj });\n } else if (modelSpan) {\n modelSpan.error({ error: streamErrorObj });\n }\n\n // Mirror the iterator catch: a captured stream error that turns out\n // to be a confirmed abort must short-circuit retry/fallback.\n const isStreamErrorAbort = executionAbortSignal?.aborted === true || streamErrorObj.name === 'AbortError';\n if (isStreamErrorAbort) {\n return {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: currentModel.modelId },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n lastError = streamErrorObj;\n if (attempt < maxRetries) continue; // retry same model\n break; // exhausted retries, try next model\n }\n\n // Run `processLLMResponse` for any input processors that implement\n // it. Pairs with `processLLMRequest`: lets a processor write the\n // response to a cache (or sink) using state stashed in the request\n // hook. Skipped on cache hit — that response did not come from the\n // model, so writing it back would just rewrite the same value.\n // Mirrors loop/workflows/agentic-execution/llm-execution-step.ts.\n if (!cachedResponse && requestStepRunner) {\n try {\n await requestStepRunner.runProcessLLMResponse({\n chunks: collectedChunks,\n model: currentModel,\n stepNumber: (inputData as any).accumulatedSteps?.length ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n warnings,\n request,\n rawResponse,\n fromCache: false,\n retryCount: (inputData as any).processorRetryCount ?? 0,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: requestStepWriter,\n abortSignal: executionAbortSignal,\n });\n } catch (error) {\n if (error instanceof TripWire) {\n logger?.warn?.('Streaming response processor tripwire triggered', {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n processorId: error.processorId,\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n },\n });\n }\n return {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings,\n isContinued: false,\n },\n metadata: {\n modelId: currentModel.modelId,\n },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processLLMResponse processors:', error);\n throw error;\n }\n }\n\n // 12. Add assistant response to message list.\n // Build parts from the full chunk sequence via the same helper\n // the regular Agent uses, so reasoning spans (including empty\n // reasoning with providerMetadata.openai.itemId) are preserved\n // alongside text and tool-calls in stream order. Without this\n // OpenAI reasoning models fail on the next turn with\n // \"Item 'fc_...' of type 'function_call' was provided without\n // its required 'reasoning' item\" (#19365).\n //\n // Mirror the regular Agent's buildResponseModelMetadata so the\n // persisted assistant message carries the same content.metadata\n // (modelId/provider): prefer the static model, fall back to the\n // response-metadata chunk.\n const responseModelId = currentModel.modelId ?? responseMetadata?.modelId;\n const responseModelMetadata =\n responseModelId || currentModel.provider\n ? {\n metadata: {\n ...(responseModelId ? { modelId: responseModelId } : {}),\n ...(currentModel.provider ? { provider: currentModel.provider } : {}),\n },\n }\n : undefined;\n const builtMessages = buildMessagesFromChunks({\n chunks: collectedChunks,\n messageId: currentMessageId,\n tools: currentTools,\n responseModelMetadata,\n });\n if (builtMessages.length > 0) {\n for (const msg of builtMessages) {\n messageList.add(msg, 'response');\n }\n\n // Sync the updated messageList to the in-process registry so\n // downstream steps (e.g. tool-call.ts's doFlush()) see the\n // assistant message when persisting before suspension.\n if (registryEntry) {\n registryEntry.messageList = messageList;\n }\n }\n\n // 13. Determine if we should continue (has tool calls)\n const isContinued = toolCalls.length > 0 && finishReason !== 'stop';\n const hasToolCalls = toolCalls.length > 0;\n\n // 13.5. Run processOutputStep for output processors (runs AFTER LLM response, BEFORE tool execution)\n // Mirrors the regular agent's llm-execution-step.ts processOutputStep call\n if (effectiveOutputProcessors.length > 0) {\n const outputStepRunner = new ProcessorRunner({\n inputProcessors: [],\n outputProcessors: effectiveOutputProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry?.processorStates,\n });\n\n const toolCallInfos = toolCalls.map(tc => ({\n toolName: tc.toolName,\n toolCallId: tc.toolCallId,\n args: tc.args,\n }));\n\n const outputStepWriter = pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n\n try {\n await outputStepRunner.runProcessOutputStep({\n steps: (inputData as any).accumulatedSteps ?? [],\n messages: messageList.get.all.db(),\n messageList,\n stepNumber: (inputData as any).accumulatedSteps?.length ?? 0,\n finishReason,\n providerMetadata: responseMetadata,\n toolCalls: toolCallInfos.length > 0 ? toolCallInfos : undefined,\n text: textDeltas.join(''),\n usage,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: outputStepWriter,\n });\n } catch (error) {\n if (error instanceof TripWire) {\n // Emit tripwire chunk and return bail response\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n reason: error.message,\n processorId: error.processorId,\n metadata: error.options?.metadata,\n },\n });\n }\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: currentModel.modelId },\n state: typedInput.state,\n };\n }\n throw error;\n }\n }\n\n // 13.9. step-finish emission strategy:\n //\n // For FINAL steps (no tool calls): emit step-finish now. The assistant\n // message is in messageList and there are no tool-results to wait for.\n //\n // For INTERMEDIATE steps (hasToolCalls): save the step-finish chunk\n // on the output so llm-mapping can emit it AFTER tool-call.ts has\n // emitted tool-result chunks. This matches the regular agent's chunk\n // ordering (tool-result → step-finish) which MastraModelOutput relies\n // on for correct step content reconstruction.\n if (pubsub && deferredStepFinishChunk) {\n if (!hasToolCalls) {\n // Final step: emit immediately with pre-computed content\n // Build step content directly from the current step's data rather\n // than relying on messageList which may contain response messages\n // from previous iterations after deserialization.\n const stepContent: Array<{ type: string; [key: string]: unknown }> = [];\n const currentText = textDeltas.join('');\n if (currentText) {\n stepContent.push({ type: 'text', text: currentText });\n }\n deferredStepFinishChunk = {\n ...deferredStepFinishChunk,\n payload: {\n ...deferredStepFinishChunk.payload,\n _durableStepContent: stepContent,\n },\n };\n await emitChunkEvent(pubsub, runId, deferredStepFinishChunk);\n deferredStepFinishChunk = null;\n }\n // else: intermediate step — saved in output.deferredStepFinishChunk below\n }\n\n // 14. Export spans if there are tool calls (so tools can be children of model_step)\n // Don't end the spans yet - they will be ended after tool execution\n const stepSpanData = hasToolCalls ? modelSpanTracker?.exportCurrentStep() : undefined;\n const stepFinishPayload = hasToolCalls ? modelSpanTracker?.getPendingStepFinishPayload() : undefined;\n\n // 15. Build output\n const output: DurableLLMStepOutput = {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls,\n stepResult: {\n reason: finishReason as any,\n warnings,\n isContinued,\n totalUsage: usage,\n headers: rawResponse?.headers,\n request,\n },\n metadata: {\n id: responseMetadata.id,\n modelId: responseMetadata.modelId || currentModel.modelId,\n timestamp: responseMetadata.timestamp || new Date().toISOString(),\n providerMetadata: responseMetadata,\n headers: rawResponse?.headers,\n request,\n },\n state: typedInput.state,\n // Pass span data so tool calls can be children of model_step\n modelSpanData: hasToolCalls ? modelSpan?.exportSpan?.() : undefined,\n stepSpanData,\n stepFinishPayload,\n // For intermediate steps (hasToolCalls), save the deferred step-finish\n // chunk so llm-mapping can emit it AFTER tool-result chunks.\n deferredStepFinishChunk: hasToolCalls ? deferredStepFinishChunk : undefined,\n };\n\n // 16. End step span only if there are NO tool calls\n // If there are tool calls, step span will be ended after tool execution\n // NOTE: We NEVER 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 if (!hasToolCalls) {\n // Close the step span with usage/finish info\n const pendingPayload = modelSpanTracker?.getPendingStepFinishPayload() as any;\n if (pendingPayload) {\n // End step span using the pending payload\n const stepSpan = modelSpanTracker?.exportCurrentStep();\n if (stepSpan && observability) {\n const rebuiltStepSpan = observability.rebuildSpan(stepSpan);\n rebuiltStepSpan?.end({\n output: {\n text: textDeltas.join(''),\n toolCalls: [],\n },\n attributes: {\n usage: pendingPayload.output?.usage,\n finishReason: pendingPayload.stepResult?.reason,\n isContinued: pendingPayload.stepResult?.isContinued,\n },\n });\n }\n }\n }\n\n // Success - return the output\n return output;\n } catch (error) {\n // TripWire errors from processLLMRequest / processLLMResponse are\n // guardrail/cache processor decisions, not model failures. They\n // must not be retried or fall back to the next model.\n if (error instanceof TripWire) {\n throw error;\n }\n\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Confirmed aborts bypass all retry / fallback / processAPIError\n // handling — the user (or upstream caller) explicitly cancelled the\n // run and we must terminate immediately rather than burning more\n // attempts or paying for fallback model calls. Re-derive the signal\n // from the registry (the inner try-scoped `executionAbortSignal` is\n // out of scope here).\n const outerRegistryEntry = globalRunRegistry.get(runId);\n const outerAbortSignal = outerRegistryEntry?.abortSignal ?? abortSignal;\n const isAbort = outerAbortSignal?.aborted === true || lastError.name === 'AbortError';\n if (isAbort) {\n // Return a clean output instead of throwing so the workflow\n // engine doesn't crash. The abort event was already emitted\n // by the inner catch.\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: modelEntry.config.modelId },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n const modelId = modelEntry.config.modelId;\n logger?.error?.(`Error executing model ${modelId}, attempt ${attempt + 1}/${maxRetries + 1}`, {\n error: lastError,\n runId,\n modelIndex,\n attempt,\n });\n\n // Error processor retry for non-stream errors (e.g. provider\n // rejections that throw before the stream opens). Stream-level\n // errors are already handled in the inner catch above.\n const registryEntry = globalRunRegistry.get(runId);\n const canRetryError = maxProcessorRetries !== undefined && processorRetryCount < maxProcessorRetries;\n if (registryEntry?.errorProcessors?.length && canRetryError) {\n try {\n const runner = new ProcessorRunner({\n inputProcessors: registryEntry.inputProcessors ?? [],\n outputProcessors: registryEntry.outputProcessors ?? [],\n errorProcessors: registryEntry.errorProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry.processorStates,\n });\n const currentMessageList = new MessageList();\n currentMessageList.deserialize(typedInput.messageListState);\n const { retry } = await runner.runProcessAPIError({\n error: lastError,\n messages: currentMessageList.get.all.db(),\n messageList: currentMessageList,\n stepNumber: (inputData as any).stepIndex ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n retryCount: processorRetryCount,\n requestContext,\n tracingContext,\n });\n if (retry) {\n processorRetryCount++;\n // Error processor retry should NOT consume a model retry attempt.\n attempt--;\n continue;\n }\n } catch (processorError) {\n logger?.debug?.(`processAPIError handler failed: ${processorError}`, { runId });\n }\n }\n\n if (attempt >= maxRetries) {\n logger?.debug?.(`Exhausted retries for model ${modelId}, trying next model`, { runId });\n break;\n }\n\n const delayMs = Math.min(1000 * Math.pow(2, attempt), 10000);\n logger?.debug?.(`Retrying model ${modelId} after ${delayMs}ms`, { runId, attempt });\n await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n } // end retry loop\n } // end model loop\n\n // All models exhausted - emit error + step-finish chunks and return a bail response.\n // This mirrors the regular agent which sets stepResult.reason = 'error' and emits\n // a deferred error chunk rather than crashing the loop.\n const fatalError =\n lastError ?? new Error('Exhausted all fallback models and reached the maximum number of retries.');\n\n // End the root spans here too — this is the only error path that covers EventedAgent,\n // whose fire-and-forget launch never sees the failure (so emitError never runs).\n endRunSpansWithError(runId, fatalError);\n\n // Emit the deferred error chunk so consumers see it\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'error',\n runId,\n from: ChunkFrom.AGENT,\n payload: { error: fatalError },\n });\n\n // Emit step-finish so MastraModelOutput resolves finishReason to 'error'\n await emitChunkEvent(pubsub, runId, {\n type: 'step-finish',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n stepResult: {\n reason: 'error',\n isContinued: false,\n },\n output: {\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n },\n metadata: {},\n },\n });\n }\n\n const modelId = modelList[0]?.id ?? 'unknown';\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'error' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId },\n state: typedInput.state,\n };\n },\n });\n}\n","import { z } from 'zod';\nimport { createBackgroundTask } from '../../../../background-tasks/create';\nimport { resolveBackgroundConfig } from '../../../../background-tasks/resolve-config';\nimport type { ToolBackgroundConfig } from '../../../../background-tasks/types';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { Mastra } from '../../../../mastra';\nimport type { MastraMemory } from '../../../../memory/memory';\nimport type { MemoryConfig } from '../../../../memory/types';\nimport type { ExportedSpan, SpanType } from '../../../../observability';\nimport type { ProcessorState } from '../../../../processors';\nimport { ProcessorRunner } from '../../../../processors/runner';\nimport type { ChunkType } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { findProviderToolByName } from '../../../../tools/provider-tool-utils';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport type { SuspendOptions } from '../../../../workflows/step';\nimport { createStep } from '../../../../workflows/workflow';\nimport { stopGoalActivity } from '../../../goal';\nimport type { MessageList } from '../../../message-list';\nimport type { SaveQueueManager } from '../../../save-queue';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitSuspendedEvent, emitChunkEvent } from '../../stream-adapter';\nimport type {\n DurableToolCallInput,\n SerializableDurableOptions,\n AgentSuspendedEventData,\n RunRegistryEntry,\n} from '../../types';\nimport { applyToolPayloadTransformToChunk } from '../../utils/apply-tool-payload-transform';\nimport { rebuildRunToolsFromMastra, resolveTool, toolRequiresApproval } from '../../utils/resolve-runtime';\nimport { serializeError } from '../../utils/serialize-state';\n\n/**\n * Input schema for the durable tool call step.\n * Each tool call flows through this schema when using .foreach()\n */\nconst durableToolCallInputSchema = z.object({\n toolCallId: z.string(),\n toolName: z.string(),\n args: z.record(z.string(), z.any()),\n providerMetadata: z.record(z.string(), z.any()).optional(),\n providerExecuted: z.boolean().optional(),\n output: z.any().optional(),\n activeTools: z.array(z.string()).nullable().optional(),\n // Exported MODEL_STEP span so the TOOL_CALL nests under the LLM call\n stepSpanData: z.any().optional(),\n});\n\n/**\n * Output schema for the durable tool call step\n */\nconst durableToolCallOutputSchema = durableToolCallInputSchema.extend({\n result: z.any().optional(),\n error: z\n .object({\n name: z.string(),\n message: z.string(),\n stack: z.string().optional(),\n })\n .optional(),\n // Approval decision for a `requireApproval` tool. Without this field Zod would strip the\n // approval off the step output, so a declined call would lose its `output-denied` marker.\n approval: z\n .object({\n id: z.string(),\n approved: z.boolean(),\n reason: z.string().optional(),\n })\n .optional(),\n});\n\n/**\n * Flush messages to memory before suspending.\n * Mirrors the base Agent's flushMessagesBeforeSuspension() to ensure\n * the thread exists and all pending messages are persisted.\n */\nasync function flushMessagesBeforeSuspension({\n saveQueueManager,\n messageList,\n memory,\n threadId,\n resourceId,\n memoryConfig,\n threadExists,\n onThreadCreated,\n}: {\n saveQueueManager?: SaveQueueManager;\n messageList?: MessageList;\n memory?: MastraMemory;\n threadId?: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n threadExists?: boolean;\n onThreadCreated?: () => void;\n}) {\n if (!saveQueueManager || !messageList || !threadId) {\n return;\n }\n\n try {\n // Ensure thread exists before flushing messages\n if (memory && !threadExists && resourceId) {\n const thread = await memory.getThreadById?.({ threadId });\n if (!thread) {\n await memory.createThread?.({\n threadId,\n resourceId,\n memoryConfig,\n });\n }\n onThreadCreated?.();\n }\n\n // Flush all pending messages immediately\n await saveQueueManager.flushMessages(messageList, threadId, memoryConfig);\n } catch {\n // Log but don't throw — suspension should proceed even if flush fails\n }\n}\n\n/**\n * Run a tool-result or tool-error chunk through the run's output processor pipeline.\n * Returns the processed chunk (possibly modified), or `null` if a processor blocked it\n * (in which case a tripwire chunk is emitted instead).\n *\n * Mirrors the regular agent's `processAndEnqueueChunk` in llm-mapping-step.ts.\n */\nasync function processChunkThroughOutputProcessors(\n chunk: ChunkType,\n registryEntry: RunRegistryEntry | undefined,\n pubsub: PubSub | undefined,\n runId: string,\n agentName: string,\n logger: any,\n messageList?: MessageList,\n): Promise<ChunkType | null> {\n if (!registryEntry?.outputProcessors?.length || !registryEntry.processorStates) {\n return chunk;\n }\n\n try {\n const runner = new ProcessorRunner({\n inputProcessors: [],\n outputProcessors: registryEntry.outputProcessors,\n logger,\n agentName,\n processorStates: registryEntry.processorStates,\n });\n\n const {\n part: processed,\n blocked,\n reason,\n tripwireOptions,\n processorId,\n } = await runner.processPart(\n chunk,\n registryEntry.processorStates as Map<string, ProcessorState>,\n undefined, // observabilityContext\n registryEntry.requestContext,\n messageList,\n 0,\n pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as ChunkType);\n },\n }\n : undefined,\n );\n\n if (blocked) {\n // Emit a tripwire chunk so downstream knows about the block\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n payload: {\n reason: reason || 'Output processor blocked content',\n retry: tripwireOptions?.retry,\n metadata: tripwireOptions?.metadata,\n processorId,\n },\n } as ChunkType);\n }\n return null;\n }\n\n return (processed as ChunkType) ?? null;\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Output processor error for tool chunk: ${error}`);\n // Fall through: emit the original chunk if processor fails\n return chunk;\n }\n}\n\n/**\n * Create a durable tool call step.\n *\n * This step mirrors the base Agent's createToolCallStep pattern:\n * 1. Resolves the tool from the run registry or Mastra\n * 2. Checks if approval is required (global or per-tool)\n * 3. If approval required, emits suspended event, persists messages, and suspends\n * 4. Executes the tool with a suspend callback for in-execution suspension\n * 5. Emits tool-result or tool-error chunks via PubSub\n * 6. Returns the result or error\n *\n * Tool suspension is handled via workflow suspend/resume mechanism:\n * - Tool approval: step suspends with approval payload\n * - In-execution suspension: tool calls suspend() callback, step suspends with suspension payload\n * - Message persistence: messages are flushed before any suspension\n */\nexport function createDurableToolCallStep() {\n return createStep({\n id: DurableStepIds.TOOL_CALL,\n inputSchema: durableToolCallInputSchema,\n outputSchema: durableToolCallOutputSchema,\n execute: async params => {\n const { inputData, mastra, suspend, resumeData: workflowResumeData, requestContext, actor, getInitData } = params;\n\n // Access pubsub via symbol\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n\n const typedInput = inputData as DurableToolCallInput;\n const { toolCallId, toolName, args: rawArgs, providerExecuted, output, activeTools } = typedInput;\n\n // Extract resumeData from tool call arguments (autoResumeSuspendedTools path)\n // When the LLM auto-resumes a suspended tool, it injects `resumeData` into the\n // tool call arguments. We extract it here to skip re-suspending for approval.\n // Mirrors the regular agent's tool-call-step.ts logic.\n let resumeDataFromArgs: any = undefined;\n let args: any = rawArgs;\n if (typeof rawArgs === 'object' && rawArgs !== null) {\n const { resumeData: resumeDataFromInput, ...argsFromInput } = rawArgs as Record<string, any>;\n args = argsFromInput;\n resumeDataFromArgs = resumeDataFromInput;\n }\n const resumeData = resumeDataFromArgs ?? workflowResumeData;\n\n // Get context from init data (the parent workflow input)\n const initData = getInitData<{\n runId: string;\n agentId: string;\n options: SerializableDurableOptions;\n state: {\n threadId?: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n threadExists?: boolean;\n };\n requestContextEntries?: Record<string, unknown>;\n agentSpanData?: unknown;\n modelSpanData?: unknown;\n }>();\n\n const { runId, options: agentOptions, state } = initData;\n const logger = (mastra as any)?.getLogger?.();\n\n // End the open MODEL_STEP + MODEL_GENERATION + AGENT_RUN as `suspended` before\n // pausing — stores persist only span-end events, so an un-ended root is dropped if\n // the run is never resumed. On resume a fresh root is opened (see DurableAgent.resume).\n const endSpansAsSuspended = (info: { toolCallId?: string; toolName?: string; reason?: string }) => {\n try {\n const obs = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({ requestContext });\n if (!obs) return;\n const output = {\n status: 'suspended' as const,\n reason: info.reason,\n toolName: info.toolName,\n toolCallId: info.toolCallId,\n };\n // After a prior resume, end the resume spans (registry override) — they are the\n // active root for this segment. Otherwise end the threaded originals.\n const reg = globalRunRegistry.get(runId);\n const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;\n const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;\n if (typedInput.stepSpanData) {\n obs.rebuildSpan(typedInput.stepSpanData as ExportedSpan<SpanType.MODEL_STEP>)?.end({ output });\n }\n if (modelSpanData) {\n obs.rebuildSpan(modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION>)?.end({ output });\n }\n if (agentSpanData) {\n obs.rebuildSpan(agentSpanData as ExportedSpan<SpanType.AGENT_RUN>)?.end({ output });\n }\n } catch (error) {\n // Span bookkeeping must never break suspension.\n logger?.warn?.(`[DurableAgent] Failed to end spans on suspend: ${error}`);\n }\n };\n\n // If the tool was already executed by the provider, return the output\n if (providerExecuted && output !== undefined) {\n return {\n ...typedInput,\n result: output,\n };\n }\n\n // 1. Resolve the tool from global registry first, then by provider-tool\n // model-facing name (e.g. `web_search` resolves to `webSearch` when the\n // provider tool advertises the snake-case name), then by id, then fall\n // back to the Mastra-wide tool registry (exact name, provider-tool\n // name, then by id). Mirrors the non-durable tool-call step.\n const registryEntry = globalRunRegistry.get(runId);\n let tool = registryEntry?.tools?.[toolName];\n let mastraTools: Record<string, any> | undefined;\n // Tools rebuilt from the Mastra instance when the per-process registry is\n // empty (cross-process worker). Populated lazily below; reused for\n // workspace/memory resolution further down.\n let rebuiltTools: Record<string, any> | undefined;\n let rebuiltWorkspace: any;\n let rebuiltMemory: any;\n let rebuiltSaveQueueManager: any;\n\n if (!tool) {\n tool = findProviderToolByName(registryEntry?.tools as any, toolName) as typeof tool;\n }\n\n if (!tool) {\n tool = Object.values(registryEntry?.tools ?? {}).find(\n (t: any) => t && typeof t === 'object' && 'id' in t && t.id === toolName,\n ) as typeof tool;\n }\n\n if (!tool) {\n tool = resolveTool(toolName, mastra as Mastra);\n }\n\n if (!tool && mastra) {\n mastraTools = (mastra as Mastra).listTools?.() as Record<string, any> | undefined;\n if (mastraTools) {\n tool = findProviderToolByName(mastraTools as any, toolName) as typeof tool;\n if (!tool) {\n tool = Object.values(mastraTools).find(\n (t: any) => t && typeof t === 'object' && 'id' in t && t.id === toolName,\n ) as typeof tool;\n }\n }\n }\n\n // Cross-process fallback: workspace/skill tools are per-request closures\n // never registered at the Mastra-instance level, so the lookups above miss\n // them when the durable steps run on a separate process (e.g. the\n // @mastra/inngest connect() worker) whose registry is empty. Rebuild the\n // full toolset from the agent — the same rebuild the LLM step already does\n // via resolveRuntimeDependencies — and retry. This is the root-cause fix\n // for `ToolNotFoundError` on skill/mastra_workspace_* tools cross-process.\n if (!tool && mastra) {\n const rebuilt = await rebuildRunToolsFromMastra({\n mastra: mastra as Mastra,\n runId,\n agentId: initData.agentId,\n state: state as any,\n options: agentOptions,\n requestContextEntries: initData.requestContextEntries,\n logger,\n });\n if (rebuilt) {\n rebuiltTools = rebuilt.tools;\n rebuiltWorkspace = rebuilt.workspace;\n rebuiltMemory = rebuilt.memory;\n rebuiltSaveQueueManager = rebuilt.saveQueueManager;\n tool = rebuiltTools[toolName] as typeof tool;\n if (!tool) {\n tool = findProviderToolByName(rebuiltTools as any, toolName) as typeof tool;\n }\n if (!tool) {\n tool = Object.values(rebuiltTools).find(\n (t: any) => t && typeof t === 'object' && 'id' in t && t.id === toolName,\n ) as typeof tool;\n }\n }\n }\n\n // Resolve the key the tool is registered under for activeTools filtering.\n // Prefer the per-run registryEntry key (exact name then identity match),\n // and fall back to the Mastra-wide registry when the tool was resolved\n // there. Without this fallback, a globally-registered tool like\n // `webSearch` invoked by its model-facing name `web_search` would be\n // hidden whenever `activeTools` was set, because the key from\n // registryEntry.tools would be `undefined`.\n const toolKey =\n registryEntry?.tools?.[toolName] || rebuiltTools?.[toolName]\n ? toolName\n : (Object.entries(registryEntry?.tools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0] ??\n Object.entries(rebuiltTools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0] ??\n Object.entries(mastraTools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0]);\n const effectiveActiveTools = activeTools === null ? undefined : (activeTools ?? agentOptions.activeTools);\n const activeToolKey = toolKey ?? toolName;\n const isHiddenByActiveTools = effectiveActiveTools !== undefined && !effectiveActiveTools.includes(activeToolKey);\n\n if (!tool || isHiddenByActiveTools) {\n const availableToolNames = effectiveActiveTools ?? Object.keys(rebuiltTools ?? registryEntry?.tools ?? {});\n const availableToolsStr =\n availableToolNames.length > 0 ? ` Available tools: ${availableToolNames.join(', ')}` : '';\n const error = {\n name: 'ToolNotFoundError',\n message: `Tool \"${toolName}\" not found.${availableToolsStr}. Call tools by their exact name only — never add prefixes, namespaces, or colons.`,\n };\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-error',\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, error },\n });\n }\n return {\n ...typedInput,\n error,\n };\n }\n\n // Get memory-related state for message persistence. Fall back to the\n // values rebuilt from Mastra above (cross-process worker), so workspace\n // tools receive their `workspace` and message flushing still works.\n const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;\n const memory = registryEntry?.memory ?? rebuiltMemory;\n const workspace = registryEntry?.workspace ?? rebuiltWorkspace;\n let threadExists = state?.threadExists ?? false;\n\n // Reconstruct MessageList from workflow state if available\n // Note: In foreach mode, the message list from the registry may be available\n // but for durability, we access what's available through the registry\n let messageList: MessageList | undefined;\n // For local execution, the globalRunRegistry might have an ExtendedRunRegistry entry\n // that stores the messageList. We cast and check safely.\n const extendedEntry = globalRunRegistry.get(runId) as any;\n if (extendedEntry?.messageList) {\n messageList = extendedEntry.messageList;\n }\n\n const doFlush = async () => {\n await flushMessagesBeforeSuspension({\n saveQueueManager,\n messageList,\n memory,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n memoryConfig: state?.memoryConfig,\n threadExists,\n onThreadCreated: () => {\n threadExists = true;\n },\n });\n };\n\n // 2. Check if tool requires approval. Prefer the live policy on the\n // in-process registry (which preserves the function form with real\n // toolName/args); fall back to the JSON-safe boolean shadow on the\n // serialized workflow input for cross-process engines.\n const registryRequireToolApproval = registryEntry?.requireToolApproval;\n const effectiveRequireToolApproval =\n registryRequireToolApproval !== undefined ? registryRequireToolApproval : agentOptions.requireToolApproval;\n const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {\n toolName,\n requestContext: registryEntry?.requestContext\n ? Object.fromEntries(\n [...registryEntry.requestContext.entries()].filter(([key]) => key !== '__mastra_requireToolApproval'),\n )\n : undefined,\n // Use the same rebuilt-workspace fallback as execution (above), so\n // workspace-aware approval policies see their workspace cross-process.\n workspace,\n });\n\n // Add suspended-tool / pending-approval metadata to the last assistant\n // message so `extractSuspendedToolsFromMessages` can detect it on the\n // next turn (autoResumeSuspendedTools) or on page-refresh resume.\n // Mirrors the regular agent's `addToolMetadata()`.\n const addToolMetadata = (opts: {\n type: 'approval' | 'suspension';\n resumeSchema?: string;\n suspendPayload?: unknown;\n }) => {\n if (!messageList) return;\n const metadataKey = opts.type === 'suspension' ? 'suspendedTools' : 'pendingToolApprovals';\n const responseMessages = messageList.get.response.db();\n const lastAssistantMessage = [...responseMessages].reverse().find(msg => msg.role === 'assistant');\n if (!lastAssistantMessage?.content) return;\n\n let metadata: Record<string, any>;\n if (\n typeof lastAssistantMessage.content.metadata === 'object' &&\n lastAssistantMessage.content.metadata !== null\n ) {\n metadata = lastAssistantMessage.content.metadata as Record<string, any>;\n } else {\n metadata = {};\n lastAssistantMessage.content.metadata = metadata;\n }\n metadata[metadataKey] = metadata[metadataKey] || {};\n metadata[metadataKey][toolCallId] = {\n toolCallId,\n toolName,\n args,\n type: opts.type,\n runId,\n ...(opts.type === 'suspension' ? { suspendPayload: opts.suspendPayload } : {}),\n ...(opts.resumeSchema ? { resumeSchema: opts.resumeSchema } : {}),\n };\n };\n\n // Remove suspended-tool / pending-approval metadata from the last\n // assistant message when a tool is being resumed. This mirrors the\n // regular agent's `removeToolMetadata()`.\n const removeToolMetadata = async (type: 'suspension' | 'approval') => {\n if (!messageList) return;\n const metadataKey = type === 'suspension' ? 'suspendedTools' : 'pendingToolApprovals';\n const allMessages = messageList.get.all.db();\n const lastAssistantMessage = [...allMessages].reverse().find(msg => {\n const content = msg.content;\n if (!content) return false;\n const meta =\n typeof content.metadata === 'object' && content.metadata !== null\n ? (content.metadata as Record<string, any>)\n : undefined;\n return (\n !!meta?.[metadataKey]?.[toolCallId] ||\n Object.values(meta?.[metadataKey] ?? {}).some(\n (e: any) => e?.toolCallId === toolCallId || e?.toolName === toolName,\n )\n );\n });\n if (!lastAssistantMessage?.content) return;\n const meta =\n typeof lastAssistantMessage.content.metadata === 'object' && lastAssistantMessage.content.metadata !== null\n ? (lastAssistantMessage.content.metadata as Record<string, any>)\n : undefined;\n if (!meta?.[metadataKey]) return;\n // Resolve key: exact toolCallId, then by entry toolCallId, then by toolName\n const entries = meta[metadataKey] as Record<string, any>;\n const key = entries[toolCallId]\n ? toolCallId\n : (Object.keys(entries).find(k => entries[k]?.toolCallId === toolCallId) ??\n Object.keys(entries).find(k => entries[k]?.toolName === toolName) ??\n (entries[toolName] ? toolName : undefined));\n if (key) {\n delete entries[key];\n if (Object.keys(entries).length === 0) {\n delete meta[metadataKey];\n }\n }\n // Flush to persist the metadata removal\n await doFlush();\n };\n\n if (requiresApproval && !resumeData) {\n const resumeSchema = JSON.stringify({\n type: 'object',\n properties: {\n approved: { type: 'boolean' },\n },\n required: ['approved'],\n });\n\n // Persist active goal time before exposing the approval wait.\n await stopGoalActivity({ agentId: initData.agentId, runId });\n\n // Emit approval chunk via PubSub (mirrors base agent's controller.enqueue)\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-call-approval',\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, resumeSchema },\n });\n }\n\n // Emit suspended event for the stream adapter\n if (pubsub) {\n await emitSuspendedEvent(pubsub, runId, {\n toolCallId,\n toolName,\n args,\n type: 'approval',\n resumeSchema,\n });\n }\n\n // Add approval metadata to message before persisting\n addToolMetadata({ type: 'approval', resumeSchema });\n\n // Flush messages before suspension\n await doFlush();\n\n // End the trace's open spans as suspended before pausing.\n endSpansAsSuspended({ toolCallId, toolName, reason: 'approval' });\n\n // Suspend and wait for approval\n return suspend(\n {\n type: 'approval',\n toolCallId,\n toolName,\n args,\n },\n {\n resumeLabel: toolCallId,\n },\n );\n }\n\n // Check if resuming from approval — only when the tool actually requires\n // approval. Without the `requiresApproval` guard, generic resume data that\n // happens to contain an `approved` field (e.g. from context.agent.suspend())\n // would be misinterpreted as an approval response.\n if (\n requiresApproval &&\n resumeData &&\n typeof resumeData === 'object' &&\n resumeData !== null &&\n 'approved' in resumeData\n ) {\n // Remove approval metadata since we're resuming (either approved or declined)\n await removeToolMetadata('approval');\n\n if (!(resumeData as { approved: boolean }).approved) {\n // Return the approval decision (not a `result` string) so it persists as\n // `state: 'output-denied'` with `approval`. The denial reason carries the\n // existing string so downstream consumers/UI keep the same message.\n return {\n ...typedInput,\n approval: {\n id: toolCallId,\n approved: false,\n reason: 'Tool call was not approved by the user',\n },\n };\n }\n }\n\n // When an approval-gated tool is approved on resume, tag the resolved output with the\n // approval decision so it round-trips through persistence as `approval: { approved: true }`.\n const approvalGrant =\n requiresApproval &&\n resumeData &&\n typeof resumeData === 'object' &&\n resumeData !== null &&\n (resumeData as { approved?: boolean }).approved === true\n ? ({ approval: { id: toolCallId, approved: true as const } } as const)\n : undefined;\n\n // Check if resuming from in-execution suspension\n // Pass resumeData through to the tool so it can continue from where it left off.\n // For approval-gated tools, the approval check above already handled the\n // `approved` field, so the tool executes fresh (not as a \"from-suspension\"\n // resume). For non-approval tools, ANY resume data is forwarded.\n const isResumingFromSuspension =\n resumeData &&\n typeof resumeData === 'object' &&\n resumeData !== null &&\n (requiresApproval ? !('approved' in resumeData) : true);\n\n // Remove suspension metadata when resuming from an in-execution (non-approval-decision) suspension.\n // `isResumingFromSuspension` already excludes the approval-decision case above.\n if (isResumingFromSuspension) {\n await removeToolMetadata('suspension');\n }\n\n // 3. Check for background task execution\n const bgManager = registryEntry?.backgroundTaskManager;\n const bgConfig = registryEntry?.backgroundTasksConfig;\n const toolBgConfig = (tool as any).backgroundConfig as ToolBackgroundConfig | undefined;\n const llmBgOverrides =\n typeof args === 'object' && args !== null && '_background' in args ? (args as any)._background : undefined;\n\n // Strip _background from args before execution (same as non-durable path)\n const cleanedArgs = { ...args };\n if ('_background' in cleanedArgs) {\n delete (cleanedArgs as any)._background;\n }\n\n // Fire onInputAvailable lifecycle hook before execution (matches non-durable path).\n if (tool && 'onInputAvailable' in tool && typeof (tool as any).onInputAvailable === 'function') {\n try {\n await (tool as any).onInputAvailable({\n toolCallId,\n input: cleanedArgs,\n messages: messageList ? messageList.get.input.aiV5.model() : [],\n });\n } catch (hookError) {\n logger?.error?.('Error calling onInputAvailable', hookError);\n }\n }\n\n // Execute the tool\n if (!tool.execute) {\n return {\n ...typedInput,\n result: undefined,\n ...(approvalGrant ?? {}),\n };\n }\n\n // Rebuild the forwarded model_step span and pass it as the tool's tracing context so\n // the TOOL_CALL span nests under the LLM call (matches the non-durable path).\n const observability = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({ requestContext });\n const stepSpan =\n typedInput.stepSpanData && observability\n ? observability.rebuildSpan(typedInput.stepSpanData as ExportedSpan<SpanType.MODEL_STEP>)\n : undefined;\n const toolTracingContext = stepSpan ? { currentSpan: stepSpan } : undefined;\n\n // Track whether the tool's suspend callback was invoked so we can skip\n // emitting a spurious tool-result after tool.execute() returns (the\n // workflow engine's suspend() sets an internal flag but does not throw,\n // so execution continues past the suspend call).\n let wasSuspended = false;\n\n // Forward abort signal from the run registry so tools can observe\n // cancellation (mirrors the non-durable tool-call-step).\n const toolAbortSignal = registryEntry?.abortSignal;\n\n const toolOptions = {\n toolCallId,\n messages: [],\n workspace,\n requestContext,\n tracingContext: toolTracingContext,\n // Use the actor supplied for this workflow segment. A resumed segment\n // must never recover the initial actor from serialized agent options.\n actor,\n resumeData: isResumingFromSuspension ? resumeData : undefined,\n ...(toolAbortSignal ? { abortSignal: toolAbortSignal } : {}),\n // Provide outputWriter so context.writer.write() / context.writer.custom()\n // emit chunks through pubsub (matching the regular agent's tool streaming).\n outputWriter: pubsub\n ? async (chunk: any) => {\n await emitChunkEvent(pubsub, runId, chunk as ChunkType);\n }\n : undefined,\n\n // In-execution suspend callback — allows tools to suspend mid-execution\n suspend: async (suspendPayload: any, suspendOptions?: SuspendOptions) => {\n wasSuspended = true;\n if (suspendOptions?.requireToolApproval) {\n // Tool is requesting approval during execution\n const approvalResumeSchema = JSON.stringify({\n type: 'object',\n properties: {\n approved: { type: 'boolean' },\n },\n required: ['approved'],\n });\n\n await stopGoalActivity({ agentId: initData.agentId, runId });\n\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-call-approval',\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, resumeSchema: approvalResumeSchema },\n });\n }\n\n if (pubsub) {\n await emitSuspendedEvent(pubsub, runId, {\n toolCallId,\n toolName,\n args,\n type: 'approval',\n resumeSchema: approvalResumeSchema,\n });\n }\n\n // Add approval metadata to message before persisting\n addToolMetadata({ type: 'approval', resumeSchema: approvalResumeSchema });\n\n await doFlush();\n\n endSpansAsSuspended({ toolCallId, toolName, reason: 'approval' });\n\n return suspend(\n {\n type: 'approval',\n requireToolApproval: { toolCallId, toolName, args },\n },\n { resumeLabel: toolCallId },\n );\n } else {\n // General tool suspension (e.g., tool calls context.agent.suspend())\n const suspendedEventData: AgentSuspendedEventData = {\n toolCallId,\n toolName,\n args,\n suspendPayload,\n type: 'suspension',\n resumeSchema: suspendOptions?.resumeSchema,\n };\n\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-call-suspended',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId,\n toolName,\n suspendPayload,\n args,\n resumeSchema: suspendOptions?.resumeSchema,\n },\n });\n\n await emitSuspendedEvent(pubsub, runId, suspendedEventData);\n }\n\n // Add suspension metadata to message before persisting\n addToolMetadata({\n type: 'suspension',\n suspendPayload,\n resumeSchema: suspendOptions?.resumeSchema,\n });\n\n await doFlush();\n\n endSpansAsSuspended({ toolCallId, toolName, reason: 'suspension' });\n\n return suspend(\n {\n type: 'suspension',\n toolCallSuspended: suspendPayload,\n toolCallId,\n toolName,\n resumeLabel: suspendOptions?.resumeLabel,\n },\n { resumeLabel: toolCallId },\n );\n }\n },\n };\n\n // Resolve whether to run in background using the shared config resolver\n if (bgManager && !bgConfig?.disabled && typeof cleanedArgs === 'object' && cleanedArgs !== null) {\n const bgResolved = resolveBackgroundConfig({\n llmBgOverrides,\n toolName,\n toolConfig: toolBgConfig,\n agentConfig: bgConfig,\n managerConfig: bgManager.config,\n });\n\n if (bgResolved.runInBackground) {\n try {\n const bgTask = createBackgroundTask(bgManager, {\n toolName,\n toolCallId,\n args: cleanedArgs,\n agentId: initData.agentId,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n runId,\n timeoutMs: bgResolved.timeoutMs,\n maxRetries: bgResolved.maxRetries,\n context: {\n executor: {\n execute: async (taskArgs: any, taskContext: any) => {\n return tool.execute!(taskArgs, {\n ...toolOptions,\n ...(taskContext?.resumeData !== undefined ? { resumeData: taskContext.resumeData } : {}),\n suspend: async (data?: unknown, options?: SuspendOptions) => {\n await toolOptions.suspend?.(data, options);\n return taskContext?.suspend?.(data, options);\n },\n outputWriter: async (chunk: any) => {\n await taskContext?.onProgress?.(chunk);\n return toolOptions.outputWriter?.(chunk);\n },\n });\n },\n },\n onChunk: (chunk: any) => {\n if (!pubsub) return;\n try {\n const bgRunId = chunk.payload.runId;\n // Emit tool-call chunk so UIs can render the invocation inline\n if (bgRunId !== runId || (bgRunId === runId && resumeData)) {\n void emitChunkEvent(pubsub, bgRunId, {\n type: 'tool-call',\n runId: bgRunId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: chunk.payload.toolCallId,\n toolName: chunk.payload.toolName,\n args: cleanedArgs,\n },\n });\n }\n\n if (chunk.type === 'background-task-completed') {\n void emitChunkEvent(pubsub, bgRunId, {\n type: 'tool-result',\n runId: bgRunId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: chunk.payload.toolCallId,\n toolName: chunk.payload.toolName,\n args: cleanedArgs,\n result: chunk.payload.result,\n },\n });\n } else if (chunk.type === 'background-task-failed') {\n void emitChunkEvent(pubsub, bgRunId, {\n type: 'tool-error',\n runId: bgRunId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: chunk.payload.toolCallId,\n toolName: chunk.payload.toolName,\n error: chunk.payload.error,\n args: cleanedArgs,\n },\n });\n }\n } catch {\n // PubSub may be closed — ignore\n }\n },\n\n onResult: async (params: any) => {\n if (!messageList) return;\n\n const result =\n params.status === 'failed'\n ? `Background task failed: ${params.error?.message ?? 'Unknown error'}`\n : params.result;\n\n const updated = messageList.updateToolInvocation(\n {\n type: 'tool-invocation',\n toolInvocation: {\n state: 'result',\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n args: cleanedArgs,\n result,\n // Preserve the approval decision for an approved approval-gated tool that\n // ran in the background so it round-trips on recall, matching the sync path.\n ...(approvalGrant ?? {}),\n },\n },\n {\n mode: 'stream',\n backgroundTasks: {\n [params.toolCallId]: {\n startedAt: params.startedAt,\n completedAt: params.completedAt,\n taskId: params.taskId,\n },\n },\n },\n );\n\n if (!updated) {\n if (params.runId !== runId || (params.runId === runId && resumeData)) {\n messageList.add(\n [\n {\n role: 'tool' as const,\n type: 'tool-call',\n id: crypto.randomUUID(),\n createdAt: new Date(),\n content: [\n {\n type: 'tool-call' as const,\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n args: cleanedArgs,\n },\n ],\n },\n ],\n 'response',\n );\n }\n messageList.add(\n [\n {\n role: 'tool' as const,\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n result,\n isError: params.status === 'failed',\n },\n ],\n },\n ],\n 'response',\n );\n }\n\n if (saveQueueManager && state?.threadId) {\n await saveQueueManager.flushMessages(messageList, state.threadId, state.memoryConfig);\n }\n },\n\n onExecution: async (params: any) => {\n if (!messageList) return;\n\n messageList.updateMessageMetadataByToolCallId(params.toolCallId, {\n mode: 'stream',\n backgroundTasks: {\n [params.toolCallId]: {\n startedAt: params.startedAt,\n suspendedAt: params.suspendedAt,\n taskId: params.taskId,\n },\n },\n });\n\n // Flush to storage so the metadata update (especially suspendedAt)\n // is persisted. Unlike the regular agent which has a single long-lived\n // messageList, the durable agent's workflow state is serialized before\n // this async callback fires, so we must flush directly.\n if (saveQueueManager && state?.threadId) {\n await saveQueueManager.flushMessages(messageList, state.threadId, state.memoryConfig);\n }\n },\n\n onComplete: toolBgConfig?.onComplete ?? bgConfig?.onTaskComplete,\n onFailed: toolBgConfig?.onFailed ?? bgConfig?.onTaskFailed,\n },\n });\n\n // If the agent is resuming this tool call and a previously-suspended\n // bg task exists for this toolCallId+runId, resume the bg task with\n // the agent-resume payload instead of dispatching a fresh one.\n const isSuspendedBgResume =\n isResumingFromSuspension && resumeData && typeof resumeData === 'object' && resumeData !== null;\n if (isSuspendedBgResume) {\n const isSuspended = await bgTask.checkIfSuspended({\n toolCallId,\n runId,\n agentId: initData.agentId,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n toolName,\n });\n if (isSuspended) {\n const task = await bgTask.resume(resumeData);\n return {\n ...typedInput,\n args: cleanedArgs,\n result: `Background task resumed. Task ID: ${task.id}. The tool \"${toolName}\" is running in the background. You will be notified when it completes.`,\n };\n }\n }\n\n const isPreviouslyRunning = await bgTask.checkIfRunning({\n toolCallId,\n runId,\n agentId: initData.agentId,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n toolName,\n });\n\n if (isPreviouslyRunning) {\n const task = await bgTask.restart();\n return {\n ...typedInput,\n args: cleanedArgs,\n result: `Background task restarted. Task ID: ${task.id}. The tool \"${toolName}\" is running in the background. You will be notified when it completes.`,\n };\n }\n\n const { task, fallbackToSync } = await bgTask.dispatch();\n\n if (!fallbackToSync) {\n // Emit background-task-started chunk via PubSub\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'background-task-started' as any,\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n taskId: task.id,\n toolName,\n toolCallId,\n },\n });\n }\n\n // Return placeholder result so the LLM can continue\n return {\n ...typedInput,\n args: cleanedArgs,\n result: `Background task started. Task ID: ${task.id}. The tool \"${toolName}\" is running in the background. You will be notified when it completes.`,\n ...(approvalGrant ?? {}),\n };\n }\n // fallbackToSync: concurrency limit hit, fall through to synchronous execution\n } catch (bgError) {\n logger?.debug?.(\n `[DurableAgent] Background task dispatch failed for ${toolName}, falling back to sync: ${bgError}`,\n );\n }\n }\n }\n\n try {\n const result = await tool.execute(cleanedArgs, toolOptions);\n\n // Fire onOutput lifecycle hook after successful execution (matches non-durable path).\n if (tool && 'onOutput' in tool && typeof (tool as any).onOutput === 'function') {\n try {\n await (tool as any).onOutput({\n toolCallId,\n toolName,\n output: result,\n });\n } catch (hookError) {\n logger?.error?.('Error calling onOutput', hookError);\n }\n }\n\n // Emit tool-result chunk (non-fatal — result is returned regardless).\n // Skip emission when the tool called suspend() — the workflow engine's\n // suspend() sets a flag but does NOT throw, so execution continues past\n // the suspend call and tool.execute() returns undefined. Emitting a\n // tool-result with undefined would produce a spurious entry that\n // confuses downstream consumers (e.g. MastraModelOutput.toolResults).\n if (pubsub && !wasSuspended) {\n try {\n const resultChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-result' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, result },\n },\n {\n policy: registryEntry?.toolPayloadTransform,\n tools: registryEntry?.tools,\n logger: logger as any,\n },\n );\n // Run through output processors (tripwire/blocking/redaction)\n const processed = await processChunkThroughOutputProcessors(\n resultChunk,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n );\n if (processed) {\n await emitChunkEvent(pubsub, runId, processed);\n }\n } catch (emitError) {\n logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);\n }\n }\n\n return {\n ...typedInput,\n result,\n ...(approvalGrant ?? {}),\n };\n } catch (error) {\n // Re-throw FGA authorization errors instead of swallowing them —\n // an authorization denial must fail the run, not be serialized as a\n // recoverable tool error for the LLM to retry (mirrors the\n // non-durable tool-call step).\n if (error instanceof Error && error.name === 'FGADeniedError') {\n throw error;\n }\n const toolError = serializeError(error);\n\n // Emit tool-error chunk (non-fatal — error result is returned regardless)\n if (pubsub && !wasSuspended) {\n try {\n const errorChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-error' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, error: toolError },\n },\n {\n policy: registryEntry?.toolPayloadTransform,\n tools: registryEntry?.tools,\n logger: logger as any,\n },\n );\n // Run through output processors (tripwire/blocking/redaction)\n const processed = await processChunkThroughOutputProcessors(\n errorChunk,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n );\n if (processed) {\n await emitChunkEvent(pubsub, runId, processed);\n }\n } catch (emitError) {\n logger?.warn?.(`[DurableAgent] Failed to emit tool-error chunk for ${toolName}: ${emitError}`);\n }\n }\n\n return {\n ...typedInput,\n error: toolError,\n ...(approvalGrant ?? {}),\n };\n }\n },\n });\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { Mastra } from '../../../../mastra';\nimport { EntityType, SpanType } from '../../../../observability';\nimport type { ExportedSpan } from '../../../../observability';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\nimport type {\n DurableLLMStepOutput,\n DurableToolCallOutput,\n DurableAgenticExecutionOutput,\n SerializableDurableState,\n} from '../../types';\n\n/**\n * Input schema for the durable LLM mapping step.\n * This combines the LLM execution output with tool call results.\n */\nconst durableLLMMappingInputSchema = z.object({\n llmOutput: z.any(), // DurableLLMStepOutput\n toolResults: z.array(z.any()), // DurableToolCallOutput[]\n runId: z.string(),\n agentId: z.string(),\n messageId: z.string(),\n state: z.any(), // SerializableDurableState\n});\n\n/**\n * Output schema for the durable LLM mapping step\n */\nconst durableLLMMappingOutputSchema = z.object({\n messageListState: z.any(),\n messageId: z.string(),\n stepResult: z.any(),\n toolResults: z.array(z.any()),\n output: z.object({\n text: z.string().optional(),\n toolCalls: z.array(z.any()).optional(),\n usage: z.any(),\n steps: z.array(z.any()),\n }),\n state: z.any(),\n delegationBailed: z.boolean().optional(),\n processorRetryCount: z.number().optional(),\n processorRetryFeedback: z.string().optional(),\n});\n\n/**\n * Normalize modelOutput from toModelOutput() into the AI SDK's\n * LanguageModelV2ToolResultOutput shape.\n *\n * The AI SDK's content array only accepts type 'text' or 'media'.\n * Mastra's createTool docs show type 'image-url' as a convenience shorthand,\n * so we normalize that here into type 'media' with the correct structure.\n *\n * Mirrors the normalizeModelOutput in llm-mapping-step.ts (regular agent).\n */\nfunction normalizeModelOutput(output: unknown): unknown {\n if (output == null || typeof output !== 'object') return output;\n\n const obj = output as Record<string, unknown>;\n if (obj.type !== 'content' || !Array.isArray(obj.value)) return output;\n\n return {\n ...obj,\n value: (obj.value as unknown[]).map(item => {\n if (item == null || typeof item !== 'object') return item;\n const part = item as Record<string, unknown>;\n if (part.type === 'image-url' && typeof part.url === 'string') {\n const mediaType =\n typeof part.mediaType === 'string' && part.mediaType\n ? part.mediaType\n : part.url.startsWith('data:')\n ? part.url.slice(5, part.url.indexOf(';')) || 'image/jpeg'\n : 'image/jpeg';\n return { type: 'media', data: part.url, mediaType };\n }\n if (part.type === 'image-data' && typeof part.data === 'string') {\n return { type: 'media', data: part.data, mediaType: part.mediaType ?? 'image/jpeg' };\n }\n if (part.type === 'file-data' && typeof part.data === 'string') {\n return { type: 'media', data: part.data, mediaType: part.mediaType ?? 'application/octet-stream' };\n }\n return part;\n }),\n };\n}\n\n/**\n * Create a durable LLM mapping step.\n *\n * This step:\n * 1. Takes the LLM execution output and tool call results\n * 2. Updates the message list with tool results\n * 3. Combines everything into the final iteration output\n *\n * This is the \"merge\" step that combines parallel tool call results\n * back into a single coherent state.\n */\nexport function createDurableLLMMappingStep() {\n return createStep({\n id: DurableStepIds.LLM_MAPPING,\n inputSchema: durableLLMMappingInputSchema,\n outputSchema: durableLLMMappingOutputSchema,\n execute: async params => {\n const { inputData, mastra, requestContext } = params;\n const {\n llmOutput,\n toolResults,\n runId: _runId,\n agentId: _agentId,\n messageId,\n state,\n } = inputData as {\n llmOutput: DurableLLMStepOutput;\n toolResults: DurableToolCallOutput[];\n runId: string;\n agentId: string;\n messageId: string;\n state: SerializableDurableState;\n };\n\n // 1. Deserialize message list\n const messageList = new MessageList({\n threadId: state.threadId,\n resourceId: state.resourceId,\n });\n messageList.deserialize(llmOutput.messageListState);\n\n // A declined approval has no `result` but is fully resolved: persist it as `output-denied`\n // with the approval decision (rather than as a successful `result`) so it round-trips on\n // recall. Mirrors the non-durable llm-mapping-step.\n const isDeniedApproval = (toolResult: { approval?: { approved?: boolean } }) =>\n toolResult?.approval?.approved === false;\n\n // 2. Add tool results to message list\n // Look up tools from the in-process registry for toModelOutput support\n const registryEntry = globalRunRegistry.get(_runId);\n const registryTools = registryEntry?.tools;\n\n // Rebuild the MODEL_STEP span early so MAPPING child spans can nest under it\n let stepSpan:\n | ReturnType<\n NonNullable<\n ReturnType<NonNullable<NonNullable<Mastra['observability']>['getSelectedInstance']>>\n >['rebuildSpan']\n >\n | undefined;\n if (llmOutput.stepSpanData) {\n try {\n const observability = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({ requestContext });\n stepSpan = observability?.rebuildSpan(llmOutput.stepSpanData as ExportedSpan<SpanType.MODEL_STEP>);\n } catch {\n // Span bookkeeping must never break the merge step.\n }\n }\n\n if (toolResults.length > 0) {\n for (const toolResult of toolResults) {\n if (isDeniedApproval(toolResult)) {\n messageList.updateToolInvocation({\n type: 'tool-invocation' as const,\n toolInvocation: {\n state: 'output-denied' as const,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n args: toolResult.args,\n approval: {\n id: toolResult.approval!.id,\n approved: false,\n reason: toolResult.approval!.reason,\n },\n },\n });\n continue;\n }\n\n const result = toolResult.error ? toolResult.error.message : toolResult.result;\n\n // Compute toModelOutput for successful tool results (Bug 9 parity).\n // Start from the existing providerMetadata so it's preserved even when\n // toModelOutput is absent or fails — otherwise provider-executed tools\n // or tools without a mapper lose their metadata.\n let providerMetadata: Record<string, unknown> | undefined = toolResult.providerMetadata as\n | Record<string, unknown>\n | undefined;\n if (!toolResult.error && toolResult.result != null && !toolResult.providerExecuted) {\n const tool = registryTools?.[toolResult.toolName] as\n | { toModelOutput?: (output: unknown) => unknown }\n | undefined;\n\n if (tool?.toModelOutput) {\n const mappingSpan = stepSpan?.createChildSpan({\n type: SpanType.MAPPING,\n name: `tool output mapping: '${toolResult.toolName}'`,\n entityType: EntityType.TOOL,\n entityId: toolResult.toolName,\n entityName: toolResult.toolName,\n input: toolResult.result,\n attributes: {\n mappingType: 'toModelOutput',\n toolCallId: toolResult.toolCallId,\n },\n });\n try {\n let modelOutput = await tool.toModelOutput(toolResult.result);\n modelOutput = normalizeModelOutput(modelOutput);\n mappingSpan?.end({ output: modelOutput });\n\n const existingMastra = (toolResult.providerMetadata as any)?.mastra;\n providerMetadata = {\n ...toolResult.providerMetadata,\n mastra: { ...existingMastra, modelOutput },\n };\n } catch (err) {\n mappingSpan?.error({ error: err as Error, endSpan: true });\n // toModelOutput errors are non-fatal — the tool result is still usable\n (mastra as Mastra | undefined)\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] toModelOutput failed for tool \"${toolResult.toolName}\": ${err}`);\n }\n }\n }\n\n const updated = messageList.updateToolInvocation({\n type: 'tool-invocation' as const,\n toolInvocation: {\n state: 'result' as const,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n args: toolResult.args,\n result,\n // Preserve the approval decision for an approved approval-gated tool so it\n // round-trips on recall as `approval: { approved: true }`.\n ...(toolResult.approval ? { approval: toolResult.approval } : {}),\n },\n ...(providerMetadata ? { providerMetadata: providerMetadata as any } : {}),\n });\n\n if (!updated) {\n messageList.add(\n [\n {\n role: 'tool' as const,\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n result,\n isError: toolResult.error !== undefined,\n },\n ],\n },\n ],\n 'response',\n );\n }\n }\n }\n\n // 2b. Sync the updated messageList back to the in-process registry.\n // The durable workflow deserializes a fresh MessageList on every step,\n // so updates (output-denied, tool results) are invisible to other\n // steps that read from the registry — in particular tool-call.ts's\n // doFlush() which persists messages before suspension. Without this\n // sync, a declined tool's output-denied state would never reach memory\n // if the workflow re-suspends on a subsequent iteration.\n if (registryEntry) {\n registryEntry.messageList = messageList;\n }\n\n // 3. Determine if we should continue\n // When tool errors occur, always continue the agentic loop so the model\n // can see the error messages (already added to messageList above) and\n // self-correct. This matches the regular agent's behaviour where both\n // ToolNotFoundError and generic tool execution errors are recoverable.\n const hasToolErrors = toolResults.some(r => r.error !== undefined);\n const isContinued = hasToolErrors ? true : llmOutput.stepResult.isContinued;\n\n // Check if any delegation hook called ctx.bail(). The bail flag is\n // communicated via requestContext because Zod output validation strips\n // unknown fields from the tool result. We read it here and propagate\n // it on the serializable output so the dowhile predicate can stop.\n let delegationBailed = false;\n if (requestContext?.get('__mastra_delegationBailed')) {\n delegationBailed = true;\n requestContext.set('__mastra_delegationBailed', false);\n }\n\n // 4. Build the output\n const output: DurableAgenticExecutionOutput = {\n messageListState: messageList.serialize(),\n messageId,\n stepResult: {\n ...llmOutput.stepResult,\n isContinued,\n },\n toolResults,\n output: {\n text: llmOutput.text,\n toolCalls: llmOutput.toolCalls,\n usage: llmOutput.stepResult.totalUsage ?? {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n },\n steps: [], // Steps are accumulated at the loop level\n },\n state: {\n ...state,\n threadExists: state.threadExists,\n },\n processorRetryCount: llmOutput.processorRetryCount,\n processorRetryFeedback: llmOutput.processorRetryFeedback,\n delegationBailed,\n };\n\n // Close the MODEL_STEP span for tool-calling iterations: the LLM step defers it so\n // tool calls can nest under it, and the tools have now run. No-ops without tool calls.\n // The span was already rebuilt earlier so MAPPING child spans could nest under it.\n if (stepSpan) {\n try {\n const pendingPayload = llmOutput.stepFinishPayload as any;\n stepSpan.end({\n output: {\n text: llmOutput.text,\n toolCalls: llmOutput.toolCalls,\n },\n attributes: {\n usage: pendingPayload?.output?.usage,\n finishReason: pendingPayload?.stepResult?.reason,\n isContinued: pendingPayload?.stepResult?.isContinued,\n },\n });\n } catch (error) {\n // Span bookkeeping must never break the merge step.\n (mastra as Mastra | undefined)\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] Failed to close model_step span: ${error}`);\n }\n }\n\n // Emit the deferred step-finish chunk for intermediate steps.\n // llm-execution defers step-finish emission for tool-calling steps so that\n // it arrives AFTER tool-result chunks (emitted by tool-call.ts). This\n // matches the regular agent's chunk ordering which MastraModelOutput\n // relies on for correct step content reconstruction in onStepFinish.\n const deferredChunk = llmOutput.deferredStepFinishChunk as any;\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n if (deferredChunk && pubsub) {\n try {\n // Build step content directly from this iteration's data.\n // We cannot rely on messageList.get.response.aiV5.modelContent(-1)\n // because each durable step deserializes a fresh MessageList, so\n // the MastraModelOutput's reference is stale. Instead, construct\n // the content array from the LLM output (text + tool calls) and\n // the tool results collected in this step.\n const stepContent: unknown[] = [];\n if (llmOutput.text) {\n stepContent.push({ type: 'text', text: llmOutput.text });\n }\n for (const tc of llmOutput.toolCalls ?? []) {\n stepContent.push({\n type: 'tool-call',\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n args: tc.args,\n });\n }\n for (const tr of toolResults ?? []) {\n stepContent.push({\n type: 'tool-result',\n toolCallId: tr.toolCallId,\n toolName: tr.toolName,\n result: tr.error ? tr.error.message : tr.result,\n ...(tr.error ? { isError: true } : {}),\n });\n }\n\n const enrichedChunk = {\n ...deferredChunk,\n payload: {\n ...deferredChunk.payload,\n _durableStepContent: stepContent,\n },\n };\n await emitChunkEvent(pubsub, _runId, enrichedChunk);\n } catch (error) {\n (mastra as Mastra | undefined)\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] Failed to emit deferred step-finish: ${error}`);\n }\n }\n\n return output;\n },\n });\n}\n","import { z } from 'zod';\nimport type { IsTaskCompleteRunResult, MastraDBMessage } from '../../../../agent';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { StreamCompletionContext } from '../../../../loop/network/validation';\nimport { formatStreamCompletionFeedback, runStreamCompletionScorers } from '../../../../loop/network/validation';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableAgentDefaults, DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\n/**\n * Create the durable isTaskComplete step.\n *\n * Mirrors the non-durable `createIsTaskCompleteStep` contract:\n * - Runs after each agentic iteration has settled its tool calls.\n * - Only scores iterations where the LLM has signaled it is done\n * (`lastStepResult.isContinued === false`) so we don't interrupt mid-loop\n * tool execution.\n * - Skips working-memory-only iterations (same heuristic as the non-durable\n * step) — those are bookkeeping, not user-visible task progress.\n * - Pulls the scorer instances + `onComplete` closure from the in-process run\n * registry. They can't survive the wire, so cross-process engines (Inngest\n * after a worker restart) simply skip this step and fall back to\n * `maxSteps` + `stopWhen`.\n * - On a verdict it flips `state.lastStepResult.isContinued` so the outer\n * `dowhile` predicate either stops the loop (passed) or runs one more LLM\n * iteration (not passed). Feedback (when not suppressed) is appended as an\n * assistant message so the next LLM call can see it.\n * - Emits an `is-task-complete` chunk via pubsub so external observers see\n * the verdict and payload exactly like the non-durable path.\n */\nexport function createDurableIsTaskCompleteStep(defaultMaxSteps: number = DurableAgentDefaults.MAX_STEPS) {\n // The step is a pass-through over the IterationState — we mutate\n // `lastStepResult.isContinued` and `messageListState` in place when a\n // verdict requires it. We use `z.any()` instead of the iteration schema to\n // avoid coupling this step to whichever extended schema each workflow uses\n // (core's IterationState extends the base shape with `modelList`).\n return createStep({\n id: DurableStepIds.IS_TASK_COMPLETE,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async params => {\n const { inputData, mastra, getInitData } = params;\n const state = inputData as {\n runId: string;\n iterationCount: number;\n messageListState: any;\n accumulatedSteps: Array<{\n text?: string;\n toolCalls?: Array<{ toolName?: string; args?: unknown }>;\n toolResults?: Array<{ toolName?: string; result?: unknown }>;\n }>;\n lastStepResult?: { isContinued?: boolean };\n options?: { maxSteps?: number };\n backgroundTaskPending?: boolean;\n };\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const initData = getInitData() as {\n agentId?: string;\n agentName?: string;\n state?: { threadId?: string; resourceId?: string };\n requestContextEntries?: Record<string, unknown>;\n };\n\n const registryEntry = globalRunRegistry.get(state.runId);\n const isTaskComplete = registryEntry?.isTaskComplete;\n const hasScorers = !!isTaskComplete?.scorers && isTaskComplete.scorers.length > 0;\n\n // Fast path — nothing to do without a registered policy.\n if (!hasScorers || !isTaskComplete) {\n return state;\n }\n\n // Don't interrupt mid-tool loops. The non-durable step has the same\n // guard via `inputData.stepResult?.isContinued`.\n const llmSignaledDone = state.lastStepResult?.isContinued === false;\n if (!llmSignaledDone) {\n return state;\n }\n\n // The background-task-check step may set backgroundTaskPending=true to\n // force one more LLM iteration after a task settles. Skip scoring in\n // that case so we don't double-score the same outcome.\n if (state.backgroundTaskPending) {\n return state;\n }\n\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n const iterationToolCalls = (lastStep?.toolCalls ?? []) as Array<{\n toolName?: string;\n args?: unknown;\n }>;\n const isWorkingMemoryToolName = (name?: string) =>\n name === 'updateWorkingMemory' || name === 'setWorkingMemory' || name === 'update-working-memory';\n const allWorkingMemory =\n iterationToolCalls.length > 0 && iterationToolCalls.every(tc => isWorkingMemoryToolName(tc.toolName));\n if (allWorkingMemory) {\n return state;\n }\n\n const runMaxSteps = state.options?.maxSteps ?? defaultMaxSteps;\n\n // Rehydrate the message list once so we can read the original task and\n // append feedback after scoring.\n const messageList = new MessageList();\n messageList.deserialize(state.messageListState);\n const userMessages = messageList.get.input.db();\n const firstUserMessage = userMessages[0];\n let originalTask = 'Unknown task';\n if (firstUserMessage) {\n if (typeof firstUserMessage.content === 'string') {\n originalTask = firstUserMessage.content;\n } else if ((firstUserMessage.content as any)?.parts?.[0]?.type === 'text') {\n originalTask = ((firstUserMessage.content as any).parts[0] as { text: string }).text;\n }\n }\n\n const toolResultsForCtx = (lastStep?.toolResults ?? []) as Array<{\n toolName?: string;\n result?: unknown;\n }>;\n\n const ctx: StreamCompletionContext = {\n iteration: state.iterationCount,\n maxIterations: runMaxSteps,\n originalTask,\n currentText: lastStep?.text || '',\n toolCalls: iterationToolCalls.map(tc => ({\n name: tc.toolName || '',\n args: (tc.args as Record<string, unknown>) ?? {},\n })),\n messages: messageList.get.all.db(),\n toolResults: toolResultsForCtx.map(tr => ({\n name: tr.toolName || '',\n result: (tr.result as Record<string, unknown>) ?? {},\n })),\n agentId: initData.agentId || '',\n agentName: initData.agentName || '',\n runId: state.runId,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n customContext: initData.requestContextEntries,\n };\n\n let result: IsTaskCompleteRunResult | undefined;\n try {\n result = await runStreamCompletionScorers(isTaskComplete.scorers!, ctx, {\n strategy: isTaskComplete.strategy,\n parallel: isTaskComplete.parallel,\n timeout: isTaskComplete.timeout,\n });\n } catch (err) {\n mastra?.getLogger?.()?.warn?.(`[DurableAgent] isTaskComplete scoring failed: ${err}`);\n return state;\n }\n\n if (!result) {\n return state;\n }\n\n if (isTaskComplete.onComplete) {\n try {\n await isTaskComplete.onComplete(result);\n } catch (err) {\n mastra?.getLogger?.()?.warn?.(`[DurableAgent] isTaskComplete onComplete callback failed: ${err}`);\n }\n }\n\n const maxIterationReached = runMaxSteps ? state.iterationCount >= runMaxSteps : false;\n\n // Flip isContinued based on the verdict so the outer dowhile predicate\n // continues (not complete) or stops (complete). This is the contract\n // the non-durable createIsTaskCompleteStep uses.\n const nextState: typeof state = { ...state };\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: !result.complete,\n };\n }\n\n // Append the feedback as an assistant message so the next LLM iteration\n // can course-correct. Skipped when the check passes, mirroring the\n // non-durable createIsTaskCompleteStep.\n if (!result.complete) {\n const feedback = formatStreamCompletionFeedback(result, maxIterationReached);\n messageList.add(\n {\n id: mastra?.generateId?.(),\n createdAt: new Date(),\n type: 'text',\n role: 'assistant',\n content: {\n parts: [{ type: 'text', text: feedback }],\n metadata: {\n mode: 'stream',\n completionResult: {\n passed: result.complete,\n suppressFeedback: !!isTaskComplete.suppressFeedback,\n },\n },\n format: 2,\n },\n } as MastraDBMessage,\n 'response',\n );\n }\n nextState.messageListState = messageList.serialize();\n\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'is-task-complete',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n iteration: state.iterationCount,\n passed: result.complete,\n results: result.scorers,\n duration: result.totalDuration,\n timedOut: result.timedOut,\n reason: result.completionReason,\n maxIterationReached,\n suppressFeedback: !!isTaskComplete.suppressFeedback,\n },\n } as any);\n } catch {\n // PubSub may be closed — fall through.\n }\n }\n\n return nextState;\n },\n });\n}\n","import { z } from 'zod';\nimport type { MastraScorer } from '../../../../evals';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { resolveModelConfig } from '../../../../llm';\nimport type { MastraLanguageModel } from '../../../../llm/model/shared.types';\nimport { runStreamCompletionScorers } from '../../../../loop/network/validation';\nimport type { StreamCompletionContext } from '../../../../loop/network/validation';\nimport { createProcessorSendSignal } from '../../../../processors/send-signal';\nimport { RequestContext } from '../../../../request-context';\nimport type { GoalObjectiveRecord } from '../../../../storage/domains/thread-state/base';\nimport type { ChunkType, GoalEvaluationActivity } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport type { ResolvedGoalStore } from '../../../goal';\nimport {\n createGoalScorer,\n GOAL_SCORE_WAITING,\n GOAL_SCORER_ID,\n readObjective,\n resolveEffectiveGoalSettings,\n resolveGoalStore,\n writeObjective,\n} from '../../../goal';\nimport { MessageList } from '../../../message-list';\nimport type { ToolsInput } from '../../../types';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\nfunction isWorkingMemoryTool(name: string): boolean {\n return name === 'updateWorkingMemory' || name === 'setWorkingMemory' || name === 'update-working-memory';\n}\n\nfunction formatJudgeActivityName(name: string | undefined): string | undefined {\n if (!name) return undefined;\n if (name === 'view') return 'read';\n if (name === 'search_content') return 'search';\n if (name === 'find_files') return 'find files';\n if (name === 'file_stat') return 'stat';\n if (name === 'lsp_inspect') return 'inspect';\n return name;\n}\n\nfunction getStringArg(args: unknown, key: string): string | undefined {\n if (!args || typeof args !== 'object' || Array.isArray(args)) return undefined;\n const value = (args as Record<string, unknown>)[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction truncateActivityDetail(value: string): string {\n return value.length > 80 ? `${value.slice(0, 77)}...` : value;\n}\n\nfunction extractPartialReasonFromStructuredText(text: string): string | undefined {\n const match = text.match(/\"reason\"\\s*:\\s*\"((?:\\\\.|[^\"\\\\])*)/);\n const partialReason = match?.[1];\n if (!partialReason) return undefined;\n return partialReason.replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, '\\\\').trim();\n}\n\nfunction formatJudgeActivityMessage(name: string | undefined, args: unknown): string | undefined {\n const label = formatJudgeActivityName(name);\n if (!label) return undefined;\n\n if (name === 'view' || name === 'file_stat') {\n const path = getStringArg(args, 'path');\n return path ? `${label} ${truncateActivityDetail(path)}` : label;\n }\n\n if (name === 'search_content') {\n const pattern = getStringArg(args, 'pattern');\n const path = getStringArg(args, 'path');\n const detail = [pattern, path].filter(Boolean).join(' in ');\n return detail ? `${label} ${truncateActivityDetail(detail)}` : label;\n }\n\n if (name === 'find_files') {\n const path = getStringArg(args, 'path');\n const pattern = getStringArg(args, 'pattern');\n const detail = [path, pattern].filter(Boolean).join(' ');\n return detail ? `${label} ${truncateActivityDetail(detail)}` : label;\n }\n\n if (name === 'lsp_inspect') {\n const path = getStringArg(args, 'path');\n const line =\n !args || typeof args !== 'object' || Array.isArray(args) ? undefined : (args as Record<string, unknown>).line;\n const detail = path ? `${path}${typeof line === 'number' ? `:${line}` : ''}` : undefined;\n return detail ? `${label} ${truncateActivityDetail(detail)}` : label;\n }\n\n return label;\n}\n\n/**\n * Create the durable goal step.\n *\n * Mirrors the non-durable `createGoalStep` contract:\n * - Runs after `isTaskCompleteStep` in the `singleIterationWorkflow`.\n * - Only evaluates iterations where the LLM has signaled it is done\n * (`lastStepResult.isContinued === false`) so we don't interrupt mid-loop\n * tool execution.\n * - Skips background-pending, working-memory-only iterations (same\n * heuristic as the non-durable step).\n * - Pulls the `goal` config from the in-process run registry (closures\n * like `judge`, `scorer`, `tools` can't survive the wire). Cross-process\n * engines without this slot skip goal evaluation.\n * - Reads/writes the `GoalObjectiveRecord` from/to thread state storage.\n * - Emits `goal` chunks via pubsub so external observers see the verdict.\n * - Injects system-reminder + goal feedback into `messageList` via\n * `createProcessorSendSignal` so the next LLM iteration can see it.\n */\nexport function createDurableGoalStep() {\n return createStep({\n id: 'durable-goal',\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async params => {\n const { inputData, mastra, getInitData } = params;\n const state = inputData as {\n runId: string;\n iterationCount: number;\n messageListState: any;\n messageId: string;\n accumulatedSteps: Array<{\n text?: string;\n toolCalls?: Array<{ toolName?: string; args?: unknown }>;\n toolResults?: Array<{ toolName?: string; result?: unknown }>;\n }>;\n lastStepResult?: { isContinued?: boolean; reason?: string };\n options?: { maxSteps?: number };\n backgroundTaskPending?: boolean;\n };\n if (state.lastStepResult?.reason === 'error') return state;\n\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const initData = getInitData() as {\n agentId?: string;\n agentName?: string;\n state?: { threadId?: string; resourceId?: string };\n requestContextEntries?: Record<string, unknown>;\n };\n\n const registryEntry = globalRunRegistry.get(state.runId);\n // This is shared agent configuration (judge, scorer, tools, defaults), not per-goal state.\n // The objective and its progress are isolated by thread and loaded from storage below.\n let goalConfig = registryEntry?.goal;\n if (!goalConfig && initData.agentId) {\n goalConfig = (mastra as any)?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();\n }\n\n // No goal mode configured → nothing to do.\n if (!goalConfig) return state;\n\n // Same gating as isTaskComplete: skip background results, mid-tool-loop\n // continuations, and working-memory-only iterations.\n if (state.backgroundTaskPending || state.lastStepResult?.isContinued) {\n return state;\n }\n\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n const iterationToolCalls = (lastStep?.toolCalls ?? []) as Array<{\n toolName?: string;\n args?: unknown;\n }>;\n if (iterationToolCalls.length > 0 && iterationToolCalls.every(tc => isWorkingMemoryTool(tc.toolName ?? ''))) {\n return state;\n }\n\n const threadId = initData.state?.threadId;\n\n // Reconstruct requestContext from serialized entries for resolvers.\n const requestContext = new RequestContext();\n if (initData.requestContextEntries) {\n for (const [key, value] of Object.entries(initData.requestContextEntries)) {\n requestContext.set(key, value);\n }\n }\n\n const store = (await resolveGoalStore(mastra as any)) as ResolvedGoalStore | undefined;\n const record = await readObjective(store, threadId);\n\n // No active objective → no gating, no chunk.\n if (!record || record.status !== 'active' || !store || !threadId) {\n return state;\n }\n\n const effective = resolveEffectiveGoalSettings(record, {\n judgeModelId: typeof goalConfig.judge === 'string' ? goalConfig.judge : undefined,\n maxRuns: goalConfig.maxRuns,\n prompt: goalConfig.prompt,\n maxSteps: goalConfig.maxSteps,\n });\n\n // Defensive budget guard.\n const nextState: typeof state = { ...state };\n if (record.runsUsed >= effective.maxRuns) {\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: false,\n };\n }\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n objective: record.objective,\n iteration: record.runsUsed,\n maxRuns: effective.maxRuns,\n passed: false,\n status: record.status,\n results: [],\n reason: undefined,\n duration: 0,\n timedOut: false,\n maxRunsReached: true,\n suppressFeedback: false,\n shouldContinue: false,\n },\n } as any);\n } catch {\n // PubSub may be closed — fall through.\n }\n }\n return nextState;\n }\n\n // Determine the judge model config. A non-string agent `goalConfig.judge` (a\n // resolved model or a model-resolver function) takes precedence.\n const nonStringAgentJudge =\n goalConfig.judge && typeof goalConfig.judge !== 'string' ? goalConfig.judge : undefined;\n\n let judgeModelConfig: unknown = nonStringAgentJudge ?? effective.judgeModelId;\n if (typeof judgeModelConfig === 'function') {\n judgeModelConfig = await (judgeModelConfig as (args: any) => unknown)({ requestContext, mastra });\n }\n if (!judgeModelConfig) {\n return state;\n }\n\n // Evaluate the goal. Catch any failure to prevent infinite loops.\n let result: Awaited<ReturnType<typeof runStreamCompletionScorers>>;\n try {\n const emitJudgeActivity = (activity: GoalEvaluationActivity, args?: unknown) => {\n const name =\n activity.type === 'reason' ? activity.name : formatJudgeActivityName(activity.name ?? activity.message);\n const message =\n activity.type === 'reason'\n ? activity.message\n : formatJudgeActivityMessage(activity.name ?? activity.message, args);\n if (!message || !pubsub) return;\n emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n objective: record.objective,\n iteration: record.runsUsed + 1,\n maxRuns: effective.maxRuns,\n passed: false,\n status: record.status,\n results: [],\n duration: 0,\n timedOut: false,\n maxRunsReached: false,\n suppressFeedback: true,\n pending: true,\n activity: [{ ...activity, name, message }],\n },\n } as any).catch(() => {});\n };\n\n const observeJudgeStream = (stream: { fullStream?: AsyncIterable<ChunkType> }) => {\n if (!stream.fullStream) return;\n void (async () => {\n try {\n let streamedText = '';\n let lastReason = '';\n for await (const chunk of stream.fullStream!) {\n if (chunk.type === 'text-delta') {\n streamedText += (chunk as any).payload?.text ?? '';\n const reason = extractPartialReasonFromStructuredText(streamedText);\n if (reason && reason !== lastReason) {\n lastReason = reason;\n emitJudgeActivity({ type: 'reason', message: reason });\n }\n } else if (chunk.type === 'tool-call') {\n emitJudgeActivity(\n {\n type: 'tool-call',\n name: (chunk as any).payload?.toolName,\n message: (chunk as any).payload?.toolName,\n },\n (chunk as any).payload?.args,\n );\n }\n }\n } catch {\n // The scorer owns structured-output fallback and error reporting.\n // Judge activity streaming is best-effort UI feedback and must not\n // turn a recoverable scorer stream failure into an unhandled rejection.\n }\n })();\n };\n\n // Resolve the scorer.\n let scorer: MastraScorer<any, any, any, any> | undefined;\n if (goalConfig.scorer) {\n scorer =\n typeof goalConfig.scorer === 'string'\n ? (mastra?.getScorer?.(goalConfig.scorer as any) as MastraScorer<any, any, any, any> | undefined)\n : goalConfig.scorer;\n }\n if (!scorer) {\n const judgeModel = (\n typeof judgeModelConfig === 'string'\n ? await resolveModelConfig(judgeModelConfig, requestContext, mastra)\n : judgeModelConfig\n ) as MastraLanguageModel;\n\n const goalTools: ToolsInput | undefined =\n typeof goalConfig.tools === 'function'\n ? ((await (goalConfig.tools as (args: any) => unknown)({ requestContext, mastra })) as\n | ToolsInput\n | undefined)\n : goalConfig.tools;\n\n scorer = createGoalScorer({\n mastra,\n judgeModel,\n prompt: effective.prompt,\n tools: goalTools,\n requestContext,\n onStream: observeJudgeStream,\n ...(effective.maxSteps ? { maxSteps: effective.maxSteps } : {}),\n });\n }\n\n // Build scorer context.\n const messageList = new MessageList();\n messageList.deserialize(state.messageListState);\n\n const toolCalls = (lastStep?.toolCalls ?? []) as Array<{ toolName?: string; args?: unknown }>;\n const toolResults = (lastStep?.toolResults ?? []) as Array<{ toolName?: string; result?: unknown }>;\n const goalContext: StreamCompletionContext = {\n iteration: record.runsUsed + 1,\n maxIterations: effective.maxRuns,\n originalTask: record.objective,\n currentText: lastStep?.text || '',\n toolCalls: toolCalls.map(tc => ({\n name: tc.toolName || '',\n args: (tc.args || {}) as Record<string, unknown>,\n })),\n messages: messageList.get.all.db(),\n toolResults: toolResults.map(tr => ({\n name: tr.toolName || '',\n result: (tr.result as Record<string, unknown>) ?? {},\n })),\n agentId: initData.agentId || '',\n agentName: initData.agentName || '',\n runId: state.runId,\n threadId,\n resourceId: initData.state?.resourceId,\n customContext: initData.requestContextEntries,\n };\n\n // Emit a pending chunk so consumers can show a loading indicator.\n if (pubsub) {\n emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n objective: record.objective,\n iteration: record.runsUsed + 1,\n maxRuns: effective.maxRuns,\n passed: false,\n status: record.status,\n results: [],\n duration: 0,\n timedOut: false,\n maxRunsReached: false,\n suppressFeedback: true,\n pending: true,\n },\n } as any).catch(() => {});\n }\n\n result = await runStreamCompletionScorers([scorer], goalContext, { strategy: 'all' });\n } catch (error: any) {\n const reason = `Goal evaluation failed: ${error?.message ?? String(error)}`;\n result = {\n complete: false,\n completionReason: undefined,\n scorers: [\n {\n score: 0,\n passed: false,\n reason,\n scorerId: GOAL_SCORER_ID,\n scorerName: 'Goal (LLM)',\n duration: 0,\n errored: true,\n },\n ],\n totalDuration: 0,\n timedOut: false,\n };\n }\n\n // Tri-state decision: done / waiting / keep working / errored.\n const erroredScorer = result.scorers.find(s => s.errored);\n const judgeFailed = !!erroredScorer;\n const waiting =\n !judgeFailed &&\n !result.complete &&\n result.scorers.some(s => s.scorerId === GOAL_SCORER_ID && s.score === GOAL_SCORE_WAITING);\n\n // Increment runs and update status.\n const runsUsed = record.runsUsed + 1;\n const maxRunsReached = runsUsed >= effective.maxRuns;\n let status: GoalObjectiveRecord['status'] = record.status;\n let pausedReason: string | undefined;\n if (judgeFailed) {\n status = 'paused';\n pausedReason = erroredScorer?.reason ?? 'The goal judge failed to evaluate the objective.';\n } else if (result.complete) {\n status = 'done';\n } else if (maxRunsReached && !waiting) {\n status = 'paused';\n pausedReason = `Ran out of evaluation budget (${effective.maxRuns} runs) before reaching the goal — raise maxRuns to resume.`;\n }\n\n const updated: GoalObjectiveRecord = {\n ...record,\n runsUsed,\n status,\n pausedReason: status === 'paused' ? pausedReason : undefined,\n updatedAt: Date.now(),\n };\n await writeObjective(store, threadId, updated, requestContext);\n\n // Continuation decision.\n const shouldContinue = !result.complete && !waiting && !judgeFailed && !maxRunsReached;\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: shouldContinue,\n };\n }\n\n const suppressFeedback = false;\n const goalEvaluationPayload = {\n objective: record.objective,\n iteration: runsUsed,\n maxRuns: effective.maxRuns,\n passed: result.complete,\n status,\n pausedReason,\n judgeFailed,\n waitingForUser: waiting,\n results: result.scorers,\n reason: status === 'paused' ? pausedReason : result.completionReason,\n duration: result.totalDuration,\n timedOut: result.timedOut,\n maxRunsReached,\n suppressFeedback,\n shouldContinue,\n };\n\n // Inject feedback into messageList via signal so the next LLM call sees it.\n const messageList = new MessageList();\n messageList.deserialize(nextState.messageListState);\n\n let currentMessageId = nextState.messageId;\n const sendSignal = createProcessorSendSignal({\n messageList,\n writer: pubsub\n ? {\n custom: async (data, _options) => {\n await emitChunkEvent(pubsub, state.runId, data as ChunkType);\n },\n }\n : undefined,\n rotateResponseMessageId: () => {\n currentMessageId = mastra?.generateId?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n nextState.messageId = currentMessageId;\n return currentMessageId;\n },\n });\n\n const feedback = result.completionReason ?? 'The goal is not yet complete.';\n const continuation = shouldContinue\n ? `[Goal attempt ${runsUsed}/${effective.maxRuns}] The goal is not yet complete. Judge feedback: ${feedback}\\n\\nContinue working toward the goal: ${record.objective}`\n : `${status} (${runsUsed}/${effective.maxRuns})\\n${goalEvaluationPayload.reason ?? ''}`;\n await sendSignal({\n type: 'system-reminder',\n contents: continuation,\n attributes: { type: 'goal-judge' },\n metadata: { goalEvaluation: goalEvaluationPayload },\n });\n\n // Re-serialize messageList after signal injection.\n nextState.messageListState = messageList.serialize();\n\n // Emit the final goal chunk for external observers.\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: goalEvaluationPayload,\n } as any);\n } catch {\n // PubSub may be closed — fall through.\n }\n }\n\n return nextState;\n },\n });\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { Mastra } from '../../../../mastra';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\nconst SIGNAL_DRAIN_STEP_ID = `${DurableStepIds.AGENTIC_EXECUTION}-signal-drain`;\n\n/**\n * Create a durable signal drain step.\n *\n * Mirrors the regular agent's `signalDrainStep` which sits between\n * backgroundTaskCheckStep and isTaskCompleteStep:\n * - Drains any signals queued while tool execution was running\n * - Adds drained signals to the messageList transcript\n * - Emits signal chunks via pubsub for the stream adapter\n * - Sets isContinued=true so the LLM processes the signals on the next turn\n * - Best-effort: swallows errors so signals remain queued on failure\n */\nexport function createDurableSignalDrainStep() {\n return createStep({\n id: SIGNAL_DRAIN_STEP_ID,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async params => {\n const { inputData, getInitData } = params;\n const execOutput = inputData as Record<string, any>;\n const initData = getInitData<{ runId: string }>();\n const runId = initData.runId;\n const registryEntry = globalRunRegistry.get(runId);\n const drainFn = registryEntry?.drainPendingSignals;\n\n if (!drainFn) return execOutput;\n\n try {\n const pendingSignals = drainFn('pending');\n if (pendingSignals.length === 0) return execOutput;\n\n const drainList = new MessageList();\n drainList.deserialize(execOutput.messageListState);\n drainList.markResponseMessageBoundary(execOutput.messageId);\n\n const nextMessageId =\n (params.mastra as Mastra | undefined)?.generateId?.() ??\n globalThis.crypto?.randomUUID?.() ??\n `msg_${Date.now()}`;\n\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n for (const pendingSignal of pendingSignals) {\n const signalForTranscript = drainList.addSignal(pendingSignal);\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, signalForTranscript.toDataPart() as any);\n }\n }\n\n return {\n ...execOutput,\n messageListState: drainList.serialize(),\n messageId: nextMessageId,\n stepResult: {\n ...execOutput.stepResult,\n messageId: nextMessageId,\n isContinued: true,\n },\n };\n } catch {\n // Signal drain is best-effort; drainPendingSignals() is inside\n // the try so signals remain queued if it throws.\n return execOutput;\n }\n },\n });\n}\n","import { z } from 'zod';\nimport type { MastraScorer, MastraScorerEntry } from '../../../evals/base';\nimport { runScorer } from '../../../evals/hooks';\nimport type { PubSub } from '../../../events/pubsub';\nimport { pruneAgentLoopSnapshot } from '../../../loop/workflows/prune-snapshot';\nimport type { Mastra } from '../../../mastra';\nimport { createObservabilityContext, InternalSpans } from '../../../observability';\nimport type { AIModelGenerationSpan, ExportedSpan, SpanType } from '../../../observability';\nimport { RequestContext } from '../../../request-context';\nimport { PUBSUB_SYMBOL } from '../../../workflows/constants';\nimport { createWorkflow } from '../../../workflows/create';\nimport { MessageList } from '../../message-list';\nimport { DurableStepIds, DurableAgentDefaults } from '../constants';\nimport { globalRunRegistry } from '../run-registry';\nimport { emitChunkEvent, emitFinishEvent, emitIterationCompleteEvent } from '../stream-adapter';\nimport type {\n DurableToolCallInput,\n DurableAgenticWorkflowInput,\n DurableAgenticExecutionOutput,\n DurableLLMStepOutput,\n DurableToolCallOutput,\n SerializableScorersConfig,\n} from '../types';\nimport {\n modelConfigSchema,\n modelListEntrySchema,\n durableAgenticOutputSchema,\n baseIterationStateSchema,\n createBaseIterationStateUpdate,\n resolveDurableToolCallConcurrency,\n} from './shared';\nimport {\n createDurableBackgroundTaskCheckStep,\n createDurableGoalStep,\n createDurableIsTaskCompleteStep,\n createDurableLLMExecutionStep,\n createDurableToolCallStep,\n createDurableLLMMappingStep,\n createDurableSignalDrainStep,\n} from './steps';\n\n/**\n * Options for creating a durable agentic workflow\n */\nexport interface DurableAgenticWorkflowOptions {\n /** Maximum number of agentic loop iterations */\n maxSteps?: number;\n}\n\n/**\n * Input schema for the durable agentic workflow.\n * Extends base schema with model list for fallback support.\n */\nconst durableAgenticInputSchema = z.object({\n __workflowKind: z.literal('durable-agent'),\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 // Model list for fallback support (when agent configured with array of models)\n modelList: z.array(modelListEntrySchema).optional(),\n options: z.any(),\n state: z.any(),\n messageId: z.string(),\n // Exported AGENT_RUN / MODEL_GENERATION span data, threaded so the run shares one trace\n agentSpanData: z.any().optional(),\n modelSpanData: z.any().optional(),\n // JSON-safe snapshot of requestContext.entries() so durable steps can read\n // it (e.g. is-task-complete scorers pass it as customContext).\n requestContextEntries: z.record(z.string(), z.any()).optional(),\n});\n\n// Re-export shared output schema (identical across implementations)\n// Note: durableAgenticOutputSchema is imported from shared\n\n/**\n * Schema for the iteration state that flows through the dowhile loop.\n * Extends base schema with model list for fallback support.\n */\nconst iterationStateSchema = baseIterationStateSchema.extend({\n // Model list for fallback support\n modelList: z.array(z.any()).optional(),\n});\n\ntype IterationState = z.infer<typeof iterationStateSchema>;\n\n/**\n * Create a durable agentic workflow.\n *\n * This workflow implements the agentic loop pattern in a durable way:\n *\n * 1. LLM Execution Step - Calls the LLM and gets response/tool calls\n * 2. Tool Call Steps (foreach) - Executes each tool call in parallel\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 */\nexport function createDurableAgenticWorkflow(options?: DurableAgenticWorkflowOptions) {\n const maxSteps = options?.maxSteps ?? DurableAgentDefaults.MAX_STEPS;\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\n const llmMappingStep = createDurableLLMMappingStep();\n\n // Create the background task check step\n const backgroundTaskCheckStep = createDurableBackgroundTaskCheckStep();\n\n // Create the signal drain step — mirrors the non-durable `signalDrainStep`\n // which drains signals queued during tool execution.\n const signalDrainStep = createDurableSignalDrainStep();\n\n // Create the isTaskComplete evaluation step (mirrors the non-durable\n // createIsTaskCompleteStep). Lives as a real step (not predicate logic)\n // so it shows up in workflow traces and produces a proper state transition.\n const isTaskCompleteStep = createDurableIsTaskCompleteStep(maxSteps);\n\n // Create the goal evaluation step — mirrors the non-durable\n // `createGoalStep`. Runs after isTaskComplete so the goal judge\n // sees whether isTaskComplete already stopped the loop.\n const goalStep = createDurableGoalStep();\n\n // Create the single iteration workflow (LLM -> Tool Calls -> Mapping)\n // Note: tool-call foreach concurrency is resolved per run at execution time\n // (see resolveDurableToolCallConcurrency) — approval/suspend flows force\n // sequential execution; otherwise the run's `toolCallConcurrency` applies.\n // The workflow is created once at startup and reused for all runs.\n const singleIterationWorkflow = createWorkflow({\n id: DurableStepIds.AGENTIC_EXECUTION,\n inputSchema: iterationStateSchema,\n outputSchema: iterationStateSchema,\n options: {\n shouldPersistSnapshot: params => {\n // We need a persisted snapshot record to support both:\n // - `resumeStream()` after a suspend (records with status\n // `pending` / `paused` / `suspended`)\n // - boot-time recovery of orphaned RUNNING runs after a process\n // restart, via `DurableAgent.recoverActiveRuns()` — this requires\n // the row to actually be stamped `running` while the loop is\n // in-flight (issue #19056).\n //\n // The engine's persist path guards against overwriting a `suspended`\n // / `paused` snapshot with a later `running` update from the same\n // run (see `persistStepUpdate` in workflows/handlers/entry.ts), so\n // it is safe to return true for `running` here.\n return (\n params.workflowStatus === 'pending' ||\n params.workflowStatus === 'paused' ||\n params.workflowStatus === 'suspended' ||\n params.workflowStatus === 'running'\n );\n },\n // Agent-loop snapshots are pure resume artifacts — strip everything a\n // resume never reads before persisting.\n pruneSnapshot: pruneAgentLoopSnapshot,\n validateInputs: false,\n sharePubsub: true,\n // Internal durable-agent execution plumbing — hide workflow spans;\n // the agent/tool/model spans within still surface for users.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\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 modelList: state.modelList,\n options: state.options,\n state: state.state,\n messageId: state.messageId,\n stepIndex: state.iterationCount,\n agentSpanData: state.agentSpanData,\n modelSpanData: state.modelSpanData,\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 (forward model_step span for nesting)\n .map(\n async ({ inputData }) => {\n const llmOutput = inputData as DurableLLMStepOutput;\n return (llmOutput.toolCalls ?? []).map(toolCall => ({\n ...toolCall,\n stepSpanData: llmOutput.stepSpanData,\n })) as DurableToolCallInput[];\n },\n { id: 'extract-tool-calls' },\n )\n // Step 3: Execute each tool call individually (with suspend support).\n // Concurrency is resolved per run from the serialized iteration state:\n // approval/suspend-capable tool sets run sequentially, everything else\n // honors the run's `toolCallConcurrency` (default 10). The workflow graph\n // is shared across runs, so this must be a resolver — never a mutated\n // shared options object.\n .foreach(toolCallStep, {\n concurrency: ({ inputData, getInitData }) => {\n const state = getInitData() as IterationState | undefined;\n return resolveDurableToolCallConcurrency({\n options: state?.options,\n toolsMetadata: state?.toolsMetadata,\n toolCalls: inputData as DurableToolCallInput[],\n });\n },\n })\n // Step 4: Collect tool results and bundle with LLM output for mapping step\n .map(\n async ({ inputData, getStepResult, getInitData }) => {\n const toolResults = inputData as DurableToolCallOutput[];\n const llmOutput = getStepResult(llmExecutionStep.id) as DurableLLMStepOutput;\n const initData = getInitData() as IterationState;\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 6.5: Drain signals that were queued while tool execution was running\n // within this iteration. Mirrors the non-durable `signalDrainStep` which\n // sits between backgroundTaskCheckStep and isTaskCompleteStep.\n .then(signalDrainStep)\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 core-specific fields\n const newIterationState: IterationState = {\n ...baseUpdate,\n modelList: initData.modelList,\n };\n\n return newIterationState;\n },\n { id: 'update-iteration-state' },\n )\n // Step 8: Evaluate user-supplied isTaskComplete scorers (if any). Runs as\n // a real step so it shows up in traces and may mutate lastStepResult /\n // messageListState before the dowhile predicate decides whether to loop\n // again. No-op when the run has no policy configured.\n .then(isTaskCompleteStep)\n // Step 9: Goal evaluation. Mirrors the non-durable createGoalStep — judges\n // whether the thread's active objective is satisfied or should continue.\n // No-op when no goal is configured or no active objective exists.\n .then(goalStep)\n .commit();\n\n // Create the main agentic loop workflow with dowhile\n return (\n createWorkflow({\n id: DurableStepIds.AGENTIC_LOOP,\n inputSchema: durableAgenticInputSchema,\n outputSchema: durableAgenticOutputSchema,\n options: {\n shouldPersistSnapshot: params => {\n // See the singleIterationWorkflow comment above — same policy for\n // the outer loop. The persist path guards against overwriting a\n // suspended snapshot with running.\n return (\n params.workflowStatus === 'pending' ||\n params.workflowStatus === 'paused' ||\n params.workflowStatus === 'suspended' ||\n params.workflowStatus === 'running'\n );\n },\n // Agent-loop snapshots are pure resume artifacts — strip everything a\n // resume never reads before persisting.\n pruneSnapshot: pruneAgentLoopSnapshot,\n validateInputs: false,\n // Internal durable-agent execution plumbing — see singleIterationWorkflow.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n // Initialize iteration state from input\n .map(\n async ({ inputData }) => {\n const input = inputData as DurableAgenticWorkflowInput;\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 };\n return iterationState;\n },\n { id: 'init-iteration-state' },\n )\n // Run the agentic loop with dowhile\n .dowhile(singleIterationWorkflow, async params => {\n const { inputData, mastra } = params;\n const state = inputData as IterationState;\n const initData = params.getInitData() as DurableAgenticWorkflowInput;\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const registryEntry = globalRunRegistry.get(state.runId);\n\n // ── Abort check ────────────────────────────────────────────────\n // If the abort signal has fired, stop the loop immediately.\n // The llm-execution step may have already emitted the ABORT event\n // and returned a clean output, but the signal may also have fired\n // between steps (e.g. inside a tool). Override the stepResult\n // reason so the FINISH event carries 'abort' and the client sees\n // the correct finishReason.\n if (registryEntry?.abortSignal?.aborted) {\n if (state.lastStepResult) {\n state.lastStepResult.reason = 'abort';\n state.lastStepResult.isContinued = false;\n }\n return false;\n }\n\n // Two-phase stop: if onIterationComplete returned { continue: false, feedback }\n // on the previous iteration, we allowed one more LLM turn with that feedback.\n // Now that the turn has completed, stop the loop unconditionally.\n let hasFinishedSteps = false;\n // Hard-stop tracks reasons that onIterationComplete must NOT override.\n // pendingFeedbackStop and delegationBailed are unconditional stops.\n let hardStop = false;\n if (state.pendingFeedbackStop) {\n hasFinishedSteps = true;\n hardStop = true;\n state.pendingFeedbackStop = false;\n }\n\n // Continuation check. isTaskComplete (when configured) runs as a\n // proper step inside singleIterationWorkflow and may have already\n // flipped lastStepResult.isContinued by the time we get here.\n // Declared as `let` because signal drain may force isContinued later.\n let shouldContinue = state.lastStepResult?.isContinued === true;\n const runMaxSteps = state.options?.maxSteps ?? maxSteps;\n const underMaxSteps = state.iterationCount < runMaxSteps;\n\n // Evaluate user-supplied stopWhen predicate(s) parked on the registry\n // up-front so we can include them in the finality decision emitted on\n // the iteration-complete event. The predicate is a closure and can't\n // survive the wire, so we read it from in-process state. Cross-process\n // engines (Inngest after worker restart) won't have the registry entry\n // and fall back to maxSteps only.\n let stopWhenMatched = false;\n if (shouldContinue && underMaxSteps && !hasFinishedSteps) {\n const stopWhen = registryEntry?.stopWhen;\n if (stopWhen && state.accumulatedSteps.length > 0) {\n const conditions = Array.isArray(stopWhen) ? stopWhen : [stopWhen];\n // Mirror agentic-loop: cast steps to any for v5/v6 StopCondition shape\n // compatibility — the StepRecord we accumulate is sufficient at runtime.\n const steps = state.accumulatedSteps as any;\n const results = await Promise.all(conditions.map(condition => condition({ steps })));\n stopWhenMatched = results.some(Boolean);\n }\n }\n\n if (stopWhenMatched) {\n hasFinishedSteps = true;\n }\n\n // Check if a delegation hook called ctx.bail() during this iteration.\n // The flag was set by the mapping step and propagated via iteration state.\n const delegationBailed = !!(state as any).delegationBailed;\n if (delegationBailed) {\n hasFinishedSteps = true;\n hardStop = true;\n // Reset the flag so it doesn't carry forward\n (state as any).delegationBailed = false;\n }\n\n // ── Inter-iteration signal drain ──────────────────────────────\n // Mirror the non-durable agentic-loop predicate: drain pending\n // signals that were queued while the previous iteration was\n // running. If signals are present, mark a response boundary,\n // rotate the messageId, add them to the transcript, emit them\n // to the stream, and force continuation so the LLM sees them.\n if (pubsub && registryEntry?.drainPendingSignals) {\n try {\n const pendingSignals = registryEntry.drainPendingSignals('pending');\n if (pendingSignals.length > 0) {\n const drainList = new MessageList();\n drainList.deserialize(state.messageListState);\n drainList.markResponseMessageBoundary();\n\n const nextMessageId =\n (mastra as Mastra | undefined)?.generateId?.() ??\n globalThis.crypto?.randomUUID?.() ??\n `msg_${Date.now()}`;\n state.messageId = nextMessageId;\n\n for (const pendingSignal of pendingSignals) {\n const signalForTranscript = drainList.addSignal(pendingSignal);\n await emitChunkEvent(pubsub, state.runId, signalForTranscript.toDataPart() as any);\n }\n\n state.messageListState = drainList.serialize();\n\n // Force continuation — the LLM must see the injected signals\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = true;\n }\n shouldContinue = true;\n }\n } catch {\n // Signal drain is best-effort; if deserialization fails\n // the next iteration still runs with the un-drained state.\n // drainPendingSignals() is inside the try so signals remain\n // queued if the drain function itself throws.\n }\n }\n\n let isFinal = !shouldContinue || !underMaxSteps || hasFinishedSteps;\n\n // Call onIterationComplete hook if provided (for every iteration, not\n // just continued ones). Mirrors the regular agentic-loop predicate:\n // the handler can return { continue: false } to stop, { continue: true }\n // to force-continue (if under maxSteps), and/or { feedback } to inject\n // a message before the next turn.\n const onIterationComplete = registryEntry?.onIterationComplete;\n if (onIterationComplete && !state.backgroundTaskPending) {\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n\n try {\n // Deserialize messageList for the callback's messages snapshot\n const callbackMessageList = new MessageList();\n try {\n callbackMessageList.deserialize(state.messageListState);\n } catch {\n // If deserialization fails, callback sees empty messages\n }\n\n const iterationContext = {\n iteration: state.accumulatedSteps.length,\n maxIterations: runMaxSteps,\n text: lastStep?.text ?? '',\n toolCalls: (lastStep?.toolCalls ?? []).map((tc: any) => ({\n id: tc.toolCallId || tc.id || '',\n name: tc.toolName || tc.name || '',\n args: (tc.args || {}) as Record<string, unknown>,\n })),\n toolResults: (lastStep?.toolResults ?? []).map((tr: any) => ({\n id: tr.toolCallId || tr.id || '',\n name: tr.toolName || tr.name || '',\n result: tr.result,\n error: tr.error,\n })),\n isFinal,\n finishReason: lastStep?.finishReason ?? 'unknown',\n runId: state.runId,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n agentId: state.agentId,\n agentName: state.agentName ?? state.agentId,\n messages: callbackMessageList.get.all.db(),\n };\n\n const iterationResult = await onIterationComplete(iterationContext);\n\n if (iterationResult) {\n // Determine whether we can run another turn. Hard stops\n // (pendingFeedbackStop, delegationBailed) are unconditional —\n // onIterationComplete cannot override them.\n const canRunAnotherTurn =\n !hardStop && underMaxSteps && (shouldContinue || iterationResult.continue === true);\n\n if (iterationResult.feedback && canRunAnotherTurn) {\n // Inject feedback as a synthetic assistant message so the LLM\n // sees it on the next turn. Mirror the regular agent: mark it\n // with completionResult.suppressFeedback so isTaskComplete\n // scorers skip it.\n const feedbackId =\n (mastra as Mastra | undefined)?.generateId?.() ??\n globalThis.crypto?.randomUUID?.() ??\n `msg_${Date.now()}`;\n callbackMessageList.add(\n {\n id: feedbackId,\n createdAt: new Date(),\n type: 'text',\n role: 'assistant',\n content: {\n parts: [{ type: 'text', text: iterationResult.feedback }],\n metadata: {\n mode: 'stream',\n completionResult: { suppressFeedback: true },\n },\n format: 2,\n },\n } as any,\n 'response',\n );\n // Re-serialize the updated messageList\n state.messageListState = callbackMessageList.serialize();\n\n if (iterationResult.continue === false) {\n // Two-phase stop: let one more LLM turn run with the feedback,\n // then stop on the next predicate evaluation.\n state.pendingFeedbackStop = true;\n isFinal = false;\n } else if (!hasFinishedSteps && underMaxSteps) {\n isFinal = false;\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = true;\n }\n }\n } else if (iterationResult.continue === false && !hasFinishedSteps) {\n hasFinishedSteps = true;\n isFinal = true;\n } else if (iterationResult.continue === true && !hardStop && (hasFinishedSteps || !shouldContinue)) {\n if (underMaxSteps || !runMaxSteps) {\n hasFinishedSteps = false;\n isFinal = false;\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = true;\n }\n }\n }\n }\n } catch (error) {\n // Log error but don't fail the iteration\n const logger = (mastra as Mastra | undefined)?.getLogger?.();\n logger?.error('Error in onIterationComplete hook:', error);\n }\n }\n\n // Rotate messageId for the next iteration. Each iteration's assistant\n // response is a distinct message, mirroring the non-durable agentic\n // loop which calls rotateResponseMessageId() between iterations. The\n // mutated state.messageId flows into the next singleIterationWorkflow\n // input via map-to-llm-input.\n //\n // We also mark the current MessageList's last assistant message as a\n // response boundary so MessageMerger won't collapse the next\n // iteration's assistant content into it. Without this, persisted\n // memory keeps a single assistant message and the rotated id is never\n // observable to consumers.\n if (!isFinal) {\n const nextMessageId =\n (mastra as Mastra | undefined)?.generateId?.() ?? globalThis.crypto?.randomUUID?.() ?? `msg_${Date.now()}`;\n state.messageId = nextMessageId;\n\n try {\n const boundaryList = new MessageList();\n boundaryList.deserialize(state.messageListState);\n boundaryList.markResponseMessageBoundary();\n state.messageListState = boundaryList.serialize();\n } catch {\n // Boundary marking is best-effort; if deserialization fails the\n // next iteration will still run with the un-marked state.\n }\n }\n\n // Emit an iteration-complete event for observability. This fires after\n // every iteration (including the last one) so client-side callbacks\n // (via stream-adapter) can track progress. The in-process callback\n // above has already been evaluated and its result applied to the\n // continuation decision.\n if (pubsub) {\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n await emitIterationCompleteEvent(pubsub, state.runId, {\n iteration: state.iterationCount,\n maxIterations: runMaxSteps,\n text: lastStep?.text,\n toolCalls: lastStep?.toolCalls,\n toolResults: lastStep?.toolResults,\n isFinal,\n finishReason: lastStep?.finishReason,\n runId: state.runId,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n agentId: initData.agentId,\n agentName: initData.agentName,\n });\n }\n\n return !isFinal;\n })\n // Map final state to output format, run output processors, persist memory, emit finish\n .map(\n async params => {\n const { inputData, mastra, requestContext, tracingContext } = params;\n const state = inputData as IterationState;\n const initData = params.getInitData() as DurableAgenticWorkflowInput;\n\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const logger = mastra?.getLogger?.();\n\n // Extract final text from last step\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n const finalText = lastStep?.text;\n\n // Run output processors (processOutputResult) if available\n const registryEntry = globalRunRegistry.get(state.runId);\n if (registryEntry?.outputProcessors?.length) {\n try {\n const { ProcessorRunner } = await import('../../../processors/runner');\n const runner = new ProcessorRunner({\n inputProcessors: registryEntry.inputProcessors ?? [],\n outputProcessors: registryEntry.outputProcessors,\n errorProcessors: registryEntry.errorProcessors ?? [],\n logger: logger as any,\n agentName: initData.agentName ?? initData.agentId,\n processorStates: registryEntry.processorStates,\n });\n const outputMessageList = new MessageList();\n outputMessageList.deserialize(state.messageListState);\n // Forward the step's tracingContext so processor_run spans parent\n // to the AGENT_RUN ancestor via ProcessorRunner's findParent walk.\n await runner.runOutputProcessors(\n outputMessageList,\n createObservabilityContext(tracingContext),\n requestContext ?? new RequestContext(),\n 0,\n );\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error running output processors: ${error}`);\n }\n }\n\n // Memory persistence (executeOnFinish equivalent)\n const durableState = initData.state;\n if (\n registryEntry?.saveQueueManager &&\n registryEntry.memory &&\n durableState?.threadId &&\n durableState?.resourceId &&\n !durableState.observationalMemory &&\n // Respect readOnly memory config (\"read memory but don't save new\n // messages\"). Mirrors the non-durable executeOnFinish `!readOnlyMemory`\n // guard and the MessageHistory output processor's readOnly check.\n !durableState.memoryConfig?.readOnly\n ) {\n try {\n const memoryMessageList = new MessageList();\n memoryMessageList.deserialize(state.messageListState);\n\n if (!durableState.threadExists) {\n await registryEntry.memory.createThread?.({\n threadId: durableState.threadId,\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n });\n }\n\n await registryEntry.saveQueueManager.flushMessages(\n memoryMessageList,\n durableState.threadId,\n durableState.memoryConfig,\n );\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error persisting messages: ${error}`);\n }\n }\n\n // Thread title generation (executeOnFinish equivalent).\n // The non-durable `#executeOnFinish` generates a thread title from the first user\n // message when `memory.options.generateTitle` is set. That branch was never ported\n // to the durable path, so `generateTitle` silently never fired for durable/evented\n // agents (and Inngest). The `generateThreadTitle` closure — parked on the registry\n // entry during preparation, where the agent instance is in scope — runs it here.\n //\n // Kept OUTSIDE the `!observationalMemory` guard above: OM handles its own message\n // persistence, but title generation is orthogonal and should still run when OM is on.\n // Non-serializable (a closure), so like the other registry closures it only fires for\n // in-process durable runs; cross-process engines (Inngest after a restart) skip it.\n if (\n registryEntry?.generateThreadTitle &&\n durableState?.threadId &&\n durableState?.resourceId &&\n !durableState.memoryConfig?.readOnly\n ) {\n try {\n await registryEntry.generateThreadTitle({\n threadId: durableState.threadId,\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n messageListState: state.messageListState,\n requestContext,\n tracingContext,\n });\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error generating thread title: ${error}`);\n }\n }\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 if (pubsub) {\n await emitFinishEvent(pubsub, state.runId, {\n output: finalOutput.output,\n stepResult: finalOutput.stepResult,\n });\n }\n\n // End MODEL_GENERATION then AGENT_RUN once at completion. After a resume the\n // originals were ended as `suspended`, so end the *resume* spans (registry override).\n try {\n const observability = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({\n requestContext,\n });\n const reg = globalRunRegistry.get(initData.runId);\n const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;\n const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;\n if (observability) {\n if (modelSpanData) {\n const modelSpan = observability.rebuildSpan(\n modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION>,\n ) as AIModelGenerationSpan | undefined;\n modelSpan?.createTracker()?.endGeneration({\n output: { text: finalText },\n attributes: { finishReason: finalOutput.stepResult?.reason },\n usage: state.accumulatedUsage,\n });\n }\n if (agentSpanData) {\n const agentSpan = observability.rebuildSpan(agentSpanData as ExportedSpan<SpanType.AGENT_RUN>);\n agentSpan?.end({ output: { text: finalText } });\n }\n }\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error ending observability spans: ${error}`);\n }\n\n return finalOutput;\n },\n { id: 'map-final-output' },\n )\n // Execute scorers (fire-and-forget, doesn't affect main result)\n .map(\n async params => {\n const { inputData, getInitData, mastra, requestContext, tracingContext } = params;\n const finalOutput = inputData;\n const initData = getInitData() as DurableAgenticWorkflowInput;\n\n // If no scorers configured, skip\n const scorers = initData.scorers as SerializableScorersConfig | undefined;\n if (!scorers || Object.keys(scorers).length === 0) {\n return finalOutput;\n }\n\n const logger = mastra?.getLogger?.();\n\n // Reconstruct input MessageList to extract scorer input\n const inputMessageList = new MessageList();\n inputMessageList.deserialize(initData.messageListState);\n\n // Build scorer input (messages before generation)\n const scorerInput = {\n inputMessages: inputMessageList.getPersisted.input.db(),\n rememberedMessages: inputMessageList.getPersisted.remembered.db(),\n systemMessages: inputMessageList.getSystemMessages(),\n taggedSystemMessages: inputMessageList.getPersisted.taggedSystemMessages,\n };\n\n // Reconstruct output MessageList to extract scorer output\n const outputMessageList = new MessageList();\n outputMessageList.deserialize(finalOutput.messageListState);\n const scorerOutput = outputMessageList.getPersisted.response.db();\n\n // Create request context for scorer resolution\n const resolveContext = requestContext ?? new RequestContext();\n\n // Execute each scorer (fire-and-forget)\n for (const [scorerKey, scorerEntry] of Object.entries(scorers)) {\n const { scorerName, sampling } = scorerEntry;\n\n try {\n // Resolve the scorer from Mastra. We serialize scorers by name,\n // and `getScorerById` searches by id-or-name without throwing\n // on the common path, so try it first. Fall back to the\n // registration-key-keyed `getScorer` for older configs.\n let scorer: MastraScorer | undefined;\n try {\n scorer = (mastra as Mastra)?.getScorerById?.(scorerName) as MastraScorer | undefined;\n } catch {\n scorer = undefined;\n }\n if (!scorer) {\n try {\n scorer = (mastra as Mastra)?.getScorer?.(scorerName) as MastraScorer | undefined;\n } catch {\n scorer = undefined;\n }\n }\n\n if (!scorer) {\n logger?.warn?.(`Scorer ${scorerName} not found in Mastra, skipping`, {\n runId: initData.runId,\n scorerKey,\n });\n continue;\n }\n\n // Create the scorer entry expected by runScorer\n const scorerObject: MastraScorerEntry = {\n scorer,\n sampling,\n };\n\n // Call runScorer (fire-and-forget via hooks)\n runScorer({\n runId: initData.runId,\n scorerId: scorerKey,\n scorerObject,\n input: scorerInput,\n output: scorerOutput,\n requestContext: resolveContext as any,\n entity: {\n id: initData.agentId,\n name: initData.agentName ?? initData.agentId,\n },\n structuredOutput: false,\n source: 'LIVE',\n entityType: 'AGENT',\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n ...createObservabilityContext(tracingContext),\n });\n } catch (error) {\n // Log but don't fail - scorer errors shouldn't affect main execution\n logger?.warn?.(`Error executing scorer ${scorerName}`, {\n error,\n runId: initData.runId,\n scorerKey,\n });\n }\n }\n\n return finalOutput;\n },\n { id: 'execute-scorers' },\n )\n .commit()\n );\n}\n","import type { MastraServerCache } from '../../cache/base';\nimport { InMemoryServerCache } from '../../cache/inmemory';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../../error';\nimport { CachingPubSub } from '../../events/caching-pubsub';\nimport { EventEmitterPubSub } from '../../events/event-emitter';\nimport type { PubSub } from '../../events/pubsub';\nimport type { Mastra } from '../../mastra';\nimport { createObservabilityContext, getOrCreateSpan, SpanType, EntityType } from '../../observability';\nimport { RequestContext } from '../../request-context';\nimport type { FullOutput, MastraModelOutput } from '../../stream/base/output';\nimport type { ChunkType, MastraOnFinishCallback, MastraStreamTransformOptions } from '../../stream/types';\nimport { ChunkFrom } from '../../stream/types';\nimport { deepMerge } from '../../utils';\nimport type { WorkflowRunState, WorkflowRunStatus } from '../../workflows/types';\nimport { Agent } from '../agent';\nimport type { AgentExecutionOptions } from '../agent.types';\nimport { beginGoalActivity, stopGoalActivity } from '../goal';\nimport { MessageList } from '../message-list';\nimport type { MessageListInput } from '../message-list';\nimport { SaveQueueManager } from '../save-queue';\nimport { agentThreadStreamRuntime } from '../thread-stream-runtime';\nimport type { ToolsInput } from '../types';\n\nimport { AGENT_STREAM_TOPIC, DurableStepIds } from './constants';\nimport { runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle } from './durable-stream-until-idle';\nimport { prepareForDurableExecution } from './preparation';\nimport { endRunSpansWithError, ExtendedRunRegistry, globalRunRegistry } from './run-registry';\nimport { createDurableAgentStream, emitChunkEvent, emitErrorEvent } from './stream-adapter';\nimport type { AgentStepFinishEventData, AgentSuspendedEventData, DurableAgenticWorkflowInput } from './types';\nimport { createDurableAgenticWorkflow } from './workflows';\n\n/**\n * Internal flag used by `generate()`/`resumeGenerate()` to tell the stream\n * adapter to close the underlying ReadableStream on SUSPENDED events so that\n * `getFullOutput()` resolves instead of hanging on a suspended run.\n * Not part of the public `DurableAgentStreamOptions` surface.\n */\nconst CLOSE_ON_SUSPEND = Symbol('mastra.durable.closeOnSuspend');\nconst RESOLVED_EXECUTION_OPTIONS = Symbol('mastra.durable.resolvedExecutionOptions');\n\n/**\n * Options for DurableAgent.stream()\n */\nexport interface DurableAgentStreamOptions<OUTPUT = undefined> {\n /** Custom instructions that override the agent's default instructions for this execution */\n instructions?: AgentExecutionOptions<OUTPUT>['instructions'];\n /** Additional context messages to provide to the agent */\n context?: AgentExecutionOptions<OUTPUT>['context'];\n /** Memory configuration for conversation persistence and retrieval */\n memory?: AgentExecutionOptions<OUTPUT>['memory'];\n /** Unique identifier for this execution run */\n runId?: string;\n /** Request Context containing dynamic configuration and state */\n requestContext?: AgentExecutionOptions<OUTPUT>['requestContext'];\n /** Maximum number of steps to run */\n maxSteps?: number;\n /**\n * Conditions for stopping execution (e.g., step count, token limit).\n *\n * The predicate is non-serializable, so it's parked on the in-process run\n * registry and evaluated by the durable loop on every iteration. Cross-process\n * durable engines (e.g. Inngest after a worker restart) cannot recover the\n * closure and degrade to `maxSteps` only.\n */\n stopWhen?: AgentExecutionOptions<OUTPUT>['stopWhen'];\n /** Additional tool sets that can be used for this execution */\n toolsets?: AgentExecutionOptions<OUTPUT>['toolsets'];\n /** Client-side tools available during execution */\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-specific settings like temperature */\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 number of tool calls to execute concurrently */\n toolCallConcurrency?: number;\n /** Whether to include raw chunks in the stream output */\n includeRawChunks?: boolean;\n /** Experimental transforms applied whenever `fullStream` is consumed. */\n experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;\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 /** 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 — receives rich step data (text, steps, toolResults) */\n onFinish?: MastraOnFinishCallback<OUTPUT>;\n /** Callback on error */\n onError?: ({ error }: { error: Error | string }) => void | Promise<void>;\n /** Callback when workflow suspends (e.g., for tool approval) */\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n /** Callback when execution is aborted via abortSignal */\n onAbort?: AgentExecutionOptions<OUTPUT>['onAbort'];\n /** Callback fired after each agentic-loop iteration */\n onIterationComplete?: AgentExecutionOptions<OUTPUT>['onIterationComplete'];\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 * Per-invocation tool payload transform policy. The closure rides on the\n * in-process run registry; only the JSON-safe `targets` shadow is serialized\n * for cross-process engines.\n */\n transform?: AgentExecutionOptions<OUTPUT>['transform'];\n /**\n * Per-step preparation hook. Closure-only: stored on the in-process run\n * registry and invoked as a `PrepareStepProcessor` at the start of every\n * iteration. Cross-process resumes lose the hook.\n */\n prepareStep?: AgentExecutionOptions<OUTPUT>['prepareStep'];\n /**\n * Per-call `isTaskComplete` policy. Scorer instances and `onComplete` are\n * closure-only and live on the in-process run registry; the JSON-safe\n * primitives (`strategy`, `timeout`, `parallel`, `suppressFeedback`,\n * `scorerNames`) are serialized for cross-process observability.\n */\n isTaskComplete?: AgentExecutionOptions<OUTPUT>['isTaskComplete'];\n /**\n * Sub-agent delegation hooks (`onDelegationStart`, `onDelegationComplete`,\n * `messageFilter`, etc.). The callbacks are forwarded into `convertTools`\n * at prepare time and burned into the sub-agent `CoreTool` wrappers on the\n * in-process run registry. Cross-process resumes lose the callbacks (only\n * `includeSubAgentToolResultsInModelContext` would be JSON-safe), so a\n * fresh worker degrades to default delegation behaviour.\n */\n delegation?: AgentExecutionOptions<OUTPUT>['delegation'];\n /**\n * When set, `stream()` delegates to the idle-loop wrapper that keeps the\n * outer stream open across background-task continuations — the same\n * behaviour as the now-deprecated `streamUntilIdle()`.\n *\n * Pass `true` for default idle timeout (5 min), or `{ maxIdleMs }` to\n * customise.\n *\n * @example\n * ```typescript\n * const { output, cleanup } = await durableAgent.stream('Research topic', {\n * untilIdle: true,\n * memory: { thread: 't1', resource: 'u1' },\n * });\n * ```\n */\n untilIdle?: boolean | { maxIdleMs?: number };\n /** When true, the in-loop background task check step skips waiting (streamUntilIdle sets this) */\n _skipBgTaskWait?: boolean;\n /**\n * External abort signal. The durable agent always installs its own internal\n * `AbortController` for the run; when this signal is provided, its `abort`\n * event is forwarded to the internal controller so either source can cancel\n * the run.\n *\n * Cross-process resumes (e.g. Inngest after a worker restart) cannot\n * recover the signal — call `resume(runId, ..., { abortSignal })` with a\n * fresh signal on each segment if you need abortability post-resume.\n */\n abortSignal?: AbortSignal;\n}\n\ntype DurableAgentResumeOptions<OUTPUT = undefined> = DurableAgentStreamOptions<OUTPUT> & {\n toolCallId?: string;\n};\n\n/**\n * Result from DurableAgent.stream()\n */\nexport interface DurableAgentStreamResult<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 for this execution */\n runId: string;\n /** Thread ID if using memory */\n threadId?: string;\n /** Resource ID if using memory */\n resourceId?: string;\n /** Cleanup function to call when done (unsubscribes from pubsub) */\n cleanup: () => void;\n /**\n * Abort the run. Flips the internal `AbortController` for this run, which\n * surfaces as an `AbortError` inside the durable LLM-execution step and\n * is bridged to the user's `onAbort` callback via the run's pubsub topic.\n *\n * Safe to call after the run has already finished — it's a no-op in that\n * case.\n */\n abort: (reason?: unknown) => void;\n}\n\n/**\n * Configuration for DurableAgent - wraps an existing Agent with durable execution\n */\nexport interface DurableAgentConfig<\n TAgentId extends string = string,\n TTools extends ToolsInput = ToolsInput,\n TOutput = undefined,\n> {\n /**\n * The Agent to wrap with durable execution capabilities.\n * All agent methods (getModel, listTools, etc.) delegate to this agent.\n */\n agent: Agent<TAgentId, TTools, TOutput>;\n\n /**\n * Optional ID override. Defaults to agent.id.\n */\n id?: TAgentId;\n\n /**\n * Optional name override. Defaults to agent.name.\n */\n name?: string;\n\n /**\n * PubSub instance for streaming events.\n * Optional - if not provided, defaults to EventEmitterPubSub.\n */\n pubsub?: PubSub;\n\n /**\n * Cache instance for storing stream events.\n * Enables resumable streams - clients can disconnect and reconnect\n * without missing events.\n *\n * - If not provided: Inherits from Mastra instance, or uses InMemoryServerCache\n * - If provided: Uses the provided cache backend (e.g., Redis)\n * - If set to `false`: Disables caching (streams are not resumable)\n */\n cache?: MastraServerCache | false;\n\n /**\n * Maximum steps for the agentic loop.\n * Defaults to the workflow default if not specified.\n */\n maxSteps?: number;\n\n /**\n * Timeout in milliseconds before automatic cleanup of registry entries\n * after a stream finishes or errors. This provides a grace period for\n * late observers to access the stream.\n *\n * Defaults to 30000 (30 seconds).\n * Set to 0 to disable auto-cleanup (manual cleanup() required).\n */\n cleanupTimeoutMs?: number;\n}\n\n/**\n * DurableAgent wraps an existing Agent with durable execution capabilities.\n *\n * Key features:\n * 1. Resumable streams - clients can disconnect and reconnect without missing events\n * 2. Serializable workflow inputs - works with durable execution engines\n * 3. PubSub-based streaming - events flow through pubsub for distribution\n *\n * DurableAgent extends Agent, delegating most methods to the wrapped agent.\n * It overrides stream() to use durable execution with the agentic workflow.\n *\n * Subclasses (EventedAgent, InngestAgent) override executeWorkflow() to\n * customize how the workflow is executed.\n *\n * @example\n * ```typescript\n * import { Agent } from '@mastra/core/agent';\n * import { DurableAgent } from '@mastra/core/agent/durable';\n *\n * const agent = new Agent({\n * id: 'my-agent',\n * instructions: 'You are a helpful assistant',\n * model: openai('gpt-4'),\n * });\n *\n * const durableAgent = new DurableAgent({ agent });\n *\n * const { output, runId, cleanup } = await durableAgent.stream('Hello!');\n * const text = await output.text;\n * cleanup();\n * ```\n */\n\n/**\n * Statuses of durable agent runs discoverable via {@link DurableAgent.listActiveRuns}.\n *\n * `running` is the status reported by the workflow engine while the durable\n * agent's agentic loop is actively executing (i.e. between suspend\n * boundaries). Persisted `running` snapshots are the recovery source for runs\n * orphaned by a process restart.\n */\nexport type DurableAgentActiveRunStatus = Extract<WorkflowRunStatus, 'running'>;\n\n/**\n * Filters for {@link DurableAgent.listActiveRuns}. Mirrors the\n * `listWorkflowRuns` filter contract, plus the agent-level `threadId` /\n * `resourceId` filters used by the base {@link Agent.listSuspendedRuns}.\n */\nexport interface DurableAgentListActiveRunsOptions {\n /** Only return runs that belong to this memory thread. */\n threadId?: string;\n /** Only return runs that belong to this memory resource. */\n resourceId?: string;\n /** Only return runs created at or after this date. */\n fromDate?: Date;\n /** Only return runs created at or before this date. */\n toDate?: Date;\n /**\n * Number of items per page. Pagination is applied when both `perPage` and\n * `page` are provided; otherwise all matching runs are returned.\n */\n perPage?: number;\n /** Zero-indexed page number. */\n page?: number;\n}\n\n/**\n * A durable agent run currently reported as `running` in workflow snapshot\n * storage. These are the runs that a boot-time or operator-initiated\n * recovery would re-drive after a process restart.\n */\nexport interface DurableAgentActiveRun {\n /** Run ID accepted by {@link DurableAgent.recoverActiveRuns} and workflow `restart`. */\n runId: string;\n status: DurableAgentActiveRunStatus;\n threadId?: string;\n resourceId?: string;\n /** When the run's snapshot was last persisted while running. */\n updatedAt: Date;\n}\n\nexport interface DurableAgentListActiveRunsResult {\n runs: DurableAgentActiveRun[];\n /** Total number of matching runs, before pagination. */\n total: number;\n}\n\n/**\n * Outcome of a single run restart attempted by\n * {@link DurableAgent.recoverActiveRuns}. `success` means `run.restart()`\n * returned; `failed` means it threw and the error was captured so recovery\n * of remaining runs could proceed.\n */\nexport interface DurableAgentRecoveredRun {\n runId: string;\n status: 'success' | 'failed';\n /** Populated only when `status === 'failed'`. */\n error?: Error;\n}\n\n/**\n * Filters for {@link DurableAgent.recoverActiveRuns}. Reuses the\n * {@link DurableAgentListActiveRunsOptions} discovery filters and adds an\n * escape hatch for targeting a specific run ID.\n */\nexport interface DurableAgentRecoverActiveRunsOptions extends DurableAgentListActiveRunsOptions {\n /**\n * Recover a specific run by ID. When set, the discovery filters and\n * pagination fields are ignored. Useful when the caller already knows the\n * run ID from another source (e.g. their own bookkeeping).\n */\n runId?: string;\n}\n\nexport interface DurableAgentRecoverActiveRunsResult {\n recovered: DurableAgentRecoveredRun[];\n /** Number of runs that restarted successfully. */\n succeeded: number;\n /** Number of runs whose restart threw. */\n failed: number;\n}\n\n/**\n * Options for {@link DurableAgent.recover}, a single-run streamable recovery\n * counterpart to {@link DurableAgent.resume}.\n *\n * `recover()` rebuilds the run's non-serializable state from the persisted\n * workflow snapshot (message list, model, tools, memory, saveQueueManager,\n * request context, agent span) and returns a fresh {@link DurableAgentStreamResult}\n * whose `fullStream` observes the recovered run through pubsub. Callbacks\n * mirror `stream()` / `resume()`.\n */\nexport interface DurableAgentRecoverOptions<OUTPUT = undefined> {\n /** Callback when chunk is received */\n onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;\n /** Experimental transforms applied whenever `fullStream` is consumed. */\n experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;\n /** Callback when a step finishes */\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n /** Callback when the recovered run finishes */\n onFinish?: MastraOnFinishCallback<OUTPUT>;\n /** Callback when the recovered run errors */\n onError?: ({ error }: { error: Error | string }) => void | Promise<void>;\n /** Callback when the recovered run suspends again */\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n /**\n * Optional abort signal for the recovered segment. Forwarded onto a fresh\n * internal `AbortController` installed on the run's registry entry, so\n * `result.abort()` and the external signal can both cancel the recovered run.\n */\n abortSignal?: AbortSignal;\n}\n\nexport class DurableAgent<\n TAgentId extends string = string,\n TTools extends ToolsInput = ToolsInput,\n TOutput = undefined,\n> extends Agent<TAgentId, TTools, TOutput> {\n /** The wrapped agent */\n readonly #wrappedAgent: Agent<TAgentId, TTools, TOutput>;\n\n /** Registry for per-run non-serializable state */\n readonly #runRegistry: ExtendedRunRegistry;\n\n /** The durable workflow for agent execution */\n #workflow: ReturnType<typeof createDurableAgenticWorkflow> | null = null;\n\n /** Maximum steps for the agentic loop */\n readonly #maxSteps?: number;\n\n /** Inner pubsub (before CachingPubSub wrapper) */\n #innerPubsub: PubSub;\n\n /** Whether the user explicitly provided a pubsub (don't override with mastra.pubsub) */\n readonly #hasCustomPubsub: boolean;\n\n /** User-provided cache (undefined = inherit from mastra, false = disabled) */\n #cacheConfig: MastraServerCache | false | undefined;\n\n /** Resolved cache instance (lazily initialized) */\n #resolvedCache: MastraServerCache | null = null;\n\n /** CachingPubSub instance (lazily initialized) */\n #cachingPubsub: PubSub | null = null;\n\n /** Mastra instance (set via __setMastra when registered) */\n #mastra: Mastra | undefined;\n\n /** Active streamUntilIdle wrappers keyed by scope (threadId|resourceId) */\n #activeStreamUntilIdle = new Map<string, () => void>();\n\n /** Timeout for auto-cleanup after stream finishes (0 = disabled) */\n readonly #cleanupTimeoutMs: number;\n\n /**\n * Create a new DurableAgent that wraps an existing Agent\n */\n constructor(config: DurableAgentConfig<TAgentId, TTools, TOutput>) {\n const { agent, id: idOverride, name: nameOverride, pubsub, cache, maxSteps, cleanupTimeoutMs } = config;\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 ?? agent.id;\n\n // Call Agent constructor with minimal config - we delegate to the wrapped agent\n super({\n id: agentId as TAgentId,\n name: agentName,\n // Delegate to wrapped agent's instructions\n instructions: ({ requestContext }) => agent.getInstructions({ requestContext }),\n // We need to provide model to satisfy the base class, but we'll delegate to wrapped agent\n model: (agent as any).__model ?? agent.getModel(),\n });\n\n this.#wrappedAgent = agent;\n this.#runRegistry = new ExtendedRunRegistry();\n this.#maxSteps = maxSteps;\n this.#hasCustomPubsub = !!pubsub;\n this.#innerPubsub = pubsub ?? new EventEmitterPubSub();\n this.#cacheConfig = cache;\n this.#cleanupTimeoutMs = cleanupTimeoutMs ?? 30_000;\n }\n\n // ===========================================================================\n // Lazy PubSub/Cache initialization (allows inheriting cache from Mastra)\n // ===========================================================================\n\n /**\n * Get the resolved cache instance.\n * Lazily initialized to allow inheriting from Mastra.\n */\n get cache(): MastraServerCache | null {\n this.#ensurePubsubInitialized();\n return this.#resolvedCache;\n }\n\n /**\n * Get the PubSub instance.\n * Returns CachingPubSub if caching is enabled, otherwise the inner pubsub.\n */\n get pubsub(): PubSub {\n this.#ensurePubsubInitialized();\n return this.#cachingPubsub!;\n }\n\n /**\n * Ensure pubsub and cache are initialized.\n * Called lazily on first access to allow inheriting cache from Mastra.\n */\n #ensurePubsubInitialized(): void {\n if (this.#cachingPubsub) return;\n\n if (this.#cacheConfig === false) {\n // Caching explicitly disabled\n this.#cachingPubsub = this.#innerPubsub;\n this.#resolvedCache = null;\n } else if (this.#innerPubsub instanceof CachingPubSub) {\n // The inner pubsub already provides caching/replay. This happens when the\n // user passes a CachingPubSub to `new Mastra({ pubsub })`: on registration\n // the agent adopts mastra.pubsub as its inner transport. Wrapping it again\n // in a second CachingPubSub that shares the same cache would store every\n // event twice (once per layer, with consecutive indices), so observe()/\n // replay would deliver the buffered prefix doubled (issue #18148). Reuse\n // the existing instance instead of double-wrapping.\n this.#cachingPubsub = this.#innerPubsub;\n this.#resolvedCache = this.#cacheConfig ?? this.#mastra?.serverCache ?? null;\n } else {\n // Resolve cache: user-provided > mastra's cache > default InMemoryServerCache\n const resolvedCache = this.#cacheConfig ?? this.#mastra?.serverCache ?? new InMemoryServerCache();\n this.#resolvedCache = resolvedCache;\n this.#cachingPubsub = new CachingPubSub(this.#innerPubsub, resolvedCache);\n }\n }\n\n // ===========================================================================\n // Delegate to wrapped agent\n // ===========================================================================\n\n /**\n * Get the wrapped agent instance.\n */\n get agent(): Agent<TAgentId, TTools, TOutput> {\n return this.#wrappedAgent;\n }\n\n /**\n * Get the run registry (for testing and advanced usage)\n */\n get runRegistry(): ExtendedRunRegistry {\n return this.#runRegistry;\n }\n\n /**\n * Get the max steps configured for this agent\n */\n get maxSteps(): number | undefined {\n return this.#maxSteps;\n }\n\n /**\n * Get the cleanup timeout in milliseconds.\n * Returns 0 if auto-cleanup is disabled.\n */\n get cleanupTimeoutMs(): number {\n return this.#cleanupTimeoutMs;\n }\n\n // ===========================================================================\n // Delegate Agent methods to wrapped agent\n //\n // DurableAgent's super() only passes id, name, instructions, and model.\n // All other private fields (#tools, #memory, #workspace, #processors, etc.)\n // are empty on the DurableAgent instance. Every public/protected method that\n // reads those fields must be overridden to delegate to the wrapped agent.\n // ===========================================================================\n\n // --- Model & LLM ---\n override getModel(options?: any) {\n return this.#wrappedAgent.getModel(options);\n }\n\n override getLLM(options?: any) {\n return this.#wrappedAgent.getLLM(options);\n }\n\n override async getModelList(requestContext?: any) {\n return this.#wrappedAgent.getModelList(requestContext);\n }\n\n // --- Instructions, description, metadata ---\n override getInstructions(options?: any) {\n return this.#wrappedAgent.getInstructions(options);\n }\n\n override getDescription() {\n return this.#wrappedAgent.getDescription();\n }\n\n override getMetadata(options?: any) {\n return this.#wrappedAgent.getMetadata(options);\n }\n\n override getTracingPolicy() {\n return this.#wrappedAgent.getTracingPolicy();\n }\n\n // --- Tools ---\n override listTools(options?: any) {\n return this.#wrappedAgent.listTools(options);\n }\n\n override getConfiguredToolHooks() {\n return this.#wrappedAgent.getConfiguredToolHooks();\n }\n\n // --- Default options ---\n override getDefaultOptions(options?: any) {\n return this.#wrappedAgent.getDefaultOptions(options);\n }\n\n async #resolveExecutionOptions(\n options?: DurableAgentStreamOptions<TOutput>,\n ): Promise<DurableAgentStreamOptions<TOutput>> {\n if ((options as any)?.[RESOLVED_EXECUTION_OPTIONS]) {\n return options!;\n }\n\n const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });\n const resolvedOptions = deepMerge(\n (defaultOptions ?? {}) as Record<string, unknown>,\n (options ?? {}) as Record<string, unknown>,\n ) as DurableAgentStreamOptions<TOutput>;\n // Actor is a per-call trust signal, so an explicit value replaces the\n // default actor as a whole rather than inheriting any of its fields.\n if (options?.actor !== undefined) {\n resolvedOptions.actor = options.actor;\n }\n if ((options as any)?.[CLOSE_ON_SUSPEND] === true) {\n Object.defineProperty(resolvedOptions, CLOSE_ON_SUSPEND, { value: true, enumerable: true });\n }\n // Preserve the marker when the until-idle wrapper spreads these options.\n Object.defineProperty(resolvedOptions, RESOLVED_EXECUTION_OPTIONS, { value: true, enumerable: true });\n return resolvedOptions;\n }\n\n override getDefaultGenerateOptionsLegacy(options?: any) {\n return this.#wrappedAgent.getDefaultGenerateOptionsLegacy(options);\n }\n\n override getDefaultStreamOptionsLegacy(options?: any) {\n return this.#wrappedAgent.getDefaultStreamOptionsLegacy(options);\n }\n\n override getDefaultNetworkOptions(options?: any) {\n return this.#wrappedAgent.getDefaultNetworkOptions(options);\n }\n\n // --- Memory ---\n override getMemory(options?: any) {\n return this.#wrappedAgent.getMemory(options);\n }\n\n override hasOwnMemory(): boolean {\n return this.#wrappedAgent.hasOwnMemory();\n }\n\n // --- Workspace ---\n override getWorkspace(options?: any) {\n return this.#wrappedAgent.getWorkspace(options);\n }\n\n override hasOwnWorkspace(): boolean {\n return this.#wrappedAgent.hasOwnWorkspace?.() ?? false;\n }\n\n // --- Voice ---\n override getVoice(options?: any) {\n return this.#wrappedAgent.getVoice(options);\n }\n\n override get voice() {\n return this.#wrappedAgent.voice;\n }\n\n // --- Request context ---\n override get requestContextSchema() {\n return this.#wrappedAgent.requestContextSchema;\n }\n\n // --- Processors ---\n override async getConfiguredProcessorWorkflows() {\n return this.#wrappedAgent.getConfiguredProcessorWorkflows();\n }\n\n override async listInputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listInputProcessors(requestContext);\n }\n\n override async listOutputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listOutputProcessors(requestContext);\n }\n\n override async listErrorProcessors(requestContext?: any) {\n return this.#wrappedAgent.listErrorProcessors(requestContext);\n }\n\n override async resolveProcessorById<TId extends string = string>(processorId: TId, requestContext?: any) {\n return this.#wrappedAgent.resolveProcessorById(processorId, requestContext);\n }\n\n override async listConfiguredInputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listConfiguredInputProcessors(requestContext);\n }\n\n override async listConfiguredOutputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listConfiguredOutputProcessors(requestContext);\n }\n\n override async getConfiguredProcessorIds(requestContext?: any) {\n return this.#wrappedAgent.getConfiguredProcessorIds(requestContext);\n }\n\n // --- Sub-agents ---\n override listAgents(options?: any) {\n return this.#wrappedAgent.listAgents(options);\n }\n\n override __getStaticAgents() {\n return this.#wrappedAgent.__getStaticAgents();\n }\n\n override __hasSubAgentsConfigured() {\n return this.#wrappedAgent.__hasSubAgentsConfigured();\n }\n\n // --- Workflows ---\n override async listWorkflows(options?: any) {\n return this.#wrappedAgent.listWorkflows(options);\n }\n\n // --- Skills ---\n override async getSkill(skillName: string, options?: any) {\n return this.#wrappedAgent.getSkill(skillName, options);\n }\n\n override async listSkills(options?: any) {\n return this.#wrappedAgent.listSkills(options);\n }\n\n // --- Scorers ---\n override async listScorers(options?: any) {\n return this.#wrappedAgent.listScorers(options);\n }\n\n // --- Background tasks ---\n override getBackgroundTasksConfig() {\n return this.#wrappedAgent.getBackgroundTasksConfig();\n }\n\n override disableBackgroundTasks() {\n this.#wrappedAgent.disableBackgroundTasks();\n }\n\n override enableBackgroundTasks() {\n this.#wrappedAgent.enableBackgroundTasks();\n }\n\n // --- Tool payload transform & goal ---\n override getToolPayloadTransform() {\n return this.#wrappedAgent.getToolPayloadTransform();\n }\n\n override __getGoalConfig() {\n return this.#wrappedAgent.__getGoalConfig();\n }\n\n // --- Browser ---\n override get browser() {\n return this.#wrappedAgent.browser;\n }\n\n override setBrowser(browser: any) {\n this.#wrappedAgent.setBrowser(browser);\n }\n\n override hasOwnBrowser() {\n return this.#wrappedAgent.hasOwnBrowser();\n }\n\n // --- Channels ---\n override getChannels() {\n return this.#wrappedAgent.getChannels();\n }\n\n override setChannels(agentChannels: any) {\n this.#wrappedAgent.setChannels(agentChannels);\n }\n\n // --- PubSub (base Agent fields — DurableAgent has its own pubsub) ---\n override hasOwnPubSub() {\n return this.#wrappedAgent.hasOwnPubSub();\n }\n\n // --- Setters called by AgentController — forward to BOTH wrapper and wrapped ---\n // We propagate to both so that:\n // - The wrapped agent sees the value for its own internal use.\n // - The DurableAgent's inherited getPubSub()/getMemory()/getWorkspace()\n // also work (they read #inheritedPubSub / #memory / #workspace set by super).\n override __setMemory(memory: any) {\n super.__setMemory(memory);\n this.#wrappedAgent.__setMemory(memory);\n }\n\n override __setPubSub(pubsub: any) {\n super.__setPubSub(pubsub);\n this.#wrappedAgent.__setPubSub(pubsub);\n }\n\n override __setWorkspace(workspace: any) {\n super.__setWorkspace(workspace);\n this.#wrappedAgent.__setWorkspace(workspace);\n }\n\n // ===========================================================================\n // Editor / fork delegation\n //\n // The base Agent serves tools/instructions/model from its own private fields,\n // but a DurableAgent serves all of them from the wrapped agent (see the\n // delegating getters above). The editor applies stored overrides per request\n // by calling `__fork()` and then mutating the fork via `__updateInstructions`\n // / `__updateModel` / `__setTools`, and inspecting it via `__getEditorConfig`\n // / `__getOverridableFields`. If those operated on the DurableAgent's own\n // (unused) base fields the served agent would silently lose its tools and\n // ignore overrides, so forward them to the wrapped agent — it stays the single\n // source of truth.\n // ===========================================================================\n\n override __getEditorConfig() {\n return this.#wrappedAgent.__getEditorConfig();\n }\n\n override __getOverridableFields() {\n return this.#wrappedAgent.__getOverridableFields();\n }\n\n override __updateInstructions(instructions: Parameters<Agent<TAgentId, TTools, TOutput>['__updateInstructions']>[0]) {\n this.#wrappedAgent.__updateInstructions(instructions);\n }\n\n override __updateModel(config: Parameters<Agent<TAgentId, TTools, TOutput>['__updateModel']>[0]) {\n this.#wrappedAgent.__updateModel(config);\n }\n\n override __setTools(tools: Parameters<Agent<TAgentId, TTools, TOutput>['__setTools']>[0]) {\n this.#wrappedAgent.__setTools(tools);\n }\n\n /**\n * Create a per-request clone for applying stored editor overrides.\n *\n * The base `Agent.__fork()` builds a bare `new Agent(...)`, which for a\n * DurableAgent would drop the wrapped agent and every delegating override\n * (tools, model, memory, voice, durable streaming) — the served fork ends up a\n * plain `Agent` with no tools. Instead, fork the wrapped agent (so overrides\n * applied to this fork don't mutate the singleton) and re-wrap it in the same\n * durable subclass, preserving pubsub/cache/run configuration.\n *\n * @internal\n */\n override __fork(): Agent<TAgentId, TTools, TOutput> {\n const innerFork = this.#wrappedAgent.__fork();\n\n const Ctor = this.constructor as new (\n config: DurableAgentConfig<TAgentId, TTools, TOutput>,\n ) => DurableAgent<TAgentId, TTools, TOutput>;\n\n const fork = new Ctor({\n agent: innerFork,\n id: this.id,\n name: this.name,\n pubsub: this.#hasCustomPubsub ? this.#innerPubsub : undefined,\n cache: this.#cacheConfig,\n maxSteps: this.#maxSteps,\n cleanupTimeoutMs: this.#cleanupTimeoutMs,\n });\n\n // Preserve runtime state set after construction (mastra registration and the\n // wired inner pubsub, e.g. mastra.pubsub) without re-triggering registration\n // side effects — mirrors Agent.__fork().\n if (this.#mastra) {\n fork.#mastra = this.#mastra;\n }\n fork.#innerPubsub = this.#innerPubsub;\n fork.source = this.source;\n // `_agentNetworkAppend` is a private base-class flag; copy it via an indexed\n // cast (the same idiom the base uses in `toRawConfig()`) so the fork mirrors\n // `Agent.__fork()` without widening the field's visibility.\n (fork as unknown as { _agentNetworkAppend: unknown })._agentNetworkAppend = (\n this as unknown as { _agentNetworkAppend: unknown }\n )._agentNetworkAppend;\n\n // DurableAgent intentionally diverges from Agent's `stream` signature, so the\n // re-wrapped fork is bridged to the base `Agent` return type here. The editor's\n // fork-then-mutate contract only relies on the base Agent surface.\n return fork as unknown as Agent<TAgentId, TTools, TOutput>;\n }\n\n // ===========================================================================\n // Protected methods for subclass overrides\n // ===========================================================================\n\n /**\n * Get the PubSub instance for use by subclasses.\n * @internal\n */\n protected get pubsubInternal(): PubSub {\n return this.pubsub;\n }\n\n /**\n * Get the run registry for use by subclasses.\n * @internal\n */\n protected get runRegistryInternal(): ExtendedRunRegistry {\n return this.#runRegistry;\n }\n\n /**\n * Execute the durable workflow.\n *\n * Subclasses override this method to customize how the workflow is executed:\n * - DurableAgent (this): Runs the workflow directly via createRun + start\n * - EventedAgent: Uses run.startAsync() for fire-and-forget execution\n * - InngestAgent: Uses inngest.send() to trigger Inngest function\n *\n * @param runId - The unique run ID\n * @param workflowInput - The serialized workflow input\n * @internal\n */\n protected async executeWorkflow(runId: string, workflowInput: DurableAgenticWorkflowInput): Promise<void> {\n const workflow = this.getWorkflow();\n const entry = globalRunRegistry.get(runId);\n const requestContext = entry?.requestContext;\n\n const run = await workflow.createRun({ runId, pubsub: this.pubsub });\n // Parent the workflow run under the AGENT_RUN span so the trace exports under it.\n const result = await run.start({\n inputData: workflowInput,\n requestContext,\n actor: workflowInput.options?.actor,\n ...createObservabilityContext({ currentSpan: entry?.agentSpan }),\n });\n if (result?.status === 'failed') {\n const error = new Error((result as any).error?.message || 'Workflow execution failed');\n await this.emitError(runId, error);\n }\n // Reaching any non-suspended terminal status means the run is done and its\n // persisted snapshot rows will never be resumed. Delete them so snapshot\n // storage doesn't grow one stale row per completed run. Suspended runs\n // keep their snapshots so `resume()` / `recoverActiveRuns()` can find them.\n if (result?.status && result.status !== 'suspended') {\n await this.deleteRunSnapshots(runId);\n }\n }\n\n /**\n * Create the durable workflow for this agent.\n *\n * Subclasses can override this method to use a different workflow implementation:\n * - DurableAgent (this): Uses createDurableAgenticWorkflow()\n * - InngestAgent: Uses createInngestDurableAgenticWorkflow()\n *\n * @internal\n */\n protected createWorkflow(): ReturnType<typeof createDurableAgenticWorkflow> {\n return createDurableAgenticWorkflow({\n maxSteps: this.#maxSteps,\n });\n }\n\n /**\n * Emit an error event to pubsub.\n *\n * @param runId - The run ID\n * @param error - The error to emit\n * @internal\n */\n protected async emitError(runId: string, error: Error): Promise<void> {\n // End the root spans on error so the trace exports (mirrors the non-durable map-results-step).\n endRunSpansWithError(runId, error);\n await emitErrorEvent(this.pubsub, runId, error);\n }\n\n /**\n * Delete the persisted workflow snapshot rows for a completed durable run.\n *\n * A durable agent write two rows per run: one for the outer `AGENTIC_LOOP`\n * workflow and one for the nested `AGENTIC_EXECUTION` workflow (persisted\n * under the same `runId`). Once the run reaches a non-suspended terminal\n * state neither row is needed again — leaving them behind fills snapshot\n * storage with stale `pending`/`running` rows for every completed run and\n * pollutes `listActiveRuns` / `recoverActiveRuns` on the next boot.\n *\n * Best-effort: a cleanup failure must never turn a finished run into an\n * error — a stale row is preferable to a broken exit path.\n *\n * @internal\n */\n protected async deleteRunSnapshots(runId: string): Promise<void> {\n try {\n const workflow = this.getWorkflow();\n await workflow.deleteWorkflowRunById(runId);\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n await workflowsStore?.deleteWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_EXECUTION,\n });\n } catch (error) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] Failed to delete workflow snapshot rows after terminal state`, { runId, error });\n }\n }\n\n // ===========================================================================\n // Public API\n // ===========================================================================\n\n /**\n * Stream a response from the agent using durable execution.\n */\n // @ts-expect-error - Intentionally different signature for durable execution\n async stream(\n messages: MessageListInput,\n options?: DurableAgentStreamOptions<TOutput>,\n ): Promise<DurableAgentStreamResult<TOutput>> {\n options = await this.#resolveExecutionOptions(options);\n\n // Delegate to the idle-loop wrapper when `untilIdle` is set.\n // Strip `untilIdle` before passing to the wrapper so its internal\n // agent.stream() call doesn't recurse.\n if (options?.untilIdle) {\n const { untilIdle, ...rest } = options;\n const maxIdleMs = typeof untilIdle === 'object' ? untilIdle.maxIdleMs : undefined;\n // The idle helper normally resolves defaults for scope discovery. These\n // options are already resolved, so keep its inner stream on the same values.\n const resolvedOptionsAgent = {\n id: this.id,\n getDefaultOptions: () => ({}),\n getMemory: (args?: any) => this.getMemory(args),\n stream: (innerMessages: MessageListInput, innerOptions?: DurableAgentStreamOptions<TOutput>) =>\n this.stream(innerMessages, innerOptions),\n } as unknown as DurableAgent<any, any, TOutput>;\n return runDurableStreamUntilIdle<TOutput>(\n resolvedOptionsAgent,\n messages,\n { ...rest, maxIdleMs },\n {\n activeStreams: this.#activeStreamUntilIdle,\n bgManager: this.#mastra?.backgroundTaskManager,\n },\n );\n }\n\n // Enforce agent-level FGA (agents:execute) before durable execution. The\n // base Agent enforces this in its stream()/generate(); durable execution\n // runs a workflow instead and would otherwise skip the gate. This also\n // covers evented subclasses, which inherit stream()/generate().\n await this.requireAgentExecutionFGA({\n requestContext: options?.requestContext,\n memory: options?.memory,\n runId: options?.runId,\n actor: options?.actor,\n });\n\n // 1. Prepare for durable execution (non-durable phase)\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options: options as AgentExecutionOptions<TOutput>,\n runId: options?.runId,\n requestContext: options?.requestContext,\n optionsAreResolved: true,\n mastra: this.#mastra,\n durableAgentId: this.id,\n durableAgentName: this.name,\n });\n\n const { runId, messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;\n\n // 1a. Install the abort controller for this run. The controller is owned\n // by this DurableAgent instance; the result's abort() method flips it,\n // and the durable LLM-execution step reads `abortSignal` off the registry\n // to thread it into the model call + abort short-circuits. If the caller\n // also supplied an external signal, forward its abort to the internal\n // controller so either source can cancel the run.\n const abortController = new AbortController();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) {\n abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n options.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n registryEntry.abortController = abortController;\n registryEntry.abortSignal = abortController.signal;\n\n // 2. Register non-serializable state (both local and global registries)\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n globalRunRegistry.set(runId, { ...registryEntry, messageList });\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Schedule automatic registry cleanup after stream ends\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n // 3. Create the durable agent stream (subscribes to pubsub)\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\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: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n onAbort: async data => {\n try {\n await (options?.onAbort as ((event: any) => void | Promise<void>) | undefined)?.(data);\n } finally {\n scheduleAutoCleanup();\n }\n },\n // onIterationComplete is NOT forwarded here — the dowhile predicate\n // now calls it in-process from globalRunRegistry and honors its return\n // value ({ continue, feedback }). The pubsub ITERATION_COMPLETE event\n // still fires for external observability subscribers.\n closeOnSuspend: (options as any)?.[CLOSE_ON_SUSPEND] === true,\n structuredOutput: registryEntry.structuredOutput as any,\n outputProcessors: registryEntry.outputProcessors,\n messageList,\n });\n\n // 4. Wait for subscription to be ready, then execute workflow\n // This prevents race conditions where events are published before subscription\n const workflowExecution = ready\n .then(async () => {\n // Emit 'start' chunk before the workflow begins (matches regular agent's stream.ts).\n // Only the initial stream() path emits 'start'; resume() does not.\n await emitChunkEvent(this.pubsub, runId, {\n type: 'start',\n runId,\n from: ChunkFrom.AGENT,\n payload: { id: workflowInput.agentId, messageId },\n });\n if (this.__getGoalConfig()) {\n await beginGoalActivity({\n mastra: this.#mastra,\n agentId: workflowInput.agentId,\n threadId,\n runId,\n requestContext: globalRunRegistry.get(runId)?.requestContext,\n });\n }\n try {\n return await this.executeWorkflow(runId, workflowInput);\n } finally {\n await stopGoalActivity({ agentId: workflowInput.agentId, runId });\n }\n })\n .catch(error => {\n void this.emitError(runId, error);\n });\n const trackedEntry = globalRunRegistry.get(runId);\n if (trackedEntry) {\n trackedEntry.workflowExecution = workflowExecution;\n }\n\n // 4b. Register with the thread-stream runtime so subscribeToThread /\n // sendMessage subscribers receive run-registered events and stream parts.\n // Uses the Mastra-level pubsub (this.getPubSub()) — not the internal\n // CachingPubSub (this.pubsub) which carries durable workflow chunks.\n await agentThreadStreamRuntime.registerRun(\n this as unknown as Agent<any, any, any, any>,\n output,\n options as AgentExecutionOptions<TOutput>,\n this.getPubSub(),\n );\n\n // 5. Create cleanup function (cancels auto-cleanup timer if called)\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId,\n resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Resume a suspended workflow execution.\n */\n async resume(\n runId: string,\n resumeData: unknown,\n options?: DurableAgentResumeOptions<TOutput>,\n ): Promise<DurableAgentStreamResult<TOutput>> {\n let entry = this.#runRegistry.get(runId);\n if (!entry) {\n // A persisted durable run can outlive this process (or the registry TTL).\n // Rebuild the non-serializable runtime state before resuming the stored\n // workflow snapshot. Keep warm resumes on the existing path to avoid\n // racing an active registry entry with a second preparation pass.\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n const persisted = await workflowsStore?.getWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_LOOP,\n });\n if (!persisted) {\n throw new Error(`No registry entry found for run ${runId}. Cannot resume.`);\n }\n\n const snapshot =\n typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n if (snapshot?.status !== 'suspended') {\n throw new Error('This workflow run was not suspended');\n }\n const workflowInput = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (!workflowInput || workflowInput.__workflowKind !== 'durable-agent') {\n throw new MastraError({\n id: 'DURABLE_AGENT_RESUME_INVALID_SNAPSHOT',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n text: `DurableAgent \"${this.name}\" resume(${runId}): persisted snapshot does not contain a durable-agent workflow input.`,\n details: { agentName: this.name, runId },\n });\n }\n if (workflowInput.agentId !== this.id) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RESUME_AGENT_MISMATCH',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}): persisted run belongs to agent \"${workflowInput.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: workflowInput.agentId },\n });\n }\n\n const messageListMemoryInfo = (\n workflowInput.messageListState as { memoryInfo?: { threadId?: string; resourceId?: string } } | undefined\n )?.memoryInfo;\n const threadId = workflowInput.state?.threadId ?? messageListMemoryInfo?.threadId;\n const resourceId = workflowInput.state?.resourceId ?? messageListMemoryInfo?.resourceId;\n const snapshotRequestContext = workflowInput.requestContextEntries\n ? new RequestContext<unknown>(Object.entries(workflowInput.requestContextEntries))\n : undefined;\n const memory = threadId\n ? {\n ...options?.memory,\n thread: threadId,\n resource: resourceId ?? options?.memory?.resource,\n }\n : options?.memory;\n\n await this.prepare([], {\n ...(options as AgentExecutionOptions<TOutput>),\n runId,\n requestContext: options?.requestContext ?? snapshotRequestContext,\n memory,\n });\n entry = this.#runRegistry.get(runId);\n }\n if (!entry) {\n throw new Error(`Failed to rehydrate registry entry for run ${runId}. Cannot resume.`);\n }\n\n const memoryInfo = this.#runRegistry.getMemoryInfo(runId);\n const registeredMemory = memoryInfo?.threadId\n ? ({\n ...options?.memory,\n thread: memoryInfo.threadId,\n resource: memoryInfo.resourceId ?? options?.memory?.resource,\n } as DurableAgentStreamOptions<TOutput>['memory'])\n : options?.memory;\n\n const resolvedOptions = (await this.#resolveExecutionOptions({\n ...(options as DurableAgentStreamOptions<TOutput>),\n requestContext:\n options?.requestContext ??\n (entry.requestContext as DurableAgentStreamOptions<TOutput>['requestContext'] | undefined),\n memory: registeredMemory ?? options?.memory,\n })) as DurableAgentResumeOptions<TOutput>;\n\n // Delegate to the idle-loop wrapper when `untilIdle` is set. Strip\n // `untilIdle` before passing to the wrapper so the inner agent.resume()\n // call (and subsequent agent.stream([]) continuations) don't recurse.\n if (resolvedOptions.untilIdle) {\n const { untilIdle, ...rest } = resolvedOptions;\n const maxIdleMs = typeof untilIdle === 'object' ? untilIdle.maxIdleMs : undefined;\n const resolvedOptionsAgent = {\n id: this.id,\n getDefaultOptions: () => ({}),\n getMemory: (args?: any) => this.getMemory(args),\n resume: (innerRunId: string, innerResumeData: unknown, innerOptions?: DurableAgentResumeOptions<TOutput>) =>\n this.resume(innerRunId, innerResumeData, innerOptions),\n stream: (innerMessages: MessageListInput, innerOptions?: DurableAgentStreamOptions<TOutput>) =>\n this.stream(innerMessages, innerOptions),\n } as unknown as DurableAgent<any, any, TOutput>;\n return runResumeDurableStreamUntilIdle<TOutput>(\n resolvedOptionsAgent,\n runId,\n resumeData,\n { ...rest, maxIdleMs } as DurableAgentStreamOptions<TOutput> & { maxIdleMs?: number },\n {\n activeStreams: this.#activeStreamUntilIdle,\n bgManager: this.#mastra?.backgroundTaskManager,\n },\n );\n }\n\n await this.requireAgentExecutionFGA({\n requestContext: resolvedOptions.requestContext,\n memory: resolvedOptions.memory,\n runId,\n snapshotMemoryInfo: memoryInfo,\n actor: resolvedOptions.actor,\n });\n\n // Install a fresh abort controller for the resumed segment. The original\n // controller is gone (the stream that owned it has already settled), so\n // we overwrite the registry slot. If the caller passed an external\n // signal, forward it onto the new internal controller.\n const abortController = new AbortController();\n if (resolvedOptions.abortSignal) {\n if (resolvedOptions.abortSignal.aborted) {\n abortController.abort((resolvedOptions.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n resolvedOptions.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((resolvedOptions.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n entry.abortController = abortController;\n entry.abortSignal = abortController.signal;\n const globalEntryForAbort = globalRunRegistry.get(runId);\n if (globalEntryForAbort) {\n globalEntryForAbort.abortController = abortController;\n globalEntryForAbort.abortSignal = abortController.signal;\n }\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n const globalEntry = globalRunRegistry.get(runId);\n const resumeModel = globalEntry?.model as any;\n\n // Skip events already broadcast by the original run (e.g. the SUSPENDED\n // chunk that paused it). Without this, a resume that closes on suspend\n // (resumeGenerate) would immediately close on the replayed SUSPENDED.\n const resumeOffset = await this.#getPubsubOffset(runId);\n\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n messageId: crypto.randomUUID(),\n model: {\n modelId: resumeModel?.modelId,\n provider: resumeModel?.provider,\n version: 'v3',\n },\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n offset: resumeOffset,\n onChunk: resolvedOptions.onChunk,\n experimentalTransform: resolvedOptions.experimentalTransform,\n onStepFinish: resolvedOptions.onStepFinish,\n onFinish: resolvedOptions.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await resolvedOptions.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: resolvedOptions.onSuspended,\n closeOnSuspend: (resolvedOptions as any)[CLOSE_ON_SUSPEND] === true,\n structuredOutput: entry.structuredOutput as any,\n outputProcessors: entry.outputProcessors,\n messageList: globalEntry?.messageList ?? this.#runRegistry.getMessageList(runId),\n });\n\n // Wait for subscription to be ready, then resume workflow\n const workflow = this.getWorkflow();\n const requestContext = resolvedOptions.requestContext;\n\n // Open a fresh AGENT_RUN + MODEL_GENERATION for the resumed segment on the same\n // traceId — the originals were ended as `suspended` and can't be reopened. Post-resume\n // steps + terminal end() target these via the registry override. (Linking = follow-up.)\n const origTraceId = entry.agentSpan?.traceId;\n const origSpanId = entry.agentSpan?.id;\n if (origTraceId && this.#mastra?.observability) {\n try {\n const ag = this.#wrappedAgent as Agent<string, any, any>;\n // Match non-durable Agent.stream() resume-span shape: same name suffix\n // `(resumed)`, forward agent-level tracingPolicy, link to the original\n // span via `resumedFromSpanId` metadata, and carry the resolvedVersionId.\n const rawConfig = typeof (ag as any).toRawConfig === 'function' ? (ag as any).toRawConfig() : undefined;\n const resolvedVersionId = rawConfig?.resolvedVersionId as string | undefined;\n const agentTracingPolicy = typeof ag.getTracingPolicy === 'function' ? ag.getTracingPolicy() : undefined;\n const resumeAgentSpan = getOrCreateSpan({\n type: SpanType.AGENT_RUN,\n name: `agent run: '${ag.id}' (resumed)`,\n entityType: EntityType.AGENT,\n entityId: ag.id,\n entityName: ag.name,\n metadata: {\n runId,\n resumed: true,\n ...(origSpanId ? { resumedFromSpanId: origSpanId } : {}),\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n tracingPolicy: agentTracingPolicy,\n tracingOptions: { traceId: origTraceId },\n requestContext,\n mastra: this.#mastra,\n });\n const resumeModelSpan = resumeAgentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n name: `llm: '${resumeModel?.modelId ?? ''}'`,\n attributes: { model: resumeModel?.modelId, provider: resumeModel?.provider, streaming: true },\n metadata: { runId, resumed: true },\n requestContext,\n });\n for (const reg of [entry, globalRunRegistry.get(runId)]) {\n if (!reg) continue;\n reg.resumeAgentSpan = resumeAgentSpan;\n reg.resumeModelSpan = resumeModelSpan;\n reg.resumeAgentSpanData = resumeAgentSpan?.exportSpan();\n reg.resumeModelSpanData = resumeModelSpan?.exportSpan();\n }\n } catch (error) {\n // Span bookkeeping must never block resume.\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open resume spans: ${error}`);\n }\n }\n\n // Capture the prior workflow execution BEFORE creating the new promise.\n // If we read it inside the `.then()` callback, the global registry will\n // already point to the NEW promise (assigned synchronously below),\n // causing a self-referential deadlock.\n const priorExecution = globalRunRegistry.get(runId)?.workflowExecution;\n\n const workflowExecution = ready\n .then(async () => {\n // Wait for the prior workflow execution (stream / previous resume) to\n // fully settle so the snapshot is persisted as 'suspended' before we\n // attempt to resume it. Without this, the pubsub tool-call-suspended\n // event can arrive (and the consumer can call resumeStream) before the\n // engine has finished writing the snapshot, leading to\n // \"This workflow run was not suspended\".\n if (priorExecution) {\n await priorExecution.catch(() => {\n /* errors already handled by the prior segment */\n });\n }\n\n const run = await workflow.createRun({ runId, pubsub: this.pubsub });\n if (this.__getGoalConfig()) {\n await beginGoalActivity({\n mastra: this.#mastra,\n agentId: this.id,\n threadId: memoryInfo?.threadId,\n runId,\n requestContext,\n });\n }\n let result;\n try {\n result = await run.resume({\n resumeData,\n label: resolvedOptions.toolCallId,\n requestContext,\n actor: resolvedOptions.actor,\n ...createObservabilityContext({ currentSpan: entry.resumeAgentSpan ?? entry.agentSpan }),\n });\n } finally {\n await stopGoalActivity({ agentId: this.id, runId });\n }\n if (result?.status === 'failed') {\n const error = new Error((result as any).error?.message || 'Workflow resume failed');\n void this.emitError(runId, error);\n }\n // Same snapshot cleanup as the initial `start()` path: once resume\n // settles on any non-suspended terminal status the persisted rows are\n // no longer needed. A resume that re-suspends must keep them so the\n // next resume/recover can find the snapshot.\n if (result?.status && result.status !== 'suspended') {\n await this.deleteRunSnapshots(runId);\n }\n })\n .catch(error => {\n void this.emitError(runId, error);\n });\n const trackedResumeEntry = globalRunRegistry.get(runId);\n if (trackedResumeEntry) {\n trackedResumeEntry.workflowExecution = workflowExecution;\n }\n\n // Register the resumed run with the thread-stream runtime so\n // subscribeToThread subscribers are notified of the new stream.\n const resumeStreamOptions: AgentExecutionOptions<TOutput> = {\n ...resolvedOptions,\n runId,\n } as AgentExecutionOptions<TOutput>;\n await agentThreadStreamRuntime.registerRun(\n this as unknown as Agent<any, any, any, any>,\n output,\n resumeStreamOptions,\n this.getPubSub(),\n );\n\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Recover a single durable run whose in-process agentic loop was orphaned by\n * a process restart. Streamable counterpart to\n * {@link DurableAgent.recoverActiveRuns} — where the bulk API only re-drives\n * the workflow and returns counts, `recover()` rebuilds the run's\n * non-serializable state (message list, model, tools, memory,\n * saveQueueManager, request context, agent span) from the persisted workflow\n * snapshot and returns a fresh {@link DurableAgentStreamResult} whose\n * `fullStream` observes the recovered run through pubsub.\n *\n * Because the rebuilt registry entry carries `memory` + `saveQueueManager`,\n * the durable agentic workflow's terminal step will flush new messages to\n * memory just like a fresh `stream()` call would. The single-run form is\n * useful when operators want to attach listeners to a specific recovered\n * run; for boot-time bulk recovery of every orphaned run, use\n * `recoverActiveRuns()`.\n *\n * @example\n * ```typescript\n * const { fullStream, output, cleanup } = await durableAgent.recover(runId, {\n * onChunk: chunk => process.stdout.write(chunk.payload?.text ?? ''),\n * });\n * for await (const chunk of fullStream) {\n * // ...\n * }\n * cleanup();\n * ```\n */\n async recover(\n runId: string,\n options?: DurableAgentRecoverOptions<TOutput>,\n ): Promise<DurableAgentStreamResult<TOutput>> {\n if (!this.#mastra) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_NO_MASTRA',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" recover() requires the agent to be registered on a Mastra instance.`,\n details: { agentName: this.name, runId },\n });\n }\n\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n if (!workflowsStore) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_NO_STORAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" recover() requires persistent storage to load the run snapshot. ` +\n `Register the agent on a Mastra instance with persistent storage (e.g. PostgreSQL, LibSQL).`,\n details: { agentName: this.name, runId },\n });\n }\n\n // 1. Load the persisted snapshot for the durable agentic loop workflow.\n const persisted = await workflowsStore.getWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_LOOP,\n });\n if (!persisted) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" recover(${runId}): no persisted workflow snapshot found. ` +\n `The run may have already completed or been cleaned up.`,\n details: { agentName: this.name, runId },\n });\n }\n\n const snapshot =\n typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n\n const workflowInput = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (!workflowInput || workflowInput.__workflowKind !== 'durable-agent') {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_INVALID_SNAPSHOT',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n text: `DurableAgent \"${this.name}\" recover(${runId}): persisted snapshot does not contain a durable-agent workflow input.`,\n details: { agentName: this.name, runId },\n });\n }\n\n // All durable agents share the same workflow name (`durable-agentic-loop`),\n // so a caller with runId in hand could otherwise recover another agent's\n // run. Refuse to rehydrate a snapshot whose agentId doesn't match this\n // instance — the caller must reach the owning agent to recover the run.\n if (workflowInput.agentId !== this.id) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_AGENT_MISMATCH',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" recover(${runId}): persisted run belongs to agent \"${workflowInput.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: workflowInput.agentId },\n });\n }\n\n // 2. Rebuild the RequestContext from the persisted JSON-safe snapshot.\n const requestContext: RequestContext = workflowInput.requestContextEntries\n ? new RequestContext(Object.entries(workflowInput.requestContextEntries) as Iterable<readonly [string, unknown]>)\n : new RequestContext();\n\n // 3. Rebuild MessageList from the persisted state. threadId/resourceId\n // come from the workflow input's `state` block when present; older\n // snapshots may only have them under `messageListState.memoryInfo`.\n const messageListMemoryInfo = (\n workflowInput.messageListState as { memoryInfo?: { threadId?: string; resourceId?: string } } | undefined\n )?.memoryInfo;\n const threadId = workflowInput.state?.threadId ?? messageListMemoryInfo?.threadId;\n const resourceId = workflowInput.state?.resourceId ?? messageListMemoryInfo?.resourceId;\n const messageList = new MessageList({ threadId, resourceId });\n try {\n messageList.deserialize(workflowInput.messageListState);\n } catch (err) {\n // Fresh (never-executed) snapshots may have a minimal `messageListState`;\n // fall back to an empty MessageList so recovery still proceeds. The\n // workflow steps rebuild the real MessageList from serialized input.\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) messageList deserialize skipped: ${err}`);\n }\n\n // 4. Resolve model/memory from the live agent. Tools are rebuilt by the\n // durable step from `toolsMetadata`, so we only need the live agent's\n // memory here to enable message persistence at the terminal step.\n const wrapped = this.#wrappedAgent as Agent<string, any, TOutput>;\n let model;\n try {\n model = await wrapped.getModel({ requestContext });\n } catch (err) {\n const logger = this.#mastra?.getLogger?.();\n logger?.warn?.(`[DurableAgent] Failed to resolve model during recover(${runId}): ${err}`);\n }\n let memory;\n try {\n memory = await wrapped.getMemory({ requestContext });\n } catch (err) {\n const logger = this.#mastra?.getLogger?.();\n logger?.warn?.(`[DurableAgent] Failed to resolve memory during recover(${runId}): ${err}`);\n }\n const saveQueueManager = memory\n ? new SaveQueueManager({ logger: this.#mastra?.getLogger?.() as any, memory })\n : undefined;\n\n // Re-wire background-task state so the recovered segment can wait for\n // pre-crash tasks (via `bg-task-check`), dispatch new background tool\n // calls (via `tool-call`), and inject the background-task system prompt\n // (via `llm-execution`). The manager is storage-backed, so in-flight\n // tasks spawned before the crash are still discoverable via\n // `bgManager.listTasks(...)`.\n const backgroundTasksConfig = this.getBackgroundTasksConfig?.();\n const backgroundTaskManager = this.#mastra?.backgroundTaskManager;\n\n // Re-resolve processors from the live agent config. `llm-execution` reads\n // `inputProcessors` / `llmRequestInputProcessors` / `outputProcessors` from\n // the global registry, and the terminal `.map(...)` reads `outputProcessors`\n // + `errorProcessors` — without these, the recovered segment would run\n // with no processors even if the agent has some configured.\n let inputProcessors: any[] = [];\n let llmRequestInputProcessors: any[] = [];\n let outputProcessors: any[] = [];\n let errorProcessors: any[] = [];\n try {\n inputProcessors = (await (wrapped as any).listInputProcessors?.(requestContext)) ?? [];\n llmRequestInputProcessors = (await (wrapped as any).__listLLMRequestProcessors?.(requestContext)) ?? [];\n outputProcessors = (await (wrapped as any).listOutputProcessors?.(requestContext)) ?? [];\n errorProcessors = (await (wrapped as any).listErrorProcessors?.(requestContext)) ?? [];\n } catch (err) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) processor resolution failed: ${err}`);\n }\n // Fresh empty processorStates for the recovered segment — the pre-crash\n // segment's in-memory processor state is gone, but the terminal state\n // (memory writes, message list) lives on the persisted snapshot.\n const processorStates = new Map<string, any>();\n\n // 5. Re-open an AGENT_RUN span for the recovered segment. Follow the same\n // pattern as resume(): reuse the original traceId when possible so the\n // recovered run stays linked to the original agent trace.\n const abortController = new AbortController();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) {\n abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n options.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n\n const origAgentSpanData = workflowInput.agentSpanData as { traceId?: string; id?: string } | undefined;\n let recoverAgentSpan: any;\n if (this.#mastra?.observability) {\n try {\n const rawConfig =\n typeof (wrapped as any).toRawConfig === 'function' ? (wrapped as any).toRawConfig() : undefined;\n const resolvedVersionId = rawConfig?.resolvedVersionId as string | undefined;\n const agentTracingPolicy =\n typeof wrapped.getTracingPolicy === 'function' ? wrapped.getTracingPolicy() : undefined;\n recoverAgentSpan = getOrCreateSpan({\n type: SpanType.AGENT_RUN,\n name: `agent run: '${wrapped.id}' (recovered)`,\n entityType: EntityType.AGENT,\n entityId: wrapped.id,\n entityName: wrapped.name,\n metadata: {\n runId,\n recovered: true,\n ...(origAgentSpanData?.id ? { recoveredFromSpanId: origAgentSpanData.id } : {}),\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n tracingPolicy: agentTracingPolicy,\n tracingOptions: origAgentSpanData?.traceId ? { traceId: origAgentSpanData.traceId } : undefined,\n requestContext,\n mastra: this.#mastra,\n });\n } catch (err) {\n // Span bookkeeping must never block recovery.\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open recover span: ${err}`);\n }\n }\n\n // 6. Assemble a minimal RunRegistryEntry. Fields that the durable steps\n // would normally populate on the fly (tools, workspace, processor\n // states, etc.) are left undefined — the workflow's own\n // `resolveRuntimeDependencies` will fall back to the persisted step\n // input to reconstruct them, so we only need the fields that the\n // terminal `.map(...)` step and stream adapter read from the registry:\n // saveQueueManager + memory + agentSpan + abortController.\n const registryEntry: any = {\n model,\n memory,\n saveQueueManager,\n requestContext,\n agentSpan: recoverAgentSpan,\n abortController,\n abortSignal: abortController.signal,\n backgroundTaskManager,\n backgroundTasksConfig,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n cleanup: () => {},\n };\n\n // 7. Register the reconstructed state in both the per-instance and global\n // registries so the workflow steps + terminal memory flush can find it.\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n globalRunRegistry.set(runId, { ...registryEntry, messageList });\n\n // 8. Cleanup plumbing (mirrors stream()/resume()).\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n // 9. Skip any pubsub events broadcast before recovery started. Persistent\n // pubsub backends may retain chunks from the pre-crash segment; the\n // caller only wants events from the recovered segment forward.\n const recoverOffset = await this.#getPubsubOffset(runId);\n\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n messageId: workflowInput.messageId ?? crypto.randomUUID(),\n model: {\n modelId: workflowInput.modelConfig?.modelId,\n provider: workflowInput.modelConfig?.provider,\n version: 'v3',\n },\n threadId,\n resourceId,\n offset: recoverOffset,\n onChunk: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n // Recovered runs use the default `closeOnSuspend: false` — a run that\n // suspends again should stay observable so a later resume/recover can\n // pick it up. Callers wanting to close on suspend can call `cleanup()`\n // from `onSuspended`.\n messageList,\n });\n\n // 10. Re-drive the workflow from the persisted snapshot in the background\n // and delete snapshot rows on non-suspended terminals (same contract\n // as start()/resume()). Errors are also broadcast via `emitError` so\n // observers on the pubsub topic see the failure. Callers who await\n // the returned `workflowExecution` (e.g. `recoverActiveRuns()`) see\n // the raw rejection so they can classify the run as failed.\n const workflow = this.getWorkflow();\n const workflowExecution = ready.then(async () => {\n try {\n const run = await workflow.createRun({ runId, pubsub: this.pubsub });\n const result = await run.restart({\n requestContext,\n ...createObservabilityContext({ currentSpan: recoverAgentSpan }),\n } as any);\n // Snapshot cleanup runs for every non-suspended terminal (success or\n // failed) so storage stays bounded — mirrors the start()/resume()\n // contract.\n if (result?.status && result.status !== 'suspended') {\n await this.deleteRunSnapshots(runId);\n }\n if (result?.status === 'failed') {\n const error = new Error((result as any).error?.message || 'Workflow recover failed');\n void this.emitError(runId, error);\n throw error;\n }\n } catch (error) {\n void this.emitError(runId, error as Error);\n throw error;\n }\n });\n const trackedRecoverEntry = globalRunRegistry.get(runId);\n if (trackedRecoverEntry) {\n trackedRecoverEntry.workflowExecution = workflowExecution;\n }\n // Guard against unhandled rejection warnings for callers who don't await\n // `workflowExecution` (single-run `recover()` returns a stream, not the\n // workflow promise). Errors are already surfaced through `emitError` /\n // the stream's `onError` callback.\n workflowExecution.catch(() => {});\n\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId,\n resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Override the inherited `resumeStream()` so that callers using the base\n * `Agent` API (including `approveToolCall` / `declineToolCall`) are routed\n * through the durable `resume()` path instead of the regular Agent's\n * snapshot-based resume.\n *\n * Returns just the `MastraModelOutput` (matching the base Agent's return\n * type) while internally delegating to `this.resume()`.\n */\n override async resumeStream(resumeData: any, streamOptions?: any): Promise<MastraModelOutput<TOutput>> {\n const runId = streamOptions?.runId;\n if (!runId) {\n throw new Error('resumeStream() on DurableAgent requires a runId in streamOptions.');\n }\n const { runId: _runId, ...resumeOptions } = streamOptions;\n const result = await this.resume(runId, resumeData, {\n ...resumeOptions,\n // Close the stream when the workflow re-suspends so the caller's\n // `for await` loop terminates. Without this the stream stays open\n // indefinitely when the resumed turn hits another suspend point.\n [CLOSE_ON_SUSPEND]: true,\n } as Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2]);\n return result.output;\n }\n\n /**\n * Override the inherited `approveToolCall()` to route through the durable\n * `resume()` path.\n */\n override async approveToolCall(\n options: { runId: string; toolCallId?: string } & Record<string, any>,\n ): Promise<MastraModelOutput<any>> {\n return this.resumeStream({ approved: true }, options);\n }\n\n /**\n * Override the inherited `declineToolCall()` to route through the durable\n * `resume()` path.\n */\n override async declineToolCall(\n options: { runId: string; toolCallId?: string } & Record<string, any>,\n ): Promise<MastraModelOutput<any>> {\n return this.resumeStream({ approved: false }, options);\n }\n\n override async approveToolCallGenerate<OUTPUT = undefined>(\n options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string },\n ): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['getFullOutput']>>> {\n const { runId, ...resumeOptions } = options;\n return this.resumeGenerate(runId, { approved: true }, resumeOptions as any) as any;\n }\n\n override async declineToolCallGenerate<OUTPUT = undefined>(\n options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string },\n ): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['getFullOutput']>>> {\n const { runId, ...resumeOptions } = options;\n return this.resumeGenerate(runId, { approved: false }, resumeOptions as any) as any;\n }\n\n /**\n * Generate a complete response from the agent using durable execution.\n *\n * Drains the underlying durable stream to completion and returns the same\n * {@link FullOutput} shape as non-durable `Agent.generate`. The underlying\n * workflow is identical to `stream()` — it just collects the final result\n * for callers that don't want to consume chunks themselves.\n *\n * This method intentionally re-implements the `stream()` setup rather than\n * delegating to `this.stream(...)` so that `prepareForDurableExecution` (and\n * downstream `convertTools`) receives `methodType: 'generate'`. Tool\n * factories that vary their `CoreTool` output based on the calling method\n * (e.g. `clientTools` vs server-side tools) rely on this signal — calling\n * `stream()` here would silently pass `methodType: 'stream'`.\n *\n * If the run suspends (e.g. tool approval or `suspend()` from a tool), the\n * returned output's `finishReason` will be `'suspended'` and\n * `suspendPayload` will be populated. Use {@link DurableAgent.resumeGenerate}\n * to continue.\n *\n * Note on suspend persistence: for the base `DurableAgent`, the workflow\n * engine's `run.start()` only resolves after the suspend snapshot is\n * persisted, so awaiting `workflowExecution` on suspend is sufficient for\n * a subsequent `resumeGenerate()` to find the snapshot. Subclasses like\n * `EventedAgent` use a fire-and-forget `run.startAsync()` and therefore\n * cannot rely on this await for snapshot durability — see the\n * `EventedAgent` docs for the recommended pattern.\n */\n // @ts-expect-error - Intentionally different signature for durable execution\n async generate(\n messages: MessageListInput,\n options?: DurableAgentStreamOptions<TOutput>,\n ): Promise<FullOutput<TOutput>> {\n options = await this.#resolveExecutionOptions(options);\n\n // Enforce agent-level FGA (agents:execute) before durable execution — see\n // stream() above. Durable/evented generate would otherwise skip the gate.\n await this.requireAgentExecutionFGA({\n requestContext: options?.requestContext,\n memory: options?.memory,\n runId: options?.runId,\n actor: options?.actor,\n });\n\n // 1. Prepare for durable execution (non-durable phase)\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options: options as AgentExecutionOptions<TOutput>,\n runId: options?.runId,\n requestContext: options?.requestContext,\n optionsAreResolved: true,\n mastra: this.#mastra,\n methodType: 'generate',\n durableAgentId: this.id,\n durableAgentName: this.name,\n });\n\n const { runId, messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;\n\n // 1a. Install the abort controller for this run. The controller is owned\n // by this DurableAgent instance; the result's abort() method flips it,\n // and the durable LLM-execution step reads `abortSignal` off the registry\n // to thread it into the model call + abort short-circuits. If the caller\n // also supplied an external signal, forward its abort to the internal\n // controller so either source can cancel the run.\n const abortController = new AbortController();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) {\n abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n options.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n registryEntry.abortController = abortController;\n registryEntry.abortSignal = abortController.signal;\n\n // 2. Register non-serializable state (both local and global registries)\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n globalRunRegistry.set(runId, { ...registryEntry, messageList });\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Schedule automatic registry cleanup after stream ends\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n // 3. Create the durable agent stream (subscribes to pubsub)\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\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: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n onAbort: async data => {\n try {\n await (options?.onAbort as ((event: any) => void | Promise<void>) | undefined)?.(data);\n } finally {\n scheduleAutoCleanup();\n }\n },\n // onIterationComplete is NOT forwarded here — the dowhile predicate\n // now calls it in-process from globalRunRegistry and honors its return\n // value ({ continue, feedback }). The pubsub ITERATION_COMPLETE event\n // still fires for external observability subscribers.\n closeOnSuspend: true,\n structuredOutput: registryEntry.structuredOutput as any,\n outputProcessors: registryEntry.outputProcessors,\n messageList,\n });\n\n // 4. Wait for subscription to be ready, then execute workflow\n // This prevents race conditions where events are published before subscription\n const workflowExecution = ready\n .then(async () => {\n // Emit 'start' chunk before the workflow begins (matches regular agent's stream.ts).\n // Only the initial generate()/stream() path emits 'start'; resume() does not.\n await emitChunkEvent(this.pubsub, runId, {\n type: 'start',\n runId,\n from: ChunkFrom.AGENT,\n payload: { id: workflowInput.agentId, messageId },\n });\n if (this.__getGoalConfig()) {\n await beginGoalActivity({\n mastra: this.#mastra,\n agentId: workflowInput.agentId,\n threadId,\n runId,\n requestContext: globalRunRegistry.get(runId)?.requestContext,\n });\n }\n try {\n return await this.executeWorkflow(runId, workflowInput);\n } finally {\n await stopGoalActivity({ agentId: workflowInput.agentId, runId });\n }\n })\n .catch(error => {\n void this.emitError(runId, error);\n });\n const trackedEntry = globalRunRegistry.get(runId);\n if (trackedEntry) {\n trackedEntry.workflowExecution = workflowExecution;\n }\n\n // 5. Create cleanup function (cancels auto-cleanup timer if called)\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n let suspended = false;\n try {\n const fullOutput = (await output.getFullOutput()) as FullOutput<TOutput>;\n if (fullOutput.error) {\n throw fullOutput.error;\n }\n suspended = fullOutput.finishReason === 'suspended';\n // On suspend, the SUSPENDED event is emitted from the tool-call step\n // before the workflow engine has persisted the snapshot. Awaiting the\n // workflow execution promise blocks until `run.start()` returns, which\n // happens after the suspend snapshot has been persisted — so a later\n // `resumeGenerate()` can find the snapshot. Subclasses that drive the\n // workflow with a fire-and-forget API (see `EventedAgent`) need their\n // own persistence guarantee here; their `executeWorkflow` promise may\n // resolve before the snapshot lands.\n if (suspended) {\n await globalRunRegistry.get(runId)?.workflowExecution;\n }\n // Fall back to the stream-level runId if MastraModelOutput.runId wasn't\n // populated (no chunk surfaced before suspend).\n if (!fullOutput.runId) {\n (fullOutput as { runId?: string }).runId = runId;\n }\n return fullOutput;\n } finally {\n // Keep the registry entry alive on suspend so `resumeGenerate()` can\n // pick it up. Auto-cleanup is scheduled by FINISH/ERROR/ABORT paths.\n if (!suspended) {\n cleanup();\n }\n }\n }\n\n /**\n * Resume a suspended durable run and drain it to a single\n * {@link FullOutput}. Mirrors {@link Agent.resumeGenerate} on top of\n * {@link DurableAgent.resume}.\n *\n * Unlike `generate()`, this delegates to `resume()` because resume reads\n * its tools from the existing run-registry entry rather than running\n * `prepareForDurableExecution` again — there is no `methodType` to thread\n * through. The same `EventedAgent` caveat about fire-and-forget snapshot\n * persistence noted on `generate()` applies if the resumed turn suspends.\n */\n async resumeGenerate(\n runId: string,\n resumeData: unknown,\n options?: Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2],\n ): Promise<FullOutput<TOutput>> {\n const result = await this.resume(runId, resumeData, {\n ...(options ?? {}),\n [CLOSE_ON_SUSPEND]: true,\n } as Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2]);\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 result.cleanup();\n }\n }\n }\n\n /**\n * List durable agent runs currently reported as `running` in workflow\n * snapshot storage.\n *\n * A `running` snapshot is a durable agent run whose agentic loop was\n * mid-execution the last time the workflow engine persisted its state. On a\n * healthy process these transition to `suspended` (waiting on\n * tool approval / resume) or a terminal status. On a crashed / restarted\n * process they are orphaned in the `running` state with no in-process\n * driver — this is the discovery API used to enumerate them for recovery\n * (see {@link DurableAgent.recoverActiveRuns} and workflow `restart`).\n *\n * Requires persistent workflow storage. Filters `agentId` against the\n * persisted `DurableAgenticWorkflowInput.agentId`, so runs started by other\n * durable agents sharing the same storage are not surfaced.\n *\n * @example\n * ```typescript\n * const { runs } = await durableAgent.listActiveRuns({ resourceId });\n * for (const run of runs) {\n * await durableAgent.recoverActiveRuns({ runId: run.runId });\n * }\n * ```\n */\n async listActiveRuns(options: DurableAgentListActiveRunsOptions = {}): Promise<DurableAgentListActiveRunsResult> {\n const { threadId, resourceId, fromDate, toDate, perPage, page } = options;\n\n if (perPage !== undefined && (!Number.isInteger(perPage) || perPage <= 0)) {\n throw new MastraError({\n id: 'DURABLE_AGENT_LIST_ACTIVE_RUNS_INVALID_PER_PAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" listActiveRuns() requires perPage to be a positive integer.`,\n details: { agentName: this.name, perPage },\n });\n }\n if (page !== undefined && (!Number.isInteger(page) || page < 0)) {\n throw new MastraError({\n id: 'DURABLE_AGENT_LIST_ACTIVE_RUNS_INVALID_PAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" listActiveRuns() requires page to be a non-negative integer.`,\n details: { agentName: this.name, page },\n });\n }\n\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n\n if (!workflowsStore) {\n throw new MastraError({\n id: 'DURABLE_AGENT_LIST_ACTIVE_RUNS_NO_STORAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" listActiveRuns() requires storage to discover running runs. ` +\n `Register the agent on a Mastra instance with persistent storage (e.g. PostgreSQL, LibSQL).`,\n details: { agentName: this.name },\n });\n }\n\n const { runs } = await workflowsStore.listWorkflowRuns({\n workflowName: DurableStepIds.AGENTIC_LOOP,\n status: 'running',\n fromDate,\n toDate,\n });\n\n const matchedRuns: DurableAgentActiveRun[] = [];\n for (const run of runs) {\n let snapshot = run.snapshot;\n if (typeof snapshot === 'string') {\n try {\n snapshot = JSON.parse(snapshot) as WorkflowRunState;\n } catch {\n continue;\n }\n }\n if (snapshot?.status !== 'running') continue;\n\n // The persisted workflow input carries the owning agentId. Default-deny:\n // a snapshot without an input or whose agentId does not match this agent\n // is skipped so runs cannot leak across agents sharing the same storage.\n const input = snapshot.context?.input as\n | { agentId?: string; messageListState?: { memoryInfo?: { threadId?: string; resourceId?: string } } }\n | undefined;\n const runAgentId = input?.agentId;\n if (runAgentId !== this.id) continue;\n\n const memoryInfo = input?.messageListState?.memoryInfo;\n const runThreadId = memoryInfo?.threadId;\n const runResourceId = run.resourceId ?? memoryInfo?.resourceId;\n if (threadId && runThreadId !== threadId) continue;\n if (resourceId && runResourceId !== resourceId) continue;\n\n matchedRuns.push({\n runId: run.runId,\n status: 'running',\n threadId: runThreadId,\n resourceId: runResourceId,\n updatedAt: run.updatedAt,\n });\n }\n\n const total = matchedRuns.length;\n const paginatedRuns =\n perPage !== undefined && page !== undefined\n ? matchedRuns.slice(page * perPage, (page + 1) * perPage)\n : matchedRuns;\n\n return { runs: paginatedRuns, total };\n }\n\n /**\n * Bulk recover durable agent runs whose in-process agentic loop was orphaned\n * by a process restart. This is the recovery half of the discovery API\n * paired with {@link DurableAgent.listActiveRuns} and is the typical\n * boot-time hook.\n *\n * Each targeted run is delegated to {@link DurableAgent.recover}, which\n * rebuilds the run's non-serializable state (message list, model, memory,\n * save-queue manager, request context, agent span), re-subscribes to the\n * run's pubsub topic, and restarts the workflow in the background. Because\n * `recover()` registers `memory` + `saveQueueManager` on the run entry, the\n * durable agentic workflow's terminal step flushes new messages to memory\n * just like a fresh `stream()` call would.\n *\n * The per-run stream returned by `recover()` is discarded — this method\n * awaits each run's workflow settlement and reports summary counts instead\n * of surfacing live event streams. Callers who want to observe a specific\n * recovered run's events should use {@link DurableAgent.recover} directly\n * (or {@link DurableAgent.observe} with the returned `runId`).\n *\n * Failures are captured per-run so a single bad run does not block\n * recovery of the rest.\n *\n * @example\n * ```typescript\n * // Recover every orphaned run for this agent (typical boot-time hook).\n * const { recovered, succeeded, failed } = await durableAgent.recoverActiveRuns();\n * logger.info('Recovered durable agent runs', { succeeded, failed });\n *\n * // Recover a single run by ID.\n * await durableAgent.recoverActiveRuns({ runId });\n * ```\n */\n async recoverActiveRuns(\n options: DurableAgentRecoverActiveRunsOptions = {},\n ): Promise<DurableAgentRecoverActiveRunsResult> {\n const { runId, ...discoveryOptions } = options;\n\n let targetRunIds: string[];\n if (runId) {\n targetRunIds = [runId];\n } else {\n const { runs } = await this.listActiveRuns(discoveryOptions);\n targetRunIds = runs.map(r => r.runId);\n }\n\n const recovered: DurableAgentRecoveredRun[] = [];\n let succeeded = 0;\n let failed = 0;\n\n for (const targetRunId of targetRunIds) {\n let runError: Error | undefined;\n try {\n // Delegate to the single-run streamable recover path so each run\n // benefits from the rebuilt registry entry (message list, memory,\n // saveQueueManager, request context, agent span) and the pubsub\n // stream / terminal snapshot-cleanup contract stays identical to\n // `recover()`. We don't surface the per-run stream here — bulk\n // callers only care about counts — so we just await the workflow\n // execution promise that `recover()` parks on the registry entry,\n // capture any failure it surfaces via `onError`, and drop the\n // stream.\n const { cleanup } = await this.recover(targetRunId, {\n onError: ({ error }) => {\n runError = error instanceof Error ? error : new Error(String(error));\n },\n });\n try {\n const workflowExecution = globalRunRegistry.get(targetRunId)?.workflowExecution;\n if (workflowExecution) {\n await workflowExecution;\n }\n } finally {\n cleanup();\n }\n if (runError) throw runError;\n recovered.push({ runId: targetRunId, status: 'success' });\n succeeded++;\n } catch (error) {\n const err = runError ?? (error instanceof Error ? error : new Error(String(error)));\n recovered.push({ runId: targetRunId, status: 'failed', error: err });\n failed++;\n this.#mastra\n ?.getLogger?.()\n ?.error?.(`[DurableAgent] Failed to recover run ${targetRunId}: ${err.message}`, { error: err });\n }\n }\n\n return { recovered, succeeded, failed };\n }\n\n /**\n * Observe an existing stream.\n * Use this to reconnect to a stream after a network disconnection.\n *\n * **Warning:** The returned `cleanup()` function destroys the run's registry\n * entries and cached PubSub events. Only call it when you are done with the\n * run entirely. If the workflow is suspended and you intend to resume later,\n * do not call cleanup — let the auto-cleanup timer handle it after\n * FINISH/ERROR. Auto-cleanup does not fire on SUSPENDED events.\n */\n async observe(\n runId: string,\n options?: {\n offset?: number;\n onChunk?: (chunk: ChunkType<TOutput>) => void | Promise<void>;\n experimentalTransform?: MastraStreamTransformOptions<TOutput>;\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<DurableAgentStreamResult<TOutput>, 'runId'> & { runId: string }> {\n const memoryInfo = this.#runRegistry.getMemoryInfo(runId);\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n messageId: crypto.randomUUID(),\n model: {\n modelId: undefined,\n provider: undefined,\n version: 'v3',\n },\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n offset: options?.offset,\n onChunk: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n structuredOutput: this.#runRegistry.get(runId)?.structuredOutput as any,\n outputProcessors: this.#runRegistry.get(runId)?.outputProcessors,\n messageList: globalRunRegistry.get(runId)?.messageList ?? this.#runRegistry.getMessageList(runId),\n });\n\n // Wait for subscription to be ready\n await ready;\n\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n // observe() doesn't own the run's lifecycle, but for API symmetry the\n // returned `abort` flips the in-process controller currently installed\n // on the registry. If the run already ended (or is running in a\n // different process), this is a best-effort no-op.\n const abort = (reason?: unknown) => {\n const controller = (globalRunRegistry.get(runId) ?? this.#runRegistry.get(runId))?.abortController;\n if (controller && !controller.signal.aborted) {\n controller.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Clear retained pubsub state for a run's topic (cached history and, for\n * persistent transports, the underlying stream). Fire-and-forget: the\n * `clearTopic` contract is best-effort and non-throwing.\n *\n * Unlike the evented workflow engine's per-run topic cleanup, this needs no\n * restart guard: cleanup timers arm only on terminal outcomes\n * (FINISH/ERROR/ABORT — never SUSPENDED), `resume()` rejects runs whose\n * snapshot isn't `suspended`, `untilIdle` continuations mint a fresh runId\n * per segment, and cross-process `recover()` can't race a dead process's\n * timer. No supported flow re-engages a runId after its timer is armed.\n */\n #clearPubsubTopic(runId: string): void {\n void this.pubsub.clearTopic(AGENT_STREAM_TOPIC(runId));\n }\n\n /**\n * Read the current number of cached events for this run's stream topic.\n * Used by `resume()` as the subscription offset so we don't re-deliver\n * events emitted by the original run (notably the SUSPENDED chunk that\n * paused it).\n */\n async #getPubsubOffset(runId: string): Promise<number> {\n const pubsub = this.pubsub as PubSub & {\n getHistory?: (topic: string) => Promise<unknown[]>;\n };\n if (typeof pubsub.getHistory !== 'function') return 0;\n try {\n const history = await pubsub.getHistory(AGENT_STREAM_TOPIC(runId));\n return Array.isArray(history) ? history.length : 0;\n } catch {\n return 0;\n }\n }\n\n /**\n * Get the workflow instance for direct execution.\n * Lazily creates the workflow and registers Mastra on it (needed for\n * getAgentById in execution steps).\n */\n getWorkflow() {\n if (!this.#workflow) {\n this.#workflow = this.createWorkflow();\n // Register mastra on the workflow so execution steps can access agents/tools.\n // DurableAgent goes through the normal Agent registration path (not the durable wrapper\n // path that calls addWorkflow), so the workflow isn't registered in Mastra's #workflows.\n // We set mastra directly here instead.\n if (this.#mastra) {\n this.#workflow.__registerMastra(this.#mastra);\n this.#workflow.__registerPrimitives({\n logger: this.#mastra.getLogger(),\n storage: this.#mastra.getStorage(),\n });\n }\n }\n return this.#workflow;\n }\n\n /**\n * @deprecated Use `stream(messages, { untilIdle: true })` instead.\n *\n * Stream until all background tasks complete and the agent is idle.\n * Mirrors the regular Agent's streamUntilIdle but adapted for durable execution.\n */\n // @ts-expect-error - Intentionally different return type for durable execution\n override async streamUntilIdle<OUTPUT = TOutput>(\n messages: MessageListInput,\n streamOptions?: DurableAgentStreamOptions<OUTPUT> & { maxIdleMs?: number },\n ): Promise<DurableAgentStreamResult<OUTPUT>> {\n const { maxIdleMs, ...options } = streamOptions ?? {};\n return this.stream(messages, {\n ...options,\n untilIdle: maxIdleMs === undefined ? true : { maxIdleMs },\n } as DurableAgentStreamOptions<TOutput>) as unknown as Promise<DurableAgentStreamResult<OUTPUT>>;\n }\n\n /**\n * Prepare for durable execution without starting it.\n */\n async prepare(messages: MessageListInput, options?: AgentExecutionOptions<TOutput>) {\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options,\n // Forward the caller-provided runId (mirrors stream()). Without this,\n // prepareForDurableExecution mints a fresh id, so prepare() registers a\n // different run than requested and a follow-up resume(runId) — e.g. when\n // rehydrating a persisted, suspended run in a fresh process — can't find\n // its registry entry.\n runId: options?.runId,\n requestContext: options?.requestContext,\n mastra: this.#mastra,\n });\n\n this.#runRegistry.registerWithMessageList(preparation.runId, preparation.registryEntry, preparation.messageList, {\n threadId: preparation.threadId,\n resourceId: preparation.resourceId,\n });\n globalRunRegistry.set(preparation.runId, {\n ...preparation.registryEntry,\n messageList: preparation.messageList,\n });\n\n return {\n runId: preparation.runId,\n messageId: preparation.messageId,\n workflowInput: preparation.workflowInput,\n registryEntry: preparation.registryEntry,\n threadId: preparation.threadId,\n resourceId: preparation.resourceId,\n };\n }\n\n /**\n * Get the durable workflows required by this agent.\n * Called by Mastra during agent registration.\n * @internal\n */\n getDurableWorkflows() {\n return [this.getWorkflow()];\n }\n\n /**\n * Set the Mastra instance.\n * Called by the durable agent registration path in addAgent().\n * Delegates to __registerMastra so the pubsub wiring and agent\n * registration happen regardless of which entry point is called first.\n * @internal\n */\n __setMastra(mastra: Mastra): void {\n this.__registerMastra(mastra);\n }\n\n /**\n * Register the Mastra instance.\n * Called by Mastra during agent registration (normal Agent path).\n *\n * Also wires mastra.pubsub as the inner pubsub (if the user didn't provide\n * a custom one), so that the OBSERVE_AGENT_STREAM_ROUTE handler can subscribe\n * to the same PubSub instance that this agent publishes to.\n * @internal\n */\n __registerMastra(mastra: Mastra): void {\n super.__registerMastra(mastra);\n this.#mastra = mastra;\n // Also set on wrapped agent\n this.#wrappedAgent.__registerMastra(mastra);\n\n // Wire mastra.pubsub as the inner pubsub if user didn't provide a custom one.\n // This must happen before CachingPubSub initialization.\n if (!this.#hasCustomPubsub && !this.#cachingPubsub) {\n this.#innerPubsub = mastra.pubsub;\n }\n }\n}\n","/**\n * Factory function to create a DurableAgent that wraps an existing Agent.\n *\n * This is the recommended way to add durable execution capabilities to an agent.\n * The factory creates a DurableAgent instance with resumable streams.\n *\n * @example\n * ```typescript\n * import { Agent } from '@mastra/core/agent';\n * import { createDurableAgent } from '@mastra/core/agent/durable';\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 = createDurableAgent({ agent });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: durableAgent },\n * });\n * ```\n */\n\nimport type { MastraServerCache } from '../../cache/base';\nimport type { PubSub } from '../../events/pubsub';\nimport type { Agent } from '../agent';\n\nimport { DurableAgent } from './durable-agent';\nimport type { DurableAgentConfig } from './durable-agent';\n\n/**\n * Options for createDurableAgent factory function.\n */\nexport interface CreateDurableAgentOptions<\n TAgentId extends string = string,\n TTools extends Record<string, any> = Record<string, any>,\n TOutput = undefined,\n> {\n /** The Agent to wrap with durable execution capabilities */\n agent: Agent<TAgentId, TTools, TOutput>;\n\n /** Optional ID override (defaults to agent.id) */\n id?: TAgentId;\n\n /** Optional name override (defaults to agent.name) */\n name?: string;\n\n /**\n * Cache instance for storing stream events.\n * Enables resumable streams - clients can disconnect and reconnect\n * without missing events.\n *\n * - If not provided: Inherits from Mastra instance, or uses InMemoryServerCache\n * - If provided: Uses the provided cache backend (e.g., Redis)\n * - If set to `false`: Disables caching (streams are not resumable)\n */\n cache?: MastraServerCache | false;\n\n /**\n * PubSub instance for streaming events.\n * Optional - if not provided, defaults to EventEmitterPubSub.\n */\n pubsub?: PubSub;\n\n /** Maximum steps for agentic loop */\n maxSteps?: number;\n\n /**\n * Auto-cleanup timer for durable stream state (ms).\n * Set to `0` to disable auto-cleanup. Defaults to `30_000` (30 seconds).\n */\n cleanupTimeoutMs?: number;\n}\n\n/**\n * Create a DurableAgent that wraps an existing Agent.\n *\n * This factory function is the recommended way to add durable execution\n * capabilities to an agent when you need to customize the cache, pubsub, or\n * other advanced options. For the common case, prefer the `durable` config\n * flag on `AgentConfig` — attaching an agent constructed with `durable: true`\n * (or `durable: { … }`) to a `Mastra` instance auto-wraps it at registration.\n *\n * @param options - Configuration options\n * @returns A DurableAgent instance\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 = createDurableAgent({ agent });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: durableAgent },\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Equivalent, using the durable config flag:\n * const agent = new Agent({\n * id: 'my-agent',\n * instructions: 'You are helpful',\n * model: openai('gpt-4'),\n * durable: true,\n * });\n *\n * const mastra = new Mastra({ agents: { myAgent: agent } });\n * ```\n */\nexport function createDurableAgent<\n TAgentId extends string = string,\n TTools extends Record<string, any> = Record<string, any>,\n TOutput = undefined,\n>(options: CreateDurableAgentOptions<TAgentId, TTools, TOutput>): DurableAgent<TAgentId, TTools, TOutput> {\n const { agent, id, name, cache, pubsub, maxSteps, cleanupTimeoutMs } = options;\n\n return new DurableAgent({\n agent,\n id,\n name,\n cache,\n pubsub,\n maxSteps,\n cleanupTimeoutMs,\n } as DurableAgentConfig<TAgentId, TTools, TOutput>);\n}\n\n/**\n * Check if an object is a DurableAgent\n */\nexport function isDurableAgent(obj: any): obj is DurableAgent {\n return obj instanceof DurableAgent;\n}\n\n/**\n * Alias for isDurableAgent for backwards compatibility\n * @deprecated Use isDurableAgent instead\n */\nexport const isLocalDurableAgent = isDurableAgent;\n\n// Re-export types for convenience\nexport type { DurableAgentConfig, DurableAgentStreamOptions, DurableAgentStreamResult } from './durable-agent';\n\n// Backwards compatibility type aliases\nexport type LocalDurableAgent<\n TAgentId extends string = string,\n TTools extends Record<string,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AY;EAC3B,CAAC;EAED,OAAO;GACL,OAAO,YAAY;GACnB,WAAW,YAAY;GACvB,eAAe,YAAY;GAC3B,eAAe,YAAY;GAC3B,UAAU,YAAY;GACtB,YAAY,YAAY;EAC1B;CACF;;;;;;CAOA,sBAAsB;EACpB,OAAO,CAAC,KAAK,YAAY,CAAC;CAC5B;;;;;;;;CASA,YAAY,QAAsB;EAChC,KAAK,iBAAiB,MAAM;CAC9B;;;;;;;;;;CAWA,iBAAiB,QAAsB;EACrC,MAAM,iBAAiB,MAAM;EAC7B,KAAKS,UAAU;EAEf,KAAKV,cAAc,iBAAiB,MAAM;EAI1C,IAAI,CAAC,KAAKG,oBAAoB,CAAC,KAAKM,gBAClC,KAAKJ,eAAe,OAAO;CAE/B;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpoFA,SAAgB,mBAId,SAAwG;CACxG,MAAM,EAAE,OAAO,IAAI,MAAM,OAAO,QAAQ,UAAU,qBAAqB;CAEvE,OAAO,IAAI,aAAa;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAkD;AACpD;;;;AAKA,SAAgB,eAAe,KAA+B;CAC5D,OAAO,eAAe;AACxB;;;;;AAMA,MAAa,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"create-durable-agent-DH_dWTMR.js","names":["#entries","#messageLists","#memoryInfo","ReadableStream","input","#wrappedAgent","#runRegistry","#maxSteps","#hasCustomPubsub","#cleanupTimeoutMs","#innerPubsub","#cacheConfig","#ensurePubsubInitialized","#resolvedCache","#cachingPubsub","#mastra","#resolveExecutionOptions","#activeStreamUntilIdle","#clearPubsubTopic","#getPubsubOffset","#workflow"],"sources":["../src/agent/durable/constants.ts","../src/agent/durable/durable-stream-until-idle.ts","../src/agent/durable/utils/serialize-state.ts","../src/agent/durable/preparation.ts","../src/agent/durable/run-registry.ts","../src/agent/durable/stream-adapter.ts","../src/agent/durable/workflows/shared/schemas.ts","../src/agent/durable/workflows/shared/iteration-state.ts","../src/agent/durable/workflows/shared/tool-call-concurrency.ts","../src/agent/durable/workflows/steps/background-task-check.ts","../src/agent/durable/utils/apply-tool-payload-transform.ts","../src/agent/durable/utils/resolve-runtime.ts","../src/agent/durable/workflows/steps/llm-execution.ts","../src/agent/durable/workflows/steps/tool-call.ts","../src/agent/durable/workflows/steps/llm-mapping.ts","../src/agent/durable/workflows/steps/is-task-complete.ts","../src/agent/durable/workflows/steps/goal.ts","../src/agent/durable/workflows/steps/signal-drain.ts","../src/agent/durable/workflows/create-durable-agentic-workflow.ts","../src/agent/durable/durable-agent.ts","../src/agent/durable/create-durable-agent.ts"],"sourcesContent":["/**\n * Constants for DurableAgent pubsub channels and event types\n */\n\n/**\n * Symbol for passing run registry to workflow steps\n * This allows steps to access the actual model/tool instances\n */\nexport const RUN_REGISTRY_SYMBOL = Symbol('run_registry');\n\n/**\n * Generate the pubsub topic name for agent streaming events\n * @param runId - The unique run identifier\n * @returns The topic name for subscribing/publishing agent stream events\n */\nexport const AGENT_STREAM_TOPIC = (runId: string): string => `agent.stream.${runId}`;\n\n/**\n * Event type constants for agent stream events\n */\nexport const AgentStreamEventTypes = {\n /** Chunk of streaming data (text, tool call, etc.) */\n CHUNK: 'chunk',\n /** Start of a new step in the agentic loop */\n STEP_START: 'step-start',\n /** End of a step in the agentic loop */\n STEP_FINISH: 'step-finish',\n /** Agent execution completed successfully */\n FINISH: 'finish',\n /** Error occurred during execution */\n ERROR: 'error',\n /** Workflow suspended (e.g., for tool approval) */\n SUSPENDED: 'suspended',\n /** Execution aborted by abortSignal */\n ABORT: 'abort',\n /** Single agentic-loop iteration completed (observability hook) */\n ITERATION_COMPLETE: 'iteration-complete',\n} as const;\n\n/**\n * Default values for durable agent execution\n */\nexport const DurableAgentDefaults = {\n /** Default maximum number of agentic loop iterations */\n MAX_STEPS: 5,\n /**\n * Default tool call concurrency.\n * Applied by `resolveDurableToolCallConcurrency` when a run doesn't\n * configure `toolCallConcurrency`. Approval / suspend-capable tool sets\n * always run sequentially (concurrency: 1) regardless of this value.\n */\n TOOL_CALL_CONCURRENCY: 10,\n} as const;\n\n/**\n * Step IDs used in the durable agentic workflow\n */\nexport const DurableStepIds = {\n /** LLM execution step */\n LLM_EXECUTION: 'durable-llm-execution',\n /** Tool call step */\n TOOL_CALL: 'durable-tool-call',\n /** LLM mapping step (combines results) */\n LLM_MAPPING: 'durable-llm-mapping',\n /** Agentic execution workflow (one iteration) */\n AGENTIC_EXECUTION: 'durable-agentic-execution',\n /** Full agentic loop workflow */\n AGENTIC_LOOP: 'durable-agentic-loop',\n /** Scorer execution step */\n SCORER_EXECUTION: 'durable-scorer-execution',\n /** isTaskComplete evaluation step */\n IS_TASK_COMPLETE: 'durable-is-task-complete',\n} as const;\n","/**\n * Implementation of `DurableAgent.streamUntilIdle` and\n * `DurableAgent.resume(..., { untilIdle })`. Mirrors the regular agent's\n * `stream-until-idle.ts` but adapted for durable execution:\n * - `DurableAgent.stream()` returns `DurableAgentStreamResult` (not `MastraModelOutput`)\n * - Each continuation starts a new durable workflow (new runId)\n * - Cleanup functions from each inner stream are tracked and called on close\n * - Inner `abort()` handles are fanned out so the outer `result.abort()`\n * cancels every active durable run\n *\n * Uses the shared `runIdleLoop` helper from `loop/shared/stream-until-idle-helpers`\n * with durable-specific hooks for cleanup/abort tracking.\n */\nimport type { BackgroundTaskManager } from '../../background-tasks/manager';\nimport { runIdleLoop } from '../../loop/shared/stream-until-idle-helpers';\nimport type { MessageListInput } from '../message-list';\n\nimport type { DurableAgent, DurableAgentStreamOptions, DurableAgentStreamResult } from './durable-agent';\n\nexport interface DurableStreamUntilIdleDeps {\n activeStreams: Map<string, () => void>;\n bgManager: BackgroundTaskManager | undefined;\n}\n\n/**\n * Run `DurableAgent.streamUntilIdle` (or `DurableAgent.stream({ untilIdle })`).\n * Initial turn invokes `agent.stream(messages, ...)`; continuations triggered\n * by background-task completions run as fresh `agent.stream([], ...)` calls\n * against the same memory thread.\n */\nexport async function runDurableStreamUntilIdle<OUTPUT = undefined>(\n agent: DurableAgent<any, any, OUTPUT>,\n messages: MessageListInput,\n streamOptions: (DurableAgentStreamOptions<OUTPUT> & { maxIdleMs?: number }) | undefined,\n deps: DurableStreamUntilIdleDeps,\n): Promise<DurableAgentStreamResult<OUTPUT>> {\n // Durable-specific: track cleanup/abort handles from each inner stream\n const innerCleanups: Array<() => void> = [];\n const innerAborts: Array<(reason?: unknown) => void> = [];\n\n return runIdleLoop<typeof agent, DurableAgentStreamResult<OUTPUT>, DurableAgentStreamResult<OUTPUT>>(\n agent,\n streamOptions,\n deps,\n opts => (agent as any).stream(messages, opts) as Promise<DurableAgentStreamResult<OUTPUT>>,\n opts => (agent as any).stream([], opts) as Promise<{ fullStream: ReadableStream<any> }>,\n (first, ctx) => {\n // No ctx means no bgManager / no memory — fall through without wrapping.\n if (!ctx) return first;\n\n return {\n output: new Proxy(first.output, {\n get(target, prop) {\n if (prop === 'fullStream') return ctx.combinedStream;\n const value = Reflect.get(target, prop, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n }) as any,\n get fullStream() {\n return ctx.combinedStream;\n },\n runId: first.runId,\n threadId: ctx.threadId,\n resourceId: ctx.resourceId,\n cleanup: ctx.forceClose,\n abort: (reason?: unknown) => {\n // Fan the abort out to every inner DurableAgent.stream() that has been\n // spawned by the idle loop so far. `forceClose` then unwinds the outer\n // stream + idle timer.\n for (const innerAbort of innerAborts) {\n try {\n innerAbort(reason);\n } catch {\n // ignore — best-effort abort across siblings\n }\n }\n ctx.forceClose();\n },\n };\n },\n {\n onInnerResult: (inner: any) => {\n if (typeof inner.cleanup === 'function') innerCleanups.push(inner.cleanup);\n if (typeof inner.abort === 'function') innerAborts.push(inner.abort);\n },\n onForceClose: () => {\n for (const fn of innerCleanups) {\n try {\n fn();\n } catch {\n // ignore\n }\n }\n },\n },\n );\n}\n\n/**\n * Run `DurableAgent.resume(..., { untilIdle })`. Same idle-loop semantics as\n * `runDurableStreamUntilIdle` — initial turn calls `agent.resume(runId,\n * resumeData, ...)` against the existing run snapshot, and subsequent\n * continuations triggered by background-task completions use\n * `agent.stream([], continuationOpts)` (a normal multi-turn agent stream)\n * since the resume completes and we're back in regular conversation flow.\n */\nexport async function runResumeDurableStreamUntilIdle<OUTPUT = undefined>(\n agent: DurableAgent<any, any, OUTPUT>,\n runId: string,\n resumeData: unknown,\n streamOptions: (DurableAgentStreamOptions<OUTPUT> & { maxIdleMs?: number }) | undefined,\n deps: DurableStreamUntilIdleDeps,\n): Promise<DurableAgentStreamResult<OUTPUT>> {\n const innerCleanups: Array<() => void> = [];\n const innerAborts: Array<(reason?: unknown) => void> = [];\n\n return runIdleLoop<typeof agent, DurableAgentStreamResult<OUTPUT>, DurableAgentStreamResult<OUTPUT>>(\n agent,\n streamOptions,\n deps,\n opts => (agent as any).resume(runId, resumeData, opts) as Promise<DurableAgentStreamResult<OUTPUT>>,\n opts => (agent as any).stream([], opts) as Promise<{ fullStream: ReadableStream<any> }>,\n (first, ctx) => {\n if (!ctx) return first;\n\n return {\n output: new Proxy(first.output, {\n get(target, prop) {\n if (prop === 'fullStream') return ctx.combinedStream;\n const value = Reflect.get(target, prop, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n }) as any,\n get fullStream() {\n return ctx.combinedStream;\n },\n runId: first.runId,\n threadId: ctx.threadId,\n resourceId: ctx.resourceId,\n cleanup: ctx.forceClose,\n abort: (reason?: unknown) => {\n for (const innerAbort of innerAborts) {\n try {\n innerAbort(reason);\n } catch {\n // ignore\n }\n }\n ctx.forceClose();\n },\n };\n },\n {\n onInnerResult: (inner: any) => {\n if (typeof inner.cleanup === 'function') innerCleanups.push(inner.cleanup);\n if (typeof inner.abort === 'function') innerAborts.push(inner.abort);\n },\n onForceClose: () => {\n for (const fn of innerCleanups) {\n try {\n fn();\n } catch {\n // ignore\n }\n }\n },\n },\n );\n}\n","import type { JSONSchema7 } from 'json-schema';\nimport type { MastraLanguageModel } from '../../../llm/model/shared.types';\nimport type { MemoryConfig } from '../../../memory/types';\nimport type { CoreTool } from '../../../tools/types';\nimport type { MessageList } from '../../message-list';\nimport type { AgentModelManagerConfig } from '../../types';\nimport type {\n SerializableToolMetadata,\n SerializableModelConfig,\n SerializableModelListEntry,\n SerializableDurableState,\n SerializableDurableOptions,\n SerializableModelSettings,\n SerializableScorersConfig,\n SerializableScorerEntry,\n DurableAgenticWorkflowInput,\n} from '../types';\n\n/**\n * Extract serializable metadata from a CoreTool\n * This strips out the execute function and converts the schema to JSON Schema\n */\nexport function serializeToolMetadata(name: string, tool: CoreTool): SerializableToolMetadata {\n // Extract JSON Schema from the parameters\n let inputSchema: JSONSchema7 = { type: 'object' };\n\n if (tool.parameters) {\n // If it's already a JSON Schema object\n if ('type' in tool.parameters && typeof tool.parameters.type === 'string') {\n inputSchema = tool.parameters as JSONSchema7;\n }\n // If it has a jsonSchema property (zod schema converted)\n else if ('jsonSchema' in tool.parameters) {\n inputSchema = (tool.parameters as any).jsonSchema as JSONSchema7;\n }\n // If it's a Zod schema with _def (try to extract)\n else if ('_def' in tool.parameters) {\n // We'll need to use zodToJsonSchema at runtime if available\n // For now, use a basic object schema\n inputSchema = { type: 'object' };\n }\n }\n\n return {\n id: 'id' in tool && typeof tool.id === 'string' ? tool.id : name,\n name,\n description: tool.description,\n inputSchema,\n requireApproval: (tool as any).requireApproval,\n hasSuspendSchema: (tool as any).hasSuspendSchema,\n };\n}\n\n/**\n * Extract serializable metadata from all tools\n */\nexport function serializeToolsMetadata(tools: Record<string, CoreTool>): SerializableToolMetadata[] {\n return Object.entries(tools).map(([name, tool]) => serializeToolMetadata(name, tool));\n}\n\n/**\n * Extract serializable model configuration\n */\nexport function serializeModelConfig(model: MastraLanguageModel): SerializableModelConfig {\n return {\n provider: model.provider,\n modelId: model.modelId,\n specificationVersion: model.specificationVersion,\n // Store the original config string for runtime resolution (e.g., 'openai/gpt-4o')\n originalConfig: `${model.provider}/${model.modelId}`,\n // Note: We don't serialize model settings here - they come from execution options\n };\n}\n\n/**\n * Extract serializable model list entry from AgentModelManagerConfig\n */\nexport function serializeModelListEntry(entry: AgentModelManagerConfig): SerializableModelListEntry {\n const model = entry.model;\n return {\n id: entry.id,\n config: {\n provider: model.provider,\n modelId: model.modelId,\n specificationVersion: model.specificationVersion,\n originalConfig: `${model.provider}/${model.modelId}`,\n providerOptions: entry.providerOptions,\n },\n maxRetries: entry.maxRetries,\n enabled: entry.enabled,\n };\n}\n\n/**\n * Serialize an array of model configs into a model list.\n * Filters out disabled models since they shouldn't be included in durable execution.\n */\nexport function serializeModelList(models: AgentModelManagerConfig[]): SerializableModelListEntry[] {\n return models.filter(m => m.enabled !== false).map(serializeModelListEntry);\n}\n\n/**\n * Serialize scorers configuration for durable execution.\n *\n * This extracts the scorer name (for resolution at runtime) and sampling config.\n * The actual scorer objects are resolved from Mastra at step execution time.\n *\n * @param scorers The agent's scorers configuration (from agent.scorers or options.scorers)\n * @returns Serializable scorer configuration\n */\nexport function serializeScorersConfig(\n scorers: Record<\n string,\n { scorer: { name: string } | string; sampling?: { type: 'none' } | { type: 'ratio'; rate: number } }\n >,\n): SerializableScorersConfig {\n const result: SerializableScorersConfig = {};\n\n for (const [key, entry] of Object.entries(scorers)) {\n // Get the scorer name - can be a string directly or from scorer.name\n const scorerName = typeof entry.scorer === 'string' ? entry.scorer : entry.scorer.name;\n\n const scorerEntry: SerializableScorerEntry = {\n scorerName,\n };\n\n // Include sampling if provided\n if (entry.sampling) {\n scorerEntry.sampling = entry.sampling;\n }\n\n result[key] = scorerEntry;\n }\n\n return result;\n}\n\n/**\n * Extract serializable state from _internal-like objects\n */\nexport function serializeDurableState(params: {\n memoryConfig?: MemoryConfig;\n threadId?: string;\n resourceId?: string;\n threadExists?: boolean;\n savePerStep?: boolean;\n observationalMemory?: boolean;\n}): SerializableDurableState {\n return {\n memoryConfig: params.memoryConfig,\n threadId: params.threadId,\n resourceId: params.resourceId,\n threadExists: params.threadExists,\n savePerStep: params.savePerStep,\n observationalMemory: params.observationalMemory,\n };\n}\n\n/**\n * Pick the JSON-safe call settings out of an arbitrary `modelSettings` input.\n * Drops any field that is not a primitive value of the expected type so that\n * non-serializable fields (functions, AbortSignal, etc.) never reach the\n * workflow input.\n */\nexport function serializeModelSettings(\n settings: SerializableModelSettings | Record<string, unknown> | undefined,\n): SerializableModelSettings | undefined {\n if (!settings || typeof settings !== 'object') return undefined;\n\n const source = settings as Record<string, unknown>;\n const out: SerializableModelSettings = {};\n const pickNumber = (key: keyof SerializableModelSettings) => {\n const value = source[key as string];\n if (typeof value === 'number' && Number.isFinite(value)) {\n (out as Record<string, unknown>)[key as string] = value;\n }\n };\n\n pickNumber('maxOutputTokens');\n pickNumber('temperature');\n pickNumber('topP');\n pickNumber('topK');\n pickNumber('presencePenalty');\n pickNumber('frequencyPenalty');\n pickNumber('seed');\n pickNumber('maxRetries');\n\n if (Array.isArray(source.stopSequences) && source.stopSequences.every(v => typeof v === 'string')) {\n out.stopSequences = source.stopSequences as string[];\n }\n\n // Headers are never serialized into the workflow input. They are stored\n // exclusively on the in-process RunRegistryEntry so they never reach\n // durable storage. The durable llm-execution step merges them back from\n // the registry at call time.\n // (Previously we had a denylist of \"sensitive\" header names, but any\n // header could carry credentials — the safest approach is to keep them\n // all off the wire.)\n\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Extract serializable options from agent execution options\n */\nexport function serializeDurableOptions(options: {\n maxSteps?: number;\n toolChoice?: any;\n activeTools?: string[];\n modelSettings?: SerializableModelSettings | Record<string, unknown>;\n requireToolApproval?: boolean;\n toolCallConcurrency?: number;\n autoResumeSuspendedTools?: boolean;\n maxProcessorRetries?: number;\n includeRawChunks?: boolean;\n returnScorerData?: boolean;\n hasErrorProcessors?: boolean;\n providerOptions?: SerializableDurableOptions['providerOptions'];\n structuredOutput?: SerializableDurableOptions['structuredOutput'];\n skipBgTaskWait?: boolean;\n disableBackgroundTasks?: boolean;\n tracingOptions?: SerializableDurableOptions['tracingOptions'];\n actor?: SerializableDurableOptions['actor'];\n instructionsOverride?: SerializableDurableOptions['instructionsOverride'];\n systemMessage?: SerializableDurableOptions['systemMessage'];\n transform?: SerializableDurableOptions['transform'];\n isTaskComplete?: SerializableDurableOptions['isTaskComplete'];\n}): SerializableDurableOptions {\n // Normalize toolChoice to serializable form\n let serializedToolChoice: SerializableDurableOptions['toolChoice'];\n if (options.toolChoice) {\n if (typeof options.toolChoice === 'string') {\n serializedToolChoice = options.toolChoice as 'auto' | 'none' | 'required';\n } else if (typeof options.toolChoice === 'object' && 'type' in options.toolChoice) {\n if (options.toolChoice.type === 'tool' && 'toolName' in options.toolChoice) {\n serializedToolChoice = {\n type: 'tool',\n toolName: options.toolChoice.toolName as string,\n };\n }\n }\n }\n\n return {\n maxSteps: options.maxSteps,\n toolChoice: serializedToolChoice,\n activeTools: options.activeTools,\n modelSettings: serializeModelSettings(options.modelSettings),\n requireToolApproval: options.requireToolApproval,\n toolCallConcurrency: options.toolCallConcurrency,\n autoResumeSuspendedTools: options.autoResumeSuspendedTools,\n maxProcessorRetries: options.maxProcessorRetries,\n includeRawChunks: options.includeRawChunks,\n returnScorerData: options.returnScorerData,\n hasErrorProcessors: options.hasErrorProcessors,\n providerOptions: options.providerOptions,\n structuredOutput: options.structuredOutput,\n skipBgTaskWait: options.skipBgTaskWait,\n disableBackgroundTasks: options.disableBackgroundTasks,\n tracingOptions: options.tracingOptions,\n actor: options.actor,\n instructionsOverride: options.instructionsOverride,\n systemMessage: options.systemMessage,\n transform: options.transform,\n isTaskComplete: options.isTaskComplete,\n };\n}\n\n/**\n * Create the full workflow input from all components\n */\nexport function createWorkflowInput(params: {\n runId: string;\n agentId: string;\n agentName?: string;\n messageList: MessageList;\n tools: Record<string, CoreTool>;\n model: MastraLanguageModel;\n modelList?: AgentModelManagerConfig[];\n scorers?: Parameters<typeof serializeScorersConfig>[0];\n options: Parameters<typeof serializeDurableOptions>[0];\n state: Parameters<typeof serializeDurableState>[0];\n messageId: string;\n agentSpanData?: unknown;\n modelSpanData?: unknown;\n requestContextEntries?: Record<string, unknown>;\n}): DurableAgenticWorkflowInput {\n return {\n __workflowKind: 'durable-agent',\n runId: params.runId,\n agentId: params.agentId,\n agentName: params.agentName,\n messageListState: params.messageList.serialize(),\n toolsMetadata: serializeToolsMetadata(params.tools),\n modelConfig: serializeModelConfig(params.model),\n modelList: params.modelList ? serializeModelList(params.modelList) : undefined,\n scorers: params.scorers ? serializeScorersConfig(params.scorers) : undefined,\n options: serializeDurableOptions(params.options),\n state: serializeDurableState(params.state),\n messageId: params.messageId,\n agentSpanData: params.agentSpanData,\n modelSpanData: params.modelSpanData,\n requestContextEntries: params.requestContextEntries,\n };\n}\n\n/**\n * Serialize an error for workflow state\n */\nexport function serializeError(error: unknown): { name: string; message: string; stack?: string } {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n }\n return {\n name: 'Error',\n message: String(error),\n };\n}\n\n/**\n * Serialize a Date to ISO string for workflow state\n */\nexport function serializeDate(date: Date | undefined): string | undefined {\n return date?.toISOString();\n}\n\n/**\n * Deserialize an ISO string back to Date\n */\nexport function deserializeDate(isoString: string | undefined): Date | undefined {\n return isoString ? new Date(isoString) : undefined;\n}\n","import type { AgentBackgroundConfig } from '../../background-tasks/types';\nimport type { MastraLanguageModel } from '../../llm/model/shared.types';\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { MastraMemory } from '../../memory/memory';\nimport type { MemoryConfig, MemoryConfig as _MemoryConfig, StorageThreadType } from '../../memory/types';\nimport { EntityType, SpanType, createObservabilityContext, getOrCreateSpan } from '../../observability';\nimport type { InputProcessorOrWorkflow, OutputProcessorOrWorkflow, ErrorProcessorOrWorkflow } from '../../processors';\nimport type { ProcessorState } from '../../processors/runner';\nimport { RequestContext, MASTRA_VERSIONS_KEY, mergeVersionOverrides } from '../../request-context';\nimport type { VersionOverrides } from '../../request-context';\nimport { toStandardSchema } from '../../schema';\nimport { normalizeToolPayloadTransformPolicy } from '../../tools/payload-transform';\nimport type { CoreTool, ToolHooks, ToolPayloadTransformPolicy } from '../../tools/types';\nimport { deepMerge } from '../../utils';\nimport type { Workspace } from '../../workspace';\nimport type { Agent } from '../agent';\nimport type { AgentExecutionOptions, DelegationConfig } from '../agent.types';\nimport { MessageList } from '../message-list';\nimport type { MessageListInput } from '../message-list';\nimport { SaveQueueManager } from '../save-queue';\nimport type { CreatedAgentSignal } from '../signals';\nimport { mastraDBMessageToSignal } from '../signals';\nimport { TripWire } from '../trip-wire';\nimport type {\n AgentInstructions,\n AgentMethodType,\n AgentModelManagerConfig,\n GoalConfig,\n ToolsetsInput,\n ToolsInput,\n} from '../types';\nimport type { DurableAgenticWorkflowInput, RunRegistryEntry, SerializableStructuredOutput } from './types';\nimport { createWorkflowInput } from './utils/serialize-state';\n\n/**\n * JSON-safe snapshot of `requestContext.entries()` so durable steps (e.g.\n * is-task-complete scorers) can see the same `customContext` the non-durable\n * path passes. Best-effort: entries that fail a JSON round-trip are skipped\n * so a single non-serializable value can't break the workflow input.\n */\nfunction snapshotRequestContextEntries(\n requestContext: RequestContext | undefined,\n): Record<string, unknown> | undefined {\n if (!requestContext) return undefined;\n const out: Record<string, unknown> = {};\n let any = false;\n for (const [key, value] of requestContext.entries()) {\n try {\n const cloned = JSON.parse(JSON.stringify(value));\n out[key as string] = cloned;\n any = true;\n } catch {\n // Skip non-serializable entries silently — they wouldn't survive the\n // wire on cross-process engines anyway.\n }\n }\n return any ? out : undefined;\n}\n\n/**\n * Mirror of Agent#convertInstructionsToString — used for the AGENT_RUN span\n * `attributes.instructions` field so durable runs publish the same shape as\n * non-durable runs. Kept local to avoid promoting the private method.\n */\nfunction convertInstructionsToString(instructions: AgentInstructions | undefined): string {\n if (!instructions) return '';\n if (typeof instructions === 'string') return instructions;\n if (Array.isArray(instructions)) {\n return instructions\n .map(msg => (typeof msg === 'string' ? msg : typeof msg.content === 'string' ? msg.content : ''))\n .filter(Boolean)\n .join('\\n\\n');\n }\n return typeof instructions.content === 'string' ? instructions.content : '';\n}\n\n/**\n * Extract signal messages already present in the messageList at run start\n * (from persisted history) so they can be echoed as data-signal stream parts\n * on the first LLM step. Mirrors `prepare-memory-step.ts#getInitialSignalEchoes`.\n */\nfunction getInitialSignalEchoes(messageList: MessageList): CreatedAgentSignal[] {\n const inputMessageIds = messageList.makeMessageSourceChecker().input;\n return messageList.get.all\n .db()\n .filter(message => message.role === 'signal' && inputMessageIds.has(message.id))\n .map(mastraDBMessageToSignal);\n}\n\n/**\n * Interface for the Agent methods needed during durable preparation.\n * This provides proper typing for the public Agent methods we call.\n */\ninterface DurablePreparationAgent {\n id: string;\n name?: string;\n getDefaultOptions(opts: { requestContext: RequestContext }): AgentExecutionOptions | Promise<AgentExecutionOptions>;\n getInstructions(opts: { requestContext: RequestContext }): AgentInstructions | Promise<AgentInstructions>;\n getModel(opts: { requestContext: RequestContext }): MastraLanguageModel | Promise<MastraLanguageModel>;\n getModelList(requestContext: RequestContext): Promise<AgentModelManagerConfig[] | null>;\n getMemory(opts: { requestContext: RequestContext }): Promise<MastraMemory | undefined>;\n getWorkspace(opts: { requestContext: RequestContext }): Promise<Workspace | undefined>;\n listScorers(opts: {\n requestContext: RequestContext;\n }): Promise<Record<string, { scorer: unknown; sampling?: unknown }> | undefined>;\n getToolsForExecution(opts: {\n toolsets?: ToolsetsInput;\n clientTools?: ToolsInput;\n threadId?: string;\n resourceId?: string;\n runId?: string;\n requestContext?: RequestContext;\n memoryConfig?: MemoryConfig;\n autoResumeSuspendedTools?: boolean;\n hooks?: ToolHooks;\n delegation?: DelegationConfig;\n methodType?: AgentMethodType;\n }): Promise<Record<string, CoreTool>>;\n listInputProcessors(requestContext?: RequestContext): Promise<InputProcessorOrWorkflow[]>;\n listOutputProcessors(requestContext?: RequestContext): Promise<OutputProcessorOrWorkflow[]>;\n listErrorProcessors(requestContext?: RequestContext): Promise<ErrorProcessorOrWorkflow[]>;\n getBackgroundTasksConfig(): AgentBackgroundConfig | undefined;\n getToolPayloadTransform?(): ToolPayloadTransformPolicy | undefined;\n __getDrainPendingSignals(): (runId: string, scope?: 'pending' | 'pre-run') => CreatedAgentSignal[];\n __getGoalConfig(): GoalConfig | undefined;\n __listLLMRequestProcessors(requestContext?: RequestContext): Promise<InputProcessorOrWorkflow[]>;\n}\n\n/**\n * Result from the preparation phase\n */\nexport interface PreparationResult<_OUTPUT = undefined> {\n /** Unique run identifier */\n runId: string;\n /** Message ID for this generation */\n messageId: string;\n /** Serialized workflow input */\n workflowInput: DurableAgenticWorkflowInput;\n /** Non-serializable state for the run registry */\n registryEntry: RunRegistryEntry;\n /** MessageList for callback access */\n messageList: MessageList;\n /** Thread ID if using memory */\n threadId?: string;\n /** Resource ID if using memory */\n resourceId?: string;\n}\n\n/**\n * Options for preparation phase\n */\nexport interface PreparationOptions<OUTPUT = undefined> {\n /** The agent instance (wrapped agent — used for config resolution: tools, model, instructions, memory) */\n agent: Agent<string, any, OUTPUT>;\n /** User messages to process */\n messages: MessageListInput;\n /** Execution options */\n options?: AgentExecutionOptions<OUTPUT>;\n /** Whether execution options already include the agent defaults. */\n optionsAreResolved?: boolean;\n /** Run ID (will be generated if not provided) */\n runId?: string;\n /** Request context */\n requestContext?: RequestContext;\n /** Logger */\n logger?: IMastraLogger;\n /** Mastra instance (for version overrides, background tasks, etc.) */\n mastra?: Mastra;\n /** Method type */\n methodType?: AgentMethodType;\n /**\n * The public-facing agent ID (the DurableAgent wrapper's ID).\n * Used for spans, background tasks, scorers, and all identification visible to Studio.\n * Falls back to `agent.id` if not provided.\n */\n durableAgentId?: string;\n /**\n * The public-facing agent name (the DurableAgent wrapper's name).\n * Used for spans, background tasks, scorers, and all identification visible to Studio.\n * Falls back to `agent.name` if not provided.\n */\n durableAgentName?: string;\n}\n\n/**\n * Prepare for durable agent execution.\n *\n * This function performs the non-durable preparation phase:\n * 1. Generates run ID and message ID\n * 2. Resolves thread/memory context\n * 3. Creates MessageList with instructions and messages\n * 4. Converts tools to CoreTool format\n * 5. Gets the model configuration\n * 6. Creates serialized workflow input\n * 7. Creates run registry entry for non-serializable state\n *\n * The result includes both the serialized workflow input (for the durable\n * workflow) and the run registry entry (for non-serializable state).\n */\nexport async function prepareForDurableExecution<OUTPUT = undefined>(\n options: PreparationOptions<OUTPUT>,\n): Promise<PreparationResult<OUTPUT>> {\n const {\n agent,\n messages,\n options: rawExecOptions,\n optionsAreResolved = false,\n runId: providedRunId,\n requestContext: providedRequestContext,\n logger,\n mastra,\n methodType = 'stream',\n durableAgentId,\n durableAgentName,\n } = options;\n\n // Public-facing identity: use the durable wrapper's ID/name for all\n // external-facing identification (spans, background tasks, scorers, Studio).\n // Fall back to the wrapped agent's ID/name when called outside the durable wrapper.\n const publicAgentId = durableAgentId ?? agent.id;\n const publicAgentName = durableAgentName ?? agent.name ?? agent.id;\n\n const typedAgent = agent as unknown as DurablePreparationAgent;\n\n // 1. Generate IDs\n const runId = providedRunId ?? crypto.randomUUID();\n const messageId = crypto.randomUUID();\n\n // 2. Get request context\n const requestContext = providedRequestContext ?? new RequestContext();\n\n // 2a. Snapshot caller-provided RequestContext entries *before* preparation\n // mutates the context (version overrides at step 3, MastraMemory at step 4).\n // The persisted `customContext` should reflect only what the caller passed in,\n // not internal-key state added during prep.\n const requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext);\n\n // 2b. Merge the wrapped agent's defaultOptions under the per-request options,\n // mirroring the non-durable Agent.stream()/generate() paths. Without this the\n // agent's configured defaults (maxSteps, providerOptions, etc.) are silently\n // dropped and durable runs fall back to DurableAgentDefaults.MAX_STEPS.\n const execOptions: AgentExecutionOptions<OUTPUT> = optionsAreResolved\n ? (rawExecOptions ?? ({} as AgentExecutionOptions<OUTPUT>))\n : (deepMerge(\n ((await typedAgent.getDefaultOptions({ requestContext })) ?? {}) as Record<string, unknown>,\n (rawExecOptions ?? {}) as Record<string, unknown>,\n ) as AgentExecutionOptions<OUTPUT>);\n\n // 3. Merge version overrides (Mastra defaults < requestContext < call-site)\n const requestVersions = requestContext.get(MASTRA_VERSIONS_KEY) as VersionOverrides | undefined;\n let mergedVersions = mergeVersionOverrides(mastra?.getVersionOverrides?.(), requestVersions);\n if ((execOptions as any)?.versions) {\n mergedVersions = mergeVersionOverrides(mergedVersions, (execOptions as any).versions);\n }\n if (mergedVersions) {\n requestContext.set(MASTRA_VERSIONS_KEY, mergedVersions);\n }\n\n // 4. Resolve thread/memory context\n const thread =\n typeof execOptions?.memory?.thread === 'string' ? { id: execOptions.memory.thread } : execOptions?.memory?.thread;\n const threadId = thread?.id;\n const resourceId = execOptions?.memory?.resource;\n let threadObject: StorageThreadType | undefined;\n let threadExists = false;\n\n // 5. Create MessageList\n const messageList = new MessageList({\n threadId,\n resourceId,\n });\n\n // Add agent instructions. Per-call `options.instructions` overrides the\n // agent's default instructions to mirror non-durable Agent.stream() behavior.\n const instructions = execOptions?.instructions || (await typedAgent.getInstructions({ requestContext }));\n if (instructions) {\n if (typeof instructions === 'string') {\n messageList.addSystem(instructions);\n } else if (Array.isArray(instructions)) {\n for (const inst of instructions) {\n messageList.addSystem(inst);\n }\n } else {\n messageList.addSystem(instructions);\n }\n }\n const workspace = await typedAgent.getWorkspace({ requestContext });\n\n // Durable preparation runs processInput processors below, but workspace\n // instructions are a processInputStep concern in the non-durable path.\n // Add them here once so durable runs get the same workspace context.\n if (workspace) {\n const hasFs =\n typeof workspace.hasFilesystemConfig === 'function' ? workspace.hasFilesystemConfig() : !!workspace.filesystem;\n const hasSb = typeof workspace.hasSandboxConfig === 'function' ? workspace.hasSandboxConfig() : !!workspace.sandbox;\n if (hasFs || hasSb) {\n const wsInstructions =\n typeof workspace.getInstructionsAsync === 'function'\n ? await workspace.getInstructionsAsync({ requestContext })\n : workspace.getInstructions({ requestContext });\n if (wsInstructions) {\n messageList.addSystem({ role: 'system', content: wsInstructions });\n }\n }\n }\n\n // Add context messages if provided\n if (execOptions?.context) {\n messageList.add(execOptions.context, 'context');\n }\n\n // Per-call `options.system` is appended as an additional system message after\n // context. Mirrors the non-durable Agent.stream() prepare-memory-step path.\n if (execOptions?.system) {\n const sys = execOptions.system;\n if (typeof sys === 'string') {\n messageList.addSystem(sys);\n } else if (Array.isArray(sys)) {\n for (const s of sys) {\n messageList.addSystem(s);\n }\n } else {\n messageList.addSystem(sys);\n }\n }\n\n // Add user messages\n messageList.add(messages, 'input');\n\n // 6. Establish the memory/thread context BEFORE resolving input processors.\n //\n // Memory.getInputProcessors() decides whether to add the working-memory\n // injector by reading requestContext.get('MastraMemory')?.memoryConfig. When\n // working memory is disabled in the constructor and enabled per-request (the\n // documented setup), that runtime config is the only signal that turns the\n // injector on. If we resolve processors before setting MastraMemory, the\n // per-request config is invisible, the chain falls back to the constructor\n // config, and the injector is silently omitted — so stored working memory is\n // saved by the update-working-memory tool but never read back into the prompt.\n // Setting the context first keeps read (inject) and write (tool) in sync.\n const memory = await typedAgent.getMemory({ requestContext });\n const memoryConfig = execOptions?.memory?.options;\n if (memory && threadId && resourceId) {\n const existingThread = await memory.getThreadById({ threadId });\n threadObject =\n existingThread ??\n (await memory.createThread({\n threadId,\n metadata: thread?.metadata,\n title: thread?.title,\n memoryConfig,\n resourceId,\n saveThread: true,\n }));\n threadExists = true;\n requestContext.set('MastraMemory', { thread: threadObject, resourceId, memoryConfig });\n } else {\n // This run has no complete per-request memory context. Clear any\n // MastraMemory inherited from a caller-provided requestContext (e.g. a\n // parent agent's context during sub-agent delegation) so processor\n // resolution can't pick up the working-memory injector from stale/parent\n // memory — that would both leak prior resource memory into this prompt and\n // break the \"no per-request memory options means no injection\" gate.\n requestContext.delete('MastraMemory');\n }\n\n // Resolve input processors now that the memory context is in place.\n const processorStates = new Map<string, ProcessorState>();\n let inputProcessors: InputProcessorOrWorkflow[] = [];\n let llmRequestInputProcessors: InputProcessorOrWorkflow[] = [];\n let outputProcessors: OutputProcessorOrWorkflow[] = [];\n let errorProcessors: ErrorProcessorOrWorkflow[] = [];\n\n try {\n inputProcessors = await typedAgent.listInputProcessors(requestContext);\n // Uncombined processors for processLLMRequest — combined (workflow-wrapped)\n // processors are skipped by ProcessorRunner.runProcessLLMRequest.\n llmRequestInputProcessors = await typedAgent.__listLLMRequestProcessors(requestContext);\n // Call-time outputProcessors replace constructor-level ones (parity with\n // Agent.listResolvedOutputProcessors which uses overrides-first semantics).\n outputProcessors = execOptions?.outputProcessors\n ? execOptions.outputProcessors\n : await typedAgent.listOutputProcessors(requestContext);\n errorProcessors = await typedAgent.listErrorProcessors(requestContext);\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error resolving processors: ${error}`);\n }\n\n // Open AGENT_RUN here so processor_run spans (and their MEMORY_OPERATION\n // children) parent to it. MODEL_GENERATION is opened later under it.\n //\n // Mirrors non-durable Agent.stream(): forward attributes (conversationId,\n // resolved instructions string, resolvedVersionId), metadata (entityVersionId),\n // and the agent-level tracingPolicy so durable runs land in the same span\n // shape as in-process runs.\n const rawConfig = typeof (agent as any).toRawConfig === 'function' ? (agent as any).toRawConfig() : undefined;\n const resolvedVersionId = rawConfig?.resolvedVersionId as string | undefined;\n const agentTracingPolicy =\n typeof (agent as any).getTracingPolicy === 'function' ? (agent as any).getTracingPolicy() : undefined;\n const agentSpan = getOrCreateSpan({\n type: SpanType.AGENT_RUN,\n name: `agent run: '${publicAgentId}'`,\n entityType: EntityType.AGENT,\n entityId: publicAgentId,\n entityName: publicAgentName,\n input: messages,\n attributes: {\n conversationId: threadId,\n instructions: convertInstructionsToString(instructions),\n // @deprecated — use entityVersionId (top-level span context field) instead.\n // Kept for backward compatibility during migration.\n ...(resolvedVersionId ? { resolvedVersionId } : {}),\n },\n metadata: {\n runId,\n resourceId,\n threadId,\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n tracingPolicy: agentTracingPolicy,\n tracingContext: execOptions?.tracingContext,\n tracingOptions: execOptions?.tracingOptions,\n requestContext,\n mastra,\n });\n // Run processInput (once, before execution) if we have any processors.\n // The MastraMemory context (thread + memoryConfig) was already established\n // above, before processor resolution, so processors that need it (working\n // memory, OM, message history) can access it here.\n let tripwireData: RunRegistryEntry['tripwire'];\n if (inputProcessors.length > 0) {\n try {\n const { ProcessorRunner } = await import('../../processors/runner');\n const runner = new ProcessorRunner({\n inputProcessors,\n outputProcessors,\n errorProcessors,\n logger: logger as any,\n agentName: publicAgentName,\n processorStates,\n });\n await runner.runInputProcessors(\n messageList,\n createObservabilityContext({ currentSpan: agentSpan }),\n requestContext,\n 0,\n );\n } catch (error) {\n if (error instanceof TripWire) {\n tripwireData = {\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n processorId: error.processorId,\n };\n logger?.warn?.('Input processor tripwire triggered', {\n agent: publicAgentName,\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n } else {\n logger?.warn?.(`[DurableAgent] Error running input processors: ${error}`);\n }\n }\n }\n\n // 7. Convert tools to CoreTool format for execution\n let tools: Record<string, CoreTool> = {};\n try {\n tools = await typedAgent.getToolsForExecution({\n toolsets: execOptions?.toolsets,\n clientTools: execOptions?.clientTools,\n threadId,\n resourceId,\n runId,\n requestContext,\n memoryConfig: execOptions?.memory?.options,\n autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,\n hooks: execOptions?.hooks,\n delegation: execOptions?.delegation,\n methodType,\n });\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error converting tools: ${error}`);\n }\n\n // 8. Get model (and model list if configured)\n const model = await typedAgent.getModel({ requestContext });\n if (!model) {\n throw new Error('Agent model not available');\n }\n\n const modelList = await typedAgent.getModelList(requestContext);\n\n // 8b. Get scorers configuration\n const overrideScorers = (execOptions as any)?.scorers;\n let scorers: Record<string, { scorer: any; sampling?: any }> | undefined;\n\n if (overrideScorers) {\n scorers = overrideScorers;\n } else {\n try {\n const agentScorers = await typedAgent.listScorers({ requestContext });\n if (agentScorers && Object.keys(agentScorers).length > 0) {\n scorers = agentScorers;\n }\n } catch (error) {\n logger?.debug?.(`[DurableAgent] Error getting scorers: ${error}`);\n }\n }\n\n // 9. Create SaveQueueManager (memory + memoryConfig were resolved in step 6)\n const saveQueueManager = memory\n ? new SaveQueueManager({\n logger,\n memory,\n })\n : undefined;\n\n // 10. Serialize structured output if provided\n let serializedStructuredOutput: SerializableStructuredOutput | undefined;\n if (execOptions?.structuredOutput) {\n const so = execOptions.structuredOutput as any;\n if (so.schema) {\n serializedStructuredOutput = {\n jsonPromptInjection: so.jsonPromptInjection,\n useAgent: so.useAgent,\n };\n // Convert Zod schema to JSON Schema if possible\n if (typeof so.schema === 'object' && 'type' in so.schema) {\n serializedStructuredOutput.schema = so.schema;\n } else if (typeof so.schema === 'object' && 'jsonSchema' in so.schema) {\n serializedStructuredOutput.schema = so.schema.jsonSchema;\n }\n }\n }\n\n // 11. Get background task config. When the caller opts out with\n // `disableBackgroundTasks: true`, drop the manager so the registry entry\n // signals \"no background tasks for this run\" to the check step.\n const backgroundTasksConfig = typedAgent.getBackgroundTasksConfig?.();\n const backgroundTaskManager = execOptions?.disableBackgroundTasks ? undefined : mastra?.backgroundTaskManager;\n\n // Resolve tool payload transform policy with the same precedence the\n // non-durable Agent uses: per-call > agent-level > mastra-level. The\n // resolved policy carries a closure, so it lives on the run registry; the\n // JSON-safe `targets` shadow is serialized into workflow input below.\n const toolPayloadTransform =\n normalizeToolPayloadTransformPolicy(execOptions?.transform) ??\n typedAgent.getToolPayloadTransform?.() ??\n normalizeToolPayloadTransformPolicy(\n mastra?.getToolPayloadTransform?.() ?? (mastra as any)?.getToolPayloadProjection?.(),\n );\n\n // 12. Resolve memory persistence flags\n const savePerStep = execOptions?.savePerStep;\n const observationalMemory = !!memoryConfig?.observationalMemory;\n\n // 12b. Open MODEL_GENERATION under the AGENT_RUN opened in step 6, and export both\n // into the workflow input so each durable step can rebuild them. No-ops when\n // observability is off.\n const modelSpan = agentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n name: `llm: '${model.modelId}'`,\n attributes: {\n model: model.modelId,\n provider: model.provider,\n streaming: true,\n },\n metadata: {\n runId,\n threadId,\n resourceId,\n },\n requestContext,\n });\n\n // 13. Create serialized workflow input\n const workflowInput = createWorkflowInput({\n runId,\n agentId: publicAgentId,\n agentName: publicAgentName,\n messageList,\n tools,\n model,\n modelList: modelList ?? undefined,\n scorers,\n options: {\n maxSteps: execOptions?.maxSteps,\n toolChoice: execOptions?.toolChoice as any,\n activeTools: execOptions?.activeTools,\n modelSettings: execOptions?.modelSettings as any,\n // Function-form approval policies are closures that can't ride on the\n // serialized workflow input — the live closure is parked on the run\n // registry below. This boolean shadow is the cross-process fallback:\n // function policies degrade to \"require approval for every tool call\"\n // when the registry slot is unavailable (e.g. Inngest after a worker\n // restart), which is the safe default.\n requireToolApproval:\n typeof execOptions?.requireToolApproval === 'function' ? true : execOptions?.requireToolApproval,\n toolCallConcurrency: execOptions?.toolCallConcurrency,\n autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,\n maxProcessorRetries: execOptions?.maxProcessorRetries,\n includeRawChunks: execOptions?.includeRawChunks,\n returnScorerData: (execOptions as any)?.returnScorerData,\n hasErrorProcessors: errorProcessors.length > 0,\n providerOptions: execOptions?.providerOptions,\n structuredOutput: serializedStructuredOutput,\n skipBgTaskWait: (execOptions as any)?._skipBgTaskWait,\n disableBackgroundTasks: execOptions?.disableBackgroundTasks,\n tracingOptions: execOptions?.tracingOptions,\n actor: execOptions?.actor,\n instructionsOverride: execOptions?.instructions,\n systemMessage: execOptions?.system,\n transform: toolPayloadTransform?.targets ? { targets: toolPayloadTransform.targets } : undefined,\n isTaskComplete: execOptions?.isTaskComplete\n ? {\n scorerNames: execOptions.isTaskComplete.scorers?.map(s => s.name).filter((n): n is string => !!n),\n strategy: execOptions.isTaskComplete.strategy,\n timeout: execOptions.isTaskComplete.timeout,\n parallel: execOptions.isTaskComplete.parallel,\n suppressFeedback: execOptions.isTaskComplete.suppressFeedback,\n }\n : undefined,\n },\n state: {\n memoryConfig,\n threadId,\n resourceId,\n threadExists,\n savePerStep,\n observationalMemory,\n },\n messageId,\n agentSpanData: agentSpan?.exportSpan(),\n modelSpanData: modelSpan?.exportSpan(),\n requestContextEntries: requestContextEntriesSnapshot,\n });\n\n // 14. Create registry entry for non-serializable state\n const registryEntry: RunRegistryEntry = {\n tools,\n saveQueueManager,\n memory,\n model,\n modelList: modelList\n ? modelList.map((entry: AgentModelManagerConfig) => ({\n id: entry.id,\n model: entry.model,\n maxRetries: entry.maxRetries ?? 0,\n enabled: entry.enabled ?? true,\n headers: entry.headers,\n }))\n : undefined,\n workspace,\n requestContext,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n backgroundTaskManager,\n backgroundTasksConfig,\n agentSpan,\n modelSpan,\n // Park the stopWhen predicate(s) on the registry so the durable agentic\n // loop can evaluate them on each iteration. The predicate is a closure and\n // cannot ride on the serialized workflow input; in-process engines read it\n // back via globalRunRegistry, cross-process engines degrade to maxSteps.\n stopWhen: execOptions?.stopWhen,\n onIterationComplete: execOptions?.onIterationComplete,\n prepareStep: execOptions?.prepareStep,\n toolPayloadTransform,\n isTaskComplete: execOptions?.isTaskComplete,\n // Park the per-call requireToolApproval policy on the registry so the\n // durable tool-call step can evaluate function-form policies with the\n // real (toolName, args) on each call. The boolean shadow on the\n // serialized workflow input is the cross-process fallback.\n requireToolApproval: execOptions?.requireToolApproval,\n // Signal drain — the closure reads from AgentThreadStreamRuntime's queues.\n // Non-serializable; cross-process engines lose it and signals go undelivered.\n drainPendingSignals: scope => typedAgent.__getDrainPendingSignals()(runId, scope),\n // Thread title generation — mirrors the non-durable `#executeOnFinish` branch,\n // which was never ported to the durable finish step (so `generateTitle` never\n // fired for durable/evented agents). Parked here because the agent instance is\n // in scope; the durable finish step invokes it after the run completes. No-op\n // when the merged config has no `generateTitle` or the thread already has a\n // title. Non-serializable — cross-process engines skip title generation.\n generateThreadTitle: memory\n ? async ({ threadId, resourceId, memoryConfig, messageListState, requestContext: rc, tracingContext }) => {\n // Re-read the thread so a title written mid-run isn't regenerated, and so we only\n // generate on the first turn (mirrors the non-durable `!thread.title` guard).\n const thread = await memory.getThreadById?.({ threadId });\n const mergedConfig = memory.getMergedThreadConfig?.(memoryConfig);\n const { shouldGenerate, model, instructions, minMessages } = agent.resolveTitleGenerationConfig(\n mergedConfig?.generateTitle as Parameters<typeof agent.resolveTitleGenerationConfig>[0],\n );\n if (!shouldGenerate || thread?.title) return;\n\n const titleMessageList = new MessageList().deserialize(messageListState);\n const uiMessages = titleMessageList.get.all.ui();\n const coreMessages = titleMessageList.get.all.core();\n if (coreMessages.length < (minMessages ?? 1)) return;\n\n const userMessage = agent.getMostRecentUserMessage(uiMessages);\n if (!userMessage) return;\n\n const title = await agent.genTitle(\n userMessage,\n rc ?? new RequestContext(),\n createObservabilityContext(tracingContext),\n model,\n instructions,\n uiMessages,\n );\n if (!title) return;\n\n // Title-only late write. Prefer updateThread when the thread record\n // already exists so its original createdAt is preserved (createThread\n // rebuilds the record with a fresh createdAt). Fall back to createThread\n // for the first-turn case where the record may not be persisted yet.\n if (thread) {\n await memory.updateThread({\n id: threadId,\n title,\n metadata: thread.metadata ?? {},\n memoryConfig,\n });\n } else {\n await memory.createThread({\n threadId,\n resourceId,\n memoryConfig,\n title,\n });\n }\n }\n : undefined,\n // Signal messages already in the messageList at run start (from persisted\n // history). Echoed as data-signal parts on the first LLM step so the client\n // sees them without refetching. Spliced once, never re-emitted.\n initialSignalEchoes: getInitialSignalEchoes(messageList),\n // Agent-level goal config (judge resolver, tools resolver, scorer).\n // Non-serializable — cross-process engines skip goal evaluation.\n goal: agent.__getGoalConfig(),\n // Tripwire from processInput (initial input processing). When an input\n // processor calls abort() during runInputProcessors, we store the tripwire\n // data here so the first llm-execution step can emit a tripwire chunk and\n // bail immediately without calling the model.\n tripwire: tripwireData,\n // Call-time headers from modelSettings.headers. Kept off the serialized\n // workflow input so they never reach durable storage; the durable\n // llm-execution step reads them from this registry slot instead.\n callTimeHeaders: extractCallTimeHeaders(execOptions?.modelSettings),\n // Call-time structured output config with the live schema. The schema is\n // non-serializable (Zod / standard-schema instance), so it lives on the\n // in-process registry. The durable stream adapter reads it to pipe LLM\n // text through `createObjectStreamTransformer`, producing `object-result`\n // chunks. Cross-process engines lose this slot and structured output\n // degrades to raw text.\n structuredOutput: execOptions?.structuredOutput?.schema\n ? {\n ...execOptions.structuredOutput,\n schema: toStandardSchema(execOptions.structuredOutput.schema),\n }\n : undefined,\n cleanup: () => {},\n };\n\n return {\n runId,\n messageId,\n workflowInput,\n registryEntry,\n messageList,\n threadId,\n resourceId,\n };\n}\n\n/**\n * Extract string-valued headers from `modelSettings.headers` for storage on the\n * in-process `RunRegistryEntry`. Returns `undefined` when no valid headers are\n * present so the registry slot stays empty rather than carrying an empty object.\n */\nfunction extractCallTimeHeaders(\n modelSettings: Record<string, unknown> | undefined,\n): Record<string, string> | undefined {\n const raw = (modelSettings as Record<string, unknown> | undefined)?.headers;\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n\n const headers: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {\n if (typeof value === 'string') headers[key] = value;\n }\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n","import { TTLCache } from '@isaacs/ttlcache';\nimport type { MastraLanguageModel } from '../../llm/model/shared.types';\nimport type { CoreTool } from '../../tools/types';\nimport type { MessageList } from '../message-list';\nimport type { SaveQueueManager } from '../save-queue';\nimport type { RunRegistryEntry } from './types';\n\n/**\n * Global registry for accessing run entries from workflow steps.\n * This is necessary because workflow steps don't have direct access to\n * the DurableAgent instance's registry.\n *\n * Entries are keyed by runId (which are unique UUIDs).\n *\n * Uses TTLCache to prevent unbounded memory growth: entries auto-expire\n * after 10 minutes (refreshed on access) and the registry is hard-capped\n * at 1000 concurrent entries.\n */\nexport const globalRunRegistry = new TTLCache<string, RunRegistryEntry>({\n max: 1000,\n ttl: 10 * 60 * 1000,\n updateAgeOnGet: true,\n dispose: entry => {\n entry?.cleanup?.();\n },\n noDisposeOnSet: true,\n});\n\n/**\n * End a run's root spans (MODEL_GENERATION then AGENT_RUN) with an error so the trace\n * still exports — stores persist only span-end events. After a resume the fresh resume\n * spans are the active root, so prefer them. Ending an already-ended span is a no-op,\n * so the duplicate error paths (workflow failure + emitError) are safe. Never throws.\n */\nexport function endRunSpansWithError(runId: string, error: Error): void {\n try {\n const entry = globalRunRegistry.get(runId);\n (entry?.resumeModelSpan ?? entry?.modelSpan)?.error({ error, endSpan: true });\n (entry?.resumeAgentSpan ?? entry?.agentSpan)?.error({ error, endSpan: true });\n } catch {\n // Span bookkeeping must never break error reporting.\n }\n}\n\n/**\n * Registry for per-run non-serializable state.\n *\n * During durable execution, the DurableAgent needs to store non-serializable\n * objects (tools with execute functions, SaveQueueManager, etc.) that can't\n * flow through workflow state. This registry provides a way to store and\n * retrieve these objects keyed by runId.\n *\n * The registry is scoped to a single DurableAgent instance and entries are\n * cleaned up when a run completes.\n */\nexport class RunRegistry {\n #entries = new Map<string, RunRegistryEntry>();\n\n /**\n * Register non-serializable state for a run\n * @param runId - The unique run identifier\n * @param entry - The registry entry containing tools, saveQueueManager, etc.\n */\n register(runId: string, entry: RunRegistryEntry): void {\n // Clean up any existing entry first\n this.cleanup(runId);\n this.#entries.set(runId, entry);\n }\n\n /**\n * Get the registry entry for a run\n * @param runId - The unique run identifier\n * @returns The registry entry or undefined if not found\n */\n get(runId: string): RunRegistryEntry | undefined {\n return this.#entries.get(runId);\n }\n\n /**\n * Get tools for a specific run\n * @param runId - The unique run identifier\n * @returns The tools record or an empty object if not found\n */\n getTools(runId: string): Record<string, CoreTool> {\n return this.#entries.get(runId)?.tools ?? {};\n }\n\n /**\n * Get SaveQueueManager for a specific run\n * @param runId - The unique run identifier\n * @returns The SaveQueueManager or undefined if not found\n */\n getSaveQueueManager(runId: string): SaveQueueManager | undefined {\n return this.#entries.get(runId)?.saveQueueManager;\n }\n\n /**\n * Get the language model for a specific run\n * @param runId - The unique run identifier\n * @returns The MastraLanguageModel or undefined if not found\n */\n getModel(runId: string): MastraLanguageModel | undefined {\n return this.#entries.get(runId)?.model;\n }\n\n /**\n * Check if a run is registered\n * @param runId - The unique run identifier\n * @returns True if the run is registered\n */\n has(runId: string): boolean {\n return this.#entries.has(runId);\n }\n\n /**\n * Cleanup and remove a run's entry from the registry\n * @param runId - The unique run identifier\n */\n cleanup(runId: string): void {\n const entry = this.#entries.get(runId);\n if (entry) {\n // Call cleanup function if provided\n entry.cleanup?.();\n this.#entries.delete(runId);\n }\n }\n\n /**\n * Get the number of active runs in the registry\n */\n get size(): number {\n return this.#entries.size;\n }\n\n /**\n * Get all active run IDs\n */\n get runIds(): string[] {\n return Array.from(this.#entries.keys());\n }\n\n /**\n * Clear all entries from the registry\n * Calls cleanup on each entry before removing\n */\n clear(): void {\n for (const runId of this.#entries.keys()) {\n this.cleanup(runId);\n }\n }\n}\n\n/**\n * Extended registry entry that also stores the MessageList reference.\n * This is useful for accessing message state outside of workflow steps\n * (e.g., for callbacks that need to read messages).\n */\nexport interface ExtendedRunRegistryEntry extends RunRegistryEntry {\n /** MessageList reference for callback access */\n messageList?: MessageList;\n /** Thread ID for memory */\n threadId?: string;\n /** Resource ID for memory */\n resourceId?: string;\n}\n\n/**\n * Extended run registry that also stores MessageList references and memory info\n */\nexport class ExtendedRunRegistry extends RunRegistry {\n #messageLists = new Map<string, MessageList>();\n #memoryInfo = new Map<string, { threadId?: string; resourceId?: string }>();\n\n /**\n * Register non-serializable state for a run including MessageList\n */\n registerWithMessageList(\n runId: string,\n entry: RunRegistryEntry,\n messageList: MessageList,\n memoryInfo?: { threadId?: string; resourceId?: string },\n ): void {\n this.register(runId, entry);\n this.#messageLists.set(runId, messageList);\n if (memoryInfo) {\n this.#memoryInfo.set(runId, memoryInfo);\n }\n }\n\n /**\n * Get MessageList for a specific run\n */\n getMessageList(runId: string): MessageList | undefined {\n return this.#messageLists.get(runId);\n }\n\n /**\n * Get memory info for a specific run\n */\n getMemoryInfo(runId: string): { threadId?: string; resourceId?: string } | undefined {\n return this.#memoryInfo.get(runId);\n }\n\n /**\n * Override cleanup to also remove MessageList and memory info\n */\n override cleanup(runId: string): void {\n super.cleanup(runId);\n this.#messageLists.delete(runId);\n this.#memoryInfo.delete(runId);\n }\n\n /**\n * Override clear to also clear MessageLists and memory info\n */\n override clear(): void {\n super.clear();\n this.#messageLists.clear();\n this.#memoryInfo.clear();\n }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport type { PubSub } from '../../events/pubsub';\nimport type { Event } from '../../events/types';\nimport type { IMastraLogger } from '../../logger';\nimport type { OutputProcessorOrWorkflow } from '../../processors';\nimport { safeClose, safeEnqueue } from '../../stream/base';\nimport { MastraModelOutput } from '../../stream/base/output';\nimport type {\n ChunkType,\n MastraOnFinishCallback,\n MastraOnStepFinishCallback,\n MastraStreamTransformOptions,\n LanguageModelUsage,\n} from '../../stream/types';\nimport { MessageList } from '../message-list';\nimport type { StructuredOutputOptions } from '../types';\nimport { AGENT_STREAM_TOPIC, AgentStreamEventTypes } from './constants';\nimport type {\n AgentStreamEvent,\n AgentChunkEventData,\n AgentStepFinishEventData,\n AgentFinishEventData,\n AgentErrorEventData,\n AgentSuspendedEventData,\n AgentAbortEventData,\n AgentIterationCompleteEventData,\n} from './types';\n\n/**\n * Map workflow usage (which may use legacy promptTokens/completionTokens) to\n * the canonical LanguageModelUsage shape (inputTokens/outputTokens).\n */\nfunction normalizeUsage(raw?: Record<string, unknown>): LanguageModelUsage {\n if (!raw) {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n }\n const inputTokens = (raw.inputTokens as number) ?? (raw.promptTokens as number) ?? 0;\n const outputTokens = (raw.outputTokens as number) ?? (raw.completionTokens as number) ?? 0;\n const totalTokens = (raw.totalTokens as number) ?? inputTokens + outputTokens;\n return { inputTokens, outputTokens, totalTokens };\n}\n\n/**\n * Options for creating a durable agent stream\n */\nexport interface DurableAgentStreamOptions<OUTPUT = undefined> {\n /** Pubsub instance to subscribe to */\n pubsub: PubSub;\n /** Run identifier */\n runId: string;\n /** Message ID for this execution */\n messageId: string;\n /** Model information for the output */\n model: {\n modelId: string | undefined;\n provider: string | undefined;\n version: 'v2' | 'v3' | 'v4';\n };\n /** Thread ID for memory */\n threadId?: string;\n /** Resource ID for memory */\n resourceId?: string;\n /**\n * Start replay from this index (0-based).\n * If undefined, uses full replay (subscribeWithReplay).\n * If specified, uses efficient indexed replay (subscribeFromOffset).\n */\n offset?: number;\n /** Callback when chunk is received */\n onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;\n /** Callback when step finishes */\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n /** Callback when execution finishes — routed through MastraModelOutput for rich step data */\n onFinish?: MastraOnFinishCallback<OUTPUT>;\n /** Lifecycle hook called after the FINISH event closes the stream (for cleanup scheduling) */\n onStreamFinished?: () => void | Promise<void>;\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 */\n onAbort?: (data: AgentAbortEventData) => void | Promise<void>;\n /** Callback fired after each agentic-loop iteration */\n onIterationComplete?: (data: AgentIterationCompleteEventData) => void | Promise<void>;\n /** Optional logger for structured logging */\n logger?: IMastraLogger;\n /**\n * If true, close the underlying ReadableStream when a SUSPENDED event is\n * received. Used by `generate()` / `resumeGenerate()` so that\n * `getFullOutput()` resolves on suspend instead of hanging. Streaming\n * callers leave this `false` so the stream stays open for a later resume.\n */\n closeOnSuspend?: boolean;\n /**\n * Structured output configuration with live schema. When provided,\n * `MastraModelOutput` pipes LLM text through `createObjectStreamTransformer`\n * to produce `object-result` chunks.\n */\n structuredOutput?: StructuredOutputOptions<OUTPUT>;\n /** Output processors to run in MastraModelOutput's stream pipeline */\n outputProcessors?: OutputProcessorOrWorkflow[];\n /** Experimental transforms applied whenever the returned full stream is consumed. */\n experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;\n /**\n * Optional external MessageList to use instead of creating a fresh empty one.\n * When provided (e.g. the registry's live MessageList), MastraModelOutput can\n * resolve step content from messages added during the workflow execution.\n */\n messageList?: MessageList;\n}\n\n/**\n * Result from creating a durable agent stream\n */\nexport interface DurableAgentStreamResult<OUTPUT = undefined> {\n /** The MastraModelOutput that streams from pubsub events */\n output: MastraModelOutput<OUTPUT>;\n /** Cleanup function to unsubscribe from pubsub */\n cleanup: () => void;\n /** Promise that resolves when subscription is established */\n ready: Promise<void>;\n}\n\n/**\n * Create a MastraModelOutput that streams from pubsub events.\n *\n * This adapter subscribes to the agent stream pubsub channel and converts\n * pubsub events into a ReadableStream that MastraModelOutput can consume.\n * Callbacks are invoked as events arrive.\n */\nexport function createDurableAgentStream<OUTPUT = undefined>(\n options: DurableAgentStreamOptions<OUTPUT>,\n): DurableAgentStreamResult<OUTPUT> {\n const {\n pubsub,\n runId,\n messageId,\n model,\n threadId,\n resourceId,\n offset,\n onChunk,\n onStepFinish,\n onFinish,\n onStreamFinished,\n onError,\n onSuspended,\n onAbort,\n onIterationComplete,\n logger,\n closeOnSuspend = false,\n structuredOutput,\n outputProcessors,\n experimentalTransform,\n messageList: externalMessageList,\n } = options;\n\n // Helper to log errors (uses logger if available, falls back to console)\n const logError = (message: string, error: unknown) => {\n if (logger) {\n logger.error(message, error);\n } else {\n console.error(message, error);\n }\n };\n\n // Use an external MessageList if provided (e.g. the live registry one that\n // llm-execution.ts keeps in sync), otherwise create a fresh empty one.\n // This lets MastraModelOutput resolve step content from the real assistant\n // messages added during the workflow execution.\n const messageList =\n externalMessageList ??\n new MessageList({\n threadId,\n resourceId,\n });\n\n // Track subscription state\n let isSubscribed = false;\n let cancelled = false;\n let controller: ReadableStreamDefaultController<ChunkType<OUTPUT>> | null = null;\n\n // Promise that resolves when subscription is established\n let resolveReady: () => void;\n let rejectReady: (error: Error) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n // Handler for pubsub events.\n //\n // All `controller.enqueue` / `controller.close` / `controller.error` calls\n // are wrapped in safe* helpers because pubsub events can arrive AFTER the\n // stream has already been closed (e.g. a stale background-task lifecycle\n // event published after the agent's FINISH chunk closed the controller).\n // Without the guards, those late events surface as\n // `TypeError: Invalid state: Controller is already closed` from the\n // controller, which the outer try/catch logs but which floods the\n // console and (in test runs) causes timeouts as event handlers retry.\n // Track the last error message seen in an 'error' chunk, so we can\n // surface it in onError when the FINISH event arrives with reason 'error'.\n let lastErrorMessage: string | undefined;\n\n const handleEvent = async (event: Event) => {\n if (!controller) return;\n\n // Parse the event data as AgentStreamEvent\n const streamEvent = event as unknown as AgentStreamEvent;\n\n try {\n switch (streamEvent.type) {\n case AgentStreamEventTypes.CHUNK: {\n const chunk = streamEvent.data as AgentChunkEventData;\n // Track error chunks for onError callback\n if ((chunk as any).type === 'error') {\n const errPayload = (chunk as any).payload;\n lastErrorMessage = errPayload?.error?.message || errPayload?.message || 'LLM execution error';\n }\n safeEnqueue(controller, chunk as ChunkType<OUTPUT>);\n await onChunk?.(chunk as ChunkType<OUTPUT>);\n break;\n }\n\n case AgentStreamEventTypes.STEP_START: {\n // Step start - enqueue if it's a chunk type\n const chunk = streamEvent.data as ChunkType<OUTPUT>;\n if (chunk && 'type' in chunk) {\n safeEnqueue(controller, chunk);\n }\n break;\n }\n\n case AgentStreamEventTypes.STEP_FINISH: {\n const data = streamEvent.data as AgentStepFinishEventData;\n await onStepFinish?.(data);\n break;\n }\n\n case AgentStreamEventTypes.FINISH: {\n const data = streamEvent.data as AgentFinishEventData;\n // Enqueue finish chunk and close stream even if callback throws\n const finishChunk = {\n type: 'finish' as const,\n payload: {\n output: data.output,\n stepResult: data.stepResult,\n },\n } as ChunkType<OUTPUT>;\n safeEnqueue(controller, finishChunk);\n safeClose(controller);\n\n // Build rich onFinish payload from finish event data.\n // The pubsub FINISH event carries output.text, output.steps, and\n // stepResult — enough to reconstruct the fields scenario tests expect\n // (text, steps, toolResults, finishReason, usage).\n if (onFinish) {\n try {\n const steps = (data.output?.steps ?? []) as any[];\n const allToolResults = steps.flatMap((s: any) => s?.toolResults ?? []);\n const allToolCalls = steps.flatMap((s: any) => s?.toolCalls ?? []);\n await onFinish({\n text: data.output?.text ?? '',\n steps,\n toolResults: allToolResults,\n toolCalls: allToolCalls,\n dynamicToolCalls: [],\n dynamicToolResults: [],\n staticToolCalls: [],\n staticToolResults: [],\n files: [],\n sources: [],\n reasoning: [],\n content: [],\n finishReason: data.stepResult?.reason ?? 'stop',\n usage: normalizeUsage(data.output?.usage),\n totalUsage: normalizeUsage(data.output?.usage),\n warnings: data.stepResult?.warnings ?? [],\n request: { body: undefined },\n response: {},\n reasoningText: undefined,\n providerMetadata: undefined,\n });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onFinish callback error:`, callbackError);\n }\n }\n\n // When the finish reason is 'abort', also fire onAbort so\n // consumers see it — the abort was handled gracefully (clean\n // return from llm-execution) rather than crashing the workflow,\n // so the separate ABORT event never fires.\n if (onAbort && (data.stepResult?.reason as string) === 'abort') {\n try {\n await onAbort({ steps: (data.output?.steps ?? []) as unknown[] });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onAbort (from FINISH) callback error:`, callbackError);\n }\n }\n\n // When the finish reason is 'error', also fire onError so\n // consumers see it — the error was handled gracefully (bail\n // response) rather than crashing the workflow, so the ERROR\n // event never fires.\n if (onError && data.stepResult?.reason === 'error') {\n try {\n await onError({ error: new Error(lastErrorMessage || 'LLM execution error') });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onError (from FINISH) callback error:`, callbackError);\n }\n }\n\n try {\n await onStreamFinished?.();\n } catch (callbackError) {\n logError(`[DurableAgentStream] onStreamFinished callback error:`, callbackError);\n }\n break;\n }\n\n case AgentStreamEventTypes.ERROR: {\n const data = streamEvent.data as AgentErrorEventData;\n const error = new Error(data.error.message);\n error.name = data.error.name;\n if (data.error.stack) {\n error.stack = data.error.stack;\n }\n // Enqueue an error chunk and close the stream normally (mirrors the\n // regular agent's deferred-error-chunk pattern). Using\n // controller.error() would error the base ReadableStream, which\n // MastraModelOutput.consumeStream swallows — leaving fullStream\n // hanging because no 'finish' event fires on the internal emitter.\n safeEnqueue(controller, {\n type: 'error',\n payload: { error },\n } as ChunkType<OUTPUT>);\n safeClose(controller);\n try {\n await onError?.({ error });\n } catch (callbackError) {\n logError(`[DurableAgentStream] onError callback error:`, callbackError);\n }\n break;\n }\n\n case AgentStreamEventTypes.SUSPENDED: {\n const data = streamEvent.data as AgentSuspendedEventData;\n await onSuspended?.(data);\n // By default we leave the stream open on suspend so a later resume\n // can keep streaming chunks. `generate()`/`resumeGenerate()` opt\n // into closing here so `getFullOutput()` can resolve.\n if (closeOnSuspend) {\n safeClose(controller);\n }\n break;\n }\n\n case AgentStreamEventTypes.ABORT: {\n const data = streamEvent.data as AgentAbortEventData;\n try {\n await onAbort?.(data);\n } catch (callbackError) {\n logError(`[DurableAgentStream] onAbort callback error:`, callbackError);\n }\n // Abort closes the stream — the run will not continue.\n safeClose(controller);\n break;\n }\n\n case AgentStreamEventTypes.ITERATION_COMPLETE: {\n const data = streamEvent.data as AgentIterationCompleteEventData;\n try {\n await onIterationComplete?.(data);\n } catch (callbackError) {\n logError(`[DurableAgentStream] onIterationComplete callback error:`, callbackError);\n }\n break;\n }\n\n default:\n // Unknown event type - ignore\n break;\n }\n } catch (error) {\n // Intentional catch-and-continue: callback errors (onChunk, onStepFinish,\n // onSuspended) must not kill the stream. onFinish/onError have their own\n // inner try/catch and close/error the stream before invoking callbacks,\n // so they are not affected by this outer handler.\n logError(`[DurableAgentStream] Error handling event ${streamEvent.type}:`, error);\n }\n };\n\n // Create the readable stream\n const stream = new ReadableStream<ChunkType<OUTPUT>>({\n start(ctrl) {\n controller = ctrl;\n\n // Subscribe to pubsub with replay support for resumable streams\n // If offset is specified, use indexed replay for efficiency\n // Otherwise use full replay\n const topic = AGENT_STREAM_TOPIC(runId);\n const subscribePromise =\n offset !== undefined\n ? pubsub.subscribeFromOffset(topic, offset, handleEvent)\n : pubsub.subscribeWithReplay(topic, handleEvent);\n\n subscribePromise\n .then(() => {\n if (cancelled) {\n // cleanup() was called before subscribe resolved — unsubscribe now\n void pubsub.unsubscribe(topic, handleEvent).catch(error => {\n logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, error);\n });\n resolveReady();\n return;\n }\n isSubscribed = true;\n resolveReady();\n })\n .catch(error => {\n logError(`[DurableAgentStream] Failed to subscribe to ${topic}:`, error);\n rejectReady(error);\n ctrl.error(error);\n });\n },\n cancel() {\n cleanup();\n },\n });\n\n // Cleanup function - intentionally fire-and-forget for unsubscribe.\n // Sets cancelled=true so the subscribe .then() handler will unsubscribe\n // if cleanup runs before the subscription promise resolves.\n const cleanup = () => {\n cancelled = true;\n if (isSubscribed) {\n isSubscribed = false;\n const topic = AGENT_STREAM_TOPIC(runId);\n void pubsub.unsubscribe(topic, handleEvent).catch(error => {\n logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, error);\n });\n }\n controller = null;\n };\n\n // Create the MastraModelOutput.\n // onStepFinish is passed to MastraModelOutput so it fires during stream\n // consumption (the harness and user code iterate fullStream, which drives\n // consumeStream internally). The pubsub STEP_FINISH event is not emitted\n // by the durable workflow, so the pubsub handler alone is not sufficient.\n //\n // onFinish is called from the pubsub FINISH handler (above) with a\n // payload built from the event data. This ensures it fires even when\n // nobody iterates the stream (e.g. resume flows with delay-only waits).\n const output = new MastraModelOutput<OUTPUT>({\n model,\n stream,\n messageList,\n messageId,\n options: {\n runId,\n onStepFinish: onStepFinish as MastraOnStepFinishCallback<OUTPUT> | undefined,\n // For durable agents there is only one MastraModelOutput for the whole run.\n // isLLMExecutionStep must be true so output processors run per-chunk\n // (processOutputStream / processPart path) rather than the batch\n // runOutputProcessors path which only fires at finish. It also gates\n // createObjectStreamTransformer for structured output.\n // resolveFinalPromises forces text/finishReason promise resolution at\n // step-finish despite isLLMExecutionStep being true — durable agents have\n // no outer MastraModelOutput to resolve them.\n structuredOutput: structuredOutput as any,\n isLLMExecutionStep: true,\n resolveFinalPromises: true,\n outputProcessors,\n experimentalTransform,\n },\n });\n\n return {\n output,\n cleanup,\n ready,\n };\n}\n\n/**\n * Helper to emit a chunk event to pubsub\n */\nexport async function emitChunkEvent<OUTPUT = undefined>(\n pubsub: PubSub,\n runId: string,\n chunk: ChunkType<OUTPUT>,\n): Promise<void> {\n const topic = AGENT_STREAM_TOPIC(runId);\n await pubsub.publish(topic, {\n type: AgentStreamEventTypes.CHUNK,\n runId,\n data: chunk,\n });\n}\n\n/**\n * Helper to emit a step start event to pubsub.\n * The `data` payload must include `type: 'step-start'` so the stream-adapter\n * consumer recognises it as a `ChunkType` and enqueues it onto the client stream.\n */\nexport async function emitStepStartEvent(\n pubsub: PubSub,\n runId: string,\n data: { stepId?: string; request?: unknown; warnings?: unknown[] },\n): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.STEP_START,\n runId,\n data: { type: 'step-start', ...data },\n });\n}\n\n/**\n * Helper to emit a step finish event to pubsub\n */\nexport async function emitStepFinishEvent(\n pubsub: PubSub,\n runId: string,\n data: AgentStepFinishEventData,\n): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.STEP_FINISH,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit a finish event to pubsub\n */\nexport async function emitFinishEvent(pubsub: PubSub, runId: string, data: AgentFinishEventData): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.FINISH,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit an error event to pubsub\n */\nexport async function emitErrorEvent(pubsub: PubSub, runId: string, error: Error): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.ERROR,\n runId,\n data: {\n error: {\n name: error.name,\n message: error.message,\n // stack intentionally omitted — avoid leaking internals through external pubsub\n },\n },\n });\n}\n\n/**\n * Helper to emit a suspended event to pubsub\n */\nexport async function emitSuspendedEvent(pubsub: PubSub, runId: string, data: AgentSuspendedEventData): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.SUSPENDED,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit an abort event to pubsub\n */\nexport async function emitAbortEvent(pubsub: PubSub, runId: string, data: AgentAbortEventData): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.ABORT,\n runId,\n data,\n });\n}\n\n/**\n * Helper to emit an iteration-complete event to pubsub\n */\nexport async function emitIterationCompleteEvent(\n pubsub: PubSub,\n runId: string,\n data: AgentIterationCompleteEventData,\n): Promise<void> {\n await pubsub.publish(AGENT_STREAM_TOPIC(runId), {\n type: AgentStreamEventTypes.ITERATION_COMPLETE,\n runId,\n data,\n });\n}\n","import { z } from 'zod';\n\n/**\n * Shared Zod schemas for durable agentic workflows.\n *\n * These schemas are used by:\n * - Core DurableAgent workflow\n * - Inngest durable agent workflow\n * - Evented durable agent workflow (future)\n */\n\n/**\n * Schema for model configuration\n */\nexport const modelConfigSchema = z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n settings: z.record(z.string(), z.any()).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n});\n\n/**\n * Schema for model list entry (fallback support)\n */\nexport const modelListEntrySchema = z.object({\n id: z.string(),\n config: z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n originalConfig: z.union([z.string(), z.record(z.string(), z.any())]).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n }),\n maxRetries: z.number(),\n enabled: z.boolean(),\n});\n\n/**\n * Schema for accumulated usage across iterations\n */\nexport const accumulatedUsageSchema = z.object({\n inputTokens: z.number(),\n outputTokens: z.number(),\n totalTokens: z.number(),\n});\n\n/**\n * Schema for output from the durable agentic workflow\n */\nexport const durableAgenticOutputSchema = z.object({\n messageListState: z.any(),\n messageId: z.string(),\n stepResult: z.any(),\n output: z.object({\n text: z.string().optional(),\n usage: z.any(),\n steps: z.array(z.any()),\n }),\n state: z.any(),\n});\n\n/**\n * Base schema for durable agentic workflow input.\n * Implementations can extend this with additional fields.\n */\nexport const baseDurableAgenticInputSchema = 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});\n\n/**\n * Base schema for iteration state.\n * Implementations can extend this with additional fields.\n */\nexport const baseIterationStateSchema = z.object({\n // Original input fields\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: z.any(),\n options: z.any(),\n state: z.any(),\n messageId: z.string(),\n // Iteration tracking\n iterationCount: z.number(),\n accumulatedSteps: z.array(z.any()),\n accumulatedUsage: accumulatedUsageSchema,\n // Last step result for continuation check\n lastStepResult: z.any().optional(),\n // Background task tracking\n backgroundTaskPending: z.boolean().optional(),\n // Set when a delegation hook calls ctx.bail() — signals the loop to stop\n delegationBailed: z.boolean().optional(),\n // Set when onIterationComplete returns { continue: false, feedback } — allows\n // one more LLM turn with the feedback, then stops on the next predicate eval.\n pendingFeedbackStop: z.boolean().optional(),\n // Span data, carried unchanged so every iteration shares one trace\n agentSpanData: z.any().optional(),\n modelSpanData: z.any().optional(),\n});\n\n/**\n * Type for the base iteration state\n */\nexport type BaseIterationState = z.infer<typeof baseIterationStateSchema>;\n\n/**\n * Type for accumulated usage\n */\nexport type AccumulatedUsage = z.infer<typeof accumulatedUsageSchema>;\n","import type { DurableAgenticExecutionOutput } from '../../types';\nimport type { AccumulatedUsage, BaseIterationState } from './schemas';\n\n/**\n * Input for creating iteration state update\n */\nexport interface IterationStateUpdateInput {\n /** Current iteration state */\n currentState: BaseIterationState;\n /** Output from the current iteration's execution */\n executionOutput: DurableAgenticExecutionOutput;\n}\n\n/**\n * Step record for tracking iteration history\n */\nexport interface StepRecord {\n text?: string;\n toolCalls?: unknown[];\n toolResults?: unknown[];\n usage?: unknown;\n finishReason?: string;\n}\n\n/**\n * Calculate accumulated usage from current state and new execution output.\n */\nexport function calculateAccumulatedUsage(\n currentUsage: AccumulatedUsage,\n executionUsage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number },\n): AccumulatedUsage {\n return {\n inputTokens: currentUsage.inputTokens + (executionUsage?.inputTokens || 0),\n outputTokens: currentUsage.outputTokens + (executionUsage?.outputTokens || 0),\n totalTokens: currentUsage.totalTokens + (executionUsage?.totalTokens || 0),\n };\n}\n\n/**\n * Build a step record from execution output.\n */\nexport function buildStepRecord(executionOutput: DurableAgenticExecutionOutput): StepRecord {\n return {\n text: executionOutput.output.text,\n toolCalls: executionOutput.output.toolCalls,\n toolResults: executionOutput.toolResults,\n usage: executionOutput.output.usage,\n finishReason: executionOutput.stepResult.reason,\n };\n}\n\n/**\n * Create the base iteration state update.\n *\n * This returns the common fields for iteration state updates.\n * Implementations can extend this with their specific fields.\n *\n * @example\n * ```typescript\n * const baseUpdate = createBaseIterationStateUpdate({\n * currentState: initData,\n * executionOutput,\n * });\n *\n * // Core extends with modelList\n * const coreState = { ...baseUpdate, modelList: initData.modelList };\n *\n * // Inngest extends with observability\n * const inngestState = {\n * ...baseUpdate,\n * agentSpanData: initData.agentSpanData,\n * modelSpanData: initData.modelSpanData,\n * stepIndex: initData.stepIndex + 1,\n * };\n * ```\n */\nexport function createBaseIterationStateUpdate(input: IterationStateUpdateInput): BaseIterationState {\n const { currentState, executionOutput } = input;\n\n const newUsage = calculateAccumulatedUsage(currentState.accumulatedUsage, executionOutput.output.usage);\n const stepRecord = buildStepRecord(executionOutput);\n\n return {\n runId: currentState.runId,\n agentId: currentState.agentId,\n agentName: currentState.agentName,\n messageListState: executionOutput.messageListState,\n toolsMetadata: currentState.toolsMetadata,\n modelConfig: currentState.modelConfig,\n options: currentState.options,\n state: executionOutput.state,\n messageId: executionOutput.messageId,\n iterationCount: currentState.iterationCount + 1,\n accumulatedSteps: [...currentState.accumulatedSteps, stepRecord],\n accumulatedUsage: newUsage,\n lastStepResult: executionOutput.stepResult,\n backgroundTaskPending: executionOutput.backgroundTaskPending,\n delegationBailed: executionOutput.delegationBailed,\n // Preserve the two-phase stop flag set by the dowhile predicate's\n // onIterationComplete handler. The predicate mutates state on the\n // *output* of the previous iteration; createBaseIterationStateUpdate\n // rebuilds the state for the next iteration, so we must carry the\n // flag forward explicitly.\n pendingFeedbackStop: currentState.pendingFeedbackStop,\n // Carry span identity forward unchanged so every iteration shares one trace.\n agentSpanData: currentState.agentSpanData,\n modelSpanData: currentState.modelSpanData,\n };\n}\n","import { DurableAgentDefaults } from '../../constants';\nimport type { DurableToolCallInput, SerializableDurableOptions, SerializableToolMetadata } from '../../types';\n\n/**\n * Resolves the effective tool-call foreach concurrency for a durable agentic\n * workflow from the serialized workflow input (iteration state) and the\n * step's tool calls.\n *\n * Mirrors @mastra/core's non-durable loop semantics\n * (loop/workflows/agentic-execution/tool-call-concurrency.ts):\n * - Global `requireToolApproval` forces sequential execution. The serialized\n * boolean shadow is `true` for function-form policies, so those degrade\n * safely to sequential as well.\n * - Any tool in the step's *effective active tool set* with `requireApproval`\n * or `hasSuspendSchema` forces sequential execution so approval/suspension\n * flows never race with concurrent tool calls. The check is against the\n * active tool set, NOT the tools the model actually called: a registered\n * suspending/approval tool the model skipped this step must still force\n * sequential execution, since a concurrently-running sibling tool would\n * race the suspension.\n * - Otherwise the configured `toolCallConcurrency` applies\n * (default {@link DurableAgentDefaults.TOOL_CALL_CONCURRENCY}).\n *\n * The active tool set is the `activeTools` allowlist the LLM step stamps on\n * each tool call (processors may narrow or clear it; all calls in one step\n * share the value, `null` = restriction cleared → unrestricted). When the\n * calls carry no stamp, the run-level `activeTools` option applies.\n *\n * Designed to be called from a foreach concurrency resolver at execution\n * time, reading only serialized state — safe across durable-engine replays\n * and shared workflow instances.\n */\nexport function resolveDurableToolCallConcurrency({\n options,\n toolsMetadata,\n toolCalls,\n}: {\n options?: Pick<SerializableDurableOptions, 'requireToolApproval' | 'toolCallConcurrency' | 'activeTools'>;\n toolsMetadata?: SerializableToolMetadata[];\n toolCalls?: Pick<DurableToolCallInput, 'activeTools'>[];\n}): number {\n if (options?.requireToolApproval) {\n return 1;\n }\n\n const stamped = toolCalls?.find(tc => tc.activeTools !== undefined);\n const activeTools = stamped ? stamped.activeTools : options?.activeTools;\n const consideredTools =\n activeTools === undefined || activeTools === null\n ? (toolsMetadata ?? [])\n : (toolsMetadata ?? []).filter(tool => activeTools.includes(tool.name));\n\n if (consideredTools.some(tool => tool.hasSuspendSchema || tool.requireApproval)) {\n return 1;\n }\n\n const configured = options?.toolCallConcurrency;\n return typeof configured === 'number' && configured > 0 ? configured : DurableAgentDefaults.TOOL_CALL_CONCURRENCY;\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\nconst BG_CHECK_STEP_ID = `${DurableStepIds.AGENTIC_EXECUTION}-bg-task-check`;\n\n/**\n * The background task check step accepts the output of llmMappingStep\n * and passes it through, adding backgroundTaskPending if tasks are running.\n */\nconst bgCheckInputSchema = z.any();\nconst bgCheckOutputSchema = z.any();\n\n/**\n * Create a durable background task check step.\n *\n * Mirrors the regular agent's backgroundTaskCheckStep pattern:\n * - After tool calls complete, checks if any background tasks are still running\n * - If no running tasks: passes through unchanged\n * - If an explicit waitTimeoutMs is configured and retryCount === 0: returns\n * immediately with backgroundTaskPending=true (caller drives continuation)\n * - Otherwise: waits for the next task to complete using the configured\n * waitTimeoutMs or a 1 s default — this keeps the workflow (and its pubsub\n * subscription) alive so background-task tool-result chunks are delivered\n * - When a task completes: sets isContinued=true so the LLM processes the result\n */\nexport function createDurableBackgroundTaskCheckStep() {\n return createStep({\n id: BG_CHECK_STEP_ID,\n inputSchema: bgCheckInputSchema,\n outputSchema: bgCheckOutputSchema,\n execute: async params => {\n const { inputData, getInitData, retryCount } = params;\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const typedInput = inputData as Record<string, any>;\n\n const initData = getInitData<{\n runId: string;\n agentId: string;\n options?: { skipBgTaskWait?: boolean };\n state?: { threadId?: string; resourceId?: string };\n }>();\n const { runId, agentId } = initData;\n\n const registryEntry = globalRunRegistry.get(runId);\n const bgManager = registryEntry?.backgroundTaskManager;\n\n if (!bgManager) {\n return typedInput;\n }\n\n const runningResult = await bgManager.listTasks({\n agentId,\n status: 'running',\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n });\n const runningTasks = runningResult?.tasks;\n\n if (!runningTasks || runningTasks.length === 0) {\n return typedInput;\n }\n\n // When the outer caller drives continuation externally (e.g. streamUntilIdle),\n // skip the in-loop wait. We still mark pending so ownstream knows.\n if (initData.options?.skipBgTaskWait) {\n return { ...typedInput, backgroundTaskPending: true };\n }\n\n const taskIds = runningTasks.map(task => task.id);\n\n const bgConfig = registryEntry?.backgroundTasksConfig;\n const managerConfig = bgManager.config;\n const waitTimeoutMs = bgConfig?.waitTimeoutMs ?? managerConfig?.waitTimeoutMs;\n\n // The regular agent gates on `retryCount === 0 || !waitTimeoutMs`\n // and can afford to skip waiting because tool-result chunks from\n // background tasks are pushed directly into the ReadableStream\n // controller via safeEnqueue — that works even after this step\n // returns.\n //\n // The durable agent emits tool-result chunks via pubsub. The\n // pubsub subscription is torn down when the stream closes and the\n // consumer calls cleanup(). If this step returns without waiting,\n // the workflow finishes, FINISH fires, the stream closes, cleanup\n // runs, and the pubsub subscriber is gone before the background\n // task can deliver its result.\n //\n // Therefore the durable agent must always wait when background\n // tasks are running — using the configured waitTimeoutMs, or a\n // sensible 1 s default to keep the workflow (and pubsub) alive.\n\n // First invocation without explicit waitTimeoutMs — match the\n // regular agent's \"signal pending, don't block\" on retryCount 0,\n // but only when the caller provided an explicit timeout (meaning\n // they'll drive continuation externally).\n if (retryCount === 0 && waitTimeoutMs) {\n return { ...typedInput, backgroundTaskPending: true };\n }\n\n // Use configured timeout, or default to 1 s so the workflow stays\n // alive long enough for pubsub to deliver background-task results.\n const effectiveWaitMs = waitTimeoutMs ?? 1000;\n\n // Emit initial progress chunk\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, runId, {\n type: 'background-task-progress' as any,\n runId,\n from: ChunkFrom.AGENT,\n payload: { taskIds, runningCount: runningTasks.length, elapsedMs: 0 },\n });\n } catch {\n // PubSub may be closed\n }\n }\n\n // Wait for the next task to complete (or until timeout)\n try {\n await bgManager.waitForNextTask(taskIds, {\n timeoutMs: effectiveWaitMs,\n onProgress: (elapsedMs: number) => {\n if (!pubsub) return;\n void emitChunkEvent(pubsub, runId, {\n type: 'background-task-progress' as any,\n runId,\n from: ChunkFrom.AGENT,\n payload: { taskIds, runningCount: runningTasks.length, elapsedMs },\n }).catch(() => {});\n },\n progressIntervalMs: 3000,\n });\n } catch {\n // Timeout elapsed — no task completed. Return unchanged so the loop can end.\n // The tasks keep running in the background — results are picked up on\n // the next user message or stream.\n return typedInput;\n }\n\n // A task completed — force the loop to continue so the LLM processes the result\n if (typedInput.stepResult) {\n return {\n ...typedInput,\n backgroundTaskPending: true,\n stepResult: { ...typedInput.stepResult, isContinued: true },\n };\n }\n\n return { ...typedInput, backgroundTaskPending: true };\n },\n });\n}\n","import type { IMastraLogger } from '../../../logger';\nimport { transformToolPayloadForTargets, withToolPayloadTransformMetadata } from '../../../tools/payload-transform';\nimport type { CoreTool, ToolPayloadTransformPolicy } from '../../../tools/types';\n\n/**\n * Apply the in-process tool payload transform policy to a chunk before the\n * durable layer publishes it. Mirrors `addToolPayloadTransformToChunk` in the\n * non-durable agentic-execution layer, restricted to the chunk types that the\n * durable loop emits (`tool-call`, `tool-result`, `tool-error`).\n *\n * The transform policy is only available for in-process durable runs (it\n * carries a closure that cannot be serialized into the workflow input). When\n * the policy is missing or the chunk is not tool-shaped, the chunk is\n * returned unchanged.\n */\nexport async function applyToolPayloadTransformToChunk<TChunk extends { type: string; payload?: any }>(\n chunk: TChunk,\n opts: {\n policy?: ToolPayloadTransformPolicy;\n tools?: Record<string, CoreTool>;\n logger?: IMastraLogger;\n },\n): Promise<TChunk> {\n const { policy, tools, logger } = opts;\n if (!policy && !tools) {\n return chunk;\n }\n\n const payload = chunk.payload;\n if (!payload || typeof payload !== 'object') {\n return chunk;\n }\n\n const toolName = (payload as { toolName?: unknown }).toolName;\n const toolCallId = (payload as { toolCallId?: unknown }).toolCallId;\n if (typeof toolName !== 'string' || typeof toolCallId !== 'string') {\n return chunk;\n }\n\n const tool = tools?.[toolName];\n const source = {\n policy,\n toolTransform: (tool as { transform?: unknown } | undefined)?.transform as any,\n };\n\n let transformedChunk: TChunk = chunk;\n let transform;\n\n if (chunk.type === 'tool-call') {\n transform = await transformToolPayloadForTargets(\n {\n phase: 'input-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n );\n } else if (chunk.type === 'tool-result') {\n transformedChunk = withToolPayloadTransformMetadata(\n transformedChunk as any,\n await transformToolPayloadForTargets(\n {\n phase: 'input-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n ),\n ) as TChunk;\n transform = await transformToolPayloadForTargets(\n {\n phase: 'output-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n output: (payload as { result?: unknown }).result,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n );\n } else if (chunk.type === 'tool-error') {\n transformedChunk = withToolPayloadTransformMetadata(\n transformedChunk as any,\n await transformToolPayloadForTargets(\n {\n phase: 'input-available',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n ),\n ) as TChunk;\n transform = await transformToolPayloadForTargets(\n {\n phase: 'error',\n toolName,\n toolCallId,\n input: (payload as { args?: unknown }).args,\n error: (payload as { error?: unknown }).error,\n providerMetadata: (payload as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n },\n source,\n logger,\n );\n } else {\n return chunk;\n }\n\n return withToolPayloadTransformMetadata(transformedChunk as any, transform) as TChunk;\n}\n","import type { ToolSet } from '@internal/ai-sdk-v5';\nimport { resolveModelConfig } from '../../../llm/model/resolve-model';\nimport type { MastraLanguageModel } from '../../../llm/model/shared.types';\nimport type { StreamInternal } from '../../../loop/types';\nimport type { Mastra } from '../../../mastra';\nimport type { MastraMemory } from '../../../memory/memory';\nimport type {\n ProcessorState,\n ErrorProcessorOrWorkflow,\n InputProcessorOrWorkflow,\n OutputProcessorOrWorkflow,\n} from '../../../processors';\nimport { RequestContext } from '../../../request-context';\nimport { getNeedsApprovalFn } from '../../../tools/toolchecks';\nimport type { CoreTool, RequireToolApproval, ToolApprovalContext } from '../../../tools/types';\nimport type { Workspace } from '../../../workspace';\nimport { MessageList } from '../../message-list';\nimport { SaveQueueManager } from '../../save-queue';\nimport { globalRunRegistry } from '../run-registry';\nimport type {\n RunRegistryEntry,\n SerializableDurableState,\n SerializableDurableOptions,\n SerializableModelConfig,\n SerializableModelListEntry,\n SerializableToolMetadata,\n DurableAgenticWorkflowInput,\n RegistryModelListEntry,\n} from '../types';\n\n/**\n * Runtime dependencies that need to be resolved at step execution time.\n * These cannot be serialized and must be recreated from available context.\n */\nexport interface ResolvedRuntimeDependencies {\n /** Reconstructed _internal object for compatibility with existing code */\n _internal: StreamInternal;\n /** Resolved tools with execute functions */\n tools: Record<string, CoreTool>;\n /** Resolved language model */\n model: MastraLanguageModel;\n /** Resolved model list for fallback support (actual model instances) */\n modelList?: RegistryModelListEntry[];\n /** Deserialized MessageList */\n messageList: MessageList;\n /** Memory instance (if available) */\n memory?: MastraMemory;\n /** SaveQueueManager for message persistence */\n saveQueueManager?: SaveQueueManager;\n /** Workspace for file/sandbox operations */\n workspace?: Workspace;\n /** Resolved input processors (rebuilt from the agent when the registry is empty) */\n inputProcessors?: InputProcessorOrWorkflow[];\n /** Uncombined input processors for processLLMRequest */\n llmRequestInputProcessors?: InputProcessorOrWorkflow[];\n /** Resolved output processors */\n outputProcessors?: OutputProcessorOrWorkflow[];\n /** Resolved error processors */\n errorProcessors?: ErrorProcessorOrWorkflow[];\n /** Processor state map */\n processorStates?: Map<string, ProcessorState>;\n}\n\n/**\n * Build a SaveQueueManager for a run's memory, or `undefined` when no memory\n * is configured. Shared by `resolveRuntimeDependencies` and\n * `rebuildRunToolsFromMastra` so the construction lives in one place.\n */\nfunction makeSaveQueueManager(memory: MastraMemory | undefined, mastra?: Mastra): SaveQueueManager | undefined {\n if (!memory) return undefined;\n return new SaveQueueManager({ logger: mastra?.getLogger?.(), memory });\n}\n\n/**\n * Options for resolving runtime dependencies\n */\nexport interface ResolveRuntimeOptions {\n /** Mastra instance for accessing services */\n mastra?: Mastra;\n /** Run identifier */\n runId: string;\n /** Agent identifier */\n agentId: string;\n /** Workflow input containing serialized state */\n input: DurableAgenticWorkflowInput;\n /** Logger for debugging */\n logger?: { debug?: (...args: any[]) => void; error?: (...args: any[]) => void };\n}\n\n/**\n * Restore a RequestContext from the JSON-safe `requestContextEntries`\n * snapshot serialized onto the workflow input (see preparation.ts). Returns\n * an empty context when no snapshot is present.\n */\nfunction restoreRequestContext(entries?: Record<string, unknown>): RequestContext {\n return entries\n ? new RequestContext(Object.entries(entries) as Iterable<readonly [string, unknown]>)\n : new RequestContext();\n}\n\n/**\n * Thrown when the per-request processor pipeline cannot be rebuilt during\n * cross-process rehydration. Propagated (not swallowed) because continuing\n * without the rebuilt processors would silently drop skills / workspace\n * instructions — the exact failure mode this rebuild exists to fix.\n */\nexport class DurableProcessorRebuildError extends Error {\n constructor(agentId: string, cause: unknown) {\n super(\n `[DurableAgent:${agentId}] Failed to rebuild processor pipeline during cross-process rehydration: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n this.name = 'DurableProcessorRebuildError';\n this.cause = cause;\n }\n}\n\n/**\n * Resolve all runtime dependencies needed for durable step execution.\n *\n * This function reconstructs the non-serializable state needed to execute\n * agent steps from:\n * 1. The Mastra instance (for agent lookup, tools, model)\n * 2. The serialized workflow input (for MessageList, state)\n *\n * Unlike the registry-based approach, this reconstructs tools and model\n * from the agent registered with Mastra, making it truly durable across\n * process restarts.\n */\nexport async function resolveRuntimeDependencies(options: ResolveRuntimeOptions): Promise<ResolvedRuntimeDependencies> {\n const { mastra, runId, agentId, input, logger } = options;\n\n // 1. Deserialize MessageList\n // Reuse the existing MessageList from the registry if available so that\n // external consumers (e.g. the stream adapter) that hold a reference to it\n // see the updated state. Creating a new instance each iteration would\n // orphan those references (their newResponseMessages Set would point at\n // stale objects).\n const existingEntry = globalRunRegistry.get(runId);\n const messageList = existingEntry?.messageList\n ? existingEntry.messageList.deserialize(input.messageListState)\n : new MessageList({\n threadId: input.state.threadId,\n resourceId: input.state.resourceId,\n }).deserialize(input.messageListState);\n\n // 2. Check global registry first (for local/test execution).\n // This is necessary because workflow steps don't have direct access to\n // DurableAgent's registry.\n //\n // On a cross-process engine (e.g. the @mastra/inngest connect() worker) the\n // durable steps run in a DIFFERENT process than the one that prepared the run,\n // so this process's registry has either no entry or a minimal placeholder\n // (see @mastra/inngest resume(): `{ isPlaceholder: true, tools: {}, model:\n // undefined }`). In that case we MUST rebuild tools / processors / model from\n // the agent registered on the Mastra instance — otherwise per-request closure\n // tools (workspace/skill tools) and per-request processors (SkillsProcessor,\n // WorkspaceInstructions) silently drop cross-process.\n //\n // IMPORTANT: an empty `tools` map is NOT a placeholder signal — agents with\n // zero tools legitimately register `{ tools: {} }` in-process. Placeholders\n // are detected by the explicit `isPlaceholder` flag or by the absence of a\n // real model instance (every in-process seeding site stores the live model;\n // placeholders and metadata-only stubs do not).\n const globalEntry = globalRunRegistry.get(runId);\n const registryModel = globalEntry?.model as (MastraLanguageModel & { __metadataOnly?: boolean }) | undefined;\n const hasHydratedEntry =\n !!globalEntry && globalEntry.isPlaceholder !== true && !!registryModel && registryModel.__metadataOnly !== true;\n let tools: Record<string, CoreTool> = globalEntry?.tools ?? {};\n let model: MastraLanguageModel = globalEntry?.model as MastraLanguageModel;\n let modelList: RegistryModelListEntry[] | undefined = globalEntry?.modelList;\n let workspace: Workspace | undefined = globalEntry?.workspace;\n let memory: MastraMemory | undefined = globalEntry?.memory;\n let inputProcessors: InputProcessorOrWorkflow[] | undefined = globalEntry?.inputProcessors;\n let llmRequestInputProcessors: InputProcessorOrWorkflow[] | undefined = globalEntry?.llmRequestInputProcessors;\n let outputProcessors: OutputProcessorOrWorkflow[] | undefined = globalEntry?.outputProcessors;\n let errorProcessors: ErrorProcessorOrWorkflow[] | undefined = globalEntry?.errorProcessors;\n let processorStates: Map<string, ProcessorState> | undefined = globalEntry?.processorStates;\n let rehydratedFromMastra = false;\n\n // If the registry entry is a real (non-placeholder) in-process entry we\n // trust it wholesale (in-process / same-process resume). Otherwise fall\n // through and rebuild from the Mastra instance.\n if (hasHydratedEntry) {\n logger?.debug?.(`[DurableAgent:${agentId}] Using model and tools from global registry for run ${runId}`);\n } else if (mastra) {\n try {\n const agent = mastra.getAgentById(agentId);\n\n // Restore the caller's request context from the JSON-safe snapshot on\n // the workflow input (mirrors durable-agent.ts resume handling), so\n // request-scoped tools / workspace / memory / processors resolve with\n // the same configuration as the original call site.\n const resolveRequestContext = restoreRequestContext(input.requestContextEntries);\n\n tools = await agent.getToolsForExecution({\n runId,\n threadId: input.state.threadId,\n resourceId: input.state.resourceId,\n requestContext: resolveRequestContext,\n memoryConfig: input.state.memoryConfig,\n autoResumeSuspendedTools: input.options?.autoResumeSuspendedTools,\n });\n\n model =\n (await (agent as any).getModel?.({ requestContext: resolveRequestContext })) ??\n resolveModel(input.modelConfig, mastra);\n\n const rawModelList = await (agent as any).getModelList?.(resolveRequestContext);\n if (rawModelList && Array.isArray(rawModelList)) {\n modelList = rawModelList.map((entry: any) => ({\n id: entry.id,\n model: entry.model,\n maxRetries: entry.maxRetries ?? 0,\n enabled: entry.enabled ?? true,\n headers: entry.headers,\n }));\n }\n\n memory = await (agent as any).getMemory?.({ requestContext: resolveRequestContext });\n workspace = await (agent as any).getWorkspace?.({ requestContext: resolveRequestContext });\n\n // Rebuild the per-request processor pipeline. `listInputProcessors` /\n // `listOutputProcessors` already inject the SkillsProcessor and\n // WorkspaceInstructionsProcessor (see Agent.listInputProcessors), so this\n // restores the missing available-skills list + workspace instructions in\n // the cross-process system prompt. Mirrors preparation.ts.\n try {\n inputProcessors = await (agent as any).listInputProcessors?.(resolveRequestContext);\n llmRequestInputProcessors = await (agent as any).__listLLMRequestProcessors?.(resolveRequestContext);\n outputProcessors = await (agent as any).listOutputProcessors?.(resolveRequestContext);\n errorProcessors = await (agent as any).listErrorProcessors?.(resolveRequestContext);\n // A fresh processor-state map is correct here: on a cross-process worker\n // there is no prior state to carry, and processors are re-run per step.\n processorStates = globalEntry?.processorStates ?? new Map<string, ProcessorState>();\n } catch (processorError) {\n // Fail the step loudly rather than continuing (and writing back) an\n // incomplete pipeline: running without the rebuilt processors would\n // silently drop skills / workspace instructions.\n logger?.error?.(`[DurableAgent:${agentId}] Failed to rebuild processors from Mastra: ${processorError}`);\n throw new DurableProcessorRebuildError(agentId, processorError);\n }\n\n rehydratedFromMastra = true;\n } catch (error) {\n if (error instanceof DurableProcessorRebuildError) throw error;\n logger?.debug?.(`[DurableAgent:${agentId}] Failed to get agent from Mastra: ${error}`);\n model = resolveModel(input.modelConfig, mastra);\n }\n } else {\n logger?.debug?.(`[DurableAgent:${agentId}] No Mastra instance available, using fallback model`);\n model = resolveModel(input.modelConfig);\n }\n\n if (Object.keys(tools).length === 0) {\n logger?.debug?.(`[DurableAgent:${agentId}] No tools resolved for run ${runId}`);\n }\n\n // Write the rebuilt state back into the per-process registry so sibling\n // durable steps in THIS process (e.g. the tool-call step that runs after the\n // LLM step on the same worker) reuse it instead of rebuilding per call. Only\n // persist when we actually rehydrated from Mastra — never clobber a fully\n // populated in-process entry.\n if (rehydratedFromMastra) {\n const rebuilt: Partial<RunRegistryEntry> = {\n // The entry now carries real runtime state — drop the placeholder mark\n // so sibling steps in this process trust it instead of rebuilding.\n isPlaceholder: false,\n tools,\n model,\n modelList,\n workspace,\n memory,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n };\n if (globalEntry) {\n Object.assign(globalEntry, rebuilt);\n } else {\n globalRunRegistry.set(runId, rebuilt as RunRegistryEntry);\n }\n }\n\n // 3. Get or create SaveQueueManager\n const saveQueueManager = makeSaveQueueManager(memory, mastra);\n\n // 4. Reconstruct _internal for compatibility with existing code\n const _internal = resolveInternalState({\n state: input.state,\n memory,\n saveQueueManager,\n tools,\n });\n\n return {\n _internal,\n tools,\n model,\n modelList,\n messageList,\n memory,\n saveQueueManager,\n workspace,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n };\n}\n\n/**\n * Tool + workspace state rebuilt for the durable tool-call step.\n */\nexport interface RebuiltRunTools {\n tools: Record<string, CoreTool>;\n workspace?: Workspace;\n memory?: MastraMemory;\n saveQueueManager?: SaveQueueManager;\n}\n\n/**\n * Rebuild the run's tools (and workspace/memory) from the agent registered on\n * the Mastra instance, then write them back into the per-process run registry.\n *\n * The durable tool-call step runs as a SEPARATE step from the LLM-execution\n * step and, on a cross-process engine (e.g. the @mastra/inngest connect()\n * worker), can execute in a different process than the one that prepared the\n * run. In that process `globalRunRegistry.get(runId)` is empty (or a minimal\n * placeholder), so per-request closure tools (workspace/skill tools:\n * `skill`, `skill_read`, `skill_search`, `mastra_workspace_*`) are absent and\n * the model's tool call rejects with `ToolNotFoundError`.\n *\n * The LLM step already rebuilds the full toolset via\n * `resolveRuntimeDependencies` → `getToolsForExecution`; this helper gives the\n * tool-call step the same rebuild so tool resolution is symmetric cross-process.\n * The writeback means the first unresolved tool call rebuilds once and later\n * calls in the same process hit the registry.\n *\n * Returns `undefined` when no Mastra instance is available or the agent can't\n * be resolved — callers fall back to their existing `ToolNotFoundError`.\n */\nexport async function rebuildRunToolsFromMastra(options: {\n mastra?: Mastra;\n runId: string;\n agentId: string;\n state: SerializableDurableState;\n options?: SerializableDurableOptions;\n /** JSON-safe request-context snapshot from the workflow input (see preparation.ts). */\n requestContextEntries?: Record<string, unknown>;\n logger?: { debug?: (...args: any[]) => void };\n}): Promise<RebuiltRunTools | undefined> {\n const { mastra, runId, agentId, state, options: execOptions, requestContextEntries, logger } = options;\n if (!mastra) return undefined;\n\n try {\n const agent = mastra.getAgentById(agentId);\n // Restore the caller's request context so request-scoped tools, workspace\n // and memory resolve with the same configuration as the original call.\n const resolveRequestContext = restoreRequestContext(requestContextEntries);\n\n const tools = await agent.getToolsForExecution({\n runId,\n threadId: state.threadId,\n resourceId: state.resourceId,\n requestContext: resolveRequestContext,\n memoryConfig: state.memoryConfig,\n autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,\n });\n\n const memory = await (agent as any).getMemory?.({ requestContext: resolveRequestContext });\n const workspace = await (agent as any).getWorkspace?.({ requestContext: resolveRequestContext });\n const saveQueueManager = makeSaveQueueManager(memory, mastra);\n\n // Write back so sibling steps in this process reuse the rebuilt tools.\n const existing = globalRunRegistry.get(runId);\n const patch: Partial<RunRegistryEntry> = { tools, workspace, memory, saveQueueManager };\n if (existing) {\n // Only fill fields the entry is missing — never clobber a populated entry.\n if (Object.keys(existing.tools ?? {}).length === 0) existing.tools = tools;\n existing.workspace ??= workspace;\n existing.memory ??= memory;\n existing.saveQueueManager ??= saveQueueManager;\n } else {\n globalRunRegistry.set(runId, patch as RunRegistryEntry);\n }\n\n return { tools, workspace, memory, saveQueueManager };\n } catch (error) {\n logger?.debug?.(`[DurableAgent:${agentId}] Failed to rebuild tools from Mastra for run ${runId}: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Resolve the language model from serialized config.\n *\n * Note: This is a fallback when the model is not in the run registry.\n * The preferred approach is to store the actual model instance in the\n * run registry during preparation and retrieve it via runRegistry.getModel().\n *\n * This fallback returns a metadata-only stub that will fail the\n * isSupportedLanguageModel check with a descriptive error message.\n */\nexport function resolveModel(config: SerializableModelConfig, _mastra?: Mastra): MastraLanguageModel {\n const metadataError = () => {\n throw new Error(\n `Model ${config.provider}/${config.modelId} is a metadata-only stub. ` +\n `The actual model instance should be resolved from the run registry.`,\n );\n };\n\n return {\n provider: config.provider,\n modelId: config.modelId,\n specificationVersion: config.specificationVersion ?? 'v2',\n supportedUrls: {},\n doGenerate: metadataError,\n doStream: metadataError,\n __metadataOnly: true,\n } as MastraLanguageModel;\n}\n\n/**\n * Reconstruct the _internal (StreamInternal) object from available state\n */\nexport function resolveInternalState(options: {\n state: SerializableDurableState;\n memory?: MastraMemory;\n saveQueueManager?: SaveQueueManager;\n tools?: Record<string, CoreTool>;\n}): StreamInternal {\n const { state, memory, saveQueueManager, tools } = options;\n\n return {\n // Functions - create fresh\n now: () => Date.now(),\n generateId: () => crypto.randomUUID(),\n currentDate: () => new Date(),\n\n // Class instances - from resolved state\n saveQueueManager,\n memory,\n\n // Serializable state\n memoryConfig: state.memoryConfig,\n threadId: state.threadId,\n resourceId: state.resourceId,\n threadExists: state.threadExists,\n\n // Tools if provided - cast to ToolSet for compatibility\n // CoreTool and ToolSet are structurally compatible at runtime\n stepTools: tools as ToolSet | undefined,\n };\n}\n\n/**\n * Resolve a single tool by name from Mastra's global tool registry\n */\nexport function resolveTool(toolName: string, mastra?: Mastra): CoreTool | undefined {\n // Get from Mastra's global tool registry\n try {\n return mastra?.getTool?.(toolName as any) as CoreTool | undefined;\n } catch {\n // Tool not found in global registry\n return undefined;\n }\n}\n\n/**\n * Check if a tool requires human approval.\n *\n * Mirrors the non-durable precedence:\n * - Function-form global `requireToolApproval` is evaluated per call with\n * `(toolName, args, ...)`. Throwing defaults to \"require approval\" (safe).\n * - Boolean global / tool-level `requireApproval` seed the decision.\n * - A per-tool `needsApprovalFn` (e.g. skill tools) is authoritative when\n * present and overrides the seed.\n *\n * In durable execution the function form lives on the run registry, not on\n * the serialized workflow input — pass the resolved value from the caller.\n */\nexport async function toolRequiresApproval(\n tool: CoreTool,\n globalRequireApproval?: RequireToolApproval,\n args?: Record<string, unknown>,\n approvalContext?: Partial<ToolApprovalContext> & { toolName: string },\n): Promise<boolean> {\n let globalRequires: boolean;\n if (typeof globalRequireApproval === 'function') {\n try {\n globalRequires = !!(await globalRequireApproval({\n toolName: approvalContext?.toolName ?? '',\n args: args ?? {},\n requestContext: approvalContext?.requestContext,\n workspace: approvalContext?.workspace,\n }));\n } catch {\n // On error, default to requiring approval (safe default).\n globalRequires = true;\n }\n } else {\n globalRequires = !!globalRequireApproval;\n }\n\n let requires = globalRequires || !!(tool as any).requireApproval;\n\n // needsApprovalFn overrides all other flags (e.g., skill tools return false)\n const needsApprovalFn = getNeedsApprovalFn(tool);\n if (needsApprovalFn) {\n try {\n requires = !!(await needsApprovalFn(args ?? {}));\n } catch {\n // On error, default to requiring approval (safe default)\n requires = true;\n }\n }\n\n return requires;\n}\n\n/**\n * Extract tool metadata needed for LLM from resolved tools\n * This is useful when we need to pass tool info to the model\n */\nexport function extractToolsForModel(\n tools: Record<string, CoreTool>,\n _toolsMetadata: SerializableToolMetadata[],\n): Record<string, CoreTool> {\n // Return the tools as-is since they're already in CoreTool format\n // The metadata is just for reference/serialization\n return tools;\n}\n\n/**\n * Resolve a language model from a serialized model config.\n *\n * This is used during durable execution to reconstruct models from\n * serialized configuration. It uses the originalConfig string (e.g., 'openai/gpt-4o')\n * to resolve the model through the standard model resolution pipeline.\n *\n * @param config The serialized model configuration\n * @param mastra Optional Mastra instance for custom gateways\n * @returns Resolved language model\n */\nexport async function resolveModelFromConfig(\n config: SerializableModelConfig,\n mastra?: Mastra,\n): Promise<MastraLanguageModel> {\n const requestContext = new RequestContext();\n\n // Use originalConfig if available (e.g., 'openai/gpt-4o'), otherwise construct from provider/modelId\n const modelConfigString = config.originalConfig ?? `${config.provider}/${config.modelId}`;\n\n if (typeof modelConfigString === 'string') {\n return (await resolveModelConfig(modelConfigString, requestContext, mastra)) as MastraLanguageModel;\n }\n\n // If originalConfig is an object, pass it through\n return (await resolveModelConfig(\n modelConfigString as Parameters<typeof resolveModelConfig>[0],\n requestContext,\n mastra,\n )) as MastraLanguageModel;\n}\n\n/**\n * Resolve a model from a model list entry.\n *\n * @param entry The model list entry with config, maxRetries, enabled\n * @param mastra Optional Mastra instance\n * @returns Resolved language model\n */\nexport async function resolveModelFromListEntry(\n entry: SerializableModelListEntry,\n mastra?: Mastra,\n): Promise<MastraLanguageModel> {\n return resolveModelFromConfig(entry.config, mastra);\n}\n","import type { LanguageModelV2Prompt } from '@ai-sdk/provider-v5';\nimport type { ToolChoice, ToolSet } from '@internal/ai-sdk-v5';\nimport { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { mergeProviderOptions } from '../../../../llm/model/provider-options';\nimport type { SharedProviderOptions } from '../../../../llm/model/shared.types';\nimport { ConsoleLogger } from '../../../../logger';\nimport { applyAutoResumeSystemMessage } from '../../../../loop/shared/auto-resume-system-message';\nimport { buildLlmPromptArgs } from '../../../../loop/shared/build-llm-prompt-args';\nimport { composeStepInput } from '../../../../loop/shared/compose-step-input';\nimport { injectBackgroundTaskPrompt } from '../../../../loop/shared/inject-background-task-prompt';\nimport { buildMemoryHeaders, mergeLlmCallHeaders } from '../../../../loop/shared/merge-llm-call-headers';\nimport { buildMessagesFromChunks } from '../../../../loop/workflows/agentic-execution/build-messages-from-chunks';\nimport type { CollectedChunk } from '../../../../loop/workflows/agentic-execution/build-messages-from-chunks';\nimport type { Mastra } from '../../../../mastra';\nimport type {\n SpanType,\n AIModelGenerationSpan,\n ExportedSpan,\n IModelSpanTracker,\n AnySpan,\n} from '../../../../observability';\nimport { EntityType } from '../../../../observability';\nimport { getStepAvailableToolNames } from '../../../../observability/utils';\nimport type { CachedLLMStepResponse } from '../../../../processors';\nimport { PrepareStepProcessor } from '../../../../processors/processors/prepare-step';\nimport { ProcessorRunner } from '../../../../processors/runner';\nimport { execute } from '../../../../stream/aisdk/v5/execute';\nimport { MastraModelOutput } from '../../../../stream/base/output';\nimport type { ChunkType, TextDeltaPayload, ToolCallPayload } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { findProviderToolByName, inferProviderExecuted } from '../../../../tools/provider-tool-utils';\nimport type { ToolToConvert } from '../../../../tools/tool-builder/builder';\nimport { isMastraTool } from '../../../../tools/toolchecks';\nimport type { CoreTool } from '../../../../tools/types';\nimport { createMastraProxy, makeCoreTool } from '../../../../utils';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { TripWire } from '../../../trip-wire';\nimport { isSupportedLanguageModel } from '../../../utils';\nimport { DurableStepIds } from '../../constants';\nimport { endRunSpansWithError, globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent, emitStepStartEvent } from '../../stream-adapter';\nimport type { DurableAgenticWorkflowInput, DurableLLMStepOutput, DurableToolCallInput } from '../../types';\nimport { applyToolPayloadTransformToChunk } from '../../utils/apply-tool-payload-transform';\nimport { resolveRuntimeDependencies, resolveModelFromListEntry } from '../../utils/resolve-runtime';\n\n/**\n * Input schema for the durable LLM execution step\n */\nconst durableLLMInputSchema = z.object({\n runId: z.string(),\n agentId: z.string(),\n agentName: z.string().optional(),\n messageListState: z.any(), // SerializedMessageListState\n toolsMetadata: z.array(z.any()),\n modelConfig: z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n originalConfig: z.union([z.string(), z.record(z.string(), z.any())]).optional(),\n settings: z.record(z.string(), z.any()).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n }),\n // Model list for fallback support (when agent configured with array of models)\n modelList: z\n .array(\n z.object({\n id: z.string(),\n config: z.object({\n provider: z.string(),\n modelId: z.string(),\n specificationVersion: z.string().optional(),\n originalConfig: z.union([z.string(), z.record(z.string(), z.any())]).optional(),\n providerOptions: z.record(z.string(), z.any()).optional(),\n }),\n maxRetries: z.number(),\n enabled: z.boolean(),\n }),\n )\n .optional(),\n options: z.any(),\n state: z.any(),\n messageId: z.string(),\n // Agent span data for model span parenting\n agentSpanData: z.any().optional(),\n // Model span data (ONE span for entire agent run, created before workflow)\n modelSpanData: z.any().optional(),\n // Step index for continuation (step: 0, 1, 2, ...)\n stepIndex: z.number().optional(),\n});\n\n/**\n * Output schema for the durable LLM execution step\n */\nconst durableLLMOutputSchema = z.object({\n messageListState: z.any(),\n text: z.string().optional(),\n toolCalls: z.array(\n z.object({\n toolCallId: z.string(),\n toolName: z.string(),\n args: z.record(z.string(), z.any()),\n providerMetadata: z.record(z.string(), z.any()).optional(),\n activeTools: z.array(z.string()).nullable().optional(),\n }),\n ),\n stepResult: z.object({\n reason: z.string(),\n warnings: z.array(z.any()),\n isContinued: z.boolean(),\n totalUsage: z.any().optional(),\n }),\n metadata: z.any(),\n processorRetryCount: z.number().optional(),\n processorRetryFeedback: z.string().optional(),\n state: z.any(),\n // Step index used in this execution (for tracking)\n stepIndex: z.number().optional(),\n // Exported span data forwarded to downstream steps for trace nesting/closing\n modelSpanData: z.any().optional(),\n stepSpanData: z.any().optional(),\n stepFinishPayload: z.any().optional(),\n});\n\n/**\n * Options for creating the durable LLM execution step\n */\nexport interface DurableLLMExecutionStepOptions {\n // No options needed - tools and model are resolved from Mastra at runtime\n}\n\n/**\n * Create a durable LLM execution step.\n *\n * This step:\n * 1. Deserializes the MessageList from workflow input\n * 2. Resolves tools and model from the runtime context\n * 3. Executes the LLM call\n * 4. Emits streaming chunks via pubsub\n * 5. Returns serialized state for the next step\n *\n * The key difference from the non-durable version is that all state\n * flows through the workflow input/output, and non-serializable\n * dependencies are resolved at execution time.\n */\nexport function createDurableLLMExecutionStep(_options?: DurableLLMExecutionStepOptions) {\n return createStep({\n id: DurableStepIds.LLM_EXECUTION,\n inputSchema: durableLLMInputSchema,\n outputSchema: durableLLMOutputSchema,\n execute: async params => {\n const { inputData, mastra, tracingContext, requestContext, abortSignal } = params;\n\n // Access pubsub via symbol\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n\n const typedInput = inputData as DurableAgenticWorkflowInput;\n const { agentId, messageId, options: execOptions } = typedInput;\n const runId = typedInput.runId;\n const logger = mastra?.getLogger?.();\n\n // 1. Resolve runtime dependencies (tools from Mastra)\n const resolved = await resolveRuntimeDependencies({\n mastra: mastra as Mastra,\n runId,\n agentId,\n input: typedInput,\n logger,\n });\n\n const {\n messageList,\n tools,\n model: resolvedModel,\n modelList: resolvedModelList,\n // Processors rebuilt from the agent when the per-process registry was\n // empty (cross-process worker). resolveRuntimeDependencies also writes\n // these back into globalRunRegistry, so `registryEntry?.inputProcessors`\n // below is populated too — these are the direct fallback if the entry is\n // evicted (TTL) or absent, restoring the SkillsProcessor /\n // WorkspaceInstructionsProcessor in the cross-process system prompt.\n inputProcessors: resolvedInputProcessors,\n llmRequestInputProcessors: resolvedLlmRequestInputProcessors,\n outputProcessors: resolvedOutputProcessors,\n } = resolved;\n\n // 1b. Check for abort signal before doing any work. If the signal is\n // already aborted (e.g. pre-aborted before the loop starts), return a\n // clean output so the dowhile predicate sees isContinued: false and\n // stops the loop. The FINISH event will be emitted by the finalization\n // block with stepResult.reason: 'abort' (set by the predicate's abort\n // guard). We intentionally do NOT emit an ABORT event here because\n // that would close the stream before the FINISH event arrives.\n const executionAbortSignalEarly = globalRunRegistry.get(runId)?.abortSignal ?? abortSignal;\n if (executionAbortSignalEarly?.aborted) {\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: {},\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n // 1c. Check for tripwire from processInput (initial input processing).\n // If an input processor called abort() during preparation, the tripwire\n // data is stored on the registry entry. Emit a tripwire chunk and bail\n // immediately — the model must never be called.\n const registryTripwire = globalRunRegistry.get(runId)?.tripwire;\n if (registryTripwire) {\n // Clear it so it doesn't fire again on a subsequent iteration (shouldn't\n // happen since the loop will stop, but belt-and-suspenders).\n const entry = globalRunRegistry.get(runId);\n if (entry) entry.tripwire = undefined;\n\n logger?.warn?.('Input processor tripwire triggered (from preparation)', {\n agent: agentId,\n reason: registryTripwire.reason,\n processorId: registryTripwire.processorId,\n retry: registryTripwire.retry,\n });\n\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n reason: registryTripwire.reason || '',\n retry: registryTripwire.retry,\n metadata: registryTripwire.metadata,\n processorId: registryTripwire.processorId,\n },\n });\n }\n\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings: [],\n isContinued: false,\n },\n metadata: {},\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n // 2. Determine if we have a model list for fallback support\n const hasModelList = typedInput.modelList && typedInput.modelList.length > 0;\n\n // 3. Build the model list - either from explicit list or single model\n // For single model case (no modelList), we use the resolved model directly\n // which supports mock models and directly-provided models\n const modelList = hasModelList\n ? typedInput.modelList!.filter(m => m.enabled)\n : [\n {\n id: `${typedInput.modelConfig.provider}/${typedInput.modelConfig.modelId}`,\n config: typedInput.modelConfig,\n maxRetries: 0,\n enabled: true,\n },\n ];\n\n if (modelList.length === 0) {\n throw new Error('No enabled models available for execution');\n }\n\n // 4. Execute with model fallback - try each model in the list with retries\n let lastError: Error | undefined;\n let processorRetryCount = 0;\n const maxProcessorRetries =\n typedInput.options?.maxProcessorRetries ??\n (globalRunRegistry.get(runId)?.errorProcessors?.length ? 10 : undefined);\n\n for (let modelIndex = 0; modelIndex < modelList.length; modelIndex++) {\n const modelEntry = modelList[modelIndex]!;\n const maxRetries = modelEntry.maxRetries || 0;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n // Resolve the model - for single model case (no modelList), use resolved model\n // For model list case, try registry first (works with mock models), then config resolution (for Inngest)\n const model = !hasModelList\n ? resolvedModel\n : (resolvedModelList?.find(m => m.id === modelEntry.id)?.model ??\n (await resolveModelFromListEntry(modelEntry, mastra as Mastra)));\n\n // Check if model is supported\n if (!isSupportedLanguageModel(model)) {\n const hint = (model as any).__metadataOnly\n ? ' The model could not be resolved from the run registry or Mastra instance.'\n : '';\n throw new Error(\n `Unsupported model version: ${(model as any).specificationVersion}. Model must implement doStream.${hint}`,\n );\n }\n\n let currentMessageId = messageId;\n\n // 5. Prepare tools - cast through unknown as CoreTool and ToolSet are structurally compatible at runtime\n let currentModel = model;\n let currentTools = tools as unknown as ToolSet;\n let currentToolChoice = execOptions.toolChoice as ToolChoice<ToolSet> | undefined;\n let currentActiveTools = execOptions.activeTools;\n let currentModelSettings: Record<string, unknown> = { ...(execOptions.modelSettings ?? {}) };\n let currentProviderOptions: SharedProviderOptions | undefined = mergeProviderOptions(\n execOptions.providerOptions,\n modelEntry.config.providerOptions,\n ) as SharedProviderOptions | undefined;\n\n // 6. Rebuild MODEL_GENERATION span from passed data\n // For durable execution, ONE model_generation span is created BEFORE the workflow starts\n // and passed through each iteration. This ensures all steps are children of the same span.\n const observability = mastra?.observability?.getSelectedInstance({ requestContext });\n\n // modelSpanData is threaded through the iteration state (seeded in preparation.ts);\n // after a resume the registry override points steps at the resumed generation.\n const inputModelSpanData = (globalRunRegistry.get(runId)?.resumeModelSpanData ??\n (inputData as any).modelSpanData) as ExportedSpan<SpanType.MODEL_GENERATION> | undefined;\n const modelSpan = inputModelSpanData\n ? (observability?.rebuildSpan(inputModelSpanData) as AIModelGenerationSpan | undefined)\n : undefined;\n\n // Create model span tracker for MODEL_STEP and MODEL_CHUNK spans\n const modelSpanTracker: IModelSpanTracker | undefined = modelSpan?.createTracker();\n\n // Set the step index for continuation (step: 0, 1, 2, ...)\n // This ensures step numbering continues across agentic loop iterations\n const stepIndex = (inputData as any).stepIndex ?? 0;\n modelSpanTracker?.setStepIndex(stepIndex);\n\n // Build structured output for AI SDK if configured. Held in a `let`\n // because `composeStepInput` (driven by input processors / prepareStep)\n // is allowed to replace `structuredOutput` for this iteration.\n const structuredOutputConfig = execOptions.structuredOutput;\n let structuredOutput =\n structuredOutputConfig?.schema && !structuredOutputConfig?.structuringModelConfig\n ? {\n schema: structuredOutputConfig.schema,\n jsonPromptInjection: structuredOutputConfig.jsonPromptInjection,\n }\n : undefined;\n\n const registryEntry = globalRunRegistry.get(runId);\n const executionAbortSignal = registryEntry?.abortSignal ?? abortSignal;\n const baseInputProcessors = registryEntry?.inputProcessors ?? resolvedInputProcessors ?? [];\n // Output processors likewise fall back to the rebuilt list when the\n // per-process registry is empty (cross-process worker).\n const effectiveOutputProcessors = registryEntry?.outputProcessors ?? resolvedOutputProcessors ?? [];\n const stepInputProcessors = registryEntry?.prepareStep\n ? [...baseInputProcessors, new PrepareStepProcessor({ prepareStep: registryEntry.prepareStep })]\n : baseInputProcessors;\n if (stepInputProcessors.length) {\n const inputStepWriter = pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n const runner = new ProcessorRunner({\n inputProcessors: stepInputProcessors,\n outputProcessors: effectiveOutputProcessors,\n errorProcessors: registryEntry?.errorProcessors ?? [],\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry?.processorStates,\n });\n try {\n const processInputStepResult = await runner.runProcessInputStep({\n messageList,\n stepNumber: stepIndex,\n steps: (inputData as any).accumulatedSteps ?? [],\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n requestContext,\n memory: registryEntry?.memory,\n resourceId: typedInput.state?.resourceId,\n threadId: typedInput.state?.threadId,\n model: currentModel,\n messageId: currentMessageId,\n rotateResponseMessageId: () => {\n currentMessageId = crypto.randomUUID();\n return currentMessageId;\n },\n tools: currentTools,\n toolChoice: currentToolChoice,\n providerOptions: currentProviderOptions,\n activeTools: currentActiveTools,\n modelSettings: currentModelSettings,\n structuredOutput: structuredOutput as any,\n retryCount: (inputData as any).processorRetryCount ?? 0,\n abortSignal: executionAbortSignal,\n writer: inputStepWriter,\n });\n const merged = composeStepInput(\n {\n messageId: currentMessageId,\n model: currentModel,\n tools: currentTools,\n toolChoice: currentToolChoice,\n activeTools: currentActiveTools,\n providerOptions: currentProviderOptions,\n modelSettings: currentModelSettings,\n structuredOutput,\n },\n processInputStepResult,\n );\n currentMessageId = merged.messageId;\n currentModel = merged.model as typeof currentModel;\n currentTools = merged.tools as ToolSet;\n currentToolChoice = merged.toolChoice as ToolChoice<ToolSet> | undefined;\n currentActiveTools = merged.activeTools;\n currentProviderOptions = merged.providerOptions;\n currentModelSettings = merged.modelSettings ?? {};\n structuredOutput = merged.structuredOutput;\n\n // Processors (e.g. ToolSearchProcessor) can inject per-step meta-tools\n // like `search_tools` / `load_tool`. In the non-durable Agent the same\n // step that shows these tools to the model also executes them, so a\n // per-step tool map is enough. The DurableAgent instead runs tool calls\n // in a SEPARATE workflow step that resolves tools from the run registry\n // (see tool-call.ts). Without a write-back, those processor-injected\n // tools are missing there and the call fails with ToolNotFoundError\n // (issue #19571).\n //\n // Convert any raw Mastra tools the processor returned into CoreTool form\n // (mirroring the non-durable llm-execution-step) and merge them into the\n // run registry so the durable tool-call step can resolve and execute them.\n if (processInputStepResult.tools) {\n const boundLogger = logger || new ConsoleLogger({ level: 'error' });\n const convertedTools: Record<string, CoreTool> = {};\n for (const [name, tool] of Object.entries(currentTools as Record<string, unknown>)) {\n if (isMastraTool(tool)) {\n convertedTools[name] = makeCoreTool(\n tool as unknown as ToolToConvert,\n {\n name,\n runId,\n threadId: typedInput.state?.threadId,\n resourceId: typedInput.state?.resourceId,\n logger: boundLogger,\n mastra: mastra ? createMastraProxy({ mastra, logger: boundLogger }) : undefined,\n memory: registryEntry?.memory,\n agentName: typedInput.agentName ?? agentId,\n requestContext,\n workspace: registryEntry?.workspace,\n requireApproval: (tool as any).requireApproval,\n backgroundConfig: (tool as any).background,\n // Emit context.writer.write() / .custom() output through pubsub,\n // matching how the durable tool-call step builds its writer.\n outputWriter: pubsub\n ? async (chunk: any) => {\n await emitChunkEvent(pubsub, runId, chunk as ChunkType);\n }\n : undefined,\n },\n undefined,\n execOptions.autoResumeSuspendedTools,\n );\n } else {\n convertedTools[name] = tool as CoreTool;\n }\n }\n currentTools = convertedTools as unknown as ToolSet;\n if (registryEntry) {\n // Store the exact per-step snapshot rather than merging onto the\n // previous step's set. `currentTools` already starts from the full\n // toolset resolved at the top of this step, so a snapshot keeps the\n // static tools while dropping processor-injected tools the current\n // step no longer exposes (e.g. a ToolSearchProcessor entry that hit\n // its TTL). Merging would leave those stale tools executable by the\n // tool-call step even though the model was never shown them.\n registryEntry.tools = convertedTools;\n }\n }\n } catch (error) {\n // Handle TripWire from processInputStep — emit tripwire chunk and\n // bail the step, mirroring the regular agent's buildTripWireBailResponse.\n // Return a bail output with reason: 'tripwire' so the dowhile loop\n // stops gracefully and emits a proper finish event.\n if (error instanceof TripWire) {\n logger?.warn?.('Streaming input processor tripwire triggered', {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n processorId: error.processorId,\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n },\n });\n }\n // Return a bail response instead of throwing — the dowhile\n // predicate will see isContinued: false and stop the loop,\n // then emitFinishEvent will emit reason: 'tripwire'.\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings: [],\n isContinued: false,\n },\n metadata: {\n modelId: currentModel.modelId,\n },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processInputStep processors:', error);\n throw error;\n }\n }\n\n // ── Signal echo & pre-run drain ───────────────────────────────\n // Mirror the non-durable llm-execution-step:\n // 1. Echo initialSignalEchoes (signals that were part of the input\n // messages, e.g. from persisted memory) so the client sees them.\n // 2. Pre-run signals: if this is the first model request of the run\n // (stepIndex === 0), drain signals that were queued before the\n // run made its first request. These must be added to messageList\n // BEFORE inputMessages is materialized so the model sees them.\n if (pubsub) {\n const initialSignalEchoes = registryEntry?.initialSignalEchoes?.splice(0) ?? [];\n for (const initialSignal of initialSignalEchoes) {\n await emitChunkEvent(pubsub, runId, initialSignal.toDataPart() as any);\n }\n\n const isFirstModelRequest = stepIndex === 0;\n if (isFirstModelRequest && registryEntry?.drainPendingSignals) {\n const preRunSignals = registryEntry.drainPendingSignals('pre-run');\n if (preRunSignals.length > 0) {\n currentMessageId = mastra?.generateId?.() ?? crypto.randomUUID();\n }\n for (const preRunSignal of preRunSignals) {\n const signalForTranscript = messageList.addSignal(preRunSignal);\n await emitChunkEvent(pubsub, runId, signalForTranscript.toDataPart() as any);\n }\n }\n }\n\n // `downloadRetries` / `downloadConcurrency` are internal-only on the\n // non-durable path today (not exposed through AgentExecutionOptions),\n // so durable also relies on the MessageList defaults here. If those\n // ever become user-facing they should be plumbed in identically.\n const messageListPromptArgs = await buildLlmPromptArgs({\n model: currentModel,\n });\n const llmPromptForModel =\n currentModel.specificationVersion === 'v4'\n ? messageList.get.all.aiV7.llmPrompt\n : currentModel.specificationVersion === 'v3'\n ? messageList.get.all.aiV6.llmPrompt\n : messageList.get.all.aiV5.llmPrompt;\n let inputMessages = (await llmPromptForModel(messageListPromptArgs)) as LanguageModelV2Prompt;\n\n // Inject the auto-resume directive into the leading system message when\n // there are suspended tools waiting for resumption (parity with the\n // non-durable agentic-execution step).\n inputMessages = applyAutoResumeSystemMessage({\n autoResume: execOptions.autoResumeSuspendedTools,\n inputMessages,\n messages: messageList.get.all.db(),\n });\n\n // Tell the model about background-task capabilities when a\n // background-task manager is wired in. Mirrors the non-durable\n // agentic-execution step so background-enabled tools surface the\n // same `_background` guidance to the LLM.\n inputMessages = injectBackgroundTaskPrompt({\n inputMessages,\n backgroundTaskManager: registryEntry?.backgroundTaskManager,\n tools: currentTools as Record<string, { background?: any; description?: string }> | undefined,\n agentBackgroundConfig: registryEntry?.backgroundTasksConfig,\n });\n\n // Run `processLLMRequest` for any input processors that implement it.\n // This hook lets processors rewrite the outbound prompt transiently\n // without persisting changes back to the message list, or short-circuit\n // the call entirely by returning a cached response.\n // Mirrors loop/workflows/agentic-execution/llm-execution-step.ts.\n //\n // Use `llmRequestInputProcessors` (uncombined) because combined\n // (workflow-wrapped) processors are skipped by\n // `ProcessorRunner.runProcessLLMRequest`. Fall back to\n // `inputProcessors` for backward compatibility.\n let cachedResponse: CachedLLMStepResponse | undefined;\n const allInputProcessors =\n registryEntry?.llmRequestInputProcessors ??\n registryEntry?.inputProcessors ??\n resolvedLlmRequestInputProcessors ??\n resolvedInputProcessors ??\n [];\n // Create a single ProcessorRunner shared between processLLMRequest\n // and processLLMResponse so processor state (e.g. cache keys stashed\n // in the request hook) is available in the response hook.\n const requestStepRunner =\n allInputProcessors.length > 0\n ? new ProcessorRunner({\n inputProcessors: allInputProcessors,\n outputProcessors: [],\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry?.processorStates,\n })\n : undefined;\n const requestStepWriter = pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n if (requestStepRunner) {\n try {\n const requestStepResult = await requestStepRunner.runProcessLLMRequest({\n prompt: inputMessages,\n model: currentModel,\n stepNumber: (inputData as any).accumulatedSteps?.length ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n retryCount: (inputData as any).processorRetryCount ?? 0,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: requestStepWriter,\n abortSignal: executionAbortSignal,\n });\n inputMessages = requestStepResult.prompt;\n cachedResponse = requestStepResult.response;\n } catch (error) {\n if (error instanceof TripWire) {\n logger?.warn?.('Streaming request processor tripwire triggered', {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n // Emit a tripwire chunk and return a bail response so the\n // dowhile loop stops gracefully with reason: 'tripwire'.\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n processorId: error.processorId,\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n },\n });\n }\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings: [],\n isContinued: false,\n },\n metadata: {\n modelId: currentModel.modelId,\n },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processLLMRequest processors:', error);\n throw error;\n }\n }\n\n // Enable defer mode - step-finish won't auto-close the step span\n // This allows us to export the step span and close it later after tool execution\n modelSpanTracker?.setDeferStepClose(true);\n\n // 7. Track state during streaming\n let warnings: any[] = [];\n let request: any = {};\n let rawResponse: any = {};\n const textDeltas: string[] = [];\n const toolCalls: DurableToolCallInput[] = [];\n let finishReason: string = 'stop';\n let usage: any = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n let responseMetadata: any = {};\n\n // ── Client-tool observability + onInputStart / onInputDelta ──\n // Mirrors the regular agent's injectClientToolObservability / endClientToolObservabilitySpan\n // helpers. Creates CLIENT_TOOL_CALL spans for tools executed on the client side and\n // invokes the tool-level onInputStart / onInputDelta callbacks as chunks arrive.\n const clientToolArgsTextByToolCallId = new Map<string, string[]>();\n const clientToolObservabilityByToolCallId = new Map<\n string,\n { carrier: unknown; span: AnySpan; ended: boolean }\n >();\n // Cache resolved tool defs by toolCallId so `tool-call-delta` chunks\n // (which may carry only a toolCallId, no toolName) can still find the\n // tool resolved during the preceding `tool-call-input-streaming-start`.\n const resolvedToolByCallId = new Map<string, CoreTool>();\n const providerToolSpansByToolCallId = new Map<string, { span: AnySpan; ended: boolean }>();\n\n const resolveToolDef = (toolName: string): CoreTool | undefined => {\n const directTool = (currentTools as unknown as Record<string, CoreTool> | undefined)?.[toolName];\n if (directTool) return directTool;\n const registryTool = registryEntry?.tools?.[toolName];\n if (registryTool) return registryTool;\n // Resolve provider tools by model-facing name (e.g. 'web_search' → provider tool with id 'anthropic.web_search').\n // Check both currentTools and registryEntry.tools to match the durable tool-call step's resolution.\n const providerTool = findProviderToolByName(currentTools as any, toolName) as CoreTool | undefined;\n if (providerTool) return providerTool;\n return findProviderToolByName(registryEntry?.tools as any, toolName) as CoreTool | undefined;\n };\n\n const endClientToolObservabilitySpan = (toolCallId: string, args?: unknown): void => {\n const entry = clientToolObservabilityByToolCallId.get(toolCallId);\n if (!entry || entry.ended) {\n clientToolArgsTextByToolCallId.delete(toolCallId);\n return;\n }\n entry.span.end(args !== undefined ? { metadata: { args } } : undefined);\n entry.ended = true;\n clientToolArgsTextByToolCallId.delete(toolCallId);\n };\n\n const parseClientToolArgsFromDeltas = (toolCallId: string): unknown | undefined => {\n const deltas = clientToolArgsTextByToolCallId.get(toolCallId);\n if (!deltas?.length) return undefined;\n const input = deltas.join('');\n if (!input) return undefined;\n try {\n return JSON.parse(input);\n } catch {\n return undefined;\n }\n };\n\n const injectClientToolObservability = ({\n toolCallId,\n toolName,\n args,\n providerExecuted,\n payload,\n }: {\n toolCallId: string;\n toolName: string;\n args?: unknown;\n providerExecuted?: boolean;\n payload: Record<string, unknown> & { observability?: unknown };\n }): { toolDef: CoreTool | undefined } => {\n const toolDef = resolveToolDef(toolName);\n const inferredProviderExecuted = inferProviderExecuted(providerExecuted, toolDef);\n const isClientTool =\n !inferredProviderExecuted && !(toolDef as { execute?: unknown } | undefined)?.execute;\n\n if (!isClientTool || !mastra || !tracingContext?.currentSpan) {\n return { toolDef };\n }\n\n const existingCarrier = clientToolObservabilityByToolCallId.get(toolCallId);\n if (existingCarrier) {\n payload.observability = existingCarrier.carrier;\n if (args !== undefined) {\n endClientToolObservabilitySpan(toolCallId, args);\n }\n return { toolDef };\n }\n\n const proxy = (mastra as Mastra).observability?.getClientObservabilityProxy?.();\n if (!proxy) return { toolDef };\n\n try {\n const parentSpan =\n tracingContext.currentSpan.type === ('agent_run' as string)\n ? tracingContext.currentSpan\n : ((tracingContext.currentSpan as any).findParent?.('agent_run') ?? tracingContext.currentSpan);\n const clientToolSpan = (parentSpan as any).createChildSpan?.({\n type: 'client_tool_call',\n name: `client_tool: '${toolName}'`,\n entityType: EntityType.TOOL,\n entityId: toolName,\n entityName: toolName,\n attributes: {\n toolDescription: (toolDef as { description?: string } | undefined)?.description,\n toolType: 'client-tool',\n },\n ...(args !== undefined ? { input: args } : {}),\n });\n if (clientToolSpan) {\n const carrier = proxy.inject(clientToolSpan);\n const entry = { carrier, span: clientToolSpan as AnySpan, ended: false };\n clientToolObservabilityByToolCallId.set(toolCallId, entry);\n payload.observability = carrier;\n if (args !== undefined) {\n endClientToolObservabilitySpan(toolCallId, args);\n }\n }\n } catch (err) {\n logger?.warn?.('[ClientObservabilityProxy] failed to create CLIENT_TOOL_CALL span', {\n error: err instanceof Error ? err.message : String(err),\n toolName,\n });\n }\n\n return { toolDef };\n };\n\n const injectProviderToolObservability = ({\n toolCallId,\n toolName,\n args,\n providerExecuted,\n }: {\n toolCallId: string;\n toolName: string;\n args?: unknown;\n providerExecuted?: boolean;\n }) => {\n if (!tracingContext?.currentSpan) return;\n\n const toolDef = resolveToolDef(toolName);\n const inferredProviderExecuted = inferProviderExecuted(providerExecuted, toolDef);\n if (!inferredProviderExecuted) return;\n const existingEntry = providerToolSpansByToolCallId.get(toolCallId);\n if (existingEntry) {\n if (args !== undefined && existingEntry.span.input === undefined) {\n (existingEntry.span as any).update?.({ input: args });\n }\n return;\n }\n\n try {\n const parentSpan =\n tracingContext.currentSpan.type === ('agent_run' as string)\n ? tracingContext.currentSpan\n : ((tracingContext.currentSpan as any).findParent?.('agent_run') ?? tracingContext.currentSpan);\n\n const span = (parentSpan as any).createChildSpan?.({\n type: 'provider_tool_call',\n name: `provider_tool: '${toolName}'`,\n entityType: EntityType.TOOL,\n entityId: toolName,\n entityName: toolName,\n attributes: {\n toolType: 'provider-tool',\n toolDescription: (toolDef as { description?: string } | undefined)?.description,\n toolCallId,\n },\n metadata: { toolCallId },\n ...(args !== undefined ? { input: args } : {}),\n });\n\n if (span) {\n providerToolSpansByToolCallId.set(toolCallId, { span: span as AnySpan, ended: false });\n }\n } catch (err) {\n logger?.warn?.('[ProviderToolObservability] failed to create PROVIDER_TOOL_CALL span', {\n error: err instanceof Error ? err.message : String(err),\n toolName,\n });\n }\n };\n\n const cleanupToolObservabilitySpans = () => {\n for (const [toolCallId, entry] of clientToolObservabilityByToolCallId.entries()) {\n if (!entry.ended) {\n const parsedArgs = parseClientToolArgsFromDeltas(toolCallId);\n entry.span.end(parsedArgs !== undefined ? { metadata: { args: parsedArgs } } : undefined);\n entry.ended = true;\n }\n }\n clientToolArgsTextByToolCallId.clear();\n\n for (const [, entry] of providerToolSpansByToolCallId.entries()) {\n if (!entry.ended) {\n entry.span.end();\n entry.ended = true;\n }\n }\n providerToolSpansByToolCallId.clear();\n };\n\n // 8. Start MODEL_STEP span at the beginning of LLM execution\n modelSpanTracker?.startStep();\n\n // Apply post-processor request-side context to MODEL_INFERENCE then\n // open the inference span immediately before the model call so its\n // startTime excludes any input processor work and availableTools /\n // toolChoice reflect per-step mutations. responseFormat tracks the\n // actual structuredOutput payload sent to execute() — which is\n // undefined when structuringModelConfig routes through a separate\n // structuring step instead of asking the model for json_schema.\n modelSpanTracker?.setInferenceContext?.({\n parameters: currentModelSettings as Record<string, unknown> | undefined,\n providerOptions: currentProviderOptions as Record<string, unknown> | undefined,\n availableTools: getStepAvailableToolNames(\n currentTools as Record<string, unknown> | undefined,\n currentActiveTools,\n ),\n toolChoice: currentToolChoice,\n responseFormat: structuredOutput ? 'json_schema' : undefined,\n });\n modelSpanTracker?.startInference?.();\n\n // Collect chunks for post-stream message building (via\n // buildMessagesFromChunks) and for the processLLMResponse hook\n // (pairs with processLLMRequest — lets processors like\n // ResponseCache persist the model's response). Always populated\n // so reasoning/text/tool parts are reconstructed in stream order,\n // including empty reasoning spans that carry providerMetadata\n // (e.g. OpenAI itemId) required by subsequent turns (#19365).\n const collectedChunks: CollectedChunk[] = [];\n\n // 10. Execute LLM call (or replay cached response)\n let modelResult: ReturnType<typeof execute>;\n if (cachedResponse) {\n // Short-circuit: replay cached chunks instead of calling the model.\n // Output processors are skipped on cache hit because the cached\n // chunks already reflect their effects from the original call.\n warnings = cachedResponse.warnings ?? [];\n request = cachedResponse.request ?? {};\n rawResponse = cachedResponse.rawResponse;\n modelSpanTracker?.updateStep?.({\n request: request || {},\n inputMessages,\n warnings: warnings || [],\n messageId: currentMessageId,\n });\n const replayChunks = cachedResponse.chunks;\n modelResult = new ReadableStream({\n start(ctrl) {\n for (const chunk of replayChunks) {\n ctrl.enqueue({\n ...chunk,\n runId,\n from: ChunkFrom.AGENT,\n });\n }\n ctrl.close();\n },\n }) as unknown as ReturnType<typeof execute>;\n } else {\n modelResult = execute({\n runId,\n model: currentModel,\n providerOptions: currentProviderOptions,\n inputMessages,\n tools: currentTools,\n toolChoice: currentToolChoice,\n activeTools: currentActiveTools,\n options: { abortSignal: executionAbortSignal },\n headers: mergeLlmCallHeaders({\n memoryHeaders: buildMemoryHeaders({\n threadId: typedInput.state?.threadId,\n resourceId: typedInput.state?.resourceId,\n }),\n modelConfigHeaders: resolvedModelList?.find(m => m.id === modelEntry.id)?.headers,\n callTimeHeaders:\n registryEntry?.callTimeHeaders || currentModelSettings?.headers\n ? {\n ...(registryEntry?.callTimeHeaders as Record<string, string> | undefined),\n ...(currentModelSettings?.headers as Record<string, string> | undefined),\n }\n : undefined,\n }),\n modelSettings: {\n ...currentModelSettings,\n maxRetries: 0,\n },\n includeRawChunks: execOptions.includeRawChunks,\n methodType: 'stream',\n structuredOutput: structuredOutput as any,\n onResult: ({ warnings: w, request: r, rawResponse: rr }) => {\n warnings = w || [];\n request = r || {};\n rawResponse = rr || {};\n modelSpanTracker?.updateStep?.({ request, inputMessages, warnings, messageId: currentMessageId });\n },\n });\n }\n\n // 10. Create output stream to process chunks\n // Note: We cast through any to handle the web/node ReadableStream type mismatch\n const outputStream = new MastraModelOutput({\n model: {\n modelId: currentModel.modelId,\n provider: currentModel.provider,\n version: currentModel.specificationVersion,\n },\n stream: modelResult as any,\n messageList,\n messageId: currentMessageId,\n options: {\n runId,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n requestContext,\n },\n });\n\n // 11. Process the stream and emit chunks via pubsub.\n // The inner LLM stream emits 'finish' but never 'step-finish' (durable calls\n // `execute` directly). Rewrite 'finish' -> 'step-finish' before the tracker so\n // MODEL_STEP / MODEL_INFERENCE close and the client buffers the step.\n const baseStream = outputStream._getBaseStream();\n const stepBoundaryStream = (baseStream as ReadableStream<any>).pipeThrough(\n new TransformStream<any, any>({\n transform(chunk, controller) {\n if (chunk?.type === 'finish') {\n controller.enqueue({ ...chunk, type: 'step-finish' });\n } else {\n controller.enqueue(chunk);\n }\n },\n }),\n );\n // Wrap with ModelSpanTracker to create/close MODEL_STEP and MODEL_CHUNK spans\n const trackedStream = modelSpanTracker?.wrapStream(stepBoundaryStream) ?? stepBoundaryStream;\n\n let deferredStepFinishChunk: any = null;\n try {\n let stepStartEmitted = false;\n for await (const rawChunk of trackedStream) {\n if (!rawChunk) continue;\n\n // Mirror the regular agent: if the abort signal fired between\n // chunks, stop consuming the stream immediately so we don't\n // send additional data to the client after cancellation.\n if (executionAbortSignal?.aborted) break;\n\n // Emit step-start before the first stream chunk so the\n // ordering matches the regular agent: start → step-start → response-metadata → …\n // onResult has already fired by the time the first chunk arrives,\n // so `request` and `warnings` are populated.\n if (!stepStartEmitted && pubsub) {\n stepStartEmitted = true;\n await emitStepStartEvent(pubsub, runId, {\n stepId: DurableStepIds.LLM_EXECUTION,\n request,\n warnings,\n });\n }\n\n // Enrich tool-related chunks with the in-process payload transform\n // policy (mirrors the non-durable agentic-execution layer). The\n // policy lives on the run registry; serializable `targets` shadow\n // travels with the workflow input. No-op for non-tool chunks or\n // when no policy is configured for this run.\n //\n // IMPORTANT: the transformed chunk is only used for client-facing\n // emission. Internal tool-call state (args persisted into\n // `toolCalls`, downstream tool execution) MUST be built from the\n // untransformed `rawChunk` so display-layer redactions/rewrites\n // do not leak into actual tool inputs.\n //\n // Use the per-step `currentTools` (post-`prepareStep` and input\n // processors) rather than the registry-level tool list — that way\n // any tool-level `transformToolPayload` added or replaced for the\n // current step is honoured, instead of being silently skipped.\n const transformTools = currentTools as unknown as Record<string, CoreTool> | undefined;\n const clientChunk =\n registryEntry?.toolPayloadTransform || transformTools\n ? await applyToolPayloadTransformToChunk(rawChunk, {\n policy: registryEntry?.toolPayloadTransform,\n tools: transformTools,\n logger: logger as any,\n })\n : rawChunk;\n\n // ── Client-tool observability injection ──\n // For tool-call streaming chunks, inject CLIENT_TOOL_CALL spans\n // and collect deltas so the span can be ended with parsed args.\n //\n // IMPORTANT: inject into `clientChunk.payload` (the published\n // chunk), not `rawChunk.payload`. When a payload transform is\n // active, `clientChunk` is a new object — mutating `rawChunk`\n // would lose the observability carrier on the wire.\n let toolInputStartToolDef: CoreTool | undefined;\n if (rawChunk.type === 'tool-call-input-streaming-start') {\n ({ toolDef: toolInputStartToolDef } = injectClientToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n providerExecuted: rawChunk.payload.providerExecuted,\n payload: (clientChunk as any).payload as Record<string, unknown> & { observability?: unknown },\n }));\n // Cache the resolved tool so subsequent delta chunks (which may\n // carry only toolCallId, no toolName) can still find it.\n if (toolInputStartToolDef) {\n resolvedToolByCallId.set(rawChunk.payload.toolCallId, toolInputStartToolDef);\n }\n injectProviderToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n providerExecuted: rawChunk.payload.providerExecuted,\n });\n } else if (rawChunk.type === 'tool-call-delta') {\n const toolCallId = rawChunk.payload.toolCallId;\n if (toolCallId && rawChunk.payload.argsTextDelta) {\n const deltas = clientToolArgsTextByToolCallId.get(toolCallId) ?? [];\n deltas.push(rawChunk.payload.argsTextDelta);\n clientToolArgsTextByToolCallId.set(toolCallId, deltas);\n }\n } else if (rawChunk.type === 'tool-call-input-streaming-end') {\n const parsedArgs = parseClientToolArgsFromDeltas(rawChunk.payload.toolCallId);\n if (parsedArgs !== undefined) {\n endClientToolObservabilitySpan(rawChunk.payload.toolCallId, parsedArgs);\n }\n } else if (rawChunk.type === 'tool-call') {\n injectClientToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n args: rawChunk.payload.args,\n providerExecuted: rawChunk.payload.providerExecuted,\n payload: (clientChunk as any).payload as Record<string, unknown> & { observability?: unknown },\n });\n injectProviderToolObservability({\n toolCallId: rawChunk.payload.toolCallId,\n toolName: rawChunk.payload.toolName,\n args: rawChunk.payload.args,\n providerExecuted: rawChunk.payload.providerExecuted,\n });\n }\n\n // Forward every chunk to the client ('finish' was rewritten to 'step-finish' above).\n // Skip 'error' chunks — they are handled internally by the retry/fallback\n // logic and must not be emitted to the client stream. When all models are\n // exhausted the fatal error is propagated via emitError (mirrors the regular\n // agent's deferredErrorChunk pattern).\n //\n // Defer 'step-finish': for intermediate steps (hasToolCalls) we save it\n // on the output so llm-mapping can emit it AFTER tool-result chunks,\n // matching the regular agent's ordering (tool-result → step-finish).\n // For final steps (no tool calls) we emit it after the assistant message\n // is added to messageList.\n if (pubsub && rawChunk.type !== 'error') {\n if (rawChunk.type === 'step-finish') {\n deferredStepFinishChunk = clientChunk;\n } else {\n await emitChunkEvent(pubsub, runId, clientChunk);\n }\n }\n\n // Collect every chunk for post-stream message building and the\n // processLLMResponse hook. Always collect — reasoning parts\n // (including empty spans with providerMetadata carrying\n // OpenAI itemIds) are required to correctly reconstruct the\n // assistant message and preserve pairing with subsequent\n // tool-calls (#19365).\n collectedChunks.push({\n type: rawChunk.type,\n payload: 'payload' in rawChunk ? rawChunk.payload : undefined,\n metadata: (rawChunk as { metadata?: Record<string, unknown> }).metadata,\n });\n\n // Process different chunk types — always from the raw chunk so\n // internal state (tool args, finish reason, usage, metadata) is\n // never affected by display-layer transforms.\n switch (rawChunk.type) {\n case 'text-delta': {\n const payload = rawChunk.payload as TextDeltaPayload;\n textDeltas.push(payload.text);\n break;\n }\n\n case 'tool-call-input-streaming-start': {\n const tool = toolInputStartToolDef || resolveToolDef(rawChunk.payload.toolName);\n if (tool && 'onInputStart' in tool) {\n try {\n // Pass the actual prompt sent to the model (post-processLLMRequest\n // rewrites) instead of rebuilding from messageList, which would\n // drop any transient prompt modifications made by input processors.\n await (tool as any).onInputStart?.({\n toolCallId: rawChunk.payload.toolCallId,\n messages: inputMessages,\n abortSignal: executionAbortSignal,\n });\n } catch (error) {\n logger?.error?.('Error calling onInputStart', error);\n }\n }\n break;\n }\n\n case 'tool-call-delta': {\n // Prefer the cached tool resolved during the preceding start chunk.\n // Fall back to toolName-based resolution for completeness.\n const tool =\n resolvedToolByCallId.get(rawChunk.payload.toolCallId) ??\n (rawChunk.payload.toolName ? resolveToolDef(rawChunk.payload.toolName) : undefined);\n if (tool && 'onInputDelta' in tool) {\n try {\n await (tool as any).onInputDelta?.({\n inputTextDelta: rawChunk.payload.argsTextDelta,\n toolCallId: rawChunk.payload.toolCallId,\n messages: inputMessages,\n abortSignal: executionAbortSignal,\n });\n } catch (error) {\n logger?.error?.('Error calling onInputDelta', error);\n }\n }\n break;\n }\n\n case 'tool-call': {\n const payload = rawChunk.payload as ToolCallPayload;\n toolCalls.push({\n toolCallId: payload.toolCallId,\n toolName: payload.toolName,\n args: payload.args || {},\n providerMetadata: payload.providerMetadata as Record<string, unknown> | undefined,\n providerExecuted: payload.providerExecuted,\n output: payload.output,\n activeTools: currentActiveTools ?? null,\n });\n break;\n }\n\n case 'tool-result': {\n const payload = rawChunk.payload as any;\n // Close PROVIDER_TOOL_CALL span if one was opened for this tool call\n const providerEntry = providerToolSpansByToolCallId.get(payload.toolCallId);\n if (providerEntry && !providerEntry.ended) {\n providerEntry.span.end({\n output: payload.result,\n attributes: { success: !payload.isError },\n });\n providerEntry.ended = true;\n } else if (!providerEntry && tracingContext?.currentSpan) {\n // Deferred result: no span was opened in this step invocation.\n // Only create a synthetic span if this is actually a provider-executed tool.\n const resultToolDef2 = resolveToolDef(payload.toolName);\n const isProviderExec = inferProviderExecuted(payload.providerExecuted, resultToolDef2);\n if (!isProviderExec) break;\n\n let spanInput = payload.args;\n if (spanInput === undefined) {\n // Fallback: find args from the tool-call already stored in messageList\n const allMessages = messageList.get.all.db();\n for (const msg of allMessages) {\n if (!msg.content?.parts) continue;\n for (const part of msg.content.parts) {\n if (\n part.type === 'tool-invocation' &&\n part.toolInvocation?.toolCallId === payload.toolCallId\n ) {\n spanInput = part.toolInvocation.args;\n break;\n }\n }\n if (spanInput !== undefined) break;\n }\n }\n injectProviderToolObservability({\n toolCallId: payload.toolCallId,\n toolName: payload.toolName,\n args: spanInput,\n providerExecuted: true,\n });\n const deferredEntry = providerToolSpansByToolCallId.get(payload.toolCallId);\n if (deferredEntry && !deferredEntry.ended) {\n deferredEntry.span.end({\n output: payload.result,\n attributes: { success: !payload.isError },\n });\n deferredEntry.ended = true;\n }\n }\n break;\n }\n\n case 'step-finish': {\n const payload = rawChunk.payload as any;\n // The terminal chunk (rewritten from 'finish' above) carries finishReason\n // in stepResult.reason and usage in output.usage.\n finishReason = payload.stepResult?.reason || payload.finishReason || 'stop';\n usage = payload.output?.usage || payload.usage || usage;\n break;\n }\n\n case 'response-metadata': {\n const payload = rawChunk.payload as any;\n responseMetadata = {\n id: payload.id,\n timestamp: payload.timestamp,\n modelId: payload.modelId,\n headers: payload.headers,\n };\n break;\n }\n\n case 'error': {\n const payload = rawChunk.payload as any;\n const errorMessage = payload?.error?.message || payload?.message || 'LLM execution error';\n const errorObj = new Error(errorMessage);\n // DON'T emit error event here - we might have fallback models to try\n // Error event will be emitted after all models are exhausted\n throw errorObj;\n }\n }\n }\n // Clean up any unclosed observability spans after successful stream completion\n cleanupToolObservabilitySpans();\n } catch (error) {\n cleanupToolObservabilitySpans();\n logger?.error?.('Error processing LLM stream', { error, runId });\n\n const errorObj = error instanceof Error ? error : new Error(String(error));\n if (modelSpanTracker) {\n modelSpanTracker.reportGenerationError({ error: errorObj });\n } else if (modelSpan) {\n modelSpan.error({ error: errorObj });\n }\n\n // If this error was triggered by abortSignal cancellation, surface an\n // abort event to the client so onAbort callbacks fire and bail out\n // of the entire fallback/retry flow — a confirmed abort should not\n // trigger retries on the same model nor fall through to other\n // models. We deliberately avoid matching on arbitrary error message\n // text (e.g. /abort/i) because that can fire for retryable provider\n // errors whose message happens to mention \"abort\"; we only trust\n // the canonical AbortError name or an actual aborted signal.\n const isAbort = executionAbortSignal?.aborted === true || errorObj.name === 'AbortError';\n if (isAbort) {\n // Return a clean output instead of throwing so the workflow\n // engine doesn't crash. The dowhile predicate will see\n // isContinued: false and stop the loop. The FINISH event\n // (emitted by the finalization block) will carry reason: 'abort'.\n return {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: currentModel.modelId },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n lastError = errorObj;\n\n // Try processAPIError before deciding retry/break\n const registryEntryInner = globalRunRegistry.get(runId);\n const canRetryErrorInner = maxProcessorRetries !== undefined && processorRetryCount < maxProcessorRetries;\n if (registryEntryInner?.errorProcessors?.length && canRetryErrorInner) {\n try {\n const runner = new ProcessorRunner({\n inputProcessors: registryEntryInner.inputProcessors ?? [],\n outputProcessors: registryEntryInner.outputProcessors ?? [],\n errorProcessors: registryEntryInner.errorProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntryInner.processorStates,\n });\n const currentMessageList = new MessageList();\n currentMessageList.deserialize(typedInput.messageListState);\n const { retry } = await runner.runProcessAPIError({\n error: lastError,\n messages: currentMessageList.get.all.db(),\n messageList: currentMessageList,\n stepNumber: (inputData as any).stepIndex ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n retryCount: processorRetryCount,\n requestContext,\n });\n if (retry) {\n processorRetryCount++;\n // Error processor retry should NOT consume a model retry attempt.\n // Decrement attempt so the `for` loop increment restores it.\n attempt--;\n continue;\n }\n } catch (processorError) {\n logger?.debug?.(`processAPIError handler failed: ${processorError}`, { runId });\n }\n }\n\n if (attempt < maxRetries) continue; // retry same model\n break; // exhausted retries, try next model\n }\n\n // Check if the stream captured an error (MastraModelOutput swallows errors internally)\n const streamError = outputStream.error;\n if (streamError) {\n const streamErrorObj = streamError instanceof Error ? streamError : new Error(String(streamError));\n logger?.error?.('Stream captured error', { error: streamErrorObj, runId });\n\n if (modelSpanTracker) {\n modelSpanTracker.reportGenerationError({ error: streamErrorObj });\n } else if (modelSpan) {\n modelSpan.error({ error: streamErrorObj });\n }\n\n // Mirror the iterator catch: a captured stream error that turns out\n // to be a confirmed abort must short-circuit retry/fallback.\n const isStreamErrorAbort = executionAbortSignal?.aborted === true || streamErrorObj.name === 'AbortError';\n if (isStreamErrorAbort) {\n return {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: currentModel.modelId },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n lastError = streamErrorObj;\n if (attempt < maxRetries) continue; // retry same model\n break; // exhausted retries, try next model\n }\n\n // Run `processLLMResponse` for any input processors that implement\n // it. Pairs with `processLLMRequest`: lets a processor write the\n // response to a cache (or sink) using state stashed in the request\n // hook. Skipped on cache hit — that response did not come from the\n // model, so writing it back would just rewrite the same value.\n // Mirrors loop/workflows/agentic-execution/llm-execution-step.ts.\n if (!cachedResponse && requestStepRunner) {\n try {\n await requestStepRunner.runProcessLLMResponse({\n chunks: collectedChunks,\n model: currentModel,\n stepNumber: (inputData as any).accumulatedSteps?.length ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n warnings,\n request,\n rawResponse,\n fromCache: false,\n retryCount: (inputData as any).processorRetryCount ?? 0,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: requestStepWriter,\n abortSignal: executionAbortSignal,\n });\n } catch (error) {\n if (error instanceof TripWire) {\n logger?.warn?.('Streaming response processor tripwire triggered', {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n processorId: error.processorId,\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n },\n });\n }\n return {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings,\n isContinued: false,\n },\n metadata: {\n modelId: currentModel.modelId,\n },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processLLMResponse processors:', error);\n throw error;\n }\n }\n\n // 12. Add assistant response to message list.\n // Build parts from the full chunk sequence via the same helper\n // the regular Agent uses, so reasoning spans (including empty\n // reasoning with providerMetadata.openai.itemId) are preserved\n // alongside text and tool-calls in stream order. Without this\n // OpenAI reasoning models fail on the next turn with\n // \"Item 'fc_...' of type 'function_call' was provided without\n // its required 'reasoning' item\" (#19365).\n //\n // Mirror the regular Agent's buildResponseModelMetadata so the\n // persisted assistant message carries the same content.metadata\n // (modelId/provider): prefer the static model, fall back to the\n // response-metadata chunk.\n const responseModelId = currentModel.modelId ?? responseMetadata?.modelId;\n const responseModelMetadata =\n responseModelId || currentModel.provider\n ? {\n metadata: {\n ...(responseModelId ? { modelId: responseModelId } : {}),\n ...(currentModel.provider ? { provider: currentModel.provider } : {}),\n },\n }\n : undefined;\n const builtMessages = buildMessagesFromChunks({\n chunks: collectedChunks,\n messageId: currentMessageId,\n tools: currentTools,\n responseModelMetadata,\n });\n if (builtMessages.length > 0) {\n for (const msg of builtMessages) {\n messageList.add(msg, 'response');\n }\n\n // Sync the updated messageList to the in-process registry so\n // downstream steps (e.g. tool-call.ts's doFlush()) see the\n // assistant message when persisting before suspension.\n if (registryEntry) {\n registryEntry.messageList = messageList;\n }\n }\n\n // 13. Determine if we should continue (has tool calls)\n const isContinued = toolCalls.length > 0 && finishReason !== 'stop';\n const hasToolCalls = toolCalls.length > 0;\n\n // 13.5. Run processOutputStep for output processors (runs AFTER LLM response, BEFORE tool execution)\n // Mirrors the regular agent's llm-execution-step.ts processOutputStep call\n if (effectiveOutputProcessors.length > 0) {\n const outputStepRunner = new ProcessorRunner({\n inputProcessors: [],\n outputProcessors: effectiveOutputProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry?.processorStates,\n });\n\n const toolCallInfos = toolCalls.map(tc => ({\n toolName: tc.toolName,\n toolCallId: tc.toolCallId,\n args: tc.args,\n }));\n\n const outputStepWriter = pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n\n try {\n await outputStepRunner.runProcessOutputStep({\n steps: (inputData as any).accumulatedSteps ?? [],\n messages: messageList.get.all.db(),\n messageList,\n stepNumber: (inputData as any).accumulatedSteps?.length ?? 0,\n finishReason,\n providerMetadata: responseMetadata,\n toolCalls: toolCallInfos.length > 0 ? toolCallInfos : undefined,\n text: textDeltas.join(''),\n usage,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: outputStepWriter,\n });\n } catch (error) {\n if (error instanceof TripWire) {\n // Emit tripwire chunk and return bail response\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n reason: error.message,\n processorId: error.processorId,\n metadata: error.options?.metadata,\n },\n });\n }\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: currentModel.modelId },\n state: typedInput.state,\n };\n }\n throw error;\n }\n }\n\n // 13.9. step-finish emission strategy:\n //\n // For FINAL steps (no tool calls): emit step-finish now. The assistant\n // message is in messageList and there are no tool-results to wait for.\n //\n // For INTERMEDIATE steps (hasToolCalls): save the step-finish chunk\n // on the output so llm-mapping can emit it AFTER tool-call.ts has\n // emitted tool-result chunks. This matches the regular agent's chunk\n // ordering (tool-result → step-finish) which MastraModelOutput relies\n // on for correct step content reconstruction.\n if (pubsub && deferredStepFinishChunk) {\n if (!hasToolCalls) {\n // Final step: emit immediately with pre-computed content\n // Build step content directly from the current step's data rather\n // than relying on messageList which may contain response messages\n // from previous iterations after deserialization.\n const stepContent: Array<{ type: string; [key: string]: unknown }> = [];\n const currentText = textDeltas.join('');\n if (currentText) {\n stepContent.push({ type: 'text', text: currentText });\n }\n deferredStepFinishChunk = {\n ...deferredStepFinishChunk,\n payload: {\n ...deferredStepFinishChunk.payload,\n _durableStepContent: stepContent,\n },\n };\n await emitChunkEvent(pubsub, runId, deferredStepFinishChunk);\n deferredStepFinishChunk = null;\n }\n // else: intermediate step — saved in output.deferredStepFinishChunk below\n }\n\n // 14. Export spans if there are tool calls (so tools can be children of model_step)\n // Don't end the spans yet - they will be ended after tool execution\n const stepSpanData = hasToolCalls ? modelSpanTracker?.exportCurrentStep() : undefined;\n const stepFinishPayload = hasToolCalls ? modelSpanTracker?.getPendingStepFinishPayload() : undefined;\n\n // 15. Build output\n const output: DurableLLMStepOutput = {\n messageListState: messageList.serialize(),\n text: textDeltas.join(''),\n toolCalls,\n stepResult: {\n reason: finishReason as any,\n warnings,\n isContinued,\n totalUsage: usage,\n headers: rawResponse?.headers,\n request,\n },\n metadata: {\n id: responseMetadata.id,\n modelId: responseMetadata.modelId || currentModel.modelId,\n timestamp: responseMetadata.timestamp || new Date().toISOString(),\n providerMetadata: responseMetadata,\n headers: rawResponse?.headers,\n request,\n },\n state: typedInput.state,\n // Pass span data so tool calls can be children of model_step\n modelSpanData: hasToolCalls ? modelSpan?.exportSpan?.() : undefined,\n stepSpanData,\n stepFinishPayload,\n // For intermediate steps (hasToolCalls), save the deferred step-finish\n // chunk so llm-mapping can emit it AFTER tool-result chunks.\n deferredStepFinishChunk: hasToolCalls ? deferredStepFinishChunk : undefined,\n };\n\n // 16. End step span only if there are NO tool calls\n // If there are tool calls, step span will be ended after tool execution\n // NOTE: We NEVER 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 if (!hasToolCalls) {\n // Close the step span with usage/finish info\n const pendingPayload = modelSpanTracker?.getPendingStepFinishPayload() as any;\n if (pendingPayload) {\n // End step span using the pending payload\n const stepSpan = modelSpanTracker?.exportCurrentStep();\n if (stepSpan && observability) {\n const rebuiltStepSpan = observability.rebuildSpan(stepSpan);\n rebuiltStepSpan?.end({\n output: {\n text: textDeltas.join(''),\n toolCalls: [],\n },\n attributes: {\n usage: pendingPayload.output?.usage,\n finishReason: pendingPayload.stepResult?.reason,\n isContinued: pendingPayload.stepResult?.isContinued,\n },\n });\n }\n }\n }\n\n // Success - return the output\n return output;\n } catch (error) {\n // TripWire errors from processLLMRequest / processLLMResponse are\n // guardrail/cache processor decisions, not model failures. They\n // must not be retried or fall back to the next model.\n if (error instanceof TripWire) {\n throw error;\n }\n\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Confirmed aborts bypass all retry / fallback / processAPIError\n // handling — the user (or upstream caller) explicitly cancelled the\n // run and we must terminate immediately rather than burning more\n // attempts or paying for fallback model calls. Re-derive the signal\n // from the registry (the inner try-scoped `executionAbortSignal` is\n // out of scope here).\n const outerRegistryEntry = globalRunRegistry.get(runId);\n const outerAbortSignal = outerRegistryEntry?.abortSignal ?? abortSignal;\n const isAbort = outerAbortSignal?.aborted === true || lastError.name === 'AbortError';\n if (isAbort) {\n // Return a clean output instead of throwing so the workflow\n // engine doesn't crash. The abort event was already emitted\n // by the inner catch.\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'abort' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId: modelEntry.config.modelId },\n state: typedInput.state,\n } satisfies DurableLLMStepOutput;\n }\n\n const modelId = modelEntry.config.modelId;\n logger?.error?.(`Error executing model ${modelId}, attempt ${attempt + 1}/${maxRetries + 1}`, {\n error: lastError,\n runId,\n modelIndex,\n attempt,\n });\n\n // Error processor retry for non-stream errors (e.g. provider\n // rejections that throw before the stream opens). Stream-level\n // errors are already handled in the inner catch above.\n const registryEntry = globalRunRegistry.get(runId);\n const canRetryError = maxProcessorRetries !== undefined && processorRetryCount < maxProcessorRetries;\n if (registryEntry?.errorProcessors?.length && canRetryError) {\n try {\n const runner = new ProcessorRunner({\n inputProcessors: registryEntry.inputProcessors ?? [],\n outputProcessors: registryEntry.outputProcessors ?? [],\n errorProcessors: registryEntry.errorProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n processorStates: registryEntry.processorStates,\n });\n const currentMessageList = new MessageList();\n currentMessageList.deserialize(typedInput.messageListState);\n const { retry } = await runner.runProcessAPIError({\n error: lastError,\n messages: currentMessageList.get.all.db(),\n messageList: currentMessageList,\n stepNumber: (inputData as any).stepIndex ?? 0,\n steps: (inputData as any).accumulatedSteps ?? [],\n retryCount: processorRetryCount,\n requestContext,\n tracingContext,\n });\n if (retry) {\n processorRetryCount++;\n // Error processor retry should NOT consume a model retry attempt.\n attempt--;\n continue;\n }\n } catch (processorError) {\n logger?.debug?.(`processAPIError handler failed: ${processorError}`, { runId });\n }\n }\n\n if (attempt >= maxRetries) {\n logger?.debug?.(`Exhausted retries for model ${modelId}, trying next model`, { runId });\n break;\n }\n\n const delayMs = Math.min(1000 * Math.pow(2, attempt), 10000);\n logger?.debug?.(`Retrying model ${modelId} after ${delayMs}ms`, { runId, attempt });\n await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n } // end retry loop\n } // end model loop\n\n // All models exhausted - emit error + step-finish chunks and return a bail response.\n // This mirrors the regular agent which sets stepResult.reason = 'error' and emits\n // a deferred error chunk rather than crashing the loop.\n const fatalError =\n lastError ?? new Error('Exhausted all fallback models and reached the maximum number of retries.');\n\n // End the root spans here too — this is the only error path that covers EventedAgent,\n // whose fire-and-forget launch never sees the failure (so emitError never runs).\n endRunSpansWithError(runId, fatalError);\n\n // Emit the deferred error chunk so consumers see it\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'error',\n runId,\n from: ChunkFrom.AGENT,\n payload: { error: fatalError },\n });\n\n // Emit step-finish so MastraModelOutput resolves finishReason to 'error'\n await emitChunkEvent(pubsub, runId, {\n type: 'step-finish',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n stepResult: {\n reason: 'error',\n isContinued: false,\n },\n output: {\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n },\n metadata: {},\n },\n });\n }\n\n const modelId = modelList[0]?.id ?? 'unknown';\n return {\n messageListState: messageList.serialize(),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'error' as any,\n warnings: [],\n isContinued: false,\n },\n metadata: { modelId },\n state: typedInput.state,\n };\n },\n });\n}\n","import { z } from 'zod';\nimport { createBackgroundTask } from '../../../../background-tasks/create';\nimport { resolveBackgroundConfig } from '../../../../background-tasks/resolve-config';\nimport type { ToolBackgroundConfig } from '../../../../background-tasks/types';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { Mastra } from '../../../../mastra';\nimport type { MastraMemory } from '../../../../memory/memory';\nimport type { MemoryConfig } from '../../../../memory/types';\nimport type { ExportedSpan, SpanType } from '../../../../observability';\nimport type { ProcessorState } from '../../../../processors';\nimport { ProcessorRunner } from '../../../../processors/runner';\nimport type { ChunkType } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { findProviderToolByName } from '../../../../tools/provider-tool-utils';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport type { SuspendOptions } from '../../../../workflows/step';\nimport { createStep } from '../../../../workflows/workflow';\nimport { stopGoalActivity } from '../../../goal';\nimport type { MessageList } from '../../../message-list';\nimport type { SaveQueueManager } from '../../../save-queue';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitSuspendedEvent, emitChunkEvent } from '../../stream-adapter';\nimport type {\n DurableToolCallInput,\n SerializableDurableOptions,\n AgentSuspendedEventData,\n RunRegistryEntry,\n} from '../../types';\nimport { applyToolPayloadTransformToChunk } from '../../utils/apply-tool-payload-transform';\nimport { rebuildRunToolsFromMastra, resolveTool, toolRequiresApproval } from '../../utils/resolve-runtime';\nimport { serializeError } from '../../utils/serialize-state';\n\n/**\n * Input schema for the durable tool call step.\n * Each tool call flows through this schema when using .foreach()\n */\nconst durableToolCallInputSchema = z.object({\n toolCallId: z.string(),\n toolName: z.string(),\n args: z.record(z.string(), z.any()),\n providerMetadata: z.record(z.string(), z.any()).optional(),\n providerExecuted: z.boolean().optional(),\n output: z.any().optional(),\n activeTools: z.array(z.string()).nullable().optional(),\n // Exported MODEL_STEP span so the TOOL_CALL nests under the LLM call\n stepSpanData: z.any().optional(),\n});\n\n/**\n * Output schema for the durable tool call step\n */\nconst durableToolCallOutputSchema = durableToolCallInputSchema.extend({\n result: z.any().optional(),\n error: z\n .object({\n name: z.string(),\n message: z.string(),\n stack: z.string().optional(),\n })\n .optional(),\n // Approval decision for a `requireApproval` tool. Without this field Zod would strip the\n // approval off the step output, so a declined call would lose its `output-denied` marker.\n approval: z\n .object({\n id: z.string(),\n approved: z.boolean(),\n reason: z.string().optional(),\n })\n .optional(),\n});\n\n/**\n * Flush messages to memory before suspending.\n * Mirrors the base Agent's flushMessagesBeforeSuspension() to ensure\n * the thread exists and all pending messages are persisted.\n */\nasync function flushMessagesBeforeSuspension({\n saveQueueManager,\n messageList,\n memory,\n threadId,\n resourceId,\n memoryConfig,\n threadExists,\n onThreadCreated,\n}: {\n saveQueueManager?: SaveQueueManager;\n messageList?: MessageList;\n memory?: MastraMemory;\n threadId?: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n threadExists?: boolean;\n onThreadCreated?: () => void;\n}) {\n if (!saveQueueManager || !messageList || !threadId) {\n return;\n }\n\n try {\n // Ensure thread exists before flushing messages\n if (memory && !threadExists && resourceId) {\n const thread = await memory.getThreadById?.({ threadId });\n if (!thread) {\n await memory.createThread?.({\n threadId,\n resourceId,\n memoryConfig,\n });\n }\n onThreadCreated?.();\n }\n\n // Flush all pending messages immediately\n await saveQueueManager.flushMessages(messageList, threadId, memoryConfig);\n } catch {\n // Log but don't throw — suspension should proceed even if flush fails\n }\n}\n\n/**\n * Run a tool-result or tool-error chunk through the run's output processor pipeline.\n * Returns the processed chunk (possibly modified), or `null` if a processor blocked it\n * (in which case a tripwire chunk is emitted instead).\n *\n * Mirrors the regular agent's `processAndEnqueueChunk` in llm-mapping-step.ts.\n */\nasync function processChunkThroughOutputProcessors(\n chunk: ChunkType,\n registryEntry: RunRegistryEntry | undefined,\n pubsub: PubSub | undefined,\n runId: string,\n agentName: string,\n logger: any,\n messageList?: MessageList,\n): Promise<ChunkType | null> {\n if (!registryEntry?.outputProcessors?.length || !registryEntry.processorStates) {\n return chunk;\n }\n\n try {\n const runner = new ProcessorRunner({\n inputProcessors: [],\n outputProcessors: registryEntry.outputProcessors,\n logger,\n agentName,\n processorStates: registryEntry.processorStates,\n });\n\n const {\n part: processed,\n blocked,\n reason,\n tripwireOptions,\n processorId,\n } = await runner.processPart(\n chunk,\n registryEntry.processorStates as Map<string, ProcessorState>,\n undefined, // observabilityContext\n registryEntry.requestContext,\n messageList,\n 0,\n pubsub\n ? {\n custom: async (data: { type: string }) => {\n await emitChunkEvent(pubsub, runId, data as ChunkType);\n },\n }\n : undefined,\n );\n\n if (blocked) {\n // Emit a tripwire chunk so downstream knows about the block\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n payload: {\n reason: reason || 'Output processor blocked content',\n retry: tripwireOptions?.retry,\n metadata: tripwireOptions?.metadata,\n processorId,\n },\n } as ChunkType);\n }\n return null;\n }\n\n return (processed as ChunkType) ?? null;\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Output processor error for tool chunk: ${error}`);\n // Fall through: emit the original chunk if processor fails\n return chunk;\n }\n}\n\n/**\n * Create a durable tool call step.\n *\n * This step mirrors the base Agent's createToolCallStep pattern:\n * 1. Resolves the tool from the run registry or Mastra\n * 2. Checks if approval is required (global or per-tool)\n * 3. If approval required, emits suspended event, persists messages, and suspends\n * 4. Executes the tool with a suspend callback for in-execution suspension\n * 5. Emits tool-result or tool-error chunks via PubSub\n * 6. Returns the result or error\n *\n * Tool suspension is handled via workflow suspend/resume mechanism:\n * - Tool approval: step suspends with approval payload\n * - In-execution suspension: tool calls suspend() callback, step suspends with suspension payload\n * - Message persistence: messages are flushed before any suspension\n */\nexport function createDurableToolCallStep() {\n return createStep({\n id: DurableStepIds.TOOL_CALL,\n inputSchema: durableToolCallInputSchema,\n outputSchema: durableToolCallOutputSchema,\n execute: async params => {\n const { inputData, mastra, suspend, resumeData: workflowResumeData, requestContext, actor, getInitData } = params;\n\n // Access pubsub via symbol\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n\n const typedInput = inputData as DurableToolCallInput;\n const { toolCallId, toolName, args: rawArgs, providerExecuted, output, activeTools } = typedInput;\n\n // Extract resumeData from tool call arguments (autoResumeSuspendedTools path)\n // When the LLM auto-resumes a suspended tool, it injects `resumeData` into the\n // tool call arguments. We extract it here to skip re-suspending for approval.\n // Mirrors the regular agent's tool-call-step.ts logic.\n let resumeDataFromArgs: any = undefined;\n let args: any = rawArgs;\n if (typeof rawArgs === 'object' && rawArgs !== null) {\n const { resumeData: resumeDataFromInput, ...argsFromInput } = rawArgs as Record<string, any>;\n args = argsFromInput;\n resumeDataFromArgs = resumeDataFromInput;\n }\n const resumeData = resumeDataFromArgs ?? workflowResumeData;\n\n // Get context from init data (the parent workflow input)\n const initData = getInitData<{\n runId: string;\n agentId: string;\n options: SerializableDurableOptions;\n state: {\n threadId?: string;\n resourceId?: string;\n memoryConfig?: MemoryConfig;\n threadExists?: boolean;\n };\n requestContextEntries?: Record<string, unknown>;\n agentSpanData?: unknown;\n modelSpanData?: unknown;\n }>();\n\n const { runId, options: agentOptions, state } = initData;\n const logger = (mastra as any)?.getLogger?.();\n\n // End the open MODEL_STEP + MODEL_GENERATION + AGENT_RUN as `suspended` before\n // pausing — stores persist only span-end events, so an un-ended root is dropped if\n // the run is never resumed. On resume a fresh root is opened (see DurableAgent.resume).\n const endSpansAsSuspended = (info: { toolCallId?: string; toolName?: string; reason?: string }) => {\n try {\n const obs = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({ requestContext });\n if (!obs) return;\n const output = {\n status: 'suspended' as const,\n reason: info.reason,\n toolName: info.toolName,\n toolCallId: info.toolCallId,\n };\n // After a prior resume, end the resume spans (registry override) — they are the\n // active root for this segment. Otherwise end the threaded originals.\n const reg = globalRunRegistry.get(runId);\n const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;\n const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;\n if (typedInput.stepSpanData) {\n obs.rebuildSpan(typedInput.stepSpanData as ExportedSpan<SpanType.MODEL_STEP>)?.end({ output });\n }\n if (modelSpanData) {\n obs.rebuildSpan(modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION>)?.end({ output });\n }\n if (agentSpanData) {\n obs.rebuildSpan(agentSpanData as ExportedSpan<SpanType.AGENT_RUN>)?.end({ output });\n }\n } catch (error) {\n // Span bookkeeping must never break suspension.\n logger?.warn?.(`[DurableAgent] Failed to end spans on suspend: ${error}`);\n }\n };\n\n // If the tool was already executed by the provider, return the output\n if (providerExecuted && output !== undefined) {\n return {\n ...typedInput,\n result: output,\n };\n }\n\n // 1. Resolve the tool from global registry first, then by provider-tool\n // model-facing name (e.g. `web_search` resolves to `webSearch` when the\n // provider tool advertises the snake-case name), then by id, then fall\n // back to the Mastra-wide tool registry (exact name, provider-tool\n // name, then by id). Mirrors the non-durable tool-call step.\n const registryEntry = globalRunRegistry.get(runId);\n let tool = registryEntry?.tools?.[toolName];\n let mastraTools: Record<string, any> | undefined;\n // Tools rebuilt from the Mastra instance when the per-process registry is\n // empty (cross-process worker). Populated lazily below; reused for\n // workspace/memory resolution further down.\n let rebuiltTools: Record<string, any> | undefined;\n let rebuiltWorkspace: any;\n let rebuiltMemory: any;\n let rebuiltSaveQueueManager: any;\n\n if (!tool) {\n tool = findProviderToolByName(registryEntry?.tools as any, toolName) as typeof tool;\n }\n\n if (!tool) {\n tool = Object.values(registryEntry?.tools ?? {}).find(\n (t: any) => t && typeof t === 'object' && 'id' in t && t.id === toolName,\n ) as typeof tool;\n }\n\n if (!tool) {\n tool = resolveTool(toolName, mastra as Mastra);\n }\n\n if (!tool && mastra) {\n mastraTools = (mastra as Mastra).listTools?.() as Record<string, any> | undefined;\n if (mastraTools) {\n tool = findProviderToolByName(mastraTools as any, toolName) as typeof tool;\n if (!tool) {\n tool = Object.values(mastraTools).find(\n (t: any) => t && typeof t === 'object' && 'id' in t && t.id === toolName,\n ) as typeof tool;\n }\n }\n }\n\n // Cross-process fallback: workspace/skill tools are per-request closures\n // never registered at the Mastra-instance level, so the lookups above miss\n // them when the durable steps run on a separate process (e.g. the\n // @mastra/inngest connect() worker) whose registry is empty. Rebuild the\n // full toolset from the agent — the same rebuild the LLM step already does\n // via resolveRuntimeDependencies — and retry. This is the root-cause fix\n // for `ToolNotFoundError` on skill/mastra_workspace_* tools cross-process.\n if (!tool && mastra) {\n const rebuilt = await rebuildRunToolsFromMastra({\n mastra: mastra as Mastra,\n runId,\n agentId: initData.agentId,\n state: state as any,\n options: agentOptions,\n requestContextEntries: initData.requestContextEntries,\n logger,\n });\n if (rebuilt) {\n rebuiltTools = rebuilt.tools;\n rebuiltWorkspace = rebuilt.workspace;\n rebuiltMemory = rebuilt.memory;\n rebuiltSaveQueueManager = rebuilt.saveQueueManager;\n tool = rebuiltTools[toolName] as typeof tool;\n if (!tool) {\n tool = findProviderToolByName(rebuiltTools as any, toolName) as typeof tool;\n }\n if (!tool) {\n tool = Object.values(rebuiltTools).find(\n (t: any) => t && typeof t === 'object' && 'id' in t && t.id === toolName,\n ) as typeof tool;\n }\n }\n }\n\n // Resolve the key the tool is registered under for activeTools filtering.\n // Prefer the per-run registryEntry key (exact name then identity match),\n // and fall back to the Mastra-wide registry when the tool was resolved\n // there. Without this fallback, a globally-registered tool like\n // `webSearch` invoked by its model-facing name `web_search` would be\n // hidden whenever `activeTools` was set, because the key from\n // registryEntry.tools would be `undefined`.\n const toolKey =\n registryEntry?.tools?.[toolName] || rebuiltTools?.[toolName]\n ? toolName\n : (Object.entries(registryEntry?.tools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0] ??\n Object.entries(rebuiltTools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0] ??\n Object.entries(mastraTools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0]);\n const effectiveActiveTools = activeTools === null ? undefined : (activeTools ?? agentOptions.activeTools);\n const activeToolKey = toolKey ?? toolName;\n const isHiddenByActiveTools = effectiveActiveTools !== undefined && !effectiveActiveTools.includes(activeToolKey);\n\n if (!tool || isHiddenByActiveTools) {\n const availableToolNames = effectiveActiveTools ?? Object.keys(rebuiltTools ?? registryEntry?.tools ?? {});\n const availableToolsStr =\n availableToolNames.length > 0 ? ` Available tools: ${availableToolNames.join(', ')}` : '';\n const error = {\n name: 'ToolNotFoundError',\n message: `Tool \"${toolName}\" not found.${availableToolsStr}. Call tools by their exact name only — never add prefixes, namespaces, or colons.`,\n };\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-error',\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, error },\n });\n }\n return {\n ...typedInput,\n error,\n };\n }\n\n // Get memory-related state for message persistence. Fall back to the\n // values rebuilt from Mastra above (cross-process worker), so workspace\n // tools receive their `workspace` and message flushing still works.\n const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;\n const memory = registryEntry?.memory ?? rebuiltMemory;\n const workspace = registryEntry?.workspace ?? rebuiltWorkspace;\n let threadExists = state?.threadExists ?? false;\n\n // Reconstruct MessageList from workflow state if available\n // Note: In foreach mode, the message list from the registry may be available\n // but for durability, we access what's available through the registry\n let messageList: MessageList | undefined;\n // For local execution, the globalRunRegistry might have an ExtendedRunRegistry entry\n // that stores the messageList. We cast and check safely.\n const extendedEntry = globalRunRegistry.get(runId) as any;\n if (extendedEntry?.messageList) {\n messageList = extendedEntry.messageList;\n }\n\n const doFlush = async () => {\n await flushMessagesBeforeSuspension({\n saveQueueManager,\n messageList,\n memory,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n memoryConfig: state?.memoryConfig,\n threadExists,\n onThreadCreated: () => {\n threadExists = true;\n },\n });\n };\n\n // 2. Check if tool requires approval. Prefer the live policy on the\n // in-process registry (which preserves the function form with real\n // toolName/args); fall back to the JSON-safe boolean shadow on the\n // serialized workflow input for cross-process engines.\n const registryRequireToolApproval = registryEntry?.requireToolApproval;\n const effectiveRequireToolApproval =\n registryRequireToolApproval !== undefined ? registryRequireToolApproval : agentOptions.requireToolApproval;\n const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {\n toolName,\n requestContext: registryEntry?.requestContext\n ? Object.fromEntries(\n [...registryEntry.requestContext.entries()].filter(([key]) => key !== '__mastra_requireToolApproval'),\n )\n : undefined,\n // Use the same rebuilt-workspace fallback as execution (above), so\n // workspace-aware approval policies see their workspace cross-process.\n workspace,\n });\n\n // Add suspended-tool / pending-approval metadata to the last assistant\n // message so `extractSuspendedToolsFromMessages` can detect it on the\n // next turn (autoResumeSuspendedTools) or on page-refresh resume.\n // Mirrors the regular agent's `addToolMetadata()`.\n const addToolMetadata = (opts: {\n type: 'approval' | 'suspension';\n resumeSchema?: string;\n suspendPayload?: unknown;\n }) => {\n if (!messageList) return;\n const metadataKey = opts.type === 'suspension' ? 'suspendedTools' : 'pendingToolApprovals';\n const responseMessages = messageList.get.response.db();\n const lastAssistantMessage = [...responseMessages].reverse().find(msg => msg.role === 'assistant');\n if (!lastAssistantMessage?.content) return;\n\n let metadata: Record<string, any>;\n if (\n typeof lastAssistantMessage.content.metadata === 'object' &&\n lastAssistantMessage.content.metadata !== null\n ) {\n metadata = lastAssistantMessage.content.metadata as Record<string, any>;\n } else {\n metadata = {};\n lastAssistantMessage.content.metadata = metadata;\n }\n metadata[metadataKey] = metadata[metadataKey] || {};\n metadata[metadataKey][toolCallId] = {\n toolCallId,\n toolName,\n args,\n type: opts.type,\n runId,\n ...(opts.type === 'suspension' ? { suspendPayload: opts.suspendPayload } : {}),\n ...(opts.resumeSchema ? { resumeSchema: opts.resumeSchema } : {}),\n };\n };\n\n // Remove suspended-tool / pending-approval metadata from the last\n // assistant message when a tool is being resumed. This mirrors the\n // regular agent's `removeToolMetadata()`.\n const removeToolMetadata = async (type: 'suspension' | 'approval') => {\n if (!messageList) return;\n const metadataKey = type === 'suspension' ? 'suspendedTools' : 'pendingToolApprovals';\n const allMessages = messageList.get.all.db();\n const lastAssistantMessage = [...allMessages].reverse().find(msg => {\n const content = msg.content;\n if (!content) return false;\n const meta =\n typeof content.metadata === 'object' && content.metadata !== null\n ? (content.metadata as Record<string, any>)\n : undefined;\n return (\n !!meta?.[metadataKey]?.[toolCallId] ||\n Object.values(meta?.[metadataKey] ?? {}).some(\n (e: any) => e?.toolCallId === toolCallId || e?.toolName === toolName,\n )\n );\n });\n if (!lastAssistantMessage?.content) return;\n const meta =\n typeof lastAssistantMessage.content.metadata === 'object' && lastAssistantMessage.content.metadata !== null\n ? (lastAssistantMessage.content.metadata as Record<string, any>)\n : undefined;\n if (!meta?.[metadataKey]) return;\n // Resolve key: exact toolCallId, then by entry toolCallId, then by toolName\n const entries = meta[metadataKey] as Record<string, any>;\n const key = entries[toolCallId]\n ? toolCallId\n : (Object.keys(entries).find(k => entries[k]?.toolCallId === toolCallId) ??\n Object.keys(entries).find(k => entries[k]?.toolName === toolName) ??\n (entries[toolName] ? toolName : undefined));\n if (key) {\n delete entries[key];\n if (Object.keys(entries).length === 0) {\n delete meta[metadataKey];\n }\n }\n // Flush to persist the metadata removal\n await doFlush();\n };\n\n if (requiresApproval && !resumeData) {\n const resumeSchema = JSON.stringify({\n type: 'object',\n properties: {\n approved: { type: 'boolean' },\n },\n required: ['approved'],\n });\n\n // Persist active goal time before exposing the approval wait.\n await stopGoalActivity({ agentId: initData.agentId, runId });\n\n // Emit approval chunk via PubSub (mirrors base agent's controller.enqueue)\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-call-approval',\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, resumeSchema },\n });\n }\n\n // Emit suspended event for the stream adapter\n if (pubsub) {\n await emitSuspendedEvent(pubsub, runId, {\n toolCallId,\n toolName,\n args,\n type: 'approval',\n resumeSchema,\n });\n }\n\n // Add approval metadata to message before persisting\n addToolMetadata({ type: 'approval', resumeSchema });\n\n // Flush messages before suspension\n await doFlush();\n\n // End the trace's open spans as suspended before pausing.\n endSpansAsSuspended({ toolCallId, toolName, reason: 'approval' });\n\n // Suspend and wait for approval\n return suspend(\n {\n type: 'approval',\n toolCallId,\n toolName,\n args,\n },\n {\n resumeLabel: toolCallId,\n },\n );\n }\n\n // Check if resuming from approval — only when the tool actually requires\n // approval. Without the `requiresApproval` guard, generic resume data that\n // happens to contain an `approved` field (e.g. from context.agent.suspend())\n // would be misinterpreted as an approval response.\n if (\n requiresApproval &&\n resumeData &&\n typeof resumeData === 'object' &&\n resumeData !== null &&\n 'approved' in resumeData\n ) {\n // Remove approval metadata since we're resuming (either approved or declined)\n await removeToolMetadata('approval');\n\n if (!(resumeData as { approved: boolean }).approved) {\n // Return the approval decision (not a `result` string) so it persists as\n // `state: 'output-denied'` with `approval`. The denial reason carries the\n // existing string so downstream consumers/UI keep the same message.\n return {\n ...typedInput,\n approval: {\n id: toolCallId,\n approved: false,\n reason: 'Tool call was not approved by the user',\n },\n };\n }\n }\n\n // When an approval-gated tool is approved on resume, tag the resolved output with the\n // approval decision so it round-trips through persistence as `approval: { approved: true }`.\n const approvalGrant =\n requiresApproval &&\n resumeData &&\n typeof resumeData === 'object' &&\n resumeData !== null &&\n (resumeData as { approved?: boolean }).approved === true\n ? ({ approval: { id: toolCallId, approved: true as const } } as const)\n : undefined;\n\n // Check if resuming from in-execution suspension\n // Pass resumeData through to the tool so it can continue from where it left off.\n // For approval-gated tools, the approval check above already handled the\n // `approved` field, so the tool executes fresh (not as a \"from-suspension\"\n // resume). For non-approval tools, ANY resume data is forwarded.\n const isResumingFromSuspension =\n resumeData &&\n typeof resumeData === 'object' &&\n resumeData !== null &&\n (requiresApproval ? !('approved' in resumeData) : true);\n\n // Remove suspension metadata when resuming from an in-execution (non-approval-decision) suspension.\n // `isResumingFromSuspension` already excludes the approval-decision case above.\n if (isResumingFromSuspension) {\n await removeToolMetadata('suspension');\n }\n\n // 3. Check for background task execution\n const bgManager = registryEntry?.backgroundTaskManager;\n const bgConfig = registryEntry?.backgroundTasksConfig;\n const toolBgConfig = (tool as any).backgroundConfig as ToolBackgroundConfig | undefined;\n const llmBgOverrides =\n typeof args === 'object' && args !== null && '_background' in args ? (args as any)._background : undefined;\n\n // Strip _background from args before execution (same as non-durable path)\n const cleanedArgs = { ...args };\n if ('_background' in cleanedArgs) {\n delete (cleanedArgs as any)._background;\n }\n\n // Fire onInputAvailable lifecycle hook before execution (matches non-durable path).\n if (tool && 'onInputAvailable' in tool && typeof (tool as any).onInputAvailable === 'function') {\n try {\n await (tool as any).onInputAvailable({\n toolCallId,\n input: cleanedArgs,\n messages: messageList ? messageList.get.input.aiV5.model() : [],\n });\n } catch (hookError) {\n logger?.error?.('Error calling onInputAvailable', hookError);\n }\n }\n\n // Execute the tool\n if (!tool.execute) {\n return {\n ...typedInput,\n result: undefined,\n ...(approvalGrant ?? {}),\n };\n }\n\n // Rebuild the forwarded model_step span and pass it as the tool's tracing context so\n // the TOOL_CALL span nests under the LLM call (matches the non-durable path).\n const observability = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({ requestContext });\n const stepSpan =\n typedInput.stepSpanData && observability\n ? observability.rebuildSpan(typedInput.stepSpanData as ExportedSpan<SpanType.MODEL_STEP>)\n : undefined;\n const toolTracingContext = stepSpan ? { currentSpan: stepSpan } : undefined;\n\n // Track whether the tool's suspend callback was invoked so we can skip\n // emitting a spurious tool-result after tool.execute() returns (the\n // workflow engine's suspend() sets an internal flag but does not throw,\n // so execution continues past the suspend call).\n let wasSuspended = false;\n\n // Forward abort signal from the run registry so tools can observe\n // cancellation (mirrors the non-durable tool-call-step).\n const toolAbortSignal = registryEntry?.abortSignal;\n\n const toolOptions = {\n toolCallId,\n messages: [],\n workspace,\n requestContext,\n tracingContext: toolTracingContext,\n // Use the actor supplied for this workflow segment. A resumed segment\n // must never recover the initial actor from serialized agent options.\n actor,\n resumeData: isResumingFromSuspension ? resumeData : undefined,\n ...(toolAbortSignal ? { abortSignal: toolAbortSignal } : {}),\n // Provide outputWriter so context.writer.write() / context.writer.custom()\n // emit chunks through pubsub (matching the regular agent's tool streaming).\n outputWriter: pubsub\n ? async (chunk: any) => {\n await emitChunkEvent(pubsub, runId, chunk as ChunkType);\n }\n : undefined,\n\n // In-execution suspend callback — allows tools to suspend mid-execution\n suspend: async (suspendPayload: any, suspendOptions?: SuspendOptions) => {\n wasSuspended = true;\n if (suspendOptions?.requireToolApproval) {\n // Tool is requesting approval during execution\n const approvalResumeSchema = JSON.stringify({\n type: 'object',\n properties: {\n approved: { type: 'boolean' },\n },\n required: ['approved'],\n });\n\n await stopGoalActivity({ agentId: initData.agentId, runId });\n\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-call-approval',\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, resumeSchema: approvalResumeSchema },\n });\n }\n\n if (pubsub) {\n await emitSuspendedEvent(pubsub, runId, {\n toolCallId,\n toolName,\n args,\n type: 'approval',\n resumeSchema: approvalResumeSchema,\n });\n }\n\n // Add approval metadata to message before persisting\n addToolMetadata({ type: 'approval', resumeSchema: approvalResumeSchema });\n\n await doFlush();\n\n endSpansAsSuspended({ toolCallId, toolName, reason: 'approval' });\n\n return suspend(\n {\n type: 'approval',\n requireToolApproval: { toolCallId, toolName, args },\n },\n { resumeLabel: toolCallId },\n );\n } else {\n // General tool suspension (e.g., tool calls context.agent.suspend())\n const suspendedEventData: AgentSuspendedEventData = {\n toolCallId,\n toolName,\n args,\n suspendPayload,\n type: 'suspension',\n resumeSchema: suspendOptions?.resumeSchema,\n };\n\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-call-suspended',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId,\n toolName,\n suspendPayload,\n args,\n resumeSchema: suspendOptions?.resumeSchema,\n },\n });\n\n await emitSuspendedEvent(pubsub, runId, suspendedEventData);\n }\n\n // Add suspension metadata to message before persisting\n addToolMetadata({\n type: 'suspension',\n suspendPayload,\n resumeSchema: suspendOptions?.resumeSchema,\n });\n\n await doFlush();\n\n endSpansAsSuspended({ toolCallId, toolName, reason: 'suspension' });\n\n return suspend(\n {\n type: 'suspension',\n toolCallSuspended: suspendPayload,\n toolCallId,\n toolName,\n resumeLabel: suspendOptions?.resumeLabel,\n },\n { resumeLabel: toolCallId },\n );\n }\n },\n };\n\n // Resolve whether to run in background using the shared config resolver\n if (bgManager && !bgConfig?.disabled && typeof cleanedArgs === 'object' && cleanedArgs !== null) {\n const bgResolved = resolveBackgroundConfig({\n llmBgOverrides,\n toolName,\n toolConfig: toolBgConfig,\n agentConfig: bgConfig,\n managerConfig: bgManager.config,\n });\n\n if (bgResolved.runInBackground) {\n try {\n const bgTask = createBackgroundTask(bgManager, {\n toolName,\n toolCallId,\n args: cleanedArgs,\n agentId: initData.agentId,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n runId,\n timeoutMs: bgResolved.timeoutMs,\n maxRetries: bgResolved.maxRetries,\n context: {\n executor: {\n execute: async (taskArgs: any, taskContext: any) => {\n return tool.execute!(taskArgs, {\n ...toolOptions,\n ...(taskContext?.resumeData !== undefined ? { resumeData: taskContext.resumeData } : {}),\n suspend: async (data?: unknown, options?: SuspendOptions) => {\n await toolOptions.suspend?.(data, options);\n return taskContext?.suspend?.(data, options);\n },\n outputWriter: async (chunk: any) => {\n await taskContext?.onProgress?.(chunk);\n return toolOptions.outputWriter?.(chunk);\n },\n });\n },\n },\n onChunk: (chunk: any) => {\n if (!pubsub) return;\n try {\n const bgRunId = chunk.payload.runId;\n // Emit tool-call chunk so UIs can render the invocation inline\n if (bgRunId !== runId || (bgRunId === runId && resumeData)) {\n void emitChunkEvent(pubsub, bgRunId, {\n type: 'tool-call',\n runId: bgRunId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: chunk.payload.toolCallId,\n toolName: chunk.payload.toolName,\n args: cleanedArgs,\n },\n });\n }\n\n if (chunk.type === 'background-task-completed') {\n void emitChunkEvent(pubsub, bgRunId, {\n type: 'tool-result',\n runId: bgRunId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: chunk.payload.toolCallId,\n toolName: chunk.payload.toolName,\n args: cleanedArgs,\n result: chunk.payload.result,\n },\n });\n } else if (chunk.type === 'background-task-failed') {\n void emitChunkEvent(pubsub, bgRunId, {\n type: 'tool-error',\n runId: bgRunId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: chunk.payload.toolCallId,\n toolName: chunk.payload.toolName,\n error: chunk.payload.error,\n args: cleanedArgs,\n },\n });\n }\n } catch {\n // PubSub may be closed — ignore\n }\n },\n\n onResult: async (params: any) => {\n if (!messageList) return;\n\n const result =\n params.status === 'failed'\n ? `Background task failed: ${params.error?.message ?? 'Unknown error'}`\n : params.result;\n\n const updated = messageList.updateToolInvocation(\n {\n type: 'tool-invocation',\n toolInvocation: {\n state: 'result',\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n args: cleanedArgs,\n result,\n // Preserve the approval decision for an approved approval-gated tool that\n // ran in the background so it round-trips on recall, matching the sync path.\n ...(approvalGrant ?? {}),\n },\n },\n {\n mode: 'stream',\n backgroundTasks: {\n [params.toolCallId]: {\n startedAt: params.startedAt,\n completedAt: params.completedAt,\n taskId: params.taskId,\n },\n },\n },\n );\n\n if (!updated) {\n if (params.runId !== runId || (params.runId === runId && resumeData)) {\n messageList.add(\n [\n {\n role: 'tool' as const,\n type: 'tool-call',\n id: crypto.randomUUID(),\n createdAt: new Date(),\n content: [\n {\n type: 'tool-call' as const,\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n args: cleanedArgs,\n },\n ],\n },\n ],\n 'response',\n );\n }\n messageList.add(\n [\n {\n role: 'tool' as const,\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n result,\n isError: params.status === 'failed',\n },\n ],\n },\n ],\n 'response',\n );\n }\n\n if (saveQueueManager && state?.threadId) {\n await saveQueueManager.flushMessages(messageList, state.threadId, state.memoryConfig);\n }\n },\n\n onExecution: async (params: any) => {\n if (!messageList) return;\n\n messageList.updateMessageMetadataByToolCallId(params.toolCallId, {\n mode: 'stream',\n backgroundTasks: {\n [params.toolCallId]: {\n startedAt: params.startedAt,\n suspendedAt: params.suspendedAt,\n taskId: params.taskId,\n },\n },\n });\n\n // Flush to storage so the metadata update (especially suspendedAt)\n // is persisted. Unlike the regular agent which has a single long-lived\n // messageList, the durable agent's workflow state is serialized before\n // this async callback fires, so we must flush directly.\n if (saveQueueManager && state?.threadId) {\n await saveQueueManager.flushMessages(messageList, state.threadId, state.memoryConfig);\n }\n },\n\n onComplete: toolBgConfig?.onComplete ?? bgConfig?.onTaskComplete,\n onFailed: toolBgConfig?.onFailed ?? bgConfig?.onTaskFailed,\n },\n });\n\n // If the agent is resuming this tool call and a previously-suspended\n // bg task exists for this toolCallId+runId, resume the bg task with\n // the agent-resume payload instead of dispatching a fresh one.\n const isSuspendedBgResume =\n isResumingFromSuspension && resumeData && typeof resumeData === 'object' && resumeData !== null;\n if (isSuspendedBgResume) {\n const isSuspended = await bgTask.checkIfSuspended({\n toolCallId,\n runId,\n agentId: initData.agentId,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n toolName,\n });\n if (isSuspended) {\n const task = await bgTask.resume(resumeData);\n return {\n ...typedInput,\n args: cleanedArgs,\n result: `Background task resumed. Task ID: ${task.id}. The tool \"${toolName}\" is running in the background. You will be notified when it completes.`,\n };\n }\n }\n\n const isPreviouslyRunning = await bgTask.checkIfRunning({\n toolCallId,\n runId,\n agentId: initData.agentId,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n toolName,\n });\n\n if (isPreviouslyRunning) {\n const task = await bgTask.restart();\n return {\n ...typedInput,\n args: cleanedArgs,\n result: `Background task restarted. Task ID: ${task.id}. The tool \"${toolName}\" is running in the background. You will be notified when it completes.`,\n };\n }\n\n const { task, fallbackToSync } = await bgTask.dispatch();\n\n if (!fallbackToSync) {\n // Emit background-task-started chunk via PubSub\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'background-task-started' as any,\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n taskId: task.id,\n toolName,\n toolCallId,\n },\n });\n }\n\n // Return placeholder result so the LLM can continue\n return {\n ...typedInput,\n args: cleanedArgs,\n result: `Background task started. Task ID: ${task.id}. The tool \"${toolName}\" is running in the background. You will be notified when it completes.`,\n ...(approvalGrant ?? {}),\n };\n }\n // fallbackToSync: concurrency limit hit, fall through to synchronous execution\n } catch (bgError) {\n logger?.debug?.(\n `[DurableAgent] Background task dispatch failed for ${toolName}, falling back to sync: ${bgError}`,\n );\n }\n }\n }\n\n try {\n const result = await tool.execute(cleanedArgs, toolOptions);\n\n // Fire onOutput lifecycle hook after successful execution (matches non-durable path).\n if (tool && 'onOutput' in tool && typeof (tool as any).onOutput === 'function') {\n try {\n await (tool as any).onOutput({\n toolCallId,\n toolName,\n output: result,\n });\n } catch (hookError) {\n logger?.error?.('Error calling onOutput', hookError);\n }\n }\n\n // Emit tool-result chunk (non-fatal — result is returned regardless).\n // Skip emission when the tool called suspend() — the workflow engine's\n // suspend() sets a flag but does NOT throw, so execution continues past\n // the suspend call and tool.execute() returns undefined. Emitting a\n // tool-result with undefined would produce a spurious entry that\n // confuses downstream consumers (e.g. MastraModelOutput.toolResults).\n if (pubsub && !wasSuspended) {\n try {\n const resultChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-result' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, result },\n },\n {\n policy: registryEntry?.toolPayloadTransform,\n tools: registryEntry?.tools,\n logger: logger as any,\n },\n );\n // Run through output processors (tripwire/blocking/redaction)\n const processed = await processChunkThroughOutputProcessors(\n resultChunk,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n );\n if (processed) {\n await emitChunkEvent(pubsub, runId, processed);\n }\n } catch (emitError) {\n logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);\n }\n }\n\n return {\n ...typedInput,\n result,\n ...(approvalGrant ?? {}),\n };\n } catch (error) {\n // Re-throw FGA authorization errors instead of swallowing them —\n // an authorization denial must fail the run, not be serialized as a\n // recoverable tool error for the LLM to retry (mirrors the\n // non-durable tool-call step).\n if (error instanceof Error && error.name === 'FGADeniedError') {\n throw error;\n }\n const toolError = serializeError(error);\n\n // Emit tool-error chunk (non-fatal — error result is returned regardless)\n if (pubsub && !wasSuspended) {\n try {\n const errorChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-error' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, error: toolError },\n },\n {\n policy: registryEntry?.toolPayloadTransform,\n tools: registryEntry?.tools,\n logger: logger as any,\n },\n );\n // Run through output processors (tripwire/blocking/redaction)\n const processed = await processChunkThroughOutputProcessors(\n errorChunk,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n );\n if (processed) {\n await emitChunkEvent(pubsub, runId, processed);\n }\n } catch (emitError) {\n logger?.warn?.(`[DurableAgent] Failed to emit tool-error chunk for ${toolName}: ${emitError}`);\n }\n }\n\n return {\n ...typedInput,\n error: toolError,\n ...(approvalGrant ?? {}),\n };\n }\n },\n });\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { Mastra } from '../../../../mastra';\nimport { EntityType, SpanType } from '../../../../observability';\nimport type { ExportedSpan } from '../../../../observability';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\nimport type {\n DurableLLMStepOutput,\n DurableToolCallOutput,\n DurableAgenticExecutionOutput,\n SerializableDurableState,\n} from '../../types';\n\n/**\n * Input schema for the durable LLM mapping step.\n * This combines the LLM execution output with tool call results.\n */\nconst durableLLMMappingInputSchema = z.object({\n llmOutput: z.any(), // DurableLLMStepOutput\n toolResults: z.array(z.any()), // DurableToolCallOutput[]\n runId: z.string(),\n agentId: z.string(),\n messageId: z.string(),\n state: z.any(), // SerializableDurableState\n});\n\n/**\n * Output schema for the durable LLM mapping step\n */\nconst durableLLMMappingOutputSchema = z.object({\n messageListState: z.any(),\n messageId: z.string(),\n stepResult: z.any(),\n toolResults: z.array(z.any()),\n output: z.object({\n text: z.string().optional(),\n toolCalls: z.array(z.any()).optional(),\n usage: z.any(),\n steps: z.array(z.any()),\n }),\n state: z.any(),\n delegationBailed: z.boolean().optional(),\n processorRetryCount: z.number().optional(),\n processorRetryFeedback: z.string().optional(),\n});\n\n/**\n * Normalize modelOutput from toModelOutput() into the AI SDK's\n * LanguageModelV2ToolResultOutput shape.\n *\n * The AI SDK's content array only accepts type 'text' or 'media'.\n * Mastra's createTool docs show type 'image-url' as a convenience shorthand,\n * so we normalize that here into type 'media' with the correct structure.\n *\n * Mirrors the normalizeModelOutput in llm-mapping-step.ts (regular agent).\n */\nfunction normalizeModelOutput(output: unknown): unknown {\n if (output == null || typeof output !== 'object') return output;\n\n const obj = output as Record<string, unknown>;\n if (obj.type !== 'content' || !Array.isArray(obj.value)) return output;\n\n return {\n ...obj,\n value: (obj.value as unknown[]).map(item => {\n if (item == null || typeof item !== 'object') return item;\n const part = item as Record<string, unknown>;\n if (part.type === 'image-url' && typeof part.url === 'string') {\n const mediaType =\n typeof part.mediaType === 'string' && part.mediaType\n ? part.mediaType\n : part.url.startsWith('data:')\n ? part.url.slice(5, part.url.indexOf(';')) || 'image/jpeg'\n : 'image/jpeg';\n return { type: 'media', data: part.url, mediaType };\n }\n if (part.type === 'image-data' && typeof part.data === 'string') {\n return { type: 'media', data: part.data, mediaType: part.mediaType ?? 'image/jpeg' };\n }\n if (part.type === 'file-data' && typeof part.data === 'string') {\n return { type: 'media', data: part.data, mediaType: part.mediaType ?? 'application/octet-stream' };\n }\n return part;\n }),\n };\n}\n\n/**\n * Create a durable LLM mapping step.\n *\n * This step:\n * 1. Takes the LLM execution output and tool call results\n * 2. Updates the message list with tool results\n * 3. Combines everything into the final iteration output\n *\n * This is the \"merge\" step that combines parallel tool call results\n * back into a single coherent state.\n */\nexport function createDurableLLMMappingStep() {\n return createStep({\n id: DurableStepIds.LLM_MAPPING,\n inputSchema: durableLLMMappingInputSchema,\n outputSchema: durableLLMMappingOutputSchema,\n execute: async params => {\n const { inputData, mastra, requestContext } = params;\n const {\n llmOutput,\n toolResults,\n runId: _runId,\n agentId: _agentId,\n messageId,\n state,\n } = inputData as {\n llmOutput: DurableLLMStepOutput;\n toolResults: DurableToolCallOutput[];\n runId: string;\n agentId: string;\n messageId: string;\n state: SerializableDurableState;\n };\n\n // 1. Deserialize message list\n const messageList = new MessageList({\n threadId: state.threadId,\n resourceId: state.resourceId,\n });\n messageList.deserialize(llmOutput.messageListState);\n\n // A declined approval has no `result` but is fully resolved: persist it as `output-denied`\n // with the approval decision (rather than as a successful `result`) so it round-trips on\n // recall. Mirrors the non-durable llm-mapping-step.\n const isDeniedApproval = (toolResult: { approval?: { approved?: boolean } }) =>\n toolResult?.approval?.approved === false;\n\n // 2. Add tool results to message list\n // Look up tools from the in-process registry for toModelOutput support\n const registryEntry = globalRunRegistry.get(_runId);\n const registryTools = registryEntry?.tools;\n\n // Rebuild the MODEL_STEP span early so MAPPING child spans can nest under it\n let stepSpan:\n | ReturnType<\n NonNullable<\n ReturnType<NonNullable<NonNullable<Mastra['observability']>['getSelectedInstance']>>\n >['rebuildSpan']\n >\n | undefined;\n if (llmOutput.stepSpanData) {\n try {\n const observability = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({ requestContext });\n stepSpan = observability?.rebuildSpan(llmOutput.stepSpanData as ExportedSpan<SpanType.MODEL_STEP>);\n } catch {\n // Span bookkeeping must never break the merge step.\n }\n }\n\n if (toolResults.length > 0) {\n for (const toolResult of toolResults) {\n if (isDeniedApproval(toolResult)) {\n messageList.updateToolInvocation({\n type: 'tool-invocation' as const,\n toolInvocation: {\n state: 'output-denied' as const,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n args: toolResult.args,\n approval: {\n id: toolResult.approval!.id,\n approved: false,\n reason: toolResult.approval!.reason,\n },\n },\n });\n continue;\n }\n\n const result = toolResult.error ? toolResult.error.message : toolResult.result;\n\n // Compute toModelOutput for successful tool results (Bug 9 parity).\n // Start from the existing providerMetadata so it's preserved even when\n // toModelOutput is absent or fails — otherwise provider-executed tools\n // or tools without a mapper lose their metadata.\n let providerMetadata: Record<string, unknown> | undefined = toolResult.providerMetadata as\n | Record<string, unknown>\n | undefined;\n if (!toolResult.error && toolResult.result != null && !toolResult.providerExecuted) {\n const tool = registryTools?.[toolResult.toolName] as\n | { toModelOutput?: (output: unknown) => unknown }\n | undefined;\n\n if (tool?.toModelOutput) {\n const mappingSpan = stepSpan?.createChildSpan({\n type: SpanType.MAPPING,\n name: `tool output mapping: '${toolResult.toolName}'`,\n entityType: EntityType.TOOL,\n entityId: toolResult.toolName,\n entityName: toolResult.toolName,\n input: toolResult.result,\n attributes: {\n mappingType: 'toModelOutput',\n toolCallId: toolResult.toolCallId,\n },\n });\n try {\n let modelOutput = await tool.toModelOutput(toolResult.result);\n modelOutput = normalizeModelOutput(modelOutput);\n mappingSpan?.end({ output: modelOutput });\n\n const existingMastra = (toolResult.providerMetadata as any)?.mastra;\n providerMetadata = {\n ...toolResult.providerMetadata,\n mastra: { ...existingMastra, modelOutput },\n };\n } catch (err) {\n mappingSpan?.error({ error: err as Error, endSpan: true });\n // toModelOutput errors are non-fatal — the tool result is still usable\n (mastra as Mastra | undefined)\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] toModelOutput failed for tool \"${toolResult.toolName}\": ${err}`);\n }\n }\n }\n\n const updated = messageList.updateToolInvocation({\n type: 'tool-invocation' as const,\n toolInvocation: {\n state: 'result' as const,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n args: toolResult.args,\n result,\n // Preserve the approval decision for an approved approval-gated tool so it\n // round-trips on recall as `approval: { approved: true }`.\n ...(toolResult.approval ? { approval: toolResult.approval } : {}),\n },\n ...(providerMetadata ? { providerMetadata: providerMetadata as any } : {}),\n });\n\n if (!updated) {\n messageList.add(\n [\n {\n role: 'tool' as const,\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n result,\n isError: toolResult.error !== undefined,\n },\n ],\n },\n ],\n 'response',\n );\n }\n }\n }\n\n // 2b. Sync the updated messageList back to the in-process registry.\n // The durable workflow deserializes a fresh MessageList on every step,\n // so updates (output-denied, tool results) are invisible to other\n // steps that read from the registry — in particular tool-call.ts's\n // doFlush() which persists messages before suspension. Without this\n // sync, a declined tool's output-denied state would never reach memory\n // if the workflow re-suspends on a subsequent iteration.\n if (registryEntry) {\n registryEntry.messageList = messageList;\n }\n\n // 3. Determine if we should continue\n // When tool errors occur, always continue the agentic loop so the model\n // can see the error messages (already added to messageList above) and\n // self-correct. This matches the regular agent's behaviour where both\n // ToolNotFoundError and generic tool execution errors are recoverable.\n const hasToolErrors = toolResults.some(r => r.error !== undefined);\n const isContinued = hasToolErrors ? true : llmOutput.stepResult.isContinued;\n\n // Check if any delegation hook called ctx.bail(). The bail flag is\n // communicated via requestContext because Zod output validation strips\n // unknown fields from the tool result. We read it here and propagate\n // it on the serializable output so the dowhile predicate can stop.\n let delegationBailed = false;\n if (requestContext?.get('__mastra_delegationBailed')) {\n delegationBailed = true;\n requestContext.set('__mastra_delegationBailed', false);\n }\n\n // 4. Build the output\n const output: DurableAgenticExecutionOutput = {\n messageListState: messageList.serialize(),\n messageId,\n stepResult: {\n ...llmOutput.stepResult,\n isContinued,\n },\n toolResults,\n output: {\n text: llmOutput.text,\n toolCalls: llmOutput.toolCalls,\n usage: llmOutput.stepResult.totalUsage ?? {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n },\n steps: [], // Steps are accumulated at the loop level\n },\n state: {\n ...state,\n threadExists: state.threadExists,\n },\n processorRetryCount: llmOutput.processorRetryCount,\n processorRetryFeedback: llmOutput.processorRetryFeedback,\n delegationBailed,\n };\n\n // Close the MODEL_STEP span for tool-calling iterations: the LLM step defers it so\n // tool calls can nest under it, and the tools have now run. No-ops without tool calls.\n // The span was already rebuilt earlier so MAPPING child spans could nest under it.\n if (stepSpan) {\n try {\n const pendingPayload = llmOutput.stepFinishPayload as any;\n stepSpan.end({\n output: {\n text: llmOutput.text,\n toolCalls: llmOutput.toolCalls,\n },\n attributes: {\n usage: pendingPayload?.output?.usage,\n finishReason: pendingPayload?.stepResult?.reason,\n isContinued: pendingPayload?.stepResult?.isContinued,\n },\n });\n } catch (error) {\n // Span bookkeeping must never break the merge step.\n (mastra as Mastra | undefined)\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] Failed to close model_step span: ${error}`);\n }\n }\n\n // Emit the deferred step-finish chunk for intermediate steps.\n // llm-execution defers step-finish emission for tool-calling steps so that\n // it arrives AFTER tool-result chunks (emitted by tool-call.ts). This\n // matches the regular agent's chunk ordering which MastraModelOutput\n // relies on for correct step content reconstruction in onStepFinish.\n const deferredChunk = llmOutput.deferredStepFinishChunk as any;\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n if (deferredChunk && pubsub) {\n try {\n // Build step content directly from this iteration's data.\n // We cannot rely on messageList.get.response.aiV5.modelContent(-1)\n // because each durable step deserializes a fresh MessageList, so\n // the MastraModelOutput's reference is stale. Instead, construct\n // the content array from the LLM output (text + tool calls) and\n // the tool results collected in this step.\n const stepContent: unknown[] = [];\n if (llmOutput.text) {\n stepContent.push({ type: 'text', text: llmOutput.text });\n }\n for (const tc of llmOutput.toolCalls ?? []) {\n stepContent.push({\n type: 'tool-call',\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n args: tc.args,\n });\n }\n for (const tr of toolResults ?? []) {\n stepContent.push({\n type: 'tool-result',\n toolCallId: tr.toolCallId,\n toolName: tr.toolName,\n result: tr.error ? tr.error.message : tr.result,\n ...(tr.error ? { isError: true } : {}),\n });\n }\n\n const enrichedChunk = {\n ...deferredChunk,\n payload: {\n ...deferredChunk.payload,\n _durableStepContent: stepContent,\n },\n };\n await emitChunkEvent(pubsub, _runId, enrichedChunk);\n } catch (error) {\n (mastra as Mastra | undefined)\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] Failed to emit deferred step-finish: ${error}`);\n }\n }\n\n return output;\n },\n });\n}\n","import { z } from 'zod';\nimport type { IsTaskCompleteRunResult, MastraDBMessage } from '../../../../agent';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { StreamCompletionContext } from '../../../../loop/network/validation';\nimport { formatStreamCompletionFeedback, runStreamCompletionScorers } from '../../../../loop/network/validation';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableAgentDefaults, DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\n/**\n * Create the durable isTaskComplete step.\n *\n * Mirrors the non-durable `createIsTaskCompleteStep` contract:\n * - Runs after each agentic iteration has settled its tool calls.\n * - Only scores iterations where the LLM has signaled it is done\n * (`lastStepResult.isContinued === false`) so we don't interrupt mid-loop\n * tool execution.\n * - Skips working-memory-only iterations (same heuristic as the non-durable\n * step) — those are bookkeeping, not user-visible task progress.\n * - Pulls the scorer instances + `onComplete` closure from the in-process run\n * registry. They can't survive the wire, so cross-process engines (Inngest\n * after a worker restart) simply skip this step and fall back to\n * `maxSteps` + `stopWhen`.\n * - On a verdict it flips `state.lastStepResult.isContinued` so the outer\n * `dowhile` predicate either stops the loop (passed) or runs one more LLM\n * iteration (not passed). Feedback (when not suppressed) is appended as an\n * assistant message so the next LLM call can see it.\n * - Emits an `is-task-complete` chunk via pubsub so external observers see\n * the verdict and payload exactly like the non-durable path.\n */\nexport function createDurableIsTaskCompleteStep(defaultMaxSteps: number = DurableAgentDefaults.MAX_STEPS) {\n // The step is a pass-through over the IterationState — we mutate\n // `lastStepResult.isContinued` and `messageListState` in place when a\n // verdict requires it. We use `z.any()` instead of the iteration schema to\n // avoid coupling this step to whichever extended schema each workflow uses\n // (core's IterationState extends the base shape with `modelList`).\n return createStep({\n id: DurableStepIds.IS_TASK_COMPLETE,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async params => {\n const { inputData, mastra, getInitData } = params;\n const state = inputData as {\n runId: string;\n iterationCount: number;\n messageListState: any;\n accumulatedSteps: Array<{\n text?: string;\n toolCalls?: Array<{ toolName?: string; args?: unknown }>;\n toolResults?: Array<{ toolName?: string; result?: unknown }>;\n }>;\n lastStepResult?: { isContinued?: boolean };\n options?: { maxSteps?: number };\n backgroundTaskPending?: boolean;\n };\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const initData = getInitData() as {\n agentId?: string;\n agentName?: string;\n state?: { threadId?: string; resourceId?: string };\n requestContextEntries?: Record<string, unknown>;\n };\n\n const registryEntry = globalRunRegistry.get(state.runId);\n const isTaskComplete = registryEntry?.isTaskComplete;\n const hasScorers = !!isTaskComplete?.scorers && isTaskComplete.scorers.length > 0;\n\n // Fast path — nothing to do without a registered policy.\n if (!hasScorers || !isTaskComplete) {\n return state;\n }\n\n // Don't interrupt mid-tool loops. The non-durable step has the same\n // guard via `inputData.stepResult?.isContinued`.\n const llmSignaledDone = state.lastStepResult?.isContinued === false;\n if (!llmSignaledDone) {\n return state;\n }\n\n // The background-task-check step may set backgroundTaskPending=true to\n // force one more LLM iteration after a task settles. Skip scoring in\n // that case so we don't double-score the same outcome.\n if (state.backgroundTaskPending) {\n return state;\n }\n\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n const iterationToolCalls = (lastStep?.toolCalls ?? []) as Array<{\n toolName?: string;\n args?: unknown;\n }>;\n const isWorkingMemoryToolName = (name?: string) =>\n name === 'updateWorkingMemory' || name === 'setWorkingMemory' || name === 'update-working-memory';\n const allWorkingMemory =\n iterationToolCalls.length > 0 && iterationToolCalls.every(tc => isWorkingMemoryToolName(tc.toolName));\n if (allWorkingMemory) {\n return state;\n }\n\n const runMaxSteps = state.options?.maxSteps ?? defaultMaxSteps;\n\n // Rehydrate the message list once so we can read the original task and\n // append feedback after scoring.\n const messageList = new MessageList();\n messageList.deserialize(state.messageListState);\n const userMessages = messageList.get.input.db();\n const firstUserMessage = userMessages[0];\n let originalTask = 'Unknown task';\n if (firstUserMessage) {\n if (typeof firstUserMessage.content === 'string') {\n originalTask = firstUserMessage.content;\n } else if ((firstUserMessage.content as any)?.parts?.[0]?.type === 'text') {\n originalTask = ((firstUserMessage.content as any).parts[0] as { text: string }).text;\n }\n }\n\n const toolResultsForCtx = (lastStep?.toolResults ?? []) as Array<{\n toolName?: string;\n result?: unknown;\n }>;\n\n const ctx: StreamCompletionContext = {\n iteration: state.iterationCount,\n maxIterations: runMaxSteps,\n originalTask,\n currentText: lastStep?.text || '',\n toolCalls: iterationToolCalls.map(tc => ({\n name: tc.toolName || '',\n args: (tc.args as Record<string, unknown>) ?? {},\n })),\n messages: messageList.get.all.db(),\n toolResults: toolResultsForCtx.map(tr => ({\n name: tr.toolName || '',\n result: (tr.result as Record<string, unknown>) ?? {},\n })),\n agentId: initData.agentId || '',\n agentName: initData.agentName || '',\n runId: state.runId,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n customContext: initData.requestContextEntries,\n };\n\n let result: IsTaskCompleteRunResult | undefined;\n try {\n result = await runStreamCompletionScorers(isTaskComplete.scorers!, ctx, {\n strategy: isTaskComplete.strategy,\n parallel: isTaskComplete.parallel,\n timeout: isTaskComplete.timeout,\n });\n } catch (err) {\n mastra?.getLogger?.()?.warn?.(`[DurableAgent] isTaskComplete scoring failed: ${err}`);\n return state;\n }\n\n if (!result) {\n return state;\n }\n\n if (isTaskComplete.onComplete) {\n try {\n await isTaskComplete.onComplete(result);\n } catch (err) {\n mastra?.getLogger?.()?.warn?.(`[DurableAgent] isTaskComplete onComplete callback failed: ${err}`);\n }\n }\n\n const maxIterationReached = runMaxSteps ? state.iterationCount >= runMaxSteps : false;\n\n // Flip isContinued based on the verdict so the outer dowhile predicate\n // continues (not complete) or stops (complete). This is the contract\n // the non-durable createIsTaskCompleteStep uses.\n const nextState: typeof state = { ...state };\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: !result.complete,\n };\n }\n\n // Append the feedback as an assistant message so the next LLM iteration\n // can course-correct. Skipped when the check passes, mirroring the\n // non-durable createIsTaskCompleteStep.\n if (!result.complete) {\n const feedback = formatStreamCompletionFeedback(result, maxIterationReached);\n messageList.add(\n {\n id: mastra?.generateId?.(),\n createdAt: new Date(),\n type: 'text',\n role: 'assistant',\n content: {\n parts: [{ type: 'text', text: feedback }],\n metadata: {\n mode: 'stream',\n completionResult: {\n passed: result.complete,\n suppressFeedback: !!isTaskComplete.suppressFeedback,\n },\n },\n format: 2,\n },\n } as MastraDBMessage,\n 'response',\n );\n }\n nextState.messageListState = messageList.serialize();\n\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'is-task-complete',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n iteration: state.iterationCount,\n passed: result.complete,\n results: result.scorers,\n duration: result.totalDuration,\n timedOut: result.timedOut,\n reason: result.completionReason,\n maxIterationReached,\n suppressFeedback: !!isTaskComplete.suppressFeedback,\n },\n } as any);\n } catch {\n // PubSub may be closed — fall through.\n }\n }\n\n return nextState;\n },\n });\n}\n","import { z } from 'zod';\nimport type { MastraScorer } from '../../../../evals';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { resolveModelConfig } from '../../../../llm';\nimport type { MastraLanguageModel } from '../../../../llm/model/shared.types';\nimport { runStreamCompletionScorers } from '../../../../loop/network/validation';\nimport type { StreamCompletionContext } from '../../../../loop/network/validation';\nimport { createProcessorSendSignal } from '../../../../processors/send-signal';\nimport { RequestContext } from '../../../../request-context';\nimport type { GoalObjectiveRecord } from '../../../../storage/domains/thread-state/base';\nimport type { ChunkType, GoalEvaluationActivity } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport type { ResolvedGoalStore } from '../../../goal';\nimport {\n createGoalScorer,\n GOAL_SCORE_WAITING,\n GOAL_SCORER_ID,\n readObjective,\n resolveEffectiveGoalSettings,\n resolveGoalStore,\n writeObjective,\n} from '../../../goal';\nimport { MessageList } from '../../../message-list';\nimport type { ToolsInput } from '../../../types';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\nfunction isWorkingMemoryTool(name: string): boolean {\n return name === 'updateWorkingMemory' || name === 'setWorkingMemory' || name === 'update-working-memory';\n}\n\nfunction formatJudgeActivityName(name: string | undefined): string | undefined {\n if (!name) return undefined;\n if (name === 'view') return 'read';\n if (name === 'search_content') return 'search';\n if (name === 'find_files') return 'find files';\n if (name === 'file_stat') return 'stat';\n if (name === 'lsp_inspect') return 'inspect';\n return name;\n}\n\nfunction getStringArg(args: unknown, key: string): string | undefined {\n if (!args || typeof args !== 'object' || Array.isArray(args)) return undefined;\n const value = (args as Record<string, unknown>)[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction truncateActivityDetail(value: string): string {\n return value.length > 80 ? `${value.slice(0, 77)}...` : value;\n}\n\nfunction extractPartialReasonFromStructuredText(text: string): string | undefined {\n const match = text.match(/\"reason\"\\s*:\\s*\"((?:\\\\.|[^\"\\\\])*)/);\n const partialReason = match?.[1];\n if (!partialReason) return undefined;\n return partialReason.replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, '\\\\').trim();\n}\n\nfunction formatJudgeActivityMessage(name: string | undefined, args: unknown): string | undefined {\n const label = formatJudgeActivityName(name);\n if (!label) return undefined;\n\n if (name === 'view' || name === 'file_stat') {\n const path = getStringArg(args, 'path');\n return path ? `${label} ${truncateActivityDetail(path)}` : label;\n }\n\n if (name === 'search_content') {\n const pattern = getStringArg(args, 'pattern');\n const path = getStringArg(args, 'path');\n const detail = [pattern, path].filter(Boolean).join(' in ');\n return detail ? `${label} ${truncateActivityDetail(detail)}` : label;\n }\n\n if (name === 'find_files') {\n const path = getStringArg(args, 'path');\n const pattern = getStringArg(args, 'pattern');\n const detail = [path, pattern].filter(Boolean).join(' ');\n return detail ? `${label} ${truncateActivityDetail(detail)}` : label;\n }\n\n if (name === 'lsp_inspect') {\n const path = getStringArg(args, 'path');\n const line =\n !args || typeof args !== 'object' || Array.isArray(args) ? undefined : (args as Record<string, unknown>).line;\n const detail = path ? `${path}${typeof line === 'number' ? `:${line}` : ''}` : undefined;\n return detail ? `${label} ${truncateActivityDetail(detail)}` : label;\n }\n\n return label;\n}\n\n/**\n * Create the durable goal step.\n *\n * Mirrors the non-durable `createGoalStep` contract:\n * - Runs after `isTaskCompleteStep` in the `singleIterationWorkflow`.\n * - Only evaluates iterations where the LLM has signaled it is done\n * (`lastStepResult.isContinued === false`) so we don't interrupt mid-loop\n * tool execution.\n * - Skips background-pending, working-memory-only iterations (same\n * heuristic as the non-durable step).\n * - Pulls the `goal` config from the in-process run registry (closures\n * like `judge`, `scorer`, `tools` can't survive the wire). Cross-process\n * engines without this slot skip goal evaluation.\n * - Reads/writes the `GoalObjectiveRecord` from/to thread state storage.\n * - Emits `goal` chunks via pubsub so external observers see the verdict.\n * - Injects system-reminder + goal feedback into `messageList` via\n * `createProcessorSendSignal` so the next LLM iteration can see it.\n */\nexport function createDurableGoalStep() {\n return createStep({\n id: 'durable-goal',\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async params => {\n const { inputData, mastra, getInitData } = params;\n const state = inputData as {\n runId: string;\n iterationCount: number;\n messageListState: any;\n messageId: string;\n accumulatedSteps: Array<{\n text?: string;\n toolCalls?: Array<{ toolName?: string; args?: unknown }>;\n toolResults?: Array<{ toolName?: string; result?: unknown }>;\n }>;\n lastStepResult?: { isContinued?: boolean; reason?: string };\n options?: { maxSteps?: number };\n backgroundTaskPending?: boolean;\n };\n if (state.lastStepResult?.reason === 'error') return state;\n\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const initData = getInitData() as {\n agentId?: string;\n agentName?: string;\n state?: { threadId?: string; resourceId?: string };\n requestContextEntries?: Record<string, unknown>;\n };\n\n const registryEntry = globalRunRegistry.get(state.runId);\n // This is shared agent configuration (judge, scorer, tools, defaults), not per-goal state.\n // The objective and its progress are isolated by thread and loaded from storage below.\n let goalConfig = registryEntry?.goal;\n if (!goalConfig && initData.agentId) {\n goalConfig = (mastra as any)?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();\n }\n\n // No goal mode configured → nothing to do.\n if (!goalConfig) return state;\n\n // Same gating as isTaskComplete: skip background results, mid-tool-loop\n // continuations, and working-memory-only iterations.\n if (state.backgroundTaskPending || state.lastStepResult?.isContinued) {\n return state;\n }\n\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n const iterationToolCalls = (lastStep?.toolCalls ?? []) as Array<{\n toolName?: string;\n args?: unknown;\n }>;\n if (iterationToolCalls.length > 0 && iterationToolCalls.every(tc => isWorkingMemoryTool(tc.toolName ?? ''))) {\n return state;\n }\n\n const threadId = initData.state?.threadId;\n\n // Reconstruct requestContext from serialized entries for resolvers.\n const requestContext = new RequestContext();\n if (initData.requestContextEntries) {\n for (const [key, value] of Object.entries(initData.requestContextEntries)) {\n requestContext.set(key, value);\n }\n }\n\n const store = (await resolveGoalStore(mastra as any)) as ResolvedGoalStore | undefined;\n const record = await readObjective(store, threadId);\n\n // No active objective → no gating, no chunk.\n if (!record || record.status !== 'active' || !store || !threadId) {\n return state;\n }\n\n const effective = resolveEffectiveGoalSettings(record, {\n judgeModelId: typeof goalConfig.judge === 'string' ? goalConfig.judge : undefined,\n maxRuns: goalConfig.maxRuns,\n prompt: goalConfig.prompt,\n maxSteps: goalConfig.maxSteps,\n });\n\n // Defensive budget guard.\n const nextState: typeof state = { ...state };\n if (record.runsUsed >= effective.maxRuns) {\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: false,\n };\n }\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n objective: record.objective,\n iteration: record.runsUsed,\n maxRuns: effective.maxRuns,\n passed: false,\n status: record.status,\n results: [],\n reason: undefined,\n duration: 0,\n timedOut: false,\n maxRunsReached: true,\n suppressFeedback: false,\n shouldContinue: false,\n },\n } as any);\n } catch {\n // PubSub may be closed — fall through.\n }\n }\n return nextState;\n }\n\n // Determine the judge model config. A non-string agent `goalConfig.judge` (a\n // resolved model or a model-resolver function) takes precedence.\n const nonStringAgentJudge =\n goalConfig.judge && typeof goalConfig.judge !== 'string' ? goalConfig.judge : undefined;\n\n let judgeModelConfig: unknown = nonStringAgentJudge ?? effective.judgeModelId;\n if (typeof judgeModelConfig === 'function') {\n judgeModelConfig = await (judgeModelConfig as (args: any) => unknown)({ requestContext, mastra });\n }\n if (!judgeModelConfig) {\n return state;\n }\n\n // Evaluate the goal. Catch any failure to prevent infinite loops.\n let result: Awaited<ReturnType<typeof runStreamCompletionScorers>>;\n try {\n const emitJudgeActivity = (activity: GoalEvaluationActivity, args?: unknown) => {\n const name =\n activity.type === 'reason' ? activity.name : formatJudgeActivityName(activity.name ?? activity.message);\n const message =\n activity.type === 'reason'\n ? activity.message\n : formatJudgeActivityMessage(activity.name ?? activity.message, args);\n if (!message || !pubsub) return;\n emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n objective: record.objective,\n iteration: record.runsUsed + 1,\n maxRuns: effective.maxRuns,\n passed: false,\n status: record.status,\n results: [],\n duration: 0,\n timedOut: false,\n maxRunsReached: false,\n suppressFeedback: true,\n pending: true,\n activity: [{ ...activity, name, message }],\n },\n } as any).catch(() => {});\n };\n\n const observeJudgeStream = (stream: { fullStream?: AsyncIterable<ChunkType> }) => {\n if (!stream.fullStream) return;\n void (async () => {\n try {\n let streamedText = '';\n let lastReason = '';\n for await (const chunk of stream.fullStream!) {\n if (chunk.type === 'text-delta') {\n streamedText += (chunk as any).payload?.text ?? '';\n const reason = extractPartialReasonFromStructuredText(streamedText);\n if (reason && reason !== lastReason) {\n lastReason = reason;\n emitJudgeActivity({ type: 'reason', message: reason });\n }\n } else if (chunk.type === 'tool-call') {\n emitJudgeActivity(\n {\n type: 'tool-call',\n name: (chunk as any).payload?.toolName,\n message: (chunk as any).payload?.toolName,\n },\n (chunk as any).payload?.args,\n );\n }\n }\n } catch {\n // The scorer owns structured-output fallback and error reporting.\n // Judge activity streaming is best-effort UI feedback and must not\n // turn a recoverable scorer stream failure into an unhandled rejection.\n }\n })();\n };\n\n // Resolve the scorer.\n let scorer: MastraScorer<any, any, any, any> | undefined;\n if (goalConfig.scorer) {\n scorer =\n typeof goalConfig.scorer === 'string'\n ? (mastra?.getScorer?.(goalConfig.scorer as any) as MastraScorer<any, any, any, any> | undefined)\n : goalConfig.scorer;\n }\n if (!scorer) {\n const judgeModel = (\n typeof judgeModelConfig === 'string'\n ? await resolveModelConfig(judgeModelConfig, requestContext, mastra)\n : judgeModelConfig\n ) as MastraLanguageModel;\n\n const goalTools: ToolsInput | undefined =\n typeof goalConfig.tools === 'function'\n ? ((await (goalConfig.tools as (args: any) => unknown)({ requestContext, mastra })) as\n | ToolsInput\n | undefined)\n : goalConfig.tools;\n\n scorer = createGoalScorer({\n mastra,\n judgeModel,\n prompt: effective.prompt,\n tools: goalTools,\n requestContext,\n onStream: observeJudgeStream,\n ...(effective.maxSteps ? { maxSteps: effective.maxSteps } : {}),\n });\n }\n\n // Build scorer context.\n const messageList = new MessageList();\n messageList.deserialize(state.messageListState);\n\n const toolCalls = (lastStep?.toolCalls ?? []) as Array<{ toolName?: string; args?: unknown }>;\n const toolResults = (lastStep?.toolResults ?? []) as Array<{ toolName?: string; result?: unknown }>;\n const goalContext: StreamCompletionContext = {\n iteration: record.runsUsed + 1,\n maxIterations: effective.maxRuns,\n originalTask: record.objective,\n currentText: lastStep?.text || '',\n toolCalls: toolCalls.map(tc => ({\n name: tc.toolName || '',\n args: (tc.args || {}) as Record<string, unknown>,\n })),\n messages: messageList.get.all.db(),\n toolResults: toolResults.map(tr => ({\n name: tr.toolName || '',\n result: (tr.result as Record<string, unknown>) ?? {},\n })),\n agentId: initData.agentId || '',\n agentName: initData.agentName || '',\n runId: state.runId,\n threadId,\n resourceId: initData.state?.resourceId,\n customContext: initData.requestContextEntries,\n };\n\n // Emit a pending chunk so consumers can show a loading indicator.\n if (pubsub) {\n emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: {\n objective: record.objective,\n iteration: record.runsUsed + 1,\n maxRuns: effective.maxRuns,\n passed: false,\n status: record.status,\n results: [],\n duration: 0,\n timedOut: false,\n maxRunsReached: false,\n suppressFeedback: true,\n pending: true,\n },\n } as any).catch(() => {});\n }\n\n result = await runStreamCompletionScorers([scorer], goalContext, { strategy: 'all' });\n } catch (error: any) {\n const reason = `Goal evaluation failed: ${error?.message ?? String(error)}`;\n result = {\n complete: false,\n completionReason: undefined,\n scorers: [\n {\n score: 0,\n passed: false,\n reason,\n scorerId: GOAL_SCORER_ID,\n scorerName: 'Goal (LLM)',\n duration: 0,\n errored: true,\n },\n ],\n totalDuration: 0,\n timedOut: false,\n };\n }\n\n // Tri-state decision: done / waiting / keep working / errored.\n const erroredScorer = result.scorers.find(s => s.errored);\n const judgeFailed = !!erroredScorer;\n const waiting =\n !judgeFailed &&\n !result.complete &&\n result.scorers.some(s => s.scorerId === GOAL_SCORER_ID && s.score === GOAL_SCORE_WAITING);\n\n // Increment runs and update status.\n const runsUsed = record.runsUsed + 1;\n const maxRunsReached = runsUsed >= effective.maxRuns;\n let status: GoalObjectiveRecord['status'] = record.status;\n let pausedReason: string | undefined;\n if (judgeFailed) {\n status = 'paused';\n pausedReason = erroredScorer?.reason ?? 'The goal judge failed to evaluate the objective.';\n } else if (result.complete) {\n status = 'done';\n } else if (maxRunsReached && !waiting) {\n status = 'paused';\n pausedReason = `Ran out of evaluation budget (${effective.maxRuns} runs) before reaching the goal — raise maxRuns to resume.`;\n }\n\n const updated: GoalObjectiveRecord = {\n ...record,\n runsUsed,\n status,\n pausedReason: status === 'paused' ? pausedReason : undefined,\n updatedAt: Date.now(),\n };\n await writeObjective(store, threadId, updated, requestContext);\n\n // Continuation decision.\n const shouldContinue = !result.complete && !waiting && !judgeFailed && !maxRunsReached;\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: shouldContinue,\n };\n }\n\n const suppressFeedback = false;\n const goalEvaluationPayload = {\n objective: record.objective,\n iteration: runsUsed,\n maxRuns: effective.maxRuns,\n passed: result.complete,\n status,\n pausedReason,\n judgeFailed,\n waitingForUser: waiting,\n results: result.scorers,\n reason: status === 'paused' ? pausedReason : result.completionReason,\n duration: result.totalDuration,\n timedOut: result.timedOut,\n maxRunsReached,\n suppressFeedback,\n shouldContinue,\n };\n\n // Inject feedback into messageList via signal so the next LLM call sees it.\n const messageList = new MessageList();\n messageList.deserialize(nextState.messageListState);\n\n let currentMessageId = nextState.messageId;\n const sendSignal = createProcessorSendSignal({\n messageList,\n writer: pubsub\n ? {\n custom: async (data, _options) => {\n await emitChunkEvent(pubsub, state.runId, data as ChunkType);\n },\n }\n : undefined,\n rotateResponseMessageId: () => {\n currentMessageId = mastra?.generateId?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n nextState.messageId = currentMessageId;\n return currentMessageId;\n },\n });\n\n const feedback = result.completionReason ?? 'The goal is not yet complete.';\n const continuation = shouldContinue\n ? `[Goal attempt ${runsUsed}/${effective.maxRuns}] The goal is not yet complete. Judge feedback: ${feedback}\\n\\nContinue working toward the goal: ${record.objective}`\n : `${status} (${runsUsed}/${effective.maxRuns})\\n${goalEvaluationPayload.reason ?? ''}`;\n await sendSignal({\n type: 'system-reminder',\n contents: continuation,\n attributes: { type: 'goal-judge' },\n metadata: { goalEvaluation: goalEvaluationPayload },\n });\n\n // Re-serialize messageList after signal injection.\n nextState.messageListState = messageList.serialize();\n\n // Emit the final goal chunk for external observers.\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'goal',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: goalEvaluationPayload,\n } as any);\n } catch {\n // PubSub may be closed — fall through.\n }\n }\n\n return nextState;\n },\n });\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport type { Mastra } from '../../../../mastra';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableStepIds } from '../../constants';\nimport { globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\n\nconst SIGNAL_DRAIN_STEP_ID = `${DurableStepIds.AGENTIC_EXECUTION}-signal-drain`;\n\n/**\n * Create a durable signal drain step.\n *\n * Mirrors the regular agent's `signalDrainStep` which sits between\n * backgroundTaskCheckStep and isTaskCompleteStep:\n * - Drains any signals queued while tool execution was running\n * - Adds drained signals to the messageList transcript\n * - Emits signal chunks via pubsub for the stream adapter\n * - Sets isContinued=true so the LLM processes the signals on the next turn\n * - Best-effort: swallows errors so signals remain queued on failure\n */\nexport function createDurableSignalDrainStep() {\n return createStep({\n id: SIGNAL_DRAIN_STEP_ID,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async params => {\n const { inputData, getInitData } = params;\n const execOutput = inputData as Record<string, any>;\n const initData = getInitData<{ runId: string }>();\n const runId = initData.runId;\n const registryEntry = globalRunRegistry.get(runId);\n const drainFn = registryEntry?.drainPendingSignals;\n\n if (!drainFn) return execOutput;\n\n try {\n const pendingSignals = drainFn('pending');\n if (pendingSignals.length === 0) return execOutput;\n\n const drainList = new MessageList();\n drainList.deserialize(execOutput.messageListState);\n drainList.markResponseMessageBoundary(execOutput.messageId);\n\n const nextMessageId =\n (params.mastra as Mastra | undefined)?.generateId?.() ??\n globalThis.crypto?.randomUUID?.() ??\n `msg_${Date.now()}`;\n\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n for (const pendingSignal of pendingSignals) {\n const signalForTranscript = drainList.addSignal(pendingSignal);\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, signalForTranscript.toDataPart() as any);\n }\n }\n\n return {\n ...execOutput,\n messageListState: drainList.serialize(),\n messageId: nextMessageId,\n stepResult: {\n ...execOutput.stepResult,\n messageId: nextMessageId,\n isContinued: true,\n },\n };\n } catch {\n // Signal drain is best-effort; drainPendingSignals() is inside\n // the try so signals remain queued if it throws.\n return execOutput;\n }\n },\n });\n}\n","import { z } from 'zod';\nimport type { MastraScorer, MastraScorerEntry } from '../../../evals/base';\nimport { runScorer } from '../../../evals/hooks';\nimport type { PubSub } from '../../../events/pubsub';\nimport { pruneAgentLoopSnapshot } from '../../../loop/workflows/prune-snapshot';\nimport type { Mastra } from '../../../mastra';\nimport { createObservabilityContext, InternalSpans } from '../../../observability';\nimport type { AIModelGenerationSpan, ExportedSpan, SpanType } from '../../../observability';\nimport { RequestContext } from '../../../request-context';\nimport { PUBSUB_SYMBOL } from '../../../workflows/constants';\nimport { createWorkflow } from '../../../workflows/create';\nimport { MessageList } from '../../message-list';\nimport { DurableStepIds, DurableAgentDefaults } from '../constants';\nimport { globalRunRegistry } from '../run-registry';\nimport { emitChunkEvent, emitFinishEvent, emitIterationCompleteEvent } from '../stream-adapter';\nimport type {\n DurableToolCallInput,\n DurableAgenticWorkflowInput,\n DurableAgenticExecutionOutput,\n DurableLLMStepOutput,\n DurableToolCallOutput,\n SerializableScorersConfig,\n} from '../types';\nimport {\n modelConfigSchema,\n modelListEntrySchema,\n durableAgenticOutputSchema,\n baseIterationStateSchema,\n createBaseIterationStateUpdate,\n resolveDurableToolCallConcurrency,\n} from './shared';\nimport {\n createDurableBackgroundTaskCheckStep,\n createDurableGoalStep,\n createDurableIsTaskCompleteStep,\n createDurableLLMExecutionStep,\n createDurableToolCallStep,\n createDurableLLMMappingStep,\n createDurableSignalDrainStep,\n} from './steps';\n\n/**\n * Options for creating a durable agentic workflow\n */\nexport interface DurableAgenticWorkflowOptions {\n /** Maximum number of agentic loop iterations */\n maxSteps?: number;\n}\n\n/**\n * Input schema for the durable agentic workflow.\n * Extends base schema with model list for fallback support.\n */\nconst durableAgenticInputSchema = z.object({\n __workflowKind: z.literal('durable-agent'),\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 // Model list for fallback support (when agent configured with array of models)\n modelList: z.array(modelListEntrySchema).optional(),\n options: z.any(),\n state: z.any(),\n messageId: z.string(),\n // Exported AGENT_RUN / MODEL_GENERATION span data, threaded so the run shares one trace\n agentSpanData: z.any().optional(),\n modelSpanData: z.any().optional(),\n // JSON-safe snapshot of requestContext.entries() so durable steps can read\n // it (e.g. is-task-complete scorers pass it as customContext).\n requestContextEntries: z.record(z.string(), z.any()).optional(),\n});\n\n// Re-export shared output schema (identical across implementations)\n// Note: durableAgenticOutputSchema is imported from shared\n\n/**\n * Schema for the iteration state that flows through the dowhile loop.\n * Extends base schema with model list for fallback support.\n */\nconst iterationStateSchema = baseIterationStateSchema.extend({\n // Model list for fallback support\n modelList: z.array(z.any()).optional(),\n});\n\ntype IterationState = z.infer<typeof iterationStateSchema>;\n\n/**\n * Create a durable agentic workflow.\n *\n * This workflow implements the agentic loop pattern in a durable way:\n *\n * 1. LLM Execution Step - Calls the LLM and gets response/tool calls\n * 2. Tool Call Steps (foreach) - Executes each tool call in parallel\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 */\nexport function createDurableAgenticWorkflow(options?: DurableAgenticWorkflowOptions) {\n const maxSteps = options?.maxSteps ?? DurableAgentDefaults.MAX_STEPS;\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\n const llmMappingStep = createDurableLLMMappingStep();\n\n // Create the background task check step\n const backgroundTaskCheckStep = createDurableBackgroundTaskCheckStep();\n\n // Create the signal drain step — mirrors the non-durable `signalDrainStep`\n // which drains signals queued during tool execution.\n const signalDrainStep = createDurableSignalDrainStep();\n\n // Create the isTaskComplete evaluation step (mirrors the non-durable\n // createIsTaskCompleteStep). Lives as a real step (not predicate logic)\n // so it shows up in workflow traces and produces a proper state transition.\n const isTaskCompleteStep = createDurableIsTaskCompleteStep(maxSteps);\n\n // Create the goal evaluation step — mirrors the non-durable\n // `createGoalStep`. Runs after isTaskComplete so the goal judge\n // sees whether isTaskComplete already stopped the loop.\n const goalStep = createDurableGoalStep();\n\n // Create the single iteration workflow (LLM -> Tool Calls -> Mapping)\n // Note: tool-call foreach concurrency is resolved per run at execution time\n // (see resolveDurableToolCallConcurrency) — approval/suspend flows force\n // sequential execution; otherwise the run's `toolCallConcurrency` applies.\n // The workflow is created once at startup and reused for all runs.\n const singleIterationWorkflow = createWorkflow({\n id: DurableStepIds.AGENTIC_EXECUTION,\n inputSchema: iterationStateSchema,\n outputSchema: iterationStateSchema,\n options: {\n shouldPersistSnapshot: params => {\n // We need a persisted snapshot record to support both:\n // - `resumeStream()` after a suspend (records with status\n // `pending` / `paused` / `suspended`)\n // - boot-time recovery of orphaned RUNNING runs after a process\n // restart, via `DurableAgent.recoverActiveRuns()` — this requires\n // the row to actually be stamped `running` while the loop is\n // in-flight (issue #19056).\n //\n // The engine's persist path guards against overwriting a `suspended`\n // / `paused` snapshot with a later `running` update from the same\n // run (see `persistStepUpdate` in workflows/handlers/entry.ts), so\n // it is safe to return true for `running` here.\n return (\n params.workflowStatus === 'pending' ||\n params.workflowStatus === 'paused' ||\n params.workflowStatus === 'suspended' ||\n params.workflowStatus === 'running'\n );\n },\n // Agent-loop snapshots are pure resume artifacts — strip everything a\n // resume never reads before persisting.\n pruneSnapshot: pruneAgentLoopSnapshot,\n validateInputs: false,\n sharePubsub: true,\n // Internal durable-agent execution plumbing — hide workflow spans;\n // the agent/tool/model spans within still surface for users.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\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 modelList: state.modelList,\n options: state.options,\n state: state.state,\n messageId: state.messageId,\n stepIndex: state.iterationCount,\n agentSpanData: state.agentSpanData,\n modelSpanData: state.modelSpanData,\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 (forward model_step span for nesting)\n .map(\n async ({ inputData }) => {\n const llmOutput = inputData as DurableLLMStepOutput;\n return (llmOutput.toolCalls ?? []).map(toolCall => ({\n ...toolCall,\n stepSpanData: llmOutput.stepSpanData,\n })) as DurableToolCallInput[];\n },\n { id: 'extract-tool-calls' },\n )\n // Step 3: Execute each tool call individually (with suspend support).\n // Concurrency is resolved per run from the serialized iteration state:\n // approval/suspend-capable tool sets run sequentially, everything else\n // honors the run's `toolCallConcurrency` (default 10). The workflow graph\n // is shared across runs, so this must be a resolver — never a mutated\n // shared options object.\n .foreach(toolCallStep, {\n concurrency: ({ inputData, getInitData }) => {\n const state = getInitData() as IterationState | undefined;\n return resolveDurableToolCallConcurrency({\n options: state?.options,\n toolsMetadata: state?.toolsMetadata,\n toolCalls: inputData as DurableToolCallInput[],\n });\n },\n })\n // Step 4: Collect tool results and bundle with LLM output for mapping step\n .map(\n async ({ inputData, getStepResult, getInitData }) => {\n const toolResults = inputData as DurableToolCallOutput[];\n const llmOutput = getStepResult(llmExecutionStep.id) as DurableLLMStepOutput;\n const initData = getInitData() as IterationState;\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 6.5: Drain signals that were queued while tool execution was running\n // within this iteration. Mirrors the non-durable `signalDrainStep` which\n // sits between backgroundTaskCheckStep and isTaskCompleteStep.\n .then(signalDrainStep)\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 core-specific fields\n const newIterationState: IterationState = {\n ...baseUpdate,\n modelList: initData.modelList,\n };\n\n return newIterationState;\n },\n { id: 'update-iteration-state' },\n )\n // Step 8: Evaluate user-supplied isTaskComplete scorers (if any). Runs as\n // a real step so it shows up in traces and may mutate lastStepResult /\n // messageListState before the dowhile predicate decides whether to loop\n // again. No-op when the run has no policy configured.\n .then(isTaskCompleteStep)\n // Step 9: Goal evaluation. Mirrors the non-durable createGoalStep — judges\n // whether the thread's active objective is satisfied or should continue.\n // No-op when no goal is configured or no active objective exists.\n .then(goalStep)\n .commit();\n\n // Create the main agentic loop workflow with dowhile\n return (\n createWorkflow({\n id: DurableStepIds.AGENTIC_LOOP,\n inputSchema: durableAgenticInputSchema,\n outputSchema: durableAgenticOutputSchema,\n options: {\n shouldPersistSnapshot: params => {\n // See the singleIterationWorkflow comment above — same policy for\n // the outer loop. The persist path guards against overwriting a\n // suspended snapshot with running.\n return (\n params.workflowStatus === 'pending' ||\n params.workflowStatus === 'paused' ||\n params.workflowStatus === 'suspended' ||\n params.workflowStatus === 'running'\n );\n },\n // Agent-loop snapshots are pure resume artifacts — strip everything a\n // resume never reads before persisting.\n pruneSnapshot: pruneAgentLoopSnapshot,\n validateInputs: false,\n // Internal durable-agent execution plumbing — see singleIterationWorkflow.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n // Initialize iteration state from input\n .map(\n async ({ inputData }) => {\n const input = inputData as DurableAgenticWorkflowInput;\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 };\n return iterationState;\n },\n { id: 'init-iteration-state' },\n )\n // Run the agentic loop with dowhile\n .dowhile(singleIterationWorkflow, async params => {\n const { inputData, mastra } = params;\n const state = inputData as IterationState;\n const initData = params.getInitData() as DurableAgenticWorkflowInput;\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const registryEntry = globalRunRegistry.get(state.runId);\n\n // ── Abort check ────────────────────────────────────────────────\n // If the abort signal has fired, stop the loop immediately.\n // The llm-execution step may have already emitted the ABORT event\n // and returned a clean output, but the signal may also have fired\n // between steps (e.g. inside a tool). Override the stepResult\n // reason so the FINISH event carries 'abort' and the client sees\n // the correct finishReason.\n if (registryEntry?.abortSignal?.aborted) {\n if (state.lastStepResult) {\n state.lastStepResult.reason = 'abort';\n state.lastStepResult.isContinued = false;\n }\n return false;\n }\n\n // Two-phase stop: if onIterationComplete returned { continue: false, feedback }\n // on the previous iteration, we allowed one more LLM turn with that feedback.\n // Now that the turn has completed, stop the loop unconditionally.\n let hasFinishedSteps = false;\n // Hard-stop tracks reasons that onIterationComplete must NOT override.\n // pendingFeedbackStop and delegationBailed are unconditional stops.\n let hardStop = false;\n if (state.pendingFeedbackStop) {\n hasFinishedSteps = true;\n hardStop = true;\n state.pendingFeedbackStop = false;\n }\n\n // Continuation check. isTaskComplete (when configured) runs as a\n // proper step inside singleIterationWorkflow and may have already\n // flipped lastStepResult.isContinued by the time we get here.\n // Declared as `let` because signal drain may force isContinued later.\n let shouldContinue = state.lastStepResult?.isContinued === true;\n const runMaxSteps = state.options?.maxSteps ?? maxSteps;\n const underMaxSteps = state.iterationCount < runMaxSteps;\n\n // Evaluate user-supplied stopWhen predicate(s) parked on the registry\n // up-front so we can include them in the finality decision emitted on\n // the iteration-complete event. The predicate is a closure and can't\n // survive the wire, so we read it from in-process state. Cross-process\n // engines (Inngest after worker restart) won't have the registry entry\n // and fall back to maxSteps only.\n let stopWhenMatched = false;\n if (shouldContinue && underMaxSteps && !hasFinishedSteps) {\n const stopWhen = registryEntry?.stopWhen;\n if (stopWhen && state.accumulatedSteps.length > 0) {\n const conditions = Array.isArray(stopWhen) ? stopWhen : [stopWhen];\n // Mirror agentic-loop: cast steps to any for v5/v6 StopCondition shape\n // compatibility — the StepRecord we accumulate is sufficient at runtime.\n const steps = state.accumulatedSteps as any;\n const results = await Promise.all(conditions.map(condition => condition({ steps })));\n stopWhenMatched = results.some(Boolean);\n }\n }\n\n if (stopWhenMatched) {\n hasFinishedSteps = true;\n }\n\n // Check if a delegation hook called ctx.bail() during this iteration.\n // The flag was set by the mapping step and propagated via iteration state.\n const delegationBailed = !!(state as any).delegationBailed;\n if (delegationBailed) {\n hasFinishedSteps = true;\n hardStop = true;\n // Reset the flag so it doesn't carry forward\n (state as any).delegationBailed = false;\n }\n\n // ── Inter-iteration signal drain ──────────────────────────────\n // Mirror the non-durable agentic-loop predicate: drain pending\n // signals that were queued while the previous iteration was\n // running. If signals are present, mark a response boundary,\n // rotate the messageId, add them to the transcript, emit them\n // to the stream, and force continuation so the LLM sees them.\n if (pubsub && registryEntry?.drainPendingSignals) {\n try {\n const pendingSignals = registryEntry.drainPendingSignals('pending');\n if (pendingSignals.length > 0) {\n const drainList = new MessageList();\n drainList.deserialize(state.messageListState);\n drainList.markResponseMessageBoundary();\n\n const nextMessageId =\n (mastra as Mastra | undefined)?.generateId?.() ??\n globalThis.crypto?.randomUUID?.() ??\n `msg_${Date.now()}`;\n state.messageId = nextMessageId;\n\n for (const pendingSignal of pendingSignals) {\n const signalForTranscript = drainList.addSignal(pendingSignal);\n await emitChunkEvent(pubsub, state.runId, signalForTranscript.toDataPart() as any);\n }\n\n state.messageListState = drainList.serialize();\n\n // Force continuation — the LLM must see the injected signals\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = true;\n }\n shouldContinue = true;\n }\n } catch {\n // Signal drain is best-effort; if deserialization fails\n // the next iteration still runs with the un-drained state.\n // drainPendingSignals() is inside the try so signals remain\n // queued if the drain function itself throws.\n }\n }\n\n let isFinal = !shouldContinue || !underMaxSteps || hasFinishedSteps;\n\n // Call onIterationComplete hook if provided (for every iteration, not\n // just continued ones). Mirrors the regular agentic-loop predicate:\n // the handler can return { continue: false } to stop, { continue: true }\n // to force-continue (if under maxSteps), and/or { feedback } to inject\n // a message before the next turn.\n const onIterationComplete = registryEntry?.onIterationComplete;\n if (onIterationComplete && !state.backgroundTaskPending) {\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n\n try {\n // Deserialize messageList for the callback's messages snapshot\n const callbackMessageList = new MessageList();\n try {\n callbackMessageList.deserialize(state.messageListState);\n } catch {\n // If deserialization fails, callback sees empty messages\n }\n\n const iterationContext = {\n iteration: state.accumulatedSteps.length,\n maxIterations: runMaxSteps,\n text: lastStep?.text ?? '',\n toolCalls: (lastStep?.toolCalls ?? []).map((tc: any) => ({\n id: tc.toolCallId || tc.id || '',\n name: tc.toolName || tc.name || '',\n args: (tc.args || {}) as Record<string, unknown>,\n })),\n toolResults: (lastStep?.toolResults ?? []).map((tr: any) => ({\n id: tr.toolCallId || tr.id || '',\n name: tr.toolName || tr.name || '',\n result: tr.result,\n error: tr.error,\n })),\n isFinal,\n finishReason: lastStep?.finishReason ?? 'unknown',\n runId: state.runId,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n agentId: state.agentId,\n agentName: state.agentName ?? state.agentId,\n messages: callbackMessageList.get.all.db(),\n };\n\n const iterationResult = await onIterationComplete(iterationContext);\n\n if (iterationResult) {\n // Determine whether we can run another turn. Hard stops\n // (pendingFeedbackStop, delegationBailed) are unconditional —\n // onIterationComplete cannot override them.\n const canRunAnotherTurn =\n !hardStop && underMaxSteps && (shouldContinue || iterationResult.continue === true);\n\n if (iterationResult.feedback && canRunAnotherTurn) {\n // Inject feedback as a synthetic assistant message so the LLM\n // sees it on the next turn. Mirror the regular agent: mark it\n // with completionResult.suppressFeedback so isTaskComplete\n // scorers skip it.\n const feedbackId =\n (mastra as Mastra | undefined)?.generateId?.() ??\n globalThis.crypto?.randomUUID?.() ??\n `msg_${Date.now()}`;\n callbackMessageList.add(\n {\n id: feedbackId,\n createdAt: new Date(),\n type: 'text',\n role: 'assistant',\n content: {\n parts: [{ type: 'text', text: iterationResult.feedback }],\n metadata: {\n mode: 'stream',\n completionResult: { suppressFeedback: true },\n },\n format: 2,\n },\n } as any,\n 'response',\n );\n // Re-serialize the updated messageList\n state.messageListState = callbackMessageList.serialize();\n\n if (iterationResult.continue === false) {\n // Two-phase stop: let one more LLM turn run with the feedback,\n // then stop on the next predicate evaluation.\n state.pendingFeedbackStop = true;\n isFinal = false;\n } else if (!hasFinishedSteps && underMaxSteps) {\n isFinal = false;\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = true;\n }\n }\n } else if (iterationResult.continue === false && !hasFinishedSteps) {\n hasFinishedSteps = true;\n isFinal = true;\n } else if (iterationResult.continue === true && !hardStop && (hasFinishedSteps || !shouldContinue)) {\n if (underMaxSteps || !runMaxSteps) {\n hasFinishedSteps = false;\n isFinal = false;\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = true;\n }\n }\n }\n }\n } catch (error) {\n // Log error but don't fail the iteration\n const logger = (mastra as Mastra | undefined)?.getLogger?.();\n logger?.error('Error in onIterationComplete hook:', error);\n }\n }\n\n // Rotate messageId for the next iteration. Each iteration's assistant\n // response is a distinct message, mirroring the non-durable agentic\n // loop which calls rotateResponseMessageId() between iterations. The\n // mutated state.messageId flows into the next singleIterationWorkflow\n // input via map-to-llm-input.\n //\n // We also mark the current MessageList's last assistant message as a\n // response boundary so MessageMerger won't collapse the next\n // iteration's assistant content into it. Without this, persisted\n // memory keeps a single assistant message and the rotated id is never\n // observable to consumers.\n if (!isFinal) {\n const nextMessageId =\n (mastra as Mastra | undefined)?.generateId?.() ?? globalThis.crypto?.randomUUID?.() ?? `msg_${Date.now()}`;\n state.messageId = nextMessageId;\n\n try {\n const boundaryList = new MessageList();\n boundaryList.deserialize(state.messageListState);\n boundaryList.markResponseMessageBoundary();\n state.messageListState = boundaryList.serialize();\n } catch {\n // Boundary marking is best-effort; if deserialization fails the\n // next iteration will still run with the un-marked state.\n }\n }\n\n // Emit an iteration-complete event for observability. This fires after\n // every iteration (including the last one) so client-side callbacks\n // (via stream-adapter) can track progress. The in-process callback\n // above has already been evaluated and its result applied to the\n // continuation decision.\n if (pubsub) {\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n await emitIterationCompleteEvent(pubsub, state.runId, {\n iteration: state.iterationCount,\n maxIterations: runMaxSteps,\n text: lastStep?.text,\n toolCalls: lastStep?.toolCalls,\n toolResults: lastStep?.toolResults,\n isFinal,\n finishReason: lastStep?.finishReason,\n runId: state.runId,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n agentId: initData.agentId,\n agentName: initData.agentName,\n });\n }\n\n return !isFinal;\n })\n // Map final state to output format, run output processors, persist memory, emit finish\n .map(\n async params => {\n const { inputData, mastra, requestContext, tracingContext } = params;\n const state = inputData as IterationState;\n const initData = params.getInitData() as DurableAgenticWorkflowInput;\n\n const pubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const logger = mastra?.getLogger?.();\n\n // Extract final text from last step\n const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];\n const finalText = lastStep?.text;\n\n // Run output processors (processOutputResult) if available\n const registryEntry = globalRunRegistry.get(state.runId);\n if (registryEntry?.outputProcessors?.length) {\n try {\n const { ProcessorRunner } = await import('../../../processors/runner');\n const runner = new ProcessorRunner({\n inputProcessors: registryEntry.inputProcessors ?? [],\n outputProcessors: registryEntry.outputProcessors,\n errorProcessors: registryEntry.errorProcessors ?? [],\n logger: logger as any,\n agentName: initData.agentName ?? initData.agentId,\n processorStates: registryEntry.processorStates,\n });\n const outputMessageList = new MessageList();\n outputMessageList.deserialize(state.messageListState);\n // Forward the step's tracingContext so processor_run spans parent\n // to the AGENT_RUN ancestor via ProcessorRunner's findParent walk.\n await runner.runOutputProcessors(\n outputMessageList,\n createObservabilityContext(tracingContext),\n requestContext ?? new RequestContext(),\n 0,\n );\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error running output processors: ${error}`);\n }\n }\n\n // Memory persistence (executeOnFinish equivalent)\n const durableState = initData.state;\n if (\n registryEntry?.saveQueueManager &&\n registryEntry.memory &&\n durableState?.threadId &&\n durableState?.resourceId &&\n !durableState.observationalMemory &&\n // Respect readOnly memory config (\"read memory but don't save new\n // messages\"). Mirrors the non-durable executeOnFinish `!readOnlyMemory`\n // guard and the MessageHistory output processor's readOnly check.\n !durableState.memoryConfig?.readOnly\n ) {\n try {\n const memoryMessageList = new MessageList();\n memoryMessageList.deserialize(state.messageListState);\n\n if (!durableState.threadExists) {\n await registryEntry.memory.createThread?.({\n threadId: durableState.threadId,\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n });\n }\n\n await registryEntry.saveQueueManager.flushMessages(\n memoryMessageList,\n durableState.threadId,\n durableState.memoryConfig,\n );\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error persisting messages: ${error}`);\n }\n }\n\n // Thread title generation (executeOnFinish equivalent).\n // The non-durable `#executeOnFinish` generates a thread title from the first user\n // message when `memory.options.generateTitle` is set. That branch was never ported\n // to the durable path, so `generateTitle` silently never fired for durable/evented\n // agents (and Inngest). The `generateThreadTitle` closure — parked on the registry\n // entry during preparation, where the agent instance is in scope — runs it here.\n //\n // Kept OUTSIDE the `!observationalMemory` guard above: OM handles its own message\n // persistence, but title generation is orthogonal and should still run when OM is on.\n // Non-serializable (a closure), so like the other registry closures it only fires for\n // in-process durable runs; cross-process engines (Inngest after a restart) skip it.\n if (\n registryEntry?.generateThreadTitle &&\n durableState?.threadId &&\n durableState?.resourceId &&\n !durableState.memoryConfig?.readOnly\n ) {\n try {\n await registryEntry.generateThreadTitle({\n threadId: durableState.threadId,\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n messageListState: state.messageListState,\n requestContext,\n tracingContext,\n });\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error generating thread title: ${error}`);\n }\n }\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 if (pubsub) {\n await emitFinishEvent(pubsub, state.runId, {\n output: finalOutput.output,\n stepResult: finalOutput.stepResult,\n });\n }\n\n // End MODEL_GENERATION then AGENT_RUN once at completion. After a resume the\n // originals were ended as `suspended`, so end the *resume* spans (registry override).\n try {\n const observability = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({\n requestContext,\n });\n const reg = globalRunRegistry.get(initData.runId);\n const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;\n const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;\n if (observability) {\n if (modelSpanData) {\n const modelSpan = observability.rebuildSpan(\n modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION>,\n ) as AIModelGenerationSpan | undefined;\n modelSpan?.createTracker()?.endGeneration({\n output: { text: finalText },\n attributes: { finishReason: finalOutput.stepResult?.reason },\n usage: state.accumulatedUsage,\n });\n }\n if (agentSpanData) {\n const agentSpan = observability.rebuildSpan(agentSpanData as ExportedSpan<SpanType.AGENT_RUN>);\n agentSpan?.end({ output: { text: finalText } });\n }\n }\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error ending observability spans: ${error}`);\n }\n\n return finalOutput;\n },\n { id: 'map-final-output' },\n )\n // Execute scorers (fire-and-forget, doesn't affect main result)\n .map(\n async params => {\n const { inputData, getInitData, mastra, requestContext, tracingContext } = params;\n const finalOutput = inputData;\n const initData = getInitData() as DurableAgenticWorkflowInput;\n\n // If no scorers configured, skip\n const scorers = initData.scorers as SerializableScorersConfig | undefined;\n if (!scorers || Object.keys(scorers).length === 0) {\n return finalOutput;\n }\n\n const logger = mastra?.getLogger?.();\n\n // Reconstruct input MessageList to extract scorer input\n const inputMessageList = new MessageList();\n inputMessageList.deserialize(initData.messageListState);\n\n // Build scorer input (messages before generation)\n const scorerInput = {\n inputMessages: inputMessageList.getPersisted.input.db(),\n rememberedMessages: inputMessageList.getPersisted.remembered.db(),\n systemMessages: inputMessageList.getSystemMessages(),\n taggedSystemMessages: inputMessageList.getPersisted.taggedSystemMessages,\n };\n\n // Reconstruct output MessageList to extract scorer output\n const outputMessageList = new MessageList();\n outputMessageList.deserialize(finalOutput.messageListState);\n const scorerOutput = outputMessageList.getPersisted.response.db();\n\n // Create request context for scorer resolution\n const resolveContext = requestContext ?? new RequestContext();\n\n // Execute each scorer (fire-and-forget)\n for (const [scorerKey, scorerEntry] of Object.entries(scorers)) {\n const { scorerName, sampling } = scorerEntry;\n\n try {\n // Resolve the scorer from Mastra. We serialize scorers by name,\n // and `getScorerById` searches by id-or-name without throwing\n // on the common path, so try it first. Fall back to the\n // registration-key-keyed `getScorer` for older configs.\n let scorer: MastraScorer | undefined;\n try {\n scorer = (mastra as Mastra)?.getScorerById?.(scorerName) as MastraScorer | undefined;\n } catch {\n scorer = undefined;\n }\n if (!scorer) {\n try {\n scorer = (mastra as Mastra)?.getScorer?.(scorerName) as MastraScorer | undefined;\n } catch {\n scorer = undefined;\n }\n }\n\n if (!scorer) {\n logger?.warn?.(`Scorer ${scorerName} not found in Mastra, skipping`, {\n runId: initData.runId,\n scorerKey,\n });\n continue;\n }\n\n // Create the scorer entry expected by runScorer\n const scorerObject: MastraScorerEntry = {\n scorer,\n sampling,\n };\n\n // Call runScorer (fire-and-forget via hooks)\n runScorer({\n runId: initData.runId,\n scorerId: scorerKey,\n scorerObject,\n input: scorerInput,\n output: scorerOutput,\n requestContext: resolveContext as any,\n entity: {\n id: initData.agentId,\n name: initData.agentName ?? initData.agentId,\n },\n structuredOutput: false,\n source: 'LIVE',\n entityType: 'AGENT',\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n ...createObservabilityContext(tracingContext),\n });\n } catch (error) {\n // Log but don't fail - scorer errors shouldn't affect main execution\n logger?.warn?.(`Error executing scorer ${scorerName}`, {\n error,\n runId: initData.runId,\n scorerKey,\n });\n }\n }\n\n return finalOutput;\n },\n { id: 'execute-scorers' },\n )\n .commit()\n );\n}\n","import type { MastraServerCache } from '../../cache/base';\nimport { InMemoryServerCache } from '../../cache/inmemory';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../../error';\nimport { CachingPubSub } from '../../events/caching-pubsub';\nimport { EventEmitterPubSub } from '../../events/event-emitter';\nimport type { PubSub } from '../../events/pubsub';\nimport type { Mastra } from '../../mastra';\nimport { createObservabilityContext, getOrCreateSpan, SpanType, EntityType } from '../../observability';\nimport { RequestContext } from '../../request-context';\nimport type { FullOutput, MastraModelOutput } from '../../stream/base/output';\nimport type { ChunkType, MastraOnFinishCallback, MastraStreamTransformOptions } from '../../stream/types';\nimport { ChunkFrom } from '../../stream/types';\nimport { deepMerge } from '../../utils';\nimport type { WorkflowRunState, WorkflowRunStatus } from '../../workflows/types';\nimport { Agent } from '../agent';\nimport type { AgentExecutionOptions } from '../agent.types';\nimport { beginGoalActivity, stopGoalActivity } from '../goal';\nimport { MessageList } from '../message-list';\nimport type { MessageListInput } from '../message-list';\nimport { SaveQueueManager } from '../save-queue';\nimport { agentThreadStreamRuntime } from '../thread-stream-runtime';\nimport type { ToolsInput } from '../types';\n\nimport { AGENT_STREAM_TOPIC, DurableStepIds } from './constants';\nimport { runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle } from './durable-stream-until-idle';\nimport { prepareForDurableExecution } from './preparation';\nimport { endRunSpansWithError, ExtendedRunRegistry, globalRunRegistry } from './run-registry';\nimport { createDurableAgentStream, emitChunkEvent, emitErrorEvent } from './stream-adapter';\nimport type { AgentStepFinishEventData, AgentSuspendedEventData, DurableAgenticWorkflowInput } from './types';\nimport { createDurableAgenticWorkflow } from './workflows';\n\n/**\n * Internal flag used by `generate()`/`resumeGenerate()` to tell the stream\n * adapter to close the underlying ReadableStream on SUSPENDED events so that\n * `getFullOutput()` resolves instead of hanging on a suspended run.\n * Not part of the public `DurableAgentStreamOptions` surface.\n */\nconst CLOSE_ON_SUSPEND = Symbol('mastra.durable.closeOnSuspend');\nconst RESOLVED_EXECUTION_OPTIONS = Symbol('mastra.durable.resolvedExecutionOptions');\n\n/**\n * Options for DurableAgent.stream()\n */\nexport interface DurableAgentStreamOptions<OUTPUT = undefined> {\n /** Custom instructions that override the agent's default instructions for this execution */\n instructions?: AgentExecutionOptions<OUTPUT>['instructions'];\n /** Additional context messages to provide to the agent */\n context?: AgentExecutionOptions<OUTPUT>['context'];\n /** Memory configuration for conversation persistence and retrieval */\n memory?: AgentExecutionOptions<OUTPUT>['memory'];\n /** Unique identifier for this execution run */\n runId?: string;\n /** Request Context containing dynamic configuration and state */\n requestContext?: AgentExecutionOptions<OUTPUT>['requestContext'];\n /** Maximum number of steps to run */\n maxSteps?: number;\n /**\n * Conditions for stopping execution (e.g., step count, token limit).\n *\n * The predicate is non-serializable, so it's parked on the in-process run\n * registry and evaluated by the durable loop on every iteration. Cross-process\n * durable engines (e.g. Inngest after a worker restart) cannot recover the\n * closure and degrade to `maxSteps` only.\n */\n stopWhen?: AgentExecutionOptions<OUTPUT>['stopWhen'];\n /** Additional tool sets that can be used for this execution */\n toolsets?: AgentExecutionOptions<OUTPUT>['toolsets'];\n /** Client-side tools available during execution */\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-specific settings like temperature */\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 number of tool calls to execute concurrently */\n toolCallConcurrency?: number;\n /** Whether to include raw chunks in the stream output */\n includeRawChunks?: boolean;\n /** Experimental transforms applied whenever `fullStream` is consumed. */\n experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;\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 /** 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 — receives rich step data (text, steps, toolResults) */\n onFinish?: MastraOnFinishCallback<OUTPUT>;\n /** Callback on error */\n onError?: ({ error }: { error: Error | string }) => void | Promise<void>;\n /** Callback when workflow suspends (e.g., for tool approval) */\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n /** Callback when execution is aborted via abortSignal */\n onAbort?: AgentExecutionOptions<OUTPUT>['onAbort'];\n /** Callback fired after each agentic-loop iteration */\n onIterationComplete?: AgentExecutionOptions<OUTPUT>['onIterationComplete'];\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 * Per-invocation tool payload transform policy. The closure rides on the\n * in-process run registry; only the JSON-safe `targets` shadow is serialized\n * for cross-process engines.\n */\n transform?: AgentExecutionOptions<OUTPUT>['transform'];\n /**\n * Per-step preparation hook. Closure-only: stored on the in-process run\n * registry and invoked as a `PrepareStepProcessor` at the start of every\n * iteration. Cross-process resumes lose the hook.\n */\n prepareStep?: AgentExecutionOptions<OUTPUT>['prepareStep'];\n /**\n * Per-call `isTaskComplete` policy. Scorer instances and `onComplete` are\n * closure-only and live on the in-process run registry; the JSON-safe\n * primitives (`strategy`, `timeout`, `parallel`, `suppressFeedback`,\n * `scorerNames`) are serialized for cross-process observability.\n */\n isTaskComplete?: AgentExecutionOptions<OUTPUT>['isTaskComplete'];\n /**\n * Sub-agent delegation hooks (`onDelegationStart`, `onDelegationComplete`,\n * `messageFilter`, etc.). The callbacks are forwarded into `convertTools`\n * at prepare time and burned into the sub-agent `CoreTool` wrappers on the\n * in-process run registry. Cross-process resumes lose the callbacks (only\n * `includeSubAgentToolResultsInModelContext` would be JSON-safe), so a\n * fresh worker degrades to default delegation behaviour.\n */\n delegation?: AgentExecutionOptions<OUTPUT>['delegation'];\n /**\n * When set, `stream()` delegates to the idle-loop wrapper that keeps the\n * outer stream open across background-task continuations — the same\n * behaviour as the now-deprecated `streamUntilIdle()`.\n *\n * Pass `true` for default idle timeout (5 min), or `{ maxIdleMs }` to\n * customise.\n *\n * @example\n * ```typescript\n * const { output, cleanup } = await durableAgent.stream('Research topic', {\n * untilIdle: true,\n * memory: { thread: 't1', resource: 'u1' },\n * });\n * ```\n */\n untilIdle?: boolean | { maxIdleMs?: number };\n /** When true, the in-loop background task check step skips waiting (streamUntilIdle sets this) */\n _skipBgTaskWait?: boolean;\n /**\n * External abort signal. The durable agent always installs its own internal\n * `AbortController` for the run; when this signal is provided, its `abort`\n * event is forwarded to the internal controller so either source can cancel\n * the run.\n *\n * Cross-process resumes (e.g. Inngest after a worker restart) cannot\n * recover the signal — call `resume(runId, ..., { abortSignal })` with a\n * fresh signal on each segment if you need abortability post-resume.\n */\n abortSignal?: AbortSignal;\n}\n\ntype DurableAgentResumeOptions<OUTPUT = undefined> = DurableAgentStreamOptions<OUTPUT> & {\n toolCallId?: string;\n};\n\n/**\n * Result from DurableAgent.stream()\n */\nexport interface DurableAgentStreamResult<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 for this execution */\n runId: string;\n /** Thread ID if using memory */\n threadId?: string;\n /** Resource ID if using memory */\n resourceId?: string;\n /** Cleanup function to call when done (unsubscribes from pubsub) */\n cleanup: () => void;\n /**\n * Abort the run. Flips the internal `AbortController` for this run, which\n * surfaces as an `AbortError` inside the durable LLM-execution step and\n * is bridged to the user's `onAbort` callback via the run's pubsub topic.\n *\n * Safe to call after the run has already finished — it's a no-op in that\n * case.\n */\n abort: (reason?: unknown) => void;\n}\n\n/**\n * Configuration for DurableAgent - wraps an existing Agent with durable execution\n */\nexport interface DurableAgentConfig<\n TAgentId extends string = string,\n TTools extends ToolsInput = ToolsInput,\n TOutput = undefined,\n> {\n /**\n * The Agent to wrap with durable execution capabilities.\n * All agent methods (getModel, listTools, etc.) delegate to this agent.\n */\n agent: Agent<TAgentId, TTools, TOutput>;\n\n /**\n * Optional ID override. Defaults to agent.id.\n */\n id?: TAgentId;\n\n /**\n * Optional name override. Defaults to agent.name.\n */\n name?: string;\n\n /**\n * PubSub instance for streaming events.\n * Optional - if not provided, defaults to EventEmitterPubSub.\n */\n pubsub?: PubSub;\n\n /**\n * Cache instance for storing stream events.\n * Enables resumable streams - clients can disconnect and reconnect\n * without missing events.\n *\n * - If not provided: Inherits from Mastra instance, or uses InMemoryServerCache\n * - If provided: Uses the provided cache backend (e.g., Redis)\n * - If set to `false`: Disables caching (streams are not resumable)\n */\n cache?: MastraServerCache | false;\n\n /**\n * Maximum steps for the agentic loop.\n * Defaults to the workflow default if not specified.\n */\n maxSteps?: number;\n\n /**\n * Timeout in milliseconds before automatic cleanup of registry entries\n * after a stream finishes or errors. This provides a grace period for\n * late observers to access the stream.\n *\n * Defaults to 30000 (30 seconds).\n * Set to 0 to disable auto-cleanup (manual cleanup() required).\n */\n cleanupTimeoutMs?: number;\n}\n\n/**\n * DurableAgent wraps an existing Agent with durable execution capabilities.\n *\n * Key features:\n * 1. Resumable streams - clients can disconnect and reconnect without missing events\n * 2. Serializable workflow inputs - works with durable execution engines\n * 3. PubSub-based streaming - events flow through pubsub for distribution\n *\n * DurableAgent extends Agent, delegating most methods to the wrapped agent.\n * It overrides stream() to use durable execution with the agentic workflow.\n *\n * Subclasses (EventedAgent, InngestAgent) override executeWorkflow() to\n * customize how the workflow is executed.\n *\n * @example\n * ```typescript\n * import { Agent } from '@mastra/core/agent';\n * import { DurableAgent } from '@mastra/core/agent/durable';\n *\n * const agent = new Agent({\n * id: 'my-agent',\n * instructions: 'You are a helpful assistant',\n * model: openai('gpt-4'),\n * });\n *\n * const durableAgent = new DurableAgent({ agent });\n *\n * const { output, runId, cleanup } = await durableAgent.stream('Hello!');\n * const text = await output.text;\n * cleanup();\n * ```\n */\n\n/**\n * Statuses of durable agent runs discoverable via {@link DurableAgent.listActiveRuns}.\n *\n * `running` is the status reported by the workflow engine while the durable\n * agent's agentic loop is actively executing (i.e. between suspend\n * boundaries). Persisted `running` snapshots are the recovery source for runs\n * orphaned by a process restart.\n */\nexport type DurableAgentActiveRunStatus = Extract<WorkflowRunStatus, 'running'>;\n\n/**\n * Filters for {@link DurableAgent.listActiveRuns}. Mirrors the\n * `listWorkflowRuns` filter contract, plus the agent-level `threadId` /\n * `resourceId` filters used by the base {@link Agent.listSuspendedRuns}.\n */\nexport interface DurableAgentListActiveRunsOptions {\n /** Only return runs that belong to this memory thread. */\n threadId?: string;\n /** Only return runs that belong to this memory resource. */\n resourceId?: string;\n /** Only return runs created at or after this date. */\n fromDate?: Date;\n /** Only return runs created at or before this date. */\n toDate?: Date;\n /**\n * Number of items per page. Pagination is applied when both `perPage` and\n * `page` are provided; otherwise all matching runs are returned.\n */\n perPage?: number;\n /** Zero-indexed page number. */\n page?: number;\n}\n\n/**\n * A durable agent run currently reported as `running` in workflow snapshot\n * storage. These are the runs that a boot-time or operator-initiated\n * recovery would re-drive after a process restart.\n */\nexport interface DurableAgentActiveRun {\n /** Run ID accepted by {@link DurableAgent.recoverActiveRuns} and workflow `restart`. */\n runId: string;\n status: DurableAgentActiveRunStatus;\n threadId?: string;\n resourceId?: string;\n /** When the run's snapshot was last persisted while running. */\n updatedAt: Date;\n}\n\nexport interface DurableAgentListActiveRunsResult {\n runs: DurableAgentActiveRun[];\n /** Total number of matching runs, before pagination. */\n total: number;\n}\n\n/**\n * Outcome of a single run restart attempted by\n * {@link DurableAgent.recoverActiveRuns}. `success` means `run.restart()`\n * returned; `failed` means it threw and the error was captured so recovery\n * of remaining runs could proceed.\n */\nexport interface DurableAgentRecoveredRun {\n runId: string;\n status: 'success' | 'failed';\n /** Populated only when `status === 'failed'`. */\n error?: Error;\n}\n\n/**\n * Filters for {@link DurableAgent.recoverActiveRuns}. Reuses the\n * {@link DurableAgentListActiveRunsOptions} discovery filters and adds an\n * escape hatch for targeting a specific run ID.\n */\nexport interface DurableAgentRecoverActiveRunsOptions extends DurableAgentListActiveRunsOptions {\n /**\n * Recover a specific run by ID. When set, the discovery filters and\n * pagination fields are ignored. Useful when the caller already knows the\n * run ID from another source (e.g. their own bookkeeping).\n */\n runId?: string;\n}\n\nexport interface DurableAgentRecoverActiveRunsResult {\n recovered: DurableAgentRecoveredRun[];\n /** Number of runs that restarted successfully. */\n succeeded: number;\n /** Number of runs whose restart threw. */\n failed: number;\n}\n\n/**\n * Options for {@link DurableAgent.recover}, a single-run streamable recovery\n * counterpart to {@link DurableAgent.resume}.\n *\n * `recover()` rebuilds the run's non-serializable state from the persisted\n * workflow snapshot (message list, model, tools, memory, saveQueueManager,\n * request context, agent span) and returns a fresh {@link DurableAgentStreamResult}\n * whose `fullStream` observes the recovered run through pubsub. Callbacks\n * mirror `stream()` / `resume()`.\n */\nexport interface DurableAgentRecoverOptions<OUTPUT = undefined> {\n /** Callback when chunk is received */\n onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;\n /** Experimental transforms applied whenever `fullStream` is consumed. */\n experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;\n /** Callback when a step finishes */\n onStepFinish?: (result: AgentStepFinishEventData) => void | Promise<void>;\n /** Callback when the recovered run finishes */\n onFinish?: MastraOnFinishCallback<OUTPUT>;\n /** Callback when the recovered run errors */\n onError?: ({ error }: { error: Error | string }) => void | Promise<void>;\n /** Callback when the recovered run suspends again */\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n /**\n * Optional abort signal for the recovered segment. Forwarded onto a fresh\n * internal `AbortController` installed on the run's registry entry, so\n * `result.abort()` and the external signal can both cancel the recovered run.\n */\n abortSignal?: AbortSignal;\n}\n\nexport class DurableAgent<\n TAgentId extends string = string,\n TTools extends ToolsInput = ToolsInput,\n TOutput = undefined,\n> extends Agent<TAgentId, TTools, TOutput> {\n /** The wrapped agent */\n readonly #wrappedAgent: Agent<TAgentId, TTools, TOutput>;\n\n /** Registry for per-run non-serializable state */\n readonly #runRegistry: ExtendedRunRegistry;\n\n /** The durable workflow for agent execution */\n #workflow: ReturnType<typeof createDurableAgenticWorkflow> | null = null;\n\n /** Maximum steps for the agentic loop */\n readonly #maxSteps?: number;\n\n /** Inner pubsub (before CachingPubSub wrapper) */\n #innerPubsub: PubSub;\n\n /** Whether the user explicitly provided a pubsub (don't override with mastra.pubsub) */\n readonly #hasCustomPubsub: boolean;\n\n /** User-provided cache (undefined = inherit from mastra, false = disabled) */\n #cacheConfig: MastraServerCache | false | undefined;\n\n /** Resolved cache instance (lazily initialized) */\n #resolvedCache: MastraServerCache | null = null;\n\n /** CachingPubSub instance (lazily initialized) */\n #cachingPubsub: PubSub | null = null;\n\n /** Mastra instance (set via __setMastra when registered) */\n #mastra: Mastra | undefined;\n\n /** Active streamUntilIdle wrappers keyed by scope (threadId|resourceId) */\n #activeStreamUntilIdle = new Map<string, () => void>();\n\n /** Timeout for auto-cleanup after stream finishes (0 = disabled) */\n readonly #cleanupTimeoutMs: number;\n\n /**\n * Create a new DurableAgent that wraps an existing Agent\n */\n constructor(config: DurableAgentConfig<TAgentId, TTools, TOutput>) {\n const { agent, id: idOverride, name: nameOverride, pubsub, cache, maxSteps, cleanupTimeoutMs } = config;\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 ?? agent.id;\n\n // Call Agent constructor with minimal config - we delegate to the wrapped agent\n super({\n id: agentId as TAgentId,\n name: agentName,\n // Delegate to wrapped agent's instructions\n instructions: ({ requestContext }) => agent.getInstructions({ requestContext }),\n // We need to provide model to satisfy the base class, but we'll delegate to wrapped agent\n model: (agent as any).__model ?? agent.getModel(),\n });\n\n this.#wrappedAgent = agent;\n this.#runRegistry = new ExtendedRunRegistry();\n this.#maxSteps = maxSteps;\n this.#hasCustomPubsub = !!pubsub;\n this.#innerPubsub = pubsub ?? new EventEmitterPubSub();\n this.#cacheConfig = cache;\n this.#cleanupTimeoutMs = cleanupTimeoutMs ?? 30_000;\n }\n\n // ===========================================================================\n // Lazy PubSub/Cache initialization (allows inheriting cache from Mastra)\n // ===========================================================================\n\n /**\n * Get the resolved cache instance.\n * Lazily initialized to allow inheriting from Mastra.\n */\n get cache(): MastraServerCache | null {\n this.#ensurePubsubInitialized();\n return this.#resolvedCache;\n }\n\n /**\n * Get the PubSub instance.\n * Returns CachingPubSub if caching is enabled, otherwise the inner pubsub.\n */\n get pubsub(): PubSub {\n this.#ensurePubsubInitialized();\n return this.#cachingPubsub!;\n }\n\n /**\n * Ensure pubsub and cache are initialized.\n * Called lazily on first access to allow inheriting cache from Mastra.\n */\n #ensurePubsubInitialized(): void {\n if (this.#cachingPubsub) return;\n\n if (this.#cacheConfig === false) {\n // Caching explicitly disabled\n this.#cachingPubsub = this.#innerPubsub;\n this.#resolvedCache = null;\n } else if (this.#innerPubsub instanceof CachingPubSub) {\n // The inner pubsub already provides caching/replay. This happens when the\n // user passes a CachingPubSub to `new Mastra({ pubsub })`: on registration\n // the agent adopts mastra.pubsub as its inner transport. Wrapping it again\n // in a second CachingPubSub that shares the same cache would store every\n // event twice (once per layer, with consecutive indices), so observe()/\n // replay would deliver the buffered prefix doubled (issue #18148). Reuse\n // the existing instance instead of double-wrapping.\n this.#cachingPubsub = this.#innerPubsub;\n this.#resolvedCache = this.#cacheConfig ?? this.#mastra?.serverCache ?? null;\n } else {\n // Resolve cache: user-provided > mastra's cache > default InMemoryServerCache\n const resolvedCache = this.#cacheConfig ?? this.#mastra?.serverCache ?? new InMemoryServerCache();\n this.#resolvedCache = resolvedCache;\n this.#cachingPubsub = new CachingPubSub(this.#innerPubsub, resolvedCache);\n }\n }\n\n // ===========================================================================\n // Delegate to wrapped agent\n // ===========================================================================\n\n /**\n * Get the wrapped agent instance.\n */\n get agent(): Agent<TAgentId, TTools, TOutput> {\n return this.#wrappedAgent;\n }\n\n /**\n * Get the run registry (for testing and advanced usage)\n */\n get runRegistry(): ExtendedRunRegistry {\n return this.#runRegistry;\n }\n\n /**\n * Get the max steps configured for this agent\n */\n get maxSteps(): number | undefined {\n return this.#maxSteps;\n }\n\n /**\n * Get the cleanup timeout in milliseconds.\n * Returns 0 if auto-cleanup is disabled.\n */\n get cleanupTimeoutMs(): number {\n return this.#cleanupTimeoutMs;\n }\n\n // ===========================================================================\n // Delegate Agent methods to wrapped agent\n //\n // DurableAgent's super() only passes id, name, instructions, and model.\n // All other private fields (#tools, #memory, #workspace, #processors, etc.)\n // are empty on the DurableAgent instance. Every public/protected method that\n // reads those fields must be overridden to delegate to the wrapped agent.\n // ===========================================================================\n\n // --- Model & LLM ---\n override getModel(options?: any) {\n return this.#wrappedAgent.getModel(options);\n }\n\n override getLLM(options?: any) {\n return this.#wrappedAgent.getLLM(options);\n }\n\n override async getModelList(requestContext?: any) {\n return this.#wrappedAgent.getModelList(requestContext);\n }\n\n // --- Instructions, description, metadata ---\n override getInstructions(options?: any) {\n return this.#wrappedAgent.getInstructions(options);\n }\n\n override getDescription() {\n return this.#wrappedAgent.getDescription();\n }\n\n override getMetadata(options?: any) {\n return this.#wrappedAgent.getMetadata(options);\n }\n\n override getTracingPolicy() {\n return this.#wrappedAgent.getTracingPolicy();\n }\n\n // --- Tools ---\n override listTools(options?: any) {\n return this.#wrappedAgent.listTools(options);\n }\n\n override getConfiguredToolHooks() {\n return this.#wrappedAgent.getConfiguredToolHooks();\n }\n\n // --- Default options ---\n override getDefaultOptions(options?: any) {\n return this.#wrappedAgent.getDefaultOptions(options);\n }\n\n async #resolveExecutionOptions(\n options?: DurableAgentStreamOptions<TOutput>,\n ): Promise<DurableAgentStreamOptions<TOutput>> {\n if ((options as any)?.[RESOLVED_EXECUTION_OPTIONS]) {\n return options!;\n }\n\n const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });\n const resolvedOptions = deepMerge(\n (defaultOptions ?? {}) as Record<string, unknown>,\n (options ?? {}) as Record<string, unknown>,\n ) as DurableAgentStreamOptions<TOutput>;\n // Actor is a per-call trust signal, so an explicit value replaces the\n // default actor as a whole rather than inheriting any of its fields.\n if (options?.actor !== undefined) {\n resolvedOptions.actor = options.actor;\n }\n if ((options as any)?.[CLOSE_ON_SUSPEND] === true) {\n Object.defineProperty(resolvedOptions, CLOSE_ON_SUSPEND, { value: true, enumerable: true });\n }\n // Preserve the marker when the until-idle wrapper spreads these options.\n Object.defineProperty(resolvedOptions, RESOLVED_EXECUTION_OPTIONS, { value: true, enumerable: true });\n return resolvedOptions;\n }\n\n override getDefaultGenerateOptionsLegacy(options?: any) {\n return this.#wrappedAgent.getDefaultGenerateOptionsLegacy(options);\n }\n\n override getDefaultStreamOptionsLegacy(options?: any) {\n return this.#wrappedAgent.getDefaultStreamOptionsLegacy(options);\n }\n\n override getDefaultNetworkOptions(options?: any) {\n return this.#wrappedAgent.getDefaultNetworkOptions(options);\n }\n\n // --- Memory ---\n override getMemory(options?: any) {\n return this.#wrappedAgent.getMemory(options);\n }\n\n override hasOwnMemory(): boolean {\n return this.#wrappedAgent.hasOwnMemory();\n }\n\n // --- Workspace ---\n override getWorkspace(options?: any) {\n return this.#wrappedAgent.getWorkspace(options);\n }\n\n override hasOwnWorkspace(): boolean {\n return this.#wrappedAgent.hasOwnWorkspace?.() ?? false;\n }\n\n // --- Voice ---\n override getVoice(options?: any) {\n return this.#wrappedAgent.getVoice(options);\n }\n\n override get voice() {\n return this.#wrappedAgent.voice;\n }\n\n // --- Request context ---\n override get requestContextSchema() {\n return this.#wrappedAgent.requestContextSchema;\n }\n\n // --- Processors ---\n override async getConfiguredProcessorWorkflows() {\n return this.#wrappedAgent.getConfiguredProcessorWorkflows();\n }\n\n override async listInputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listInputProcessors(requestContext);\n }\n\n override async listOutputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listOutputProcessors(requestContext);\n }\n\n override async listErrorProcessors(requestContext?: any) {\n return this.#wrappedAgent.listErrorProcessors(requestContext);\n }\n\n override async resolveProcessorById<TId extends string = string>(processorId: TId, requestContext?: any) {\n return this.#wrappedAgent.resolveProcessorById(processorId, requestContext);\n }\n\n override async listConfiguredInputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listConfiguredInputProcessors(requestContext);\n }\n\n override async listConfiguredOutputProcessors(requestContext?: any) {\n return this.#wrappedAgent.listConfiguredOutputProcessors(requestContext);\n }\n\n override async getConfiguredProcessorIds(requestContext?: any) {\n return this.#wrappedAgent.getConfiguredProcessorIds(requestContext);\n }\n\n // --- Sub-agents ---\n override listAgents(options?: any) {\n return this.#wrappedAgent.listAgents(options);\n }\n\n override __getStaticAgents() {\n return this.#wrappedAgent.__getStaticAgents();\n }\n\n override __hasSubAgentsConfigured() {\n return this.#wrappedAgent.__hasSubAgentsConfigured();\n }\n\n // --- Workflows ---\n override async listWorkflows(options?: any) {\n return this.#wrappedAgent.listWorkflows(options);\n }\n\n // --- Skills ---\n override async getSkill(skillName: string, options?: any) {\n return this.#wrappedAgent.getSkill(skillName, options);\n }\n\n override async listSkills(options?: any) {\n return this.#wrappedAgent.listSkills(options);\n }\n\n // --- Scorers ---\n override async listScorers(options?: any) {\n return this.#wrappedAgent.listScorers(options);\n }\n\n // --- Background tasks ---\n override getBackgroundTasksConfig() {\n return this.#wrappedAgent.getBackgroundTasksConfig();\n }\n\n override disableBackgroundTasks() {\n this.#wrappedAgent.disableBackgroundTasks();\n }\n\n override enableBackgroundTasks() {\n this.#wrappedAgent.enableBackgroundTasks();\n }\n\n // --- Tool payload transform & goal ---\n override getToolPayloadTransform() {\n return this.#wrappedAgent.getToolPayloadTransform();\n }\n\n override __getGoalConfig() {\n return this.#wrappedAgent.__getGoalConfig();\n }\n\n // --- Browser ---\n override get browser() {\n return this.#wrappedAgent.browser;\n }\n\n override setBrowser(browser: any) {\n this.#wrappedAgent.setBrowser(browser);\n }\n\n override hasOwnBrowser() {\n return this.#wrappedAgent.hasOwnBrowser();\n }\n\n // --- Channels ---\n override getChannels() {\n return this.#wrappedAgent.getChannels();\n }\n\n override setChannels(agentChannels: any) {\n this.#wrappedAgent.setChannels(agentChannels);\n }\n\n // --- PubSub (base Agent fields — DurableAgent has its own pubsub) ---\n override hasOwnPubSub() {\n return this.#wrappedAgent.hasOwnPubSub();\n }\n\n // --- Setters called by AgentController — forward to BOTH wrapper and wrapped ---\n // We propagate to both so that:\n // - The wrapped agent sees the value for its own internal use.\n // - The DurableAgent's inherited getPubSub()/getMemory()/getWorkspace()\n // also work (they read #inheritedPubSub / #memory / #workspace set by super).\n override __setMemory(memory: any) {\n super.__setMemory(memory);\n this.#wrappedAgent.__setMemory(memory);\n }\n\n override __setPubSub(pubsub: any) {\n super.__setPubSub(pubsub);\n this.#wrappedAgent.__setPubSub(pubsub);\n }\n\n override __setWorkspace(workspace: any) {\n super.__setWorkspace(workspace);\n this.#wrappedAgent.__setWorkspace(workspace);\n }\n\n // ===========================================================================\n // Editor / fork delegation\n //\n // The base Agent serves tools/instructions/model from its own private fields,\n // but a DurableAgent serves all of them from the wrapped agent (see the\n // delegating getters above). The editor applies stored overrides per request\n // by calling `__fork()` and then mutating the fork via `__updateInstructions`\n // / `__updateModel` / `__setTools`, and inspecting it via `__getEditorConfig`\n // / `__getOverridableFields`. If those operated on the DurableAgent's own\n // (unused) base fields the served agent would silently lose its tools and\n // ignore overrides, so forward them to the wrapped agent — it stays the single\n // source of truth.\n // ===========================================================================\n\n override __getEditorConfig() {\n return this.#wrappedAgent.__getEditorConfig();\n }\n\n override __getOverridableFields() {\n return this.#wrappedAgent.__getOverridableFields();\n }\n\n override __updateInstructions(instructions: Parameters<Agent<TAgentId, TTools, TOutput>['__updateInstructions']>[0]) {\n this.#wrappedAgent.__updateInstructions(instructions);\n }\n\n override __updateModel(config: Parameters<Agent<TAgentId, TTools, TOutput>['__updateModel']>[0]) {\n this.#wrappedAgent.__updateModel(config);\n }\n\n override __setTools(tools: Parameters<Agent<TAgentId, TTools, TOutput>['__setTools']>[0]) {\n this.#wrappedAgent.__setTools(tools);\n }\n\n /**\n * Create a per-request clone for applying stored editor overrides.\n *\n * The base `Agent.__fork()` builds a bare `new Agent(...)`, which for a\n * DurableAgent would drop the wrapped agent and every delegating override\n * (tools, model, memory, voice, durable streaming) — the served fork ends up a\n * plain `Agent` with no tools. Instead, fork the wrapped agent (so overrides\n * applied to this fork don't mutate the singleton) and re-wrap it in the same\n * durable subclass, preserving pubsub/cache/run configuration.\n *\n * @internal\n */\n override __fork(): Agent<TAgentId, TTools, TOutput> {\n const innerFork = this.#wrappedAgent.__fork();\n\n const Ctor = this.constructor as new (\n config: DurableAgentConfig<TAgentId, TTools, TOutput>,\n ) => DurableAgent<TAgentId, TTools, TOutput>;\n\n const fork = new Ctor({\n agent: innerFork,\n id: this.id,\n name: this.name,\n pubsub: this.#hasCustomPubsub ? this.#innerPubsub : undefined,\n cache: this.#cacheConfig,\n maxSteps: this.#maxSteps,\n cleanupTimeoutMs: this.#cleanupTimeoutMs,\n });\n\n // Preserve runtime state set after construction (mastra registration and the\n // wired inner pubsub, e.g. mastra.pubsub) without re-triggering registration\n // side effects — mirrors Agent.__fork().\n if (this.#mastra) {\n fork.#mastra = this.#mastra;\n }\n fork.#innerPubsub = this.#innerPubsub;\n fork.source = this.source;\n // `_agentNetworkAppend` is a private base-class flag; copy it via an indexed\n // cast (the same idiom the base uses in `toRawConfig()`) so the fork mirrors\n // `Agent.__fork()` without widening the field's visibility.\n (fork as unknown as { _agentNetworkAppend: unknown })._agentNetworkAppend = (\n this as unknown as { _agentNetworkAppend: unknown }\n )._agentNetworkAppend;\n\n // DurableAgent intentionally diverges from Agent's `stream` signature, so the\n // re-wrapped fork is bridged to the base `Agent` return type here. The editor's\n // fork-then-mutate contract only relies on the base Agent surface.\n return fork as unknown as Agent<TAgentId, TTools, TOutput>;\n }\n\n // ===========================================================================\n // Protected methods for subclass overrides\n // ===========================================================================\n\n /**\n * Get the PubSub instance for use by subclasses.\n * @internal\n */\n protected get pubsubInternal(): PubSub {\n return this.pubsub;\n }\n\n /**\n * Get the run registry for use by subclasses.\n * @internal\n */\n protected get runRegistryInternal(): ExtendedRunRegistry {\n return this.#runRegistry;\n }\n\n /**\n * Execute the durable workflow.\n *\n * Subclasses override this method to customize how the workflow is executed:\n * - DurableAgent (this): Runs the workflow directly via createRun + start\n * - EventedAgent: Uses run.startAsync() for fire-and-forget execution\n * - InngestAgent: Uses inngest.send() to trigger Inngest function\n *\n * @param runId - The unique run ID\n * @param workflowInput - The serialized workflow input\n * @internal\n */\n protected async executeWorkflow(runId: string, workflowInput: DurableAgenticWorkflowInput): Promise<void> {\n const workflow = this.getWorkflow();\n const entry = globalRunRegistry.get(runId);\n const requestContext = entry?.requestContext;\n\n const run = await workflow.createRun({ runId, pubsub: this.pubsub });\n // Parent the workflow run under the AGENT_RUN span so the trace exports under it.\n const result = await run.start({\n inputData: workflowInput,\n requestContext,\n actor: workflowInput.options?.actor,\n ...createObservabilityContext({ currentSpan: entry?.agentSpan }),\n });\n if (result?.status === 'failed') {\n const error = new Error((result as any).error?.message || 'Workflow execution failed');\n await this.emitError(runId, error);\n }\n // Reaching any non-suspended terminal status means the run is done and its\n // persisted snapshot rows will never be resumed. Delete them so snapshot\n // storage doesn't grow one stale row per completed run. Suspended runs\n // keep their snapshots so `resume()` / `recoverActiveRuns()` can find them.\n if (result?.status && result.status !== 'suspended') {\n await this.deleteRunSnapshots(runId);\n }\n }\n\n /**\n * Create the durable workflow for this agent.\n *\n * Subclasses can override this method to use a different workflow implementation:\n * - DurableAgent (this): Uses createDurableAgenticWorkflow()\n * - InngestAgent: Uses createInngestDurableAgenticWorkflow()\n *\n * @internal\n */\n protected createWorkflow(): ReturnType<typeof createDurableAgenticWorkflow> {\n return createDurableAgenticWorkflow({\n maxSteps: this.#maxSteps,\n });\n }\n\n /**\n * Emit an error event to pubsub.\n *\n * @param runId - The run ID\n * @param error - The error to emit\n * @internal\n */\n protected async emitError(runId: string, error: Error): Promise<void> {\n // End the root spans on error so the trace exports (mirrors the non-durable map-results-step).\n endRunSpansWithError(runId, error);\n await emitErrorEvent(this.pubsub, runId, error);\n }\n\n /**\n * Delete the persisted workflow snapshot rows for a completed durable run.\n *\n * A durable agent write two rows per run: one for the outer `AGENTIC_LOOP`\n * workflow and one for the nested `AGENTIC_EXECUTION` workflow (persisted\n * under the same `runId`). Once the run reaches a non-suspended terminal\n * state neither row is needed again — leaving them behind fills snapshot\n * storage with stale `pending`/`running` rows for every completed run and\n * pollutes `listActiveRuns` / `recoverActiveRuns` on the next boot.\n *\n * Best-effort: a cleanup failure must never turn a finished run into an\n * error — a stale row is preferable to a broken exit path.\n *\n * @internal\n */\n protected async deleteRunSnapshots(runId: string): Promise<void> {\n try {\n const workflow = this.getWorkflow();\n await workflow.deleteWorkflowRunById(runId);\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n await workflowsStore?.deleteWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_EXECUTION,\n });\n } catch (error) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] Failed to delete workflow snapshot rows after terminal state`, { runId, error });\n }\n }\n\n // ===========================================================================\n // Public API\n // ===========================================================================\n\n /**\n * Stream a response from the agent using durable execution.\n */\n // @ts-expect-error - Intentionally different signature for durable execution\n async stream(\n messages: MessageListInput,\n options?: DurableAgentStreamOptions<TOutput>,\n ): Promise<DurableAgentStreamResult<TOutput>> {\n options = await this.#resolveExecutionOptions(options);\n\n // Delegate to the idle-loop wrapper when `untilIdle` is set.\n // Strip `untilIdle` before passing to the wrapper so its internal\n // agent.stream() call doesn't recurse.\n if (options?.untilIdle) {\n const { untilIdle, ...rest } = options;\n const maxIdleMs = typeof untilIdle === 'object' ? untilIdle.maxIdleMs : undefined;\n // The idle helper normally resolves defaults for scope discovery. These\n // options are already resolved, so keep its inner stream on the same values.\n const resolvedOptionsAgent = {\n id: this.id,\n getDefaultOptions: () => ({}),\n getMemory: (args?: any) => this.getMemory(args),\n stream: (innerMessages: MessageListInput, innerOptions?: DurableAgentStreamOptions<TOutput>) =>\n this.stream(innerMessages, innerOptions),\n } as unknown as DurableAgent<any, any, TOutput>;\n return runDurableStreamUntilIdle<TOutput>(\n resolvedOptionsAgent,\n messages,\n { ...rest, maxIdleMs },\n {\n activeStreams: this.#activeStreamUntilIdle,\n bgManager: this.#mastra?.backgroundTaskManager,\n },\n );\n }\n\n // Enforce agent-level FGA (agents:execute) before durable execution. The\n // base Agent enforces this in its stream()/generate(); durable execution\n // runs a workflow instead and would otherwise skip the gate. This also\n // covers evented subclasses, which inherit stream()/generate().\n await this.requireAgentExecutionFGA({\n requestContext: options?.requestContext,\n memory: options?.memory,\n runId: options?.runId,\n actor: options?.actor,\n });\n\n // 1. Prepare for durable execution (non-durable phase)\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options: options as AgentExecutionOptions<TOutput>,\n runId: options?.runId,\n requestContext: options?.requestContext,\n optionsAreResolved: true,\n mastra: this.#mastra,\n durableAgentId: this.id,\n durableAgentName: this.name,\n });\n\n const { runId, messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;\n\n // 1a. Install the abort controller for this run. The controller is owned\n // by this DurableAgent instance; the result's abort() method flips it,\n // and the durable LLM-execution step reads `abortSignal` off the registry\n // to thread it into the model call + abort short-circuits. If the caller\n // also supplied an external signal, forward its abort to the internal\n // controller so either source can cancel the run.\n const abortController = new AbortController();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) {\n abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n options.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n registryEntry.abortController = abortController;\n registryEntry.abortSignal = abortController.signal;\n\n // 2. Register non-serializable state (both local and global registries)\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n globalRunRegistry.set(runId, { ...registryEntry, messageList });\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Schedule automatic registry cleanup after stream ends\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n // 3. Create the durable agent stream (subscribes to pubsub)\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\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: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n onAbort: async data => {\n try {\n await (options?.onAbort as ((event: any) => void | Promise<void>) | undefined)?.(data);\n } finally {\n scheduleAutoCleanup();\n }\n },\n // onIterationComplete is NOT forwarded here — the dowhile predicate\n // now calls it in-process from globalRunRegistry and honors its return\n // value ({ continue, feedback }). The pubsub ITERATION_COMPLETE event\n // still fires for external observability subscribers.\n closeOnSuspend: (options as any)?.[CLOSE_ON_SUSPEND] === true,\n structuredOutput: registryEntry.structuredOutput as any,\n outputProcessors: registryEntry.outputProcessors,\n messageList,\n });\n\n // 4. Wait for subscription to be ready, then execute workflow\n // This prevents race conditions where events are published before subscription\n const workflowExecution = ready\n .then(async () => {\n // Emit 'start' chunk before the workflow begins (matches regular agent's stream.ts).\n // Only the initial stream() path emits 'start'; resume() does not.\n await emitChunkEvent(this.pubsub, runId, {\n type: 'start',\n runId,\n from: ChunkFrom.AGENT,\n payload: { id: workflowInput.agentId, messageId },\n });\n if (this.__getGoalConfig()) {\n await beginGoalActivity({\n mastra: this.#mastra,\n agentId: workflowInput.agentId,\n threadId,\n runId,\n requestContext: globalRunRegistry.get(runId)?.requestContext,\n });\n }\n try {\n return await this.executeWorkflow(runId, workflowInput);\n } finally {\n await stopGoalActivity({ agentId: workflowInput.agentId, runId });\n }\n })\n .catch(error => {\n void this.emitError(runId, error);\n });\n const trackedEntry = globalRunRegistry.get(runId);\n if (trackedEntry) {\n trackedEntry.workflowExecution = workflowExecution;\n }\n\n // 4b. Register with the thread-stream runtime so subscribeToThread /\n // sendMessage subscribers receive run-registered events and stream parts.\n // Uses the Mastra-level pubsub (this.getPubSub()) — not the internal\n // CachingPubSub (this.pubsub) which carries durable workflow chunks.\n await agentThreadStreamRuntime.registerRun(\n this as unknown as Agent<any, any, any, any>,\n output,\n options as AgentExecutionOptions<TOutput>,\n this.getPubSub(),\n );\n\n // 5. Create cleanup function (cancels auto-cleanup timer if called)\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId,\n resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Resume a suspended workflow execution.\n */\n async resume(\n runId: string,\n resumeData: unknown,\n options?: DurableAgentResumeOptions<TOutput>,\n ): Promise<DurableAgentStreamResult<TOutput>> {\n let entry = this.#runRegistry.get(runId);\n if (!entry) {\n // A persisted durable run can outlive this process (or the registry TTL).\n // Rebuild the non-serializable runtime state before resuming the stored\n // workflow snapshot. Keep warm resumes on the existing path to avoid\n // racing an active registry entry with a second preparation pass.\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n const persisted = await workflowsStore?.getWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_LOOP,\n });\n if (!persisted) {\n throw new Error(`No registry entry found for run ${runId}. Cannot resume.`);\n }\n\n const snapshot =\n typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n if (snapshot?.status !== 'suspended') {\n throw new Error('This workflow run was not suspended');\n }\n const workflowInput = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (!workflowInput || workflowInput.__workflowKind !== 'durable-agent') {\n throw new MastraError({\n id: 'DURABLE_AGENT_RESUME_INVALID_SNAPSHOT',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n text: `DurableAgent \"${this.name}\" resume(${runId}): persisted snapshot does not contain a durable-agent workflow input.`,\n details: { agentName: this.name, runId },\n });\n }\n if (workflowInput.agentId !== this.id) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RESUME_AGENT_MISMATCH',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}): persisted run belongs to agent \"${workflowInput.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: workflowInput.agentId },\n });\n }\n\n const messageListMemoryInfo = (\n workflowInput.messageListState as { memoryInfo?: { threadId?: string; resourceId?: string } } | undefined\n )?.memoryInfo;\n const threadId = workflowInput.state?.threadId ?? messageListMemoryInfo?.threadId;\n const resourceId = workflowInput.state?.resourceId ?? messageListMemoryInfo?.resourceId;\n const snapshotRequestContext = workflowInput.requestContextEntries\n ? new RequestContext<unknown>(Object.entries(workflowInput.requestContextEntries))\n : undefined;\n const memory = threadId\n ? {\n ...options?.memory,\n thread: threadId,\n resource: resourceId ?? options?.memory?.resource,\n }\n : options?.memory;\n\n await this.prepare([], {\n ...(options as AgentExecutionOptions<TOutput>),\n runId,\n requestContext: options?.requestContext ?? snapshotRequestContext,\n memory,\n });\n entry = this.#runRegistry.get(runId);\n }\n if (!entry) {\n throw new Error(`Failed to rehydrate registry entry for run ${runId}. Cannot resume.`);\n }\n\n const memoryInfo = this.#runRegistry.getMemoryInfo(runId);\n const registeredMemory = memoryInfo?.threadId\n ? ({\n ...options?.memory,\n thread: memoryInfo.threadId,\n resource: memoryInfo.resourceId ?? options?.memory?.resource,\n } as DurableAgentStreamOptions<TOutput>['memory'])\n : options?.memory;\n\n const resolvedOptions = (await this.#resolveExecutionOptions({\n ...(options as DurableAgentStreamOptions<TOutput>),\n requestContext:\n options?.requestContext ??\n (entry.requestContext as DurableAgentStreamOptions<TOutput>['requestContext'] | undefined),\n memory: registeredMemory ?? options?.memory,\n })) as DurableAgentResumeOptions<TOutput>;\n\n // Delegate to the idle-loop wrapper when `untilIdle` is set. Strip\n // `untilIdle` before passing to the wrapper so the inner agent.resume()\n // call (and subsequent agent.stream([]) continuations) don't recurse.\n if (resolvedOptions.untilIdle) {\n const { untilIdle, ...rest } = resolvedOptions;\n const maxIdleMs = typeof untilIdle === 'object' ? untilIdle.maxIdleMs : undefined;\n const resolvedOptionsAgent = {\n id: this.id,\n getDefaultOptions: () => ({}),\n getMemory: (args?: any) => this.getMemory(args),\n resume: (innerRunId: string, innerResumeData: unknown, innerOptions?: DurableAgentResumeOptions<TOutput>) =>\n this.resume(innerRunId, innerResumeData, innerOptions),\n stream: (innerMessages: MessageListInput, innerOptions?: DurableAgentStreamOptions<TOutput>) =>\n this.stream(innerMessages, innerOptions),\n } as unknown as DurableAgent<any, any, TOutput>;\n return runResumeDurableStreamUntilIdle<TOutput>(\n resolvedOptionsAgent,\n runId,\n resumeData,\n { ...rest, maxIdleMs } as DurableAgentStreamOptions<TOutput> & { maxIdleMs?: number },\n {\n activeStreams: this.#activeStreamUntilIdle,\n bgManager: this.#mastra?.backgroundTaskManager,\n },\n );\n }\n\n await this.requireAgentExecutionFGA({\n requestContext: resolvedOptions.requestContext,\n memory: resolvedOptions.memory,\n runId,\n snapshotMemoryInfo: memoryInfo,\n actor: resolvedOptions.actor,\n });\n\n // Install a fresh abort controller for the resumed segment. The original\n // controller is gone (the stream that owned it has already settled), so\n // we overwrite the registry slot. If the caller passed an external\n // signal, forward it onto the new internal controller.\n const abortController = new AbortController();\n if (resolvedOptions.abortSignal) {\n if (resolvedOptions.abortSignal.aborted) {\n abortController.abort((resolvedOptions.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n resolvedOptions.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((resolvedOptions.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n entry.abortController = abortController;\n entry.abortSignal = abortController.signal;\n const globalEntryForAbort = globalRunRegistry.get(runId);\n if (globalEntryForAbort) {\n globalEntryForAbort.abortController = abortController;\n globalEntryForAbort.abortSignal = abortController.signal;\n }\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n const globalEntry = globalRunRegistry.get(runId);\n const resumeModel = globalEntry?.model as any;\n\n // Skip events already broadcast by the original run (e.g. the SUSPENDED\n // chunk that paused it). Without this, a resume that closes on suspend\n // (resumeGenerate) would immediately close on the replayed SUSPENDED.\n const resumeOffset = await this.#getPubsubOffset(runId);\n\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n messageId: crypto.randomUUID(),\n model: {\n modelId: resumeModel?.modelId,\n provider: resumeModel?.provider,\n version: 'v3',\n },\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n offset: resumeOffset,\n onChunk: resolvedOptions.onChunk,\n experimentalTransform: resolvedOptions.experimentalTransform,\n onStepFinish: resolvedOptions.onStepFinish,\n onFinish: resolvedOptions.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await resolvedOptions.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: resolvedOptions.onSuspended,\n closeOnSuspend: (resolvedOptions as any)[CLOSE_ON_SUSPEND] === true,\n structuredOutput: entry.structuredOutput as any,\n outputProcessors: entry.outputProcessors,\n messageList: globalEntry?.messageList ?? this.#runRegistry.getMessageList(runId),\n });\n\n // Wait for subscription to be ready, then resume workflow\n const workflow = this.getWorkflow();\n const requestContext = resolvedOptions.requestContext;\n\n // Open a fresh AGENT_RUN + MODEL_GENERATION for the resumed segment on the same\n // traceId — the originals were ended as `suspended` and can't be reopened. Post-resume\n // steps + terminal end() target these via the registry override. (Linking = follow-up.)\n const origTraceId = entry.agentSpan?.traceId;\n const origSpanId = entry.agentSpan?.id;\n if (origTraceId && this.#mastra?.observability) {\n try {\n const ag = this.#wrappedAgent as Agent<string, any, any>;\n // Match non-durable Agent.stream() resume-span shape: same name suffix\n // `(resumed)`, forward agent-level tracingPolicy, link to the original\n // span via `resumedFromSpanId` metadata, and carry the resolvedVersionId.\n const rawConfig = typeof (ag as any).toRawConfig === 'function' ? (ag as any).toRawConfig() : undefined;\n const resolvedVersionId = rawConfig?.resolvedVersionId as string | undefined;\n const agentTracingPolicy = typeof ag.getTracingPolicy === 'function' ? ag.getTracingPolicy() : undefined;\n const resumeAgentSpan = getOrCreateSpan({\n type: SpanType.AGENT_RUN,\n name: `agent run: '${ag.id}' (resumed)`,\n entityType: EntityType.AGENT,\n entityId: ag.id,\n entityName: ag.name,\n metadata: {\n runId,\n resumed: true,\n ...(origSpanId ? { resumedFromSpanId: origSpanId } : {}),\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n tracingPolicy: agentTracingPolicy,\n tracingOptions: { traceId: origTraceId },\n requestContext,\n mastra: this.#mastra,\n });\n const resumeModelSpan = resumeAgentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n name: `llm: '${resumeModel?.modelId ?? ''}'`,\n attributes: { model: resumeModel?.modelId, provider: resumeModel?.provider, streaming: true },\n metadata: { runId, resumed: true },\n requestContext,\n });\n for (const reg of [entry, globalRunRegistry.get(runId)]) {\n if (!reg) continue;\n reg.resumeAgentSpan = resumeAgentSpan;\n reg.resumeModelSpan = resumeModelSpan;\n reg.resumeAgentSpanData = resumeAgentSpan?.exportSpan();\n reg.resumeModelSpanData = resumeModelSpan?.exportSpan();\n }\n } catch (error) {\n // Span bookkeeping must never block resume.\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open resume spans: ${error}`);\n }\n }\n\n // Capture the prior workflow execution BEFORE creating the new promise.\n // If we read it inside the `.then()` callback, the global registry will\n // already point to the NEW promise (assigned synchronously below),\n // causing a self-referential deadlock.\n const priorExecution = globalRunRegistry.get(runId)?.workflowExecution;\n\n const workflowExecution = ready\n .then(async () => {\n // Wait for the prior workflow execution (stream / previous resume) to\n // fully settle so the snapshot is persisted as 'suspended' before we\n // attempt to resume it. Without this, the pubsub tool-call-suspended\n // event can arrive (and the consumer can call resumeStream) before the\n // engine has finished writing the snapshot, leading to\n // \"This workflow run was not suspended\".\n if (priorExecution) {\n await priorExecution.catch(() => {\n /* errors already handled by the prior segment */\n });\n }\n\n const run = await workflow.createRun({ runId, pubsub: this.pubsub });\n if (this.__getGoalConfig()) {\n await beginGoalActivity({\n mastra: this.#mastra,\n agentId: this.id,\n threadId: memoryInfo?.threadId,\n runId,\n requestContext,\n });\n }\n let result;\n try {\n result = await run.resume({\n resumeData,\n label: resolvedOptions.toolCallId,\n requestContext,\n actor: resolvedOptions.actor,\n ...createObservabilityContext({ currentSpan: entry.resumeAgentSpan ?? entry.agentSpan }),\n });\n } finally {\n await stopGoalActivity({ agentId: this.id, runId });\n }\n if (result?.status === 'failed') {\n const error = new Error((result as any).error?.message || 'Workflow resume failed');\n void this.emitError(runId, error);\n }\n // Same snapshot cleanup as the initial `start()` path: once resume\n // settles on any non-suspended terminal status the persisted rows are\n // no longer needed. A resume that re-suspends must keep them so the\n // next resume/recover can find the snapshot.\n if (result?.status && result.status !== 'suspended') {\n await this.deleteRunSnapshots(runId);\n }\n })\n .catch(error => {\n void this.emitError(runId, error);\n });\n const trackedResumeEntry = globalRunRegistry.get(runId);\n if (trackedResumeEntry) {\n trackedResumeEntry.workflowExecution = workflowExecution;\n }\n\n // Register the resumed run with the thread-stream runtime so\n // subscribeToThread subscribers are notified of the new stream.\n const resumeStreamOptions: AgentExecutionOptions<TOutput> = {\n ...resolvedOptions,\n runId,\n } as AgentExecutionOptions<TOutput>;\n await agentThreadStreamRuntime.registerRun(\n this as unknown as Agent<any, any, any, any>,\n output,\n resumeStreamOptions,\n this.getPubSub(),\n );\n\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Recover a single durable run whose in-process agentic loop was orphaned by\n * a process restart. Streamable counterpart to\n * {@link DurableAgent.recoverActiveRuns} — where the bulk API only re-drives\n * the workflow and returns counts, `recover()` rebuilds the run's\n * non-serializable state (message list, model, tools, memory,\n * saveQueueManager, request context, agent span) from the persisted workflow\n * snapshot and returns a fresh {@link DurableAgentStreamResult} whose\n * `fullStream` observes the recovered run through pubsub.\n *\n * Because the rebuilt registry entry carries `memory` + `saveQueueManager`,\n * the durable agentic workflow's terminal step will flush new messages to\n * memory just like a fresh `stream()` call would. The single-run form is\n * useful when operators want to attach listeners to a specific recovered\n * run; for boot-time bulk recovery of every orphaned run, use\n * `recoverActiveRuns()`.\n *\n * @example\n * ```typescript\n * const { fullStream, output, cleanup } = await durableAgent.recover(runId, {\n * onChunk: chunk => process.stdout.write(chunk.payload?.text ?? ''),\n * });\n * for await (const chunk of fullStream) {\n * // ...\n * }\n * cleanup();\n * ```\n */\n async recover(\n runId: string,\n options?: DurableAgentRecoverOptions<TOutput>,\n ): Promise<DurableAgentStreamResult<TOutput>> {\n if (!this.#mastra) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_NO_MASTRA',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" recover() requires the agent to be registered on a Mastra instance.`,\n details: { agentName: this.name, runId },\n });\n }\n\n const workflowsStore = await this.#mastra.getStorage()?.getStore('workflows');\n if (!workflowsStore) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_NO_STORAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" recover() requires persistent storage to load the run snapshot. ` +\n `Register the agent on a Mastra instance with persistent storage (e.g. PostgreSQL, LibSQL).`,\n details: { agentName: this.name, runId },\n });\n }\n\n // 1. Load the persisted snapshot for the durable agentic loop workflow.\n const persisted = await workflowsStore.getWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_LOOP,\n });\n if (!persisted) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" recover(${runId}): no persisted workflow snapshot found. ` +\n `The run may have already completed or been cleaned up.`,\n details: { agentName: this.name, runId },\n });\n }\n\n const snapshot =\n typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n\n const workflowInput = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (!workflowInput || workflowInput.__workflowKind !== 'durable-agent') {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_INVALID_SNAPSHOT',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n text: `DurableAgent \"${this.name}\" recover(${runId}): persisted snapshot does not contain a durable-agent workflow input.`,\n details: { agentName: this.name, runId },\n });\n }\n\n // All durable agents share the same workflow name (`durable-agentic-loop`),\n // so a caller with runId in hand could otherwise recover another agent's\n // run. Refuse to rehydrate a snapshot whose agentId doesn't match this\n // instance — the caller must reach the owning agent to recover the run.\n if (workflowInput.agentId !== this.id) {\n throw new MastraError({\n id: 'DURABLE_AGENT_RECOVER_AGENT_MISMATCH',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" recover(${runId}): persisted run belongs to agent \"${workflowInput.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: workflowInput.agentId },\n });\n }\n\n // 2. Rebuild the RequestContext from the persisted JSON-safe snapshot.\n const requestContext: RequestContext = workflowInput.requestContextEntries\n ? new RequestContext(Object.entries(workflowInput.requestContextEntries) as Iterable<readonly [string, unknown]>)\n : new RequestContext();\n\n // 3. Rebuild MessageList from the persisted state. threadId/resourceId\n // come from the workflow input's `state` block when present; older\n // snapshots may only have them under `messageListState.memoryInfo`.\n const messageListMemoryInfo = (\n workflowInput.messageListState as { memoryInfo?: { threadId?: string; resourceId?: string } } | undefined\n )?.memoryInfo;\n const threadId = workflowInput.state?.threadId ?? messageListMemoryInfo?.threadId;\n const resourceId = workflowInput.state?.resourceId ?? messageListMemoryInfo?.resourceId;\n const messageList = new MessageList({ threadId, resourceId });\n try {\n messageList.deserialize(workflowInput.messageListState);\n } catch (err) {\n // Fresh (never-executed) snapshots may have a minimal `messageListState`;\n // fall back to an empty MessageList so recovery still proceeds. The\n // workflow steps rebuild the real MessageList from serialized input.\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) messageList deserialize skipped: ${err}`);\n }\n\n // 4. Resolve model/memory from the live agent. Tools are rebuilt by the\n // durable step from `toolsMetadata`, so we only need the live agent's\n // memory here to enable message persistence at the terminal step.\n const wrapped = this.#wrappedAgent as Agent<string, any, TOutput>;\n let model;\n try {\n model = await wrapped.getModel({ requestContext });\n } catch (err) {\n const logger = this.#mastra?.getLogger?.();\n logger?.warn?.(`[DurableAgent] Failed to resolve model during recover(${runId}): ${err}`);\n }\n let memory;\n try {\n memory = await wrapped.getMemory({ requestContext });\n } catch (err) {\n const logger = this.#mastra?.getLogger?.();\n logger?.warn?.(`[DurableAgent] Failed to resolve memory during recover(${runId}): ${err}`);\n }\n const saveQueueManager = memory\n ? new SaveQueueManager({ logger: this.#mastra?.getLogger?.() as any, memory })\n : undefined;\n\n // Re-wire background-task state so the recovered segment can wait for\n // pre-crash tasks (via `bg-task-check`), dispatch new background tool\n // calls (via `tool-call`), and inject the background-task system prompt\n // (via `llm-execution`). The manager is storage-backed, so in-flight\n // tasks spawned before the crash are still discoverable via\n // `bgManager.listTasks(...)`.\n const backgroundTasksConfig = this.getBackgroundTasksConfig?.();\n const backgroundTaskManager = this.#mastra?.backgroundTaskManager;\n\n // Re-resolve processors from the live agent config. `llm-execution` reads\n // `inputProcessors` / `llmRequestInputProcessors` / `outputProcessors` from\n // the global registry, and the terminal `.map(...)` reads `outputProcessors`\n // + `errorProcessors` — without these, the recovered segment would run\n // with no processors even if the agent has some configured.\n let inputProcessors: any[] = [];\n let llmRequestInputProcessors: any[] = [];\n let outputProcessors: any[] = [];\n let errorProcessors: any[] = [];\n try {\n inputProcessors = (await (wrapped as any).listInputProcessors?.(requestContext)) ?? [];\n llmRequestInputProcessors = (await (wrapped as any).__listLLMRequestProcessors?.(requestContext)) ?? [];\n outputProcessors = (await (wrapped as any).listOutputProcessors?.(requestContext)) ?? [];\n errorProcessors = (await (wrapped as any).listErrorProcessors?.(requestContext)) ?? [];\n } catch (err) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) processor resolution failed: ${err}`);\n }\n // Fresh empty processorStates for the recovered segment — the pre-crash\n // segment's in-memory processor state is gone, but the terminal state\n // (memory writes, message list) lives on the persisted snapshot.\n const processorStates = new Map<string, any>();\n\n // 5. Re-open an AGENT_RUN span for the recovered segment. Follow the same\n // pattern as resume(): reuse the original traceId when possible so the\n // recovered run stays linked to the original agent trace.\n const abortController = new AbortController();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) {\n abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n options.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n\n const origAgentSpanData = workflowInput.agentSpanData as { traceId?: string; id?: string } | undefined;\n let recoverAgentSpan: any;\n if (this.#mastra?.observability) {\n try {\n const rawConfig =\n typeof (wrapped as any).toRawConfig === 'function' ? (wrapped as any).toRawConfig() : undefined;\n const resolvedVersionId = rawConfig?.resolvedVersionId as string | undefined;\n const agentTracingPolicy =\n typeof wrapped.getTracingPolicy === 'function' ? wrapped.getTracingPolicy() : undefined;\n recoverAgentSpan = getOrCreateSpan({\n type: SpanType.AGENT_RUN,\n name: `agent run: '${wrapped.id}' (recovered)`,\n entityType: EntityType.AGENT,\n entityId: wrapped.id,\n entityName: wrapped.name,\n metadata: {\n runId,\n recovered: true,\n ...(origAgentSpanData?.id ? { recoveredFromSpanId: origAgentSpanData.id } : {}),\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n tracingPolicy: agentTracingPolicy,\n tracingOptions: origAgentSpanData?.traceId ? { traceId: origAgentSpanData.traceId } : undefined,\n requestContext,\n mastra: this.#mastra,\n });\n } catch (err) {\n // Span bookkeeping must never block recovery.\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open recover span: ${err}`);\n }\n }\n\n // 6. Assemble a minimal RunRegistryEntry. Fields that the durable steps\n // would normally populate on the fly (tools, workspace, processor\n // states, etc.) are left undefined — the workflow's own\n // `resolveRuntimeDependencies` will fall back to the persisted step\n // input to reconstruct them, so we only need the fields that the\n // terminal `.map(...)` step and stream adapter read from the registry:\n // saveQueueManager + memory + agentSpan + abortController.\n const registryEntry: any = {\n model,\n memory,\n saveQueueManager,\n requestContext,\n agentSpan: recoverAgentSpan,\n abortController,\n abortSignal: abortController.signal,\n backgroundTaskManager,\n backgroundTasksConfig,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n cleanup: () => {},\n };\n\n // 7. Register the reconstructed state in both the per-instance and global\n // registries so the workflow steps + terminal memory flush can find it.\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n globalRunRegistry.set(runId, { ...registryEntry, messageList });\n\n // 8. Cleanup plumbing (mirrors stream()/resume()).\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n // 9. Skip any pubsub events broadcast before recovery started. Persistent\n // pubsub backends may retain chunks from the pre-crash segment; the\n // caller only wants events from the recovered segment forward.\n const recoverOffset = await this.#getPubsubOffset(runId);\n\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n messageId: workflowInput.messageId ?? crypto.randomUUID(),\n model: {\n modelId: workflowInput.modelConfig?.modelId,\n provider: workflowInput.modelConfig?.provider,\n version: 'v3',\n },\n threadId,\n resourceId,\n offset: recoverOffset,\n onChunk: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n // Recovered runs use the default `closeOnSuspend: false` — a run that\n // suspends again should stay observable so a later resume/recover can\n // pick it up. Callers wanting to close on suspend can call `cleanup()`\n // from `onSuspended`.\n messageList,\n });\n\n // 10. Re-drive the workflow from the persisted snapshot in the background\n // and delete snapshot rows on non-suspended terminals (same contract\n // as start()/resume()). Errors are also broadcast via `emitError` so\n // observers on the pubsub topic see the failure. Callers who await\n // the returned `workflowExecution` (e.g. `recoverActiveRuns()`) see\n // the raw rejection so they can classify the run as failed.\n const workflow = this.getWorkflow();\n const workflowExecution = ready.then(async () => {\n try {\n const run = await workflow.createRun({ runId, pubsub: this.pubsub });\n const result = await run.restart({\n requestContext,\n ...createObservabilityContext({ currentSpan: recoverAgentSpan }),\n } as any);\n // Snapshot cleanup runs for every non-suspended terminal (success or\n // failed) so storage stays bounded — mirrors the start()/resume()\n // contract.\n if (result?.status && result.status !== 'suspended') {\n await this.deleteRunSnapshots(runId);\n }\n if (result?.status === 'failed') {\n const error = new Error((result as any).error?.message || 'Workflow recover failed');\n void this.emitError(runId, error);\n throw error;\n }\n } catch (error) {\n void this.emitError(runId, error as Error);\n throw error;\n }\n });\n const trackedRecoverEntry = globalRunRegistry.get(runId);\n if (trackedRecoverEntry) {\n trackedRecoverEntry.workflowExecution = workflowExecution;\n }\n // Guard against unhandled rejection warnings for callers who don't await\n // `workflowExecution` (single-run `recover()` returns a stream, not the\n // workflow promise). Errors are already surfaced through `emitError` /\n // the stream's `onError` callback.\n workflowExecution.catch(() => {});\n\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n const abort = (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId,\n resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Override the inherited `resumeStream()` so that callers using the base\n * `Agent` API (including `approveToolCall` / `declineToolCall`) are routed\n * through the durable `resume()` path instead of the regular Agent's\n * snapshot-based resume.\n *\n * Returns just the `MastraModelOutput` (matching the base Agent's return\n * type) while internally delegating to `this.resume()`.\n */\n override async resumeStream(resumeData: any, streamOptions?: any): Promise<MastraModelOutput<TOutput>> {\n const runId = streamOptions?.runId;\n if (!runId) {\n throw new Error('resumeStream() on DurableAgent requires a runId in streamOptions.');\n }\n const { runId: _runId, ...resumeOptions } = streamOptions;\n const result = await this.resume(runId, resumeData, {\n ...resumeOptions,\n // Close the stream when the workflow re-suspends so the caller's\n // `for await` loop terminates. Without this the stream stays open\n // indefinitely when the resumed turn hits another suspend point.\n [CLOSE_ON_SUSPEND]: true,\n } as Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2]);\n return result.output;\n }\n\n /**\n * Override the inherited `approveToolCall()` to route through the durable\n * `resume()` path.\n */\n override async approveToolCall(\n options: { runId: string; toolCallId?: string } & Record<string, any>,\n ): Promise<MastraModelOutput<any>> {\n return this.resumeStream({ approved: true }, options);\n }\n\n /**\n * Override the inherited `declineToolCall()` to route through the durable\n * `resume()` path.\n */\n override async declineToolCall(\n options: { runId: string; toolCallId?: string } & Record<string, any>,\n ): Promise<MastraModelOutput<any>> {\n return this.resumeStream({ approved: false }, options);\n }\n\n override async approveToolCallGenerate<OUTPUT = undefined>(\n options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string },\n ): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['getFullOutput']>>> {\n const { runId, ...resumeOptions } = options;\n return this.resumeGenerate(runId, { approved: true }, resumeOptions as any) as any;\n }\n\n override async declineToolCallGenerate<OUTPUT = undefined>(\n options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string },\n ): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['getFullOutput']>>> {\n const { runId, ...resumeOptions } = options;\n return this.resumeGenerate(runId, { approved: false }, resumeOptions as any) as any;\n }\n\n /**\n * Generate a complete response from the agent using durable execution.\n *\n * Drains the underlying durable stream to completion and returns the same\n * {@link FullOutput} shape as non-durable `Agent.generate`. The underlying\n * workflow is identical to `stream()` — it just collects the final result\n * for callers that don't want to consume chunks themselves.\n *\n * This method intentionally re-implements the `stream()` setup rather than\n * delegating to `this.stream(...)` so that `prepareForDurableExecution` (and\n * downstream `convertTools`) receives `methodType: 'generate'`. Tool\n * factories that vary their `CoreTool` output based on the calling method\n * (e.g. `clientTools` vs server-side tools) rely on this signal — calling\n * `stream()` here would silently pass `methodType: 'stream'`.\n *\n * If the run suspends (e.g. tool approval or `suspend()` from a tool), the\n * returned output's `finishReason` will be `'suspended'` and\n * `suspendPayload` will be populated. Use {@link DurableAgent.resumeGenerate}\n * to continue.\n *\n * Note on suspend persistence: for the base `DurableAgent`, the workflow\n * engine's `run.start()` only resolves after the suspend snapshot is\n * persisted, so awaiting `workflowExecution` on suspend is sufficient for\n * a subsequent `resumeGenerate()` to find the snapshot. Subclasses like\n * `EventedAgent` use a fire-and-forget `run.startAsync()` and therefore\n * cannot rely on this await for snapshot durability — see the\n * `EventedAgent` docs for the recommended pattern.\n */\n // @ts-expect-error - Intentionally different signature for durable execution\n async generate(\n messages: MessageListInput,\n options?: DurableAgentStreamOptions<TOutput>,\n ): Promise<FullOutput<TOutput>> {\n options = await this.#resolveExecutionOptions(options);\n\n // Enforce agent-level FGA (agents:execute) before durable execution — see\n // stream() above. Durable/evented generate would otherwise skip the gate.\n await this.requireAgentExecutionFGA({\n requestContext: options?.requestContext,\n memory: options?.memory,\n runId: options?.runId,\n actor: options?.actor,\n });\n\n // 1. Prepare for durable execution (non-durable phase)\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options: options as AgentExecutionOptions<TOutput>,\n runId: options?.runId,\n requestContext: options?.requestContext,\n optionsAreResolved: true,\n mastra: this.#mastra,\n methodType: 'generate',\n durableAgentId: this.id,\n durableAgentName: this.name,\n });\n\n const { runId, messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;\n\n // 1a. Install the abort controller for this run. The controller is owned\n // by this DurableAgent instance; the result's abort() method flips it,\n // and the durable LLM-execution step reads `abortSignal` off the registry\n // to thread it into the model call + abort short-circuits. If the caller\n // also supplied an external signal, forward its abort to the internal\n // controller so either source can cancel the run.\n const abortController = new AbortController();\n if (options?.abortSignal) {\n if (options.abortSignal.aborted) {\n abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason);\n } else {\n options.abortSignal.addEventListener(\n 'abort',\n () => abortController.abort((options.abortSignal as AbortSignal & { reason?: unknown }).reason),\n { once: true },\n );\n }\n }\n registryEntry.abortController = abortController;\n registryEntry.abortSignal = abortController.signal;\n\n // 2. Register non-serializable state (both local and global registries)\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n globalRunRegistry.set(runId, { ...registryEntry, messageList });\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Schedule automatic registry cleanup after stream ends\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n // 3. Create the durable agent stream (subscribes to pubsub)\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\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: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n onAbort: async data => {\n try {\n await (options?.onAbort as ((event: any) => void | Promise<void>) | undefined)?.(data);\n } finally {\n scheduleAutoCleanup();\n }\n },\n // onIterationComplete is NOT forwarded here — the dowhile predicate\n // now calls it in-process from globalRunRegistry and honors its return\n // value ({ continue, feedback }). The pubsub ITERATION_COMPLETE event\n // still fires for external observability subscribers.\n closeOnSuspend: true,\n structuredOutput: registryEntry.structuredOutput as any,\n outputProcessors: registryEntry.outputProcessors,\n messageList,\n });\n\n // 4. Wait for subscription to be ready, then execute workflow\n // This prevents race conditions where events are published before subscription\n const workflowExecution = ready\n .then(async () => {\n // Emit 'start' chunk before the workflow begins (matches regular agent's stream.ts).\n // Only the initial generate()/stream() path emits 'start'; resume() does not.\n await emitChunkEvent(this.pubsub, runId, {\n type: 'start',\n runId,\n from: ChunkFrom.AGENT,\n payload: { id: workflowInput.agentId, messageId },\n });\n if (this.__getGoalConfig()) {\n await beginGoalActivity({\n mastra: this.#mastra,\n agentId: workflowInput.agentId,\n threadId,\n runId,\n requestContext: globalRunRegistry.get(runId)?.requestContext,\n });\n }\n try {\n return await this.executeWorkflow(runId, workflowInput);\n } finally {\n await stopGoalActivity({ agentId: workflowInput.agentId, runId });\n }\n })\n .catch(error => {\n void this.emitError(runId, error);\n });\n const trackedEntry = globalRunRegistry.get(runId);\n if (trackedEntry) {\n trackedEntry.workflowExecution = workflowExecution;\n }\n\n // 5. Create cleanup function (cancels auto-cleanup timer if called)\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n let suspended = false;\n try {\n const fullOutput = (await output.getFullOutput()) as FullOutput<TOutput>;\n if (fullOutput.error) {\n throw fullOutput.error;\n }\n suspended = fullOutput.finishReason === 'suspended';\n // On suspend, the SUSPENDED event is emitted from the tool-call step\n // before the workflow engine has persisted the snapshot. Awaiting the\n // workflow execution promise blocks until `run.start()` returns, which\n // happens after the suspend snapshot has been persisted — so a later\n // `resumeGenerate()` can find the snapshot. Subclasses that drive the\n // workflow with a fire-and-forget API (see `EventedAgent`) need their\n // own persistence guarantee here; their `executeWorkflow` promise may\n // resolve before the snapshot lands.\n if (suspended) {\n await globalRunRegistry.get(runId)?.workflowExecution;\n }\n // Fall back to the stream-level runId if MastraModelOutput.runId wasn't\n // populated (no chunk surfaced before suspend).\n if (!fullOutput.runId) {\n (fullOutput as { runId?: string }).runId = runId;\n }\n return fullOutput;\n } finally {\n // Keep the registry entry alive on suspend so `resumeGenerate()` can\n // pick it up. Auto-cleanup is scheduled by FINISH/ERROR/ABORT paths.\n if (!suspended) {\n cleanup();\n }\n }\n }\n\n /**\n * Resume a suspended durable run and drain it to a single\n * {@link FullOutput}. Mirrors {@link Agent.resumeGenerate} on top of\n * {@link DurableAgent.resume}.\n *\n * Unlike `generate()`, this delegates to `resume()` because resume reads\n * its tools from the existing run-registry entry rather than running\n * `prepareForDurableExecution` again — there is no `methodType` to thread\n * through. The same `EventedAgent` caveat about fire-and-forget snapshot\n * persistence noted on `generate()` applies if the resumed turn suspends.\n */\n async resumeGenerate(\n runId: string,\n resumeData: unknown,\n options?: Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2],\n ): Promise<FullOutput<TOutput>> {\n const result = await this.resume(runId, resumeData, {\n ...(options ?? {}),\n [CLOSE_ON_SUSPEND]: true,\n } as Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2]);\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 result.cleanup();\n }\n }\n }\n\n /**\n * List durable agent runs currently reported as `running` in workflow\n * snapshot storage.\n *\n * A `running` snapshot is a durable agent run whose agentic loop was\n * mid-execution the last time the workflow engine persisted its state. On a\n * healthy process these transition to `suspended` (waiting on\n * tool approval / resume) or a terminal status. On a crashed / restarted\n * process they are orphaned in the `running` state with no in-process\n * driver — this is the discovery API used to enumerate them for recovery\n * (see {@link DurableAgent.recoverActiveRuns} and workflow `restart`).\n *\n * Requires persistent workflow storage. Filters `agentId` against the\n * persisted `DurableAgenticWorkflowInput.agentId`, so runs started by other\n * durable agents sharing the same storage are not surfaced.\n *\n * @example\n * ```typescript\n * const { runs } = await durableAgent.listActiveRuns({ resourceId });\n * for (const run of runs) {\n * await durableAgent.recoverActiveRuns({ runId: run.runId });\n * }\n * ```\n */\n async listActiveRuns(options: DurableAgentListActiveRunsOptions = {}): Promise<DurableAgentListActiveRunsResult> {\n const { threadId, resourceId, fromDate, toDate, perPage, page } = options;\n\n if (perPage !== undefined && (!Number.isInteger(perPage) || perPage <= 0)) {\n throw new MastraError({\n id: 'DURABLE_AGENT_LIST_ACTIVE_RUNS_INVALID_PER_PAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" listActiveRuns() requires perPage to be a positive integer.`,\n details: { agentName: this.name, perPage },\n });\n }\n if (page !== undefined && (!Number.isInteger(page) || page < 0)) {\n throw new MastraError({\n id: 'DURABLE_AGENT_LIST_ACTIVE_RUNS_INVALID_PAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" listActiveRuns() requires page to be a non-negative integer.`,\n details: { agentName: this.name, page },\n });\n }\n\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n\n if (!workflowsStore) {\n throw new MastraError({\n id: 'DURABLE_AGENT_LIST_ACTIVE_RUNS_NO_STORAGE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" listActiveRuns() requires storage to discover running runs. ` +\n `Register the agent on a Mastra instance with persistent storage (e.g. PostgreSQL, LibSQL).`,\n details: { agentName: this.name },\n });\n }\n\n const { runs } = await workflowsStore.listWorkflowRuns({\n workflowName: DurableStepIds.AGENTIC_LOOP,\n status: 'running',\n fromDate,\n toDate,\n });\n\n const matchedRuns: DurableAgentActiveRun[] = [];\n for (const run of runs) {\n let snapshot = run.snapshot;\n if (typeof snapshot === 'string') {\n try {\n snapshot = JSON.parse(snapshot) as WorkflowRunState;\n } catch {\n continue;\n }\n }\n if (snapshot?.status !== 'running') continue;\n\n // The persisted workflow input carries the owning agentId. Default-deny:\n // a snapshot without an input or whose agentId does not match this agent\n // is skipped so runs cannot leak across agents sharing the same storage.\n const input = snapshot.context?.input as\n | { agentId?: string; messageListState?: { memoryInfo?: { threadId?: string; resourceId?: string } } }\n | undefined;\n const runAgentId = input?.agentId;\n if (runAgentId !== this.id) continue;\n\n const memoryInfo = input?.messageListState?.memoryInfo;\n const runThreadId = memoryInfo?.threadId;\n const runResourceId = run.resourceId ?? memoryInfo?.resourceId;\n if (threadId && runThreadId !== threadId) continue;\n if (resourceId && runResourceId !== resourceId) continue;\n\n matchedRuns.push({\n runId: run.runId,\n status: 'running',\n threadId: runThreadId,\n resourceId: runResourceId,\n updatedAt: run.updatedAt,\n });\n }\n\n const total = matchedRuns.length;\n const paginatedRuns =\n perPage !== undefined && page !== undefined\n ? matchedRuns.slice(page * perPage, (page + 1) * perPage)\n : matchedRuns;\n\n return { runs: paginatedRuns, total };\n }\n\n /**\n * Bulk recover durable agent runs whose in-process agentic loop was orphaned\n * by a process restart. This is the recovery half of the discovery API\n * paired with {@link DurableAgent.listActiveRuns} and is the typical\n * boot-time hook.\n *\n * Each targeted run is delegated to {@link DurableAgent.recover}, which\n * rebuilds the run's non-serializable state (message list, model, memory,\n * save-queue manager, request context, agent span), re-subscribes to the\n * run's pubsub topic, and restarts the workflow in the background. Because\n * `recover()` registers `memory` + `saveQueueManager` on the run entry, the\n * durable agentic workflow's terminal step flushes new messages to memory\n * just like a fresh `stream()` call would.\n *\n * The per-run stream returned by `recover()` is discarded — this method\n * awaits each run's workflow settlement and reports summary counts instead\n * of surfacing live event streams. Callers who want to observe a specific\n * recovered run's events should use {@link DurableAgent.recover} directly\n * (or {@link DurableAgent.observe} with the returned `runId`).\n *\n * Failures are captured per-run so a single bad run does not block\n * recovery of the rest.\n *\n * @example\n * ```typescript\n * // Recover every orphaned run for this agent (typical boot-time hook).\n * const { recovered, succeeded, failed } = await durableAgent.recoverActiveRuns();\n * logger.info('Recovered durable agent runs', { succeeded, failed });\n *\n * // Recover a single run by ID.\n * await durableAgent.recoverActiveRuns({ runId });\n * ```\n */\n async recoverActiveRuns(\n options: DurableAgentRecoverActiveRunsOptions = {},\n ): Promise<DurableAgentRecoverActiveRunsResult> {\n const { runId, ...discoveryOptions } = options;\n\n let targetRunIds: string[];\n if (runId) {\n targetRunIds = [runId];\n } else {\n const { runs } = await this.listActiveRuns(discoveryOptions);\n targetRunIds = runs.map(r => r.runId);\n }\n\n const recovered: DurableAgentRecoveredRun[] = [];\n let succeeded = 0;\n let failed = 0;\n\n for (const targetRunId of targetRunIds) {\n let runError: Error | undefined;\n try {\n // Delegate to the single-run streamable recover path so each run\n // benefits from the rebuilt registry entry (message list, memory,\n // saveQueueManager, request context, agent span) and the pubsub\n // stream / terminal snapshot-cleanup contract stays identical to\n // `recover()`. We don't surface the per-run stream here — bulk\n // callers only care about counts — so we just await the workflow\n // execution promise that `recover()` parks on the registry entry,\n // capture any failure it surfaces via `onError`, and drop the\n // stream.\n const { cleanup } = await this.recover(targetRunId, {\n onError: ({ error }) => {\n runError = error instanceof Error ? error : new Error(String(error));\n },\n });\n try {\n const workflowExecution = globalRunRegistry.get(targetRunId)?.workflowExecution;\n if (workflowExecution) {\n await workflowExecution;\n }\n } finally {\n cleanup();\n }\n if (runError) throw runError;\n recovered.push({ runId: targetRunId, status: 'success' });\n succeeded++;\n } catch (error) {\n const err = runError ?? (error instanceof Error ? error : new Error(String(error)));\n recovered.push({ runId: targetRunId, status: 'failed', error: err });\n failed++;\n this.#mastra\n ?.getLogger?.()\n ?.error?.(`[DurableAgent] Failed to recover run ${targetRunId}: ${err.message}`, { error: err });\n }\n }\n\n return { recovered, succeeded, failed };\n }\n\n /**\n * Observe an existing stream.\n * Use this to reconnect to a stream after a network disconnection.\n *\n * **Warning:** The returned `cleanup()` function destroys the run's registry\n * entries and cached PubSub events. Only call it when you are done with the\n * run entirely. If the workflow is suspended and you intend to resume later,\n * do not call cleanup — let the auto-cleanup timer handle it after\n * FINISH/ERROR. Auto-cleanup does not fire on SUSPENDED events.\n */\n async observe(\n runId: string,\n options?: {\n offset?: number;\n onChunk?: (chunk: ChunkType<TOutput>) => void | Promise<void>;\n experimentalTransform?: MastraStreamTransformOptions<TOutput>;\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<DurableAgentStreamResult<TOutput>, 'runId'> & { runId: string }> {\n const memoryInfo = this.#runRegistry.getMemoryInfo(runId);\n\n // Track cleanup state to avoid double cleanup\n let cleanedUp = false;\n let autoCleanupTimer: ReturnType<typeof setTimeout> | null = null;\n\n const scheduleAutoCleanup = () => {\n if (autoCleanupTimer || cleanedUp || this.#cleanupTimeoutMs === 0) return;\n autoCleanupTimer = setTimeout(() => {\n if (!cleanedUp) {\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n }, this.#cleanupTimeoutMs);\n };\n\n const {\n output,\n cleanup: streamCleanup,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n messageId: crypto.randomUUID(),\n model: {\n modelId: undefined,\n provider: undefined,\n version: 'v3',\n },\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n offset: options?.offset,\n onChunk: options?.onChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await options?.onError?.(error);\n scheduleAutoCleanup();\n },\n onSuspended: options?.onSuspended,\n structuredOutput: this.#runRegistry.get(runId)?.structuredOutput as any,\n outputProcessors: this.#runRegistry.get(runId)?.outputProcessors,\n messageList: globalRunRegistry.get(runId)?.messageList ?? this.#runRegistry.getMessageList(runId),\n });\n\n // Wait for subscription to be ready\n await ready;\n\n const cleanup = () => {\n if (autoCleanupTimer) {\n clearTimeout(autoCleanupTimer);\n autoCleanupTimer = null;\n }\n if (!cleanedUp) {\n streamCleanup();\n this.#runRegistry.cleanup(runId);\n globalRunRegistry.delete(runId);\n this.#clearPubsubTopic(runId);\n cleanedUp = true;\n }\n };\n\n // observe() doesn't own the run's lifecycle, but for API symmetry the\n // returned `abort` flips the in-process controller currently installed\n // on the registry. If the run already ended (or is running in a\n // different process), this is a best-effort no-op.\n const abort = (reason?: unknown) => {\n const controller = (globalRunRegistry.get(runId) ?? this.#runRegistry.get(runId))?.abortController;\n if (controller && !controller.signal.aborted) {\n controller.abort(reason);\n }\n };\n\n return {\n output,\n get fullStream() {\n return output.fullStream as ReadableStream<any>;\n },\n runId,\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n cleanup,\n abort,\n };\n }\n\n /**\n * Clear retained pubsub state for a run's topic (cached history and, for\n * persistent transports, the underlying stream). Fire-and-forget: the\n * `clearTopic` contract is best-effort and non-throwing.\n *\n * Unlike the evented workflow engine's per-run topic cleanup, this needs no\n * restart guard: cleanup timers arm only on terminal outcomes\n * (FINISH/ERROR/ABORT — never SUSPENDED), `resume()` rejects runs whose\n * snapshot isn't `suspended`, `untilIdle` continuations mint a fresh runId\n * per segment, and cross-process `recover()` can't race a dead process's\n * timer. No supported flow re-engages a runId after its timer is armed.\n */\n #clearPubsubTopic(runId: string): void {\n void this.pubsub.clearTopic(AGENT_STREAM_TOPIC(runId));\n }\n\n /**\n * Read the current number of cached events for this run's stream topic.\n * Used by `resume()` as the subscription offset so we don't re-deliver\n * events emitted by the original run (notably the SUSPENDED chunk that\n * paused it).\n */\n async #getPubsubOffset(runId: string): Promise<number> {\n const pubsub = this.pubsub as PubSub & {\n getHistory?: (topic: string) => Promise<unknown[]>;\n };\n if (typeof pubsub.getHistory !== 'function') return 0;\n try {\n const history = await pubsub.getHistory(AGENT_STREAM_TOPIC(runId));\n return Array.isArray(history) ? history.length : 0;\n } catch {\n return 0;\n }\n }\n\n /**\n * Get the workflow instance for direct execution.\n * Lazily creates the workflow and registers Mastra on it (needed for\n * getAgentById in execution steps).\n */\n getWorkflow() {\n if (!this.#workflow) {\n this.#workflow = this.createWorkflow();\n // Register mastra on the workflow so execution steps can access agents/tools.\n // DurableAgent goes through the normal Agent registration path (not the durable wrapper\n // path that calls addWorkflow), so the workflow isn't registered in Mastra's #workflows.\n // We set mastra directly here instead.\n if (this.#mastra) {\n this.#workflow.__registerMastra(this.#mastra);\n this.#workflow.__registerPrimitives({\n logger: this.#mastra.getLogger(),\n storage: this.#mastra.getStorage(),\n });\n }\n }\n return this.#workflow;\n }\n\n /**\n * @deprecated Use `stream(messages, { untilIdle: true })` instead.\n *\n * Stream until all background tasks complete and the agent is idle.\n * Mirrors the regular Agent's streamUntilIdle but adapted for durable execution.\n */\n // @ts-expect-error - Intentionally different return type for durable execution\n override async streamUntilIdle<OUTPUT = TOutput>(\n messages: MessageListInput,\n streamOptions?: DurableAgentStreamOptions<OUTPUT> & { maxIdleMs?: number },\n ): Promise<DurableAgentStreamResult<OUTPUT>> {\n const { maxIdleMs, ...options } = streamOptions ?? {};\n return this.stream(messages, {\n ...options,\n untilIdle: maxIdleMs === undefined ? true : { maxIdleMs },\n } as DurableAgentStreamOptions<TOutput>) as unknown as Promise<DurableAgentStreamResult<OUTPUT>>;\n }\n\n /**\n * Prepare for durable execution without starting it.\n */\n async prepare(messages: MessageListInput, options?: AgentExecutionOptions<TOutput>) {\n const preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options,\n // Forward the caller-provided runId (mirrors stream()). Without this,\n // prepareForDurableExecution mints a fresh id, so prepare() registers a\n // different run than requested and a follow-up resume(runId) — e.g. when\n // rehydrating a persisted, suspended run in a fresh process — can't find\n // its registry entry.\n runId: options?.runId,\n requestContext: options?.requestContext,\n mastra: this.#mastra,\n });\n\n this.#runRegistry.registerWithMessageList(preparation.runId, preparation.registryEntry, preparation.messageList, {\n threadId: preparation.threadId,\n resourceId: preparation.resourceId,\n });\n globalRunRegistry.set(preparation.runId, {\n ...preparation.registryEntry,\n messageList: preparation.messageList,\n });\n\n return {\n runId: preparation.runId,\n messageId: preparation.messageId,\n workflowInput: preparation.workflowInput,\n registryEntry: preparation.registryEntry,\n threadId: preparation.threadId,\n resourceId: preparation.resourceId,\n };\n }\n\n /**\n * Get the durable workflows required by this agent.\n * Called by Mastra during agent registration.\n * @internal\n */\n getDurableWorkflows() {\n return [this.getWorkflow()];\n }\n\n /**\n * Set the Mastra instance.\n * Called by the durable agent registration path in addAgent().\n * Delegates to __registerMastra so the pubsub wiring and agent\n * registration happen regardless of which entry point is called first.\n * @internal\n */\n __setMastra(mastra: Mastra): void {\n this.__registerMastra(mastra);\n }\n\n /**\n * Register the Mastra instance.\n * Called by Mastra during agent registration (normal Agent path).\n *\n * Also wires mastra.pubsub as the inner pubsub (if the user didn't provide\n * a custom one), so that the OBSERVE_AGENT_STREAM_ROUTE handler can subscribe\n * to the same PubSub instance that this agent publishes to.\n * @internal\n */\n __registerMastra(mastra: Mastra): void {\n super.__registerMastra(mastra);\n this.#mastra = mastra;\n // Also set on wrapped agent\n this.#wrappedAgent.__registerMastra(mastra);\n\n // Wire mastra.pubsub as the inner pubsub if user didn't provide a custom one.\n // This must happen before CachingPubSub initialization.\n if (!this.#hasCustomPubsub && !this.#cachingPubsub) {\n this.#innerPubsub = mastra.pubsub;\n }\n }\n}\n","/**\n * Factory function to create a DurableAgent that wraps an existing Agent.\n *\n * This is the recommended way to add durable execution capabilities to an agent.\n * The factory creates a DurableAgent instance with resumable streams.\n *\n * @example\n * ```typescript\n * import { Agent } from '@mastra/core/agent';\n * import { createDurableAgent } from '@mastra/core/agent/durable';\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 = createDurableAgent({ agent });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: durableAgent },\n * });\n * ```\n */\n\nimport type { MastraServerCache } from '../../cache/base';\nimport type { PubSub } from '../../events/pubsub';\nimport type { Agent } from '../agent';\n\nimport { DurableAgent } from './durable-agent';\nimport type { DurableAgentConfig } from './durable-agent';\n\n/**\n * Options for createDurableAgent factory function.\n */\nexport interface CreateDurableAgentOptions<\n TAgentId extends string = string,\n TTools extends Record<string, any> = Record<string, any>,\n TOutput = undefined,\n> {\n /** The Agent to wrap with durable execution capabilities */\n agent: Agent<TAgentId, TTools, TOutput>;\n\n /** Optional ID override (defaults to agent.id) */\n id?: TAgentId;\n\n /** Optional name override (defaults to agent.name) */\n name?: string;\n\n /**\n * Cache instance for storing stream events.\n * Enables resumable streams - clients can disconnect and reconnect\n * without missing events.\n *\n * - If not provided: Inherits from Mastra instance, or uses InMemoryServerCache\n * - If provided: Uses the provided cache backend (e.g., Redis)\n * - If set to `false`: Disables caching (streams are not resumable)\n */\n cache?: MastraServerCache | false;\n\n /**\n * PubSub instance for streaming events.\n * Optional - if not provided, defaults to EventEmitterPubSub.\n */\n pubsub?: PubSub;\n\n /** Maximum steps for agentic loop */\n maxSteps?: number;\n\n /**\n * Auto-cleanup timer for durable stream state (ms).\n * Set to `0` to disable auto-cleanup. Defaults to `30_000` (30 seconds).\n */\n cleanupTimeoutMs?: number;\n}\n\n/**\n * Create a DurableAgent that wraps an existing Agent.\n *\n * This factory function is the recommended way to add durable execution\n * capabilities to an agent when you need to customize the cache, pubsub, or\n * other advanced options. For the common case, prefer the `durable` config\n * flag on `AgentConfig` — attaching an agent constructed with `durable: true`\n * (or `durable: { … }`) to a `Mastra` instance auto-wraps it at registration.\n *\n * @param options - Configuration options\n * @returns A DurableAgent instance\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 = createDurableAgent({ agent });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: durableAgent },\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Equivalent, using the durable config flag:\n * const agent = new Agent({\n * id: 'my-agent',\n * instructions: 'You are helpful',\n * model: openai('gpt-4'),\n * durable: true,\n * });\n *\n * const mastra = new Mastra({ agents: { myAgent: agent } });\n * ```\n */\nexport function createDurableAgent<\n TAgentId extends string = string,\n TTools extends Record<string, any> = Record<string, any>,\n TOutput = undefined,\n>(options: CreateDurableAgentOptions<TAgentId, TTools, TOutput>): DurableAgent<TAgentId, TTools, TOutput> {\n const { agent, id, name, cache, pubsub, maxSteps, cleanupTimeoutMs } = options;\n\n return new DurableAgent({\n agent,\n id,\n name,\n cache,\n pubsub,\n maxSteps,\n cleanupTimeoutMs,\n } as DurableAgentConfig<TAgentId, TTools, TOutput>);\n}\n\n/**\n * Check if an object is a DurableAgent\n */\nexport function isDurableAgent(obj: any): obj is DurableAgent {\n return obj instanceof DurableAgent;\n}\n\n/**\n * Alias for isDurableAgent for backwards compatibility\n * @deprecated Use isDurableAgent instead\n */\nexport const isLocalDurableAgent = isDurableAgent;\n\n// Re-export types for convenience\nexport type { DurableAgentConfig, DurableAgentStreamOptions, DurableAgentStreamResult } from './durable-agent';\n\n// Backwards compatibility type aliases\nexport type LocalDurableAgent<\n TAgentId extends string = string,\n TTools extends Record<string, any> = Record<string, any>,\n TOutput = undefined,\n> = DurableAgent<TAgentId, TTools, TOutput>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAa,sBAAsB,UAA0B,gBAAgB;;;;AAK7E,MAAa,wBAAwB;;CAEnC,OAAO;;CAEP,YAAY;;CAEZ,aAAa;;CAEb,QAAQ;;CAER,OAAO;;CAEP,WAAW;;CAEX,OAAO;;CAEP,oBAAoB;AACtB;;;;AAKA,MAAa,uBAAuB;;CAElC,WAAW;;;;;;;CAOX,uBAAuB;AACzB;;;;AAKA,MA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