@mastra/core
Version:
1 lines • 1.25 MB
Source Map (JSON)
{"version":3,"file":"index.cjs","names":["getRunRegistryEntry","setRunRegistryEntry","getRunStreamPublisher","isMastraTimeoutError","MastraTimeoutError","runIdleLoop","MessageList","checkThreadFGA","usesOpenAIStrictJsonSchema","toStandardSchema","wrapSchemaWithNullTransform","TTLCache","MemoryMessageRefs","SaveQueueManager","withoutLiveRequestKeys","liveRequestEntries","MASTRA_AUTH_TOKEN_KEY","MastraError","ErrorDomain","ErrorCategory","getRunRegistryEntry","isDurableAgentLike","restoreRequestContext","isApprovalExempt","getNeedsApprovalFn","RequestContext","resolveModelConfig","createRunScopeKey","createRunScope","isMemoryMessageRef","MastraError","delay","createStoredMessageLoader","getRunRegistryEntry","restoreRequestContext","RequestContext","withoutLiveRequestKeys","convertMessages","coreContentToString","noopLogger","getRunRegistryEntry","MessageList","toStandardSchema","createOutputHandler","assertExecutionOwned","resolveOutputMessageSkippingCompletionChecks","isDurableAgentLike","ProcessorRunner","createObservabilityContext","TripWire","undoSavedResponseMessages","MastraFGAPermissions","isExecutionFenceError","isTerminalToolInvocationState","TOOL_ABORT_NOTICE","resolveProcessorWriterMessageId","StructuredOutputProcessor","MessageList","RequestContext","createObservabilityContext","z","CONTINUATION_STOP_CAUSES","normalizeToolCallConcurrency","DurableAgentDefaults","DurableStepIds","z","createStep","PUBSUB_SYMBOL","getRunRegistryEntry","checkBackgroundTasks","emitChunkEvent","getAbortReason","isMastraTimeoutError","DurableOutputProcessorError","DurableChunkPublishError","z","createStep","DurableStepIds","getExecutionOwnershipGuard","PUBSUB_SYMBOL","emitIterationStartEvent","getRunRegistryEntry","ExecutionFence","createSignal","LOCAL_MODEL_REQUEST_KEY","executionFailureTermination","emitChunkEvent","serializeError","agentLoopTermination","resolveMaxProcessorRetries","snapshotSignalOutcome","isSupportedLanguageModel","mergeProviderOptions","TripWire","PrepareStepProcessor","needsTrailingAssistantGuard","ProcessorRunner","expandDurableSteps","composeStepInput","ConsoleLogger","isMastraTool","makeProcessorCoreTool","createMastraProxy","buildLlmPromptArgs","snapshotBackgroundOutcomes","persistUnavailableAttachments","applyAutoResumeSystemMessage","injectBackgroundTaskPrompt","resolveApiProviderId","createRunScope","STEP_MODEL_MESSAGES_KEY","backgroundOutcomesInPrompt","findProviderToolByName","inferProviderExecuted","EntityType","getToolDefinitionsForTracing","sendsNativeResponseFormat","getRootExportSpan","buildMessagesFromChunks","markRunActive","executeWithContextSync","execute","mergeLlmCallHeaders","buildMemoryHeaders","watchInterruptibleStream","MastraModelOutput","startRunStep","createStepStartChunk","processAndEmitChunk","createObservabilityContext","publishStepStartChunk","readToolResultFromMessageList","applyToolPayloadTransformToChunk","getToolResultInvocationState","withToolPayloadTransformProviderMetadata","STEP_CONTENT_CHUNK_TYPES","MastraError","ErrorDomain","ErrorCategory","TERMINAL_FINISH_REASONS","resolveResponseModelId","extractUsageMetrics","isDownloadAssetsError","boundedStringify","getSpanErrorOrigin","z","isMastraTimeoutError","isExecutionFenceError","ProcessorRunner","processAndEmitChunk","emitChunkEvent","createStep","DurableStepIds","getExecutionOwnershipGuard","PUBSUB_SYMBOL","ownToolCallSuspendData","getRunRegistryEntry","compactStopReasonContext","createObservabilityContext","findProviderToolByName","assertExecutionOwned","assertExecutionNotSuperseded","assertExecutionNotSupersededInStorage","restoreRequestContext","MastraFGAPermissions","INTERNAL_APPROVAL_KEYS","applyToolPayloadTransformToChunk","runBeforeApprovalChecks","getModelFacingValidationError","computeModelOutputProviderMetadata","stopGoalActivity","approvalResumeSchema","emitSuspendedEvent","resolveFrameworkSuspendedToolIdentity","resolveDeclineReason","TOOL_ABORT_NOTICE","STEP_MODEL_MESSAGES_KEY","defineLazyWriter","ToolStream","withAgentWorkflowToolMarker","dispatchBackgroundTool","executeAdoptedBackgroundOperation","BACKGROUND_WORK_CONTEXT","runFencedToClaim","validateToolOutput","resolveToolOutputValidationSchema","getToolTitle","getTransformedToolPayload","hasTransformedToolPayload","withToolPayloadTransformProviderMetadata","applyBackgroundToolResult","applyBackgroundToolExecution","takeDelegationFailure","startRunStep","executeToolCall","markRunActive","isProcessorWorkflow","EntityType","normalizeModelOutput","hasToolResultProcessor","snapshotToolResult","readModelOutput","readToolResultFromMessageList","TripWire","resolveModelOutputAfterToolResultProcessors","z","createStep","DurableStepIds","getRunRegistryEntry","MessageList","getSpanErrorOrigin","computeModelOutputProviderMetadata","withToolPayloadTransformProviderMetadata","TOOL_CALL_TERMINAL_FINISH_REASONS","compactDurableStepContent","getAbortReason","isMastraTimeoutError","executionFailureTermination","agentLoopTermination","extractUsageMetrics","MastraFGAPermissions","assertExecutionOwned","isExecutionFenceError","DurableAgentDefaults","createStep","DurableStepIds","z","PUBSUB_SYMBOL","getRunRegistryEntry","restoreRequestContext","MessageList","evaluateTaskCompletion","emitChunkEvent","createStep","z","PUBSUB_SYMBOL","getRunRegistryEntry","restoreRequestContext","evaluateGoal","emitChunkEvent","z","AGENT_STREAM_TOPIC","AgenticLoopBuilder","DurableAgentDefaults","createEventedWorkflow","createWorkflow","pruneAgentLoopSnapshot","getRunRegistryEntry","PUBSUB_SYMBOL","withExecutionStreamProducer","getExecutionClaim","emitChunkEvent","createStep","DurableStepIds","drainSignalsToTranscript","withExecutionFence","isExecutionFenceError","isForeignExecutionContext","buildDeferredStepFinishChunk","currentRunGeneration","diffResponseMessages","getAbortReason","isMastraTimeoutError","getErrorFromUnknown","markNonRedeliverable","MastraError","DURABLE_STOP_WHEN_ERROR_ID","ErrorDomain","ErrorCategory","decideContinuation","durableStopConditionSteps","normalizeToolOutput","emitIterationCompleteEvent","markFrameworkCondition","expandDurableSteps","emitFinishEvent","agentLoopTermination","isUsageIncomplete","calculateObservedUsage","takeRunScorerInstances","DurableStepIds","emitAbortEvent","ExecutionFence","resolveLeaseProvider","supportsRunFencing","withExecutionStreamProducer","fencePubSub","markErrorForStreamRejection","getErrorFromUnknown","getRunRegistryEntry","MastraFGAPermissions","assertExecutionOwned","mastraDBMessageToSignal","RequestContext","getRequestContextInputValues","MastraError","ErrorDomain","ErrorCategory","deepMerge","withDefaultToolCallConcurrencyLimit","incomingAgentScopes","resolveAgentScopes","applyResolvedAgentScopes","MASTRA_VERSIONS_KEY","mergeVersionOverrides","MessageList","MastraFGAPermissions","signalSpanAttributes","getOrCreateSpan","EntityType","modelSpanAttributes","createObservabilityContext","TripWire","executionFailureTermination","snapshotRequestContextEntries","MASTRA_SCOPES_KEY","boundedStringify","fireClientToolOutputHooks","applyClientToolModelOutput","SaveQueueManager","mergeProviderOptions","asJsonSchema","normalizeToolPayloadTransformPolicy","isObservationalMemoryEnabled","createRunScope","LOCAL_MODEL_REQUEST_KEY","getRunRegistryEntry","MASTRA_THREAD_ID_KEY","MASTRA_RESOURCE_ID_KEY","resolveThreadIdFromArgs","RUN_ACTIVE_ERROR_ID","RECOVER_RUN_ACTIVE_LOCALLY_ERROR_ID","RECOVER_ALREADY_IN_PROGRESS_ERROR_ID","Agent","ExtendedRunRegistry","MastraError","ErrorDomain","ErrorCategory","DurableStepIds","readAgentRunRecord","durableReplayOwnerKey","readDurableReplayOwner","getExecutionStreamOwner","DurableExecutionFenceError","agentThreadStreamRuntime","RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID","RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID","RECOVER_RUN_SUSPENDED_ERROR_ID","RECOVER_RUN_NOT_ACTIVE_ERROR_ID","createDurableAgentStream","AgentThreadLeaseConflictError","RequestContext","MessageList","SaveQueueManager","getOrCreateSpan","EntityType","modelSpanAttributes","getResumeTracingContext","deepMerge","withDefaultToolCallConcurrencyLimit","incomingAgentScopes","resolveAgentScopes","applyResolvedAgentScopes","createObservabilityContext","runOutsideRunFenceScope","emitErrorEvent","shouldRejectStream","isMastraTimeoutError","settledOrElapsed","whenRunStepsSettle","DEADLINE_SAVE_WAIT_MS","DEADLINE_SAVE_CLAIM_HOLD_MS","untilIdleHandlesBackgroundTask","getScopeStreamSlot","publishAbortRequest","getRunStreamSlot","requestAcknowledgedAbort","emitAbortEvent","createTimeoutAbortSignal","createRunAbortController","emitChunkEvent","fencePubSub","beginGoalActivity","stopGoalActivity","markResumeInFlight","withoutLiveRequestKeys","MASTRA_SCOPES_KEY","rebindProcessorTools","ExecutionFence","emitOwnershipClaimedEvent","emitFinishEvent","runWithConcurrency","AGENT_STREAM_TOPIC","AgentStreamEventTypes","createSupersededEventFilter","readRunGeneration","supportsRunFencing","createRunGenerationFilter","resolveLeaseProvider","executionLeaseKey","replayResponseMessages","withRebuiltResponseMessages","withAck","isDurableAgentLike","EventEmitterPubSub","DurableExecutionFenceError","getRunRegistryEntry","agentThreadStreamRuntime","createObservabilityContext"],"sources":["../../../src/agent/durable/abort-transport.ts","../../../src/agent/durable/durable-stream-until-idle.ts","../../../src/agent/durable/utils/run-message-list.ts","../../../src/agent/durable/memory-fga.ts","../../../src/agent/durable/structured-output-null-transform.ts","../../../src/agent/durable/run-message-refs.ts","../../../src/agent/durable/utils/resolve-runtime.ts","../../../src/agent/durable/workflows/shared/background-results.ts","../../../src/agent/durable/workflows/shared/message-list-state.ts","../../../src/agent/durable/workflows/finalize-run.ts","../../../src/agent/durable/workflows/shared/execute-scorers.ts","../../../src/agent/durable/workflows/shared/schemas.ts","../../../src/agent/durable/workflows/shared/iteration-state.ts","../../../src/agent/durable/workflows/shared/accumulated-steps.ts","../../../src/agent/durable/workflows/shared/tool-call-concurrency.ts","../../../src/agent/durable/workflows/steps/background-task-check.ts","../../../src/agent/durable/workflows/steps/llm-execution.ts","../../../src/agent/durable/utils/serialize-state.ts","../../../src/agent/durable/workflows/steps/tool-call.ts","../../../src/agent/durable/workflows/steps/llm-mapping.ts","../../../src/agent/durable/utils/restore-completion.ts","../../../src/agent/durable/workflows/steps/is-task-complete.ts","../../../src/agent/durable/workflows/steps/goal.ts","../../../src/agent/durable/workflows/durable-loop-builder.ts","../../../src/agent/durable/workflows/create-durable-agentic-workflow.ts","../../../src/agent/durable/execution-engine.ts","../../../src/agent/durable/persist-run-input.ts","../../../src/agent/durable/preparation.ts","../../../src/agent/durable/run-cleanup.ts","../../../src/agent/durable/utils/resume-generate-args.ts","../../../src/agent/durable/durable-agent.ts","../../../src/agent/durable/create-durable-agent.ts","../../../src/agent/durable/evented-execution-engine.ts","../../../src/agent/durable/evented-agent.ts","../../../src/agent/durable/create-evented-agent.ts","../../../src/agent/durable/workflows/deprecated-tool-execution.ts"],"sourcesContent":["/**\n * Cross-process abort transport for durable agents.\n *\n * `abort()` runs in the caller's process, but a durable run's steps may execute\n * in a different process entirely (a load-balanced server replica, or an Inngest\n * worker). Flipping a local `AbortController` is therefore invisible to the code\n * that is actually driving the model call.\n *\n * These helpers carry the abort *intent* over pubsub so the executing process\n * can flip its own controller and unwind gracefully — emitting the usual\n * `finish` event with reason `abort`. That matters: hard-cancelling the\n * underlying workflow run would tear execution down before the terminal stream\n * event is ever published, leaving stream consumers hanging forever.\n */\nimport type { PubSub } from '../../events';\nimport { isMastraTimeoutError, MastraTimeoutError } from '../../loop/timeout';\nimport type { Mastra } from '../../mastra';\nimport { getRunRegistryEntry, setRunRegistryEntry } from './run-registry';\nimport { getRunStreamPublisher } from './run-stream-publisher';\nimport type { RunRegistryEntry } from './types';\n\nexport { publishAbortRequest, requestAcknowledgedAbort, subscribeToAbortRequests } from '../streams/abort-transport';\n\n/**\n * Make the current process responsive to abort requests for `runId`.\n *\n * Called by durable steps as they start work. The step may be running on a\n * worker that never saw the caller's `abort()`, so this is where that process\n * grows an `AbortController` of its own — the same one every downstream call\n * already reads off the run registry (`registryEntry.abortSignal`), so nothing\n * downstream needs to know abort arrived from elsewhere.\n *\n * Idempotent: a run executes many steps in the same process, and each of them\n * calls this. The subscription is torn down with the registry entry, whether\n * that happens on explicit cleanup or TTL eviction.\n */\nexport async function ensureRemoteAbortListener(\n pubsub: PubSub,\n runId: string,\n mastra?: Mastra,\n deadline?: RunDeadline,\n): Promise<void> {\n let entry = getRunRegistryEntry(runId, mastra);\n\n if (!entry) {\n // A worker can reach its first step before anything has populated the\n // registry for this run. Returning early here would leave that run\n // permanently deaf to remote aborts, so seed a minimal entry instead. It is\n // marked as a placeholder (and carries no model) so `resolveRuntimeDependencies`\n // still rebuilds the real runtime state into it rather than trusting it.\n entry = { isPlaceholder: true } as RunRegistryEntry;\n // Another instance's live run holds this runId; don't wire our abort to it.\n if (!setRunRegistryEntry(runId, entry, mastra)) return;\n }\n\n // The owner process already has a controller wired to its `abort()`. A worker\n // rebuilding state from storage has none, so give it one — flipping it is\n // what actually stops the model call.\n if (!entry.abortController) giveWorkerController(entry);\n\n // The deadline's abort request is published once, live. A worker that subscribes after it went\n // out never hears it, so the run's deadline also travels with the run and is armed here. It is\n // armed whether or not the subscription below succeeds, and re-armed when a resumed segment\n // on a warm worker carries a new deadline.\n syncRunDeadline(entry, deadline);\n\n if (entry.remoteAbortListenerInstalled) return;\n\n // Claim before awaiting: two steps starting concurrently in this process\n // would otherwise both pass the check and install duplicate subscriptions.\n entry.remoteAbortListenerInstalled = true;\n\n const publisher = getRunStreamPublisher(runId, entry, mastra);\n const listener = publisher.listenForAbort(pubsub, () => {\n const controller = getRunRegistryEntry(runId, mastra)?.abortController ?? entry.abortController;\n if (controller && !controller.signal.aborted) controller.abort(new Error('Aborted'));\n });\n try {\n await listener.ready;\n } catch (error) {\n await listener.detach();\n // Release the claim so the next step retries a transient subscription failure.\n entry.remoteAbortListenerInstalled = false;\n throw error;\n }\n}\n\n/** Controllers this module created for a worker that had none, as opposed to an owner's controller wired to its `abort()`. */\nconst workerControllers = new WeakSet<AbortController>();\n\nfunction giveWorkerController(entry: RunRegistryEntry): void {\n const controller = new AbortController();\n workerControllers.add(controller);\n entry.abortController = controller;\n entry.abortSignal = controller.signal;\n}\n\n/**\n * A new segment is starting on a warm worker. If the previous segment's total deadline already\n * stopped the worker's own controller (e.g. it passed while the run was suspended), the resumed\n * segment gets a fresh one instead of inheriting that abort. Any other abort is kept.\n */\nfunction replaceTimedOutWorkerController(entry: RunRegistryEntry): void {\n const controller = entry.abortController;\n if (!controller || !workerControllers.has(controller) || !controller.signal.aborted) return;\n const reason: unknown = controller.signal.reason;\n if (!isMastraTimeoutError(reason) || reason.timeoutType !== 'total') return;\n giveWorkerController(entry);\n}\n\n/** The deadline each entry currently has armed, and the controller it stops, so a later segment can replace it. */\nconst armedDeadlines = new WeakMap<\n RunRegistryEntry,\n { at: number; controller?: AbortController; timer?: ReturnType<typeof setTimeout> }\n>();\n\n/** Arm the entry's deadline, replacing a timer armed for a different deadline. */\nfunction syncRunDeadline(entry: RunRegistryEntry, deadline: RunDeadline | undefined): void {\n const armed = armedDeadlines.get(entry);\n if (armed && armed.at !== deadline?.at) replaceTimedOutWorkerController(entry);\n if (!deadline) {\n // A segment without a deadline (e.g. resumed without totalMs) must not inherit the last one's.\n if (armed) {\n clearTimeout(armed.timer);\n armedDeadlines.delete(entry);\n }\n return;\n }\n // A warm resume swaps a fresh controller onto the entry, so the timer is re-armed for it too.\n if (armed?.at === deadline.at && armed.controller === entry.abortController) return;\n if (armed) {\n clearTimeout(armed.timer);\n } else {\n const previousCleanup = entry.cleanup;\n entry.cleanup = () => {\n try {\n previousCleanup?.();\n } finally {\n clearTimeout(armedDeadlines.get(entry)?.timer);\n armedDeadlines.delete(entry);\n }\n };\n }\n const controller = entry.abortController;\n armedDeadlines.set(entry, { at: deadline.at, controller, timer: armRunDeadline(controller, deadline) });\n}\n\n/**\n * Request-context key the caller sets to the run's absolute total deadline for one execution\n * segment (stream or resume), so every worker can stop at it on its own clock.\n */\nexport const RUN_DEADLINE_KEY = '__mastra_runDeadline';\n\n/** The run's total deadline: when it fires (epoch ms) and the budget it enforces. */\nexport type RunDeadline = { at: number; timeoutMs: number };\n\n/** The run deadline a step's request context carries, if any. */\nexport function readRunDeadline(requestContext?: { get(key: string): unknown }): RunDeadline | undefined {\n const value = requestContext?.get(RUN_DEADLINE_KEY) as Partial<RunDeadline> | undefined;\n if (typeof value?.at !== 'number' || typeof value.timeoutMs !== 'number') return undefined;\n return { at: value.at, timeoutMs: value.timeoutMs };\n}\n\n/**\n * Abort the controller with the deadline's timeout error now, or when the deadline arrives.\n * The timer is bound to the controller it was armed for: a warm resume swaps a fresh controller\n * onto the entry, and the previous segment's timer must not stop the resumed segment.\n */\nfunction armRunDeadline(\n controller: AbortController | undefined,\n deadline: RunDeadline,\n): ReturnType<typeof setTimeout> | undefined {\n const expire = () => {\n if (controller && !controller.signal.aborted) {\n controller.abort(new MastraTimeoutError({ timeoutType: 'total', timeoutMs: deadline.timeoutMs }));\n }\n };\n const remaining = deadline.at - Date.now();\n if (remaining <= 0) {\n expire();\n return undefined;\n }\n const timer = setTimeout(expire, remaining);\n timer.unref?.();\n return timer;\n}\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 * - The initial segment preserves a caller-supplied runId; each autonomous continuation starts a new durable workflow\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: async (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 await Promise.all(\n innerAborts.map(async innerAbort => {\n try {\n await innerAbort(reason);\n } catch {\n // ignore — best-effort abort across siblings\n }\n }),\n );\n ctx.abort();\n },\n };\n },\n {\n detachOnCancel: streamOptions?._detachObserverOnCancel === true,\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 onAbortActive: () => {\n const abort = innerAborts.at(-1);\n if (!abort) return;\n try {\n void Promise.resolve(abort(new Error('Aborted'))).catch(() => {});\n } catch {\n // ignore\n }\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 // The wrapper takes the resumed run's slot up front so it supersedes the run's parked wrapper.\n { ...streamOptions, runId },\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: async (reason?: unknown) => {\n await Promise.all(\n innerAborts.map(async innerAbort => {\n try {\n await innerAbort(reason);\n } catch {\n // ignore\n }\n }),\n );\n ctx.abort();\n },\n };\n },\n {\n detachOnCancel: streamOptions?._detachObserverOnCancel === true,\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 onAbortActive: () => {\n const abort = innerAborts.at(-1);\n if (!abort) return;\n try {\n void Promise.resolve(abort(new Error('Aborted'))).catch(() => {});\n } catch {\n // ignore\n }\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 { Mastra } from '../../../mastra';\nimport { MessageList } from '../../message-list';\n\n/** The id generator does not survive the serialize/deserialize round-trip a durable run makes on every step. */\nexport function createRunMessageList({\n mastra,\n threadId,\n resourceId,\n}: {\n mastra?: Mastra;\n threadId?: string;\n resourceId?: string;\n}): MessageList {\n return new MessageList({ threadId, resourceId, generateMessageId: mastra?.generateId?.bind(mastra) });\n}\n","import type { MastraFGAPermissionInput } from '../../auth/ee';\nimport type { CheckThreadFGAOptions } from '../../memory/thread-fga';\nimport { checkThreadFGA } from '../../memory/thread-fga';\nimport type { RunRegistryEntry } from './types';\n\nexport function getDurableMemoryAuthorizationChecks(\n entry?: RunRegistryEntry,\n): Map<MastraFGAPermissionInput, Promise<void>> {\n if (!entry) return new Map();\n return (entry.memoryAuthorizationChecks ??= new Map());\n}\n\nexport function authorizeDurableMemory(\n checks: Map<MastraFGAPermissionInput, Promise<void>>,\n options: CheckThreadFGAOptions & { permission: MastraFGAPermissionInput },\n): Promise<void> {\n const existingCheck = checks.get(options.permission);\n if (existingCheck) return existingCheck;\n\n const check = checkThreadFGA(options).catch(error => {\n checks.delete(options.permission);\n throw error;\n });\n checks.set(options.permission, check);\n return check;\n}\n","import { wrapSchemaWithNullTransform } from '@mastra/schema-compat';\nimport type { SharedProviderOptions } from '../../llm/model/shared.types';\nimport { toStandardSchema } from '../../schema';\nimport { usesOpenAIStrictJsonSchema } from '../../stream/aisdk/v5/execute';\n\ntype StrictModel = Parameters<typeof usesOpenAIStrictJsonSchema>[0];\n\n/**\n * Mirrors the check in `Agent.#execute`: OpenAI-style strict JSON schema models answer\n * omitted optional fields with `null`, so the live schema must map `null` back to `undefined`.\n */\nexport function needsNullToUndefined(\n model: StrictModel & { modelId?: string },\n providerOptions?: SharedProviderOptions,\n) {\n return (\n model.provider.includes('openai') ||\n Boolean(model.modelId?.includes('openai')) ||\n usesOpenAIStrictJsonSchema(model, providerOptions)\n );\n}\n\n/** Builds a live standard schema from a persisted JSON Schema, applying the null transform when flagged. */\nexport function toLiveStructuredOutputSchema<T = unknown>(schema: unknown, nullToUndefined?: boolean) {\n const standard = toStandardSchema<any>(schema as any);\n return (nullToUndefined ? wrapSchemaWithNullTransform(standard) : standard) as ReturnType<typeof toStandardSchema<T>>;\n}\n","import { TTLCache } from '@isaacs/ttlcache';\nimport type { MastraDBMessage } from '../message-list';\nimport { MemoryMessageRefs } from '../message-list/memory-message-refs';\n\n/**\n * Messages each run knows memory storage holds — recalled ones it verified and\n * ones it saved itself — shared by every step this process runs for it. Losing\n * an entry only costs a storage read (or keeps saved messages inline until the\n * next save).\n */\nconst runMessageRefs = new TTLCache<string, MemoryMessageRefs>({\n max: 1000,\n ttl: 10 * 60 * 1000,\n updateAgeOnGet: true,\n});\n\nexport function getRunMessageRefs(runId: string | undefined): MemoryMessageRefs {\n let refs = runId ? runMessageRefs.get(runId) : undefined;\n if (!refs) {\n refs = new MemoryMessageRefs();\n if (runId) runMessageRefs.set(runId, refs);\n }\n return refs;\n}\n\n/** The run's refs if this process holds them, without creating an entry. */\nexport function peekRunMessageRefs(runId: string | undefined): MemoryMessageRefs | undefined {\n return runId ? runMessageRefs.get(runId) : undefined;\n}\n\nexport function releaseRunMessageRefs(runId: string | undefined): void {\n if (runId) runMessageRefs.delete(runId);\n}\n\n/**\n * A `SaveQueueManager` `onSaved` callback that records the rows a run saved,\n * so its persisted transcript references them instead of repeating them. Only\n * runs that store refs hold an entry (the transcript store creates it), so saves\n * for other runs, or landing after the run released its entry, are not kept.\n */\nexport function recordRunSavedMessages(runId: string): (rows: MastraDBMessage[]) => void {\n return rows => {\n const refs = peekRunMessageRefs(runId);\n if (!refs) return;\n const byThread = new Map<string, MastraDBMessage[]>();\n for (const row of rows) {\n if (!row.threadId) continue;\n const key = `${row.threadId}\\u0000${row.resourceId ?? ''}`;\n byThread.set(key, [...(byThread.get(key) ?? []), row]);\n }\n for (const threadRows of byThread.values()) {\n const { threadId, resourceId } = threadRows[0]!;\n refs.recordSaved(threadRows, { threadId: threadId!, resourceId });\n }\n };\n}\n","import type { ToolSet } from '@internal/ai-sdk-v5';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../../error';\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 LLMRequestProcessorOrWorkflow,\n OutputProcessorOrWorkflow,\n} from '../../../processors';\nimport { MASTRA_AUTH_TOKEN_KEY, RequestContext, withoutLiveRequestKeys } from '../../../request-context';\nimport { getNeedsApprovalFn, isApprovalExempt } from '../../../tools/toolchecks';\nimport type { CoreTool, RequireToolApproval, ToolApprovalContext } from '../../../tools/types';\nimport type { Workspace } from '../../../workspace';\nimport type { Agent } from '../../agent';\nimport type { MessageList } from '../../message-list';\nimport { liveRequestEntries, restoreRequestContext } from '../../request-context-snapshot';\nimport { SaveQueueManager } from '../../save-queue';\nimport type { ToolsInput } from '../../types';\nimport { isDurableAgentLike } from '../../types';\nimport { recordRunSavedMessages } from '../run-message-refs';\nimport { getRunRegistryEntry, globalRunRegistry, setRunRegistryEntry } from '../run-registry';\nimport type {\n RunRegistryEntry,\n SerializableDurableState,\n SerializableDurableOptions,\n SerializableModelConfig,\n SerializableModelListEntry,\n SerializableToolMetadata,\n DurableAgenticWorkflowInput,\n RegistryModelListEntry,\n} from '../types';\nimport { createRunMessageList } from './run-message-list';\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 processors for processLLMRequest: input processors plus error-phase processors */\n llmRequestInputProcessors?: LLMRequestProcessorOrWorkflow[];\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(\n memory: MastraMemory | undefined,\n runId: string,\n mastra?: Mastra,\n): SaveQueueManager | undefined {\n if (!memory) return undefined;\n return new SaveQueueManager({ logger: mastra?.getLogger?.(), memory, onSaved: recordRunSavedMessages(runId) });\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 /**\n * The step's run-level RequestContext, used when the step input carries no\n * `requestContextEntries` snapshot. See `restoreRequestContext`.\n */\n requestContext?: RequestContext;\n /** Logger for debugging */\n logger?: { debug?: (...args: any[]) => void; error?: (...args: any[]) => void };\n}\n\nexport { restoreRequestContext };\n\n/**\n * The run's `requestContextEntries` as handed to scorers (`customContext`), with\n * the signed-in user taken from the live run-level context rather than the\n * snapshot. The bearer token is never included.\n */\nexport function restoreCustomContext(\n entries?: Record<string, unknown>,\n runLevel?: RequestContext,\n): Record<string, unknown> | undefined {\n if (!entries) return undefined;\n return Object.fromEntries([\n ...Object.entries(withoutLiveRequestKeys(entries)),\n ...liveRequestEntries(runLevel).filter(([key]) => key !== MASTRA_AUTH_TOKEN_KEY),\n ]);\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\nasync function rebuildProcessorPipeline(options: {\n agent: any;\n agentId: string;\n requestContext: RequestContext;\n emptyErrorProcessorOverride?: boolean;\n processorStates?: Map<string, ProcessorState>;\n logger?: { error?: (...args: any[]) => void };\n}) {\n const { agent, agentId, requestContext, emptyErrorProcessorOverride, processorStates, logger } = options;\n\n try {\n const inputProcessors = await agent.listInputProcessors?.(requestContext);\n const outputProcessors = await agent.listOutputProcessors?.(requestContext);\n const errorProcessorOverride = emptyErrorProcessorOverride ? [] : undefined;\n const errorProcessors = (await agent.__resolveRunErrorProcessors?.(requestContext, errorProcessorOverride))\n ?.errorProcessors;\n const llmRequestInputProcessors = await agent.__listLLMRequestProcessors?.(requestContext, errorProcessors);\n\n return {\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates: processorStates ?? new Map<string, ProcessorState>(),\n };\n } catch (processorError) {\n logger?.error?.(`[DurableAgent:${agentId}] Failed to rebuild processors from Mastra: ${processorError}`);\n throw new DurableProcessorRebuildError(agentId, processorError);\n }\n}\n\n/** True when the registry entry was seeded in this process (not a cross-process placeholder). */\nfunction isHydratedRegistryEntry(entry: RunRegistryEntry | undefined): boolean {\n const model = entry?.model as (MastraLanguageModel & { __metadataOnly?: boolean }) | undefined;\n return !!entry && entry.isPlaceholder !== true && !!model && model.__metadataOnly !== true;\n}\n\n/**\n * Throws when call-time `toolsets` tools named in the durable options are missing\n * after a cross-process rebuild, instead of silently running without them.\n */\nfunction assertToolsetToolsAvailable(\n tools: Record<string, unknown>,\n toolsetToolNames: string[] | undefined,\n agentId: string,\n runId: string,\n): void {\n const missingToolsetTools = (toolsetToolNames ?? []).filter(name => !(name in tools));\n if (missingToolsetTools.length > 0) {\n throw new MastraError({\n id: 'DURABLE_AGENT_TOOLSETS_UNAVAILABLE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `Call-time toolsets tool(s) ${missingToolsetTools.map(n => `\"${n}\"`).join(', ')} are not available ` +\n `to durable agent \"${agentId}\" in this worker process. Toolset tools contain server-side code that ` +\n `cannot be serialized across processes; register them on the agent (statically or via requestContext) instead.`,\n details: { agentId, runId, missingTools: missingToolsetTools.join(',') },\n });\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 = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const messageList = existingEntry?.messageList\n ? existingEntry.messageList.deserialize(input.messageListState)\n : createRunMessageList({\n mastra,\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 = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const hasHydratedEntry = isHydratedRegistryEntry(globalEntry);\n // Prefer the full toolset over `tools`: after the first step `tools` holds the\n // per-step snapshot the model was shown (possibly narrowed by processors such\n // as ToolSearchProcessor), and seeding from it would drop every tool the\n // processors withheld on the previous step (issue #22933).\n let tools: Record<string, CoreTool> = globalEntry?.baseTools ?? 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: LLMRequestProcessorOrWorkflow[] | 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 let rebuiltAgent: Agent<any, any, any, any> | undefined;\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 rebuiltAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;\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, options.requestContext);\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 clientTools: input.options?.clientTools as ToolsInput | undefined,\n });\n assertToolsetToolsAvailable(tools, input.options?.toolsetToolNames, agentId, runId);\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 const rebuiltProcessors = await rebuildProcessorPipeline({\n agent,\n agentId,\n requestContext: resolveRequestContext,\n emptyErrorProcessorOverride: input.options?.emptyErrorProcessorOverride,\n processorStates: globalEntry?.processorStates,\n logger,\n });\n inputProcessors = rebuiltProcessors.inputProcessors;\n llmRequestInputProcessors = rebuiltProcessors.llmRequestInputProcessors;\n outputProcessors = rebuiltProcessors.outputProcessors;\n errorProcessors = rebuiltProcessors.errorProcessors;\n processorStates = rebuiltProcessors.processorStates;\n\n rehydratedFromMastra = true;\n } catch (error) {\n if (error instanceof DurableProcessorRebuildError) throw error;\n if ((input.options?.toolsetToolNames?.length ?? 0) > 0) 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 // Build this before the registry write-back. On a remote worker that\n // write-back is what makes finish-time persistence available to later steps.\n const saveQueueManager = makeSaveQueueManager(memory, runId, mastra);\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 saveQueueManager,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n agent: rebuiltAgent,\n };\n if (globalEntry) {\n Object.assign(globalEntry, rebuilt);\n } else {\n setRunRegistryEntry(runId, rebuilt as RunRegistryEntry, mastra as Mastra | undefined);\n }\n }\n\n // 3. 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 inputProcessors?: InputProcessorOrWorkflow[];\n llmRequestInputProcessors?: LLMRequestProcessorOrWorkflow[];\n outputProcessors?: OutputProcessorOrWorkflow[];\n errorProcessors?: ErrorProcessorOrWorkflow[];\n processorStates?: Map<string, ProcessorState>;\n /**\n * The restored RequestContext the rebuilt tools were BUILT with (their\n * closures capture this instance, not the step's own). Exposed so the\n * tool-call step can read back by-reference signals a tool wrapper writes\n * to its build-time context — e.g. the delegation bail flag — which would\n * otherwise be invisible cross-process.\n */\n requestContext: RequestContext;\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 `getRunRegistryEntry(runId, mastra as Mastra | undefined)` 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 /**\n * The step's run-level RequestContext, used when `requestContextEntries` is\n * absent. See `restoreRequestContext`.\n */\n requestContext?: RequestContext;\n /** Restore processors for tool execution, not persistence-only rebuilds. */\n rehydrateProcessors?: boolean;\n logger?: { debug?: (...args: any[]) => void; error?: (...args: any[]) => void };\n}): Promise<RebuiltRunTools | undefined> {\n const {\n mastra,\n runId,\n agentId,\n state,\n options: execOptions,\n requestContextEntries,\n requestContext,\n logger,\n } = options;\n if (!mastra) return undefined;\n\n let agentResolved = false;\n try {\n const agent = mastra.getAgentById(agentId);\n agentResolved = true;\n const processorAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;\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, requestContext);\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 clientTools: execOptions?.clientTools as ToolsInput | undefined,\n });\n\n // A hydrated entry means the caller's process still holds the toolset tools\n // (e.g. a memoryless run rebuilding only for a save queue), so nothing was lost.\n const toolsetsLocal = isHydratedRegistryEntry(getRunRegistryEntry(runId, mastra as Mastra | undefined));\n if (!toolsetsLocal) assertToolsetToolsAvailable(tools, execOptions?.toolsetToolNames, agentId, runId);\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, runId, mastra);\n let existing = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const rebuiltProcessors: Partial<Awaited<ReturnType<typeof rebuildProcessorPipeline>>> =\n !options.rehydrateProcessors\n ? {}\n : existing?.outputProcessors && existing.processorStates\n ? {\n inputProcessors: existing.inputProcessors,\n llmRequestInputProcessors: existing.llmRequestInputProcessors,\n outputProcessors: existing.outputProcessors,\n errorProcessors: existing.errorProcessors,\n processorStates: existing.processorStates,\n }\n : await rebuildProcessorPipeline({\n agent,\n agentId,\n requestContext: resolveRequestContext,\n emptyErrorProcessorOverride: execOptions?.emptyErrorProcessorOverride,\n processorStates: existing?.processorStates,\n logger,\n });\n\n // Write back so sibling steps in this process reuse the rebuilt tools and\n // processor pipeline. Only fill fields the entry is missing — never clobber\n // live per-request instances from a populated in-process entry.\n const patch: Partial<RunRegistryEntry> = {\n tools,\n workspace,\n memory,\n saveQueueManager,\n agent: processorAgent,\n ...rebuiltProcessors,\n ...(options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}),\n };\n // A sibling may have published during construction. Keep lookup, merge and return synchronous.\n existing = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n if (existing) {\n const needsProcessorPipeline = !existing.outputProcessors || !existing.processorStates;\n if (\n options.rehydrateProcessors &&\n ((existing.isPlaceholder && needsProcessorPipeline) || !existing.requestContext)\n ) {\n existing.requestContext = resolveRequestContext;\n }\n const registryModel = existing.model as { __metadataOnly?: boolean } | undefined;\n const hasAuthoritativeToolSnapshot =\n existing.isPlaceholder !== true &&\n !!registryModel &&\n registryModel.__metadataOnly !== true &&\n (existing.baseTools !== undefined || existing.tools !== undefined);\n if (!hasAuthoritativeToolSnapshot && Object.keys(existing.tools ?? {}).length === 0) existing.tools = tools;\n existing.workspace ??= workspace;\n existing.memory ??= memory;\n existing.saveQueueManager ??= saveQueueManager;\n existing.inputProcessors ??= rebuiltProcessors.inputProcessors;\n existing.llmRequestInputProcessors ??= rebuiltProcessors.llmRequestInputProcessors;\n existing.outputProcessors ??= rebuiltProcessors.outputProcessors;\n existing.errorProcessors ??= rebuiltProcessors.errorProcessors;\n existing.processorStates ??= rebuiltProcessors.processorStates;\n existing.agent ??= processorAgent;\n } else {\n existing = patch as RunRegistryEntry;\n setRunRegistryEntry(runId, existing, mastra as Mastra | undefined);\n }\n\n return {\n tools,\n workspace,\n memory,\n saveQueueManager,\n inputProcessors: existing.inputProcessors,\n llmRequestInputProcessors: existing.llmRequestInputProcessors,\n outputProcessors: existing.outputProcessors,\n errorProcessors: existing.errorProcessors,\n processorStates: existing.processorStates,\n requestContext: resolveRequestContext,\n };\n } catch (error) {\n if (error instanceof DurableProcessorRebuildError) throw error;\n\n const entry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n // Falling back would silently drop call-time toolsets, so surface the failure.\n if ((execOptions?.toolsetToolNames?.length ?? 0) > 0 && !isHydratedRegistryEntry(entry)) {\n throw error;\n }\n if (agentResolved && options.rehydrateProcessors && (!entry?.outputProcessors || !entry.processorStates)) {\n throw new DurableProcessorRebuildError(agentId, error);\n }\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 * - Approval-exempt tools (skill tools) never require approval.\n * - A per-tool `needsApprovalFn` is authoritative when\n * present and overrides the seed. It receives `{ requestContext, workspace }`\n * as its second argument, exactly like the non-durable loop.\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 if (isApprovalExempt(tool)) return false;\n\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\n const needsApprovalFn = getNeedsApprovalFn(tool);\n if (needsApprovalFn) {\n try {\n requires = !!(await needsApprovalFn(args ?? {}, {\n requestContext: approvalContext?.requestContext,\n workspace: approvalContext?.workspace,\n }));\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 { createRunScope, createRunScopeKey } from '../../../../mastra/run-scope';\nimport type { MessageList } from '../../../message-list';\nimport type { RunRegistryEntry } from '../../types';\n\n/**\n * A background tool result this process applied, kept so later steps can write it into their transcript.\n *\n * `onResult` writes a finished task into the message list the tool-call step held. Later steps rebuild\n * the transcript from workflow state, which still holds the placeholder, so without this the next model\n * call would see the placeholder and the final save would write it over the stored result.\n */\nexport type BackgroundResultRecord = {\n toolCallId: string;\n /** Resolves once `onResult` has finished, whether or not it applied the result. */\n settled: Promise<unknown>;\n done?: boolean;\n /** Writes the result into a transcript without saving it. Set by `onResult`. */\n apply?: (messageList: MessageList) => Promise<void>;\n};\n\nconst BACKGROUND_RESULTS = createRunScopeKey<Map<string, BackgroundResultRecord>>('durable-background-results');\n\n/** Returns the record for `taskId`, replacing one left by an earlier attempt of the tool-call step. */\nexport function recordBackgroundResult(\n entry: RunRegistryEntry,\n taskId: string,\n toolCallId: string,\n settled: Promise<unknown>,\n): BackgroundResultRecord {\n const scope = (entry.runScope ??= createRunScope());\n let records = scope.get(BACKGROUND_RESULTS);\n if (!records) scope.set(BACKGROUND_RESULTS, (records = new Map()));\n let record = records.get(taskId);\n if (record?.settled !== settled) {\n const created: BackgroundResultRecord = { toolCallId, settled };\n void settled.then(() => (created.done = true));\n records.set(taskId, (record = created));\n }\n return record;\n}\n\n/** Whether `onResult` has applied any result that a transcript may still need. */\nexport function hasAppliedBackgroundResults(entry: RunRegistryEntry | undefined): boolean {\n for (const record of entry?.runScope?.get(BACKGROUND_RESULTS)?.values() ?? []) {\n if (record.apply) return true;\n }\n return false;\n}\n\nfunction holdsPlaceholder(messageList: MessageList, taskId: string, toolCallId: string): boolean {\n return messageList.get.all.db().some(\n message =>\n message.role === 'assistant' &&\n message.content?.parts?.some(part => {\n if (part.type !== 'tool-invocation' || part.toolInvocation?.toolCallId !== toolCallId) return false;\n const backgroundTask = (part.providerMetadata as any)?.mastra?.backgroundTask;\n return backgroundTask?.taskId === taskId && backgroundTask.status === 'running';\n }),\n );\n}\n\n/**\n * Writes every result `onResult` has applied into `messageList` where it still shows that task's\n * placeholder. Returns whether anything changed.\n */\nexport async function foldBackgroundResults(\n entry: RunRegistryEntry | undefined,\n messageList: MessageList,\n): Promise<boolean> {\n let changed = false;\n for (const [taskId, record] of entry?.runScope?.get(BACKGROUND_RESULTS) ?? []) {\n if (!record.apply || !holdsPlaceholder(messageList, taskId, record.toolCallId)) continue;\n await record.apply(messageList);\n changed = true;\n }\n return changed;\n}\n\n/**\n * A task's status turns terminal before its `onResult` hook runs. Waits for the hooks of recorded tasks\n * that `isFinished` reports done, giving up after `timeoutMs` so a lost completion event cannot hang the step.\n */\nexport async function settleFinishedBackgroundResults(\n entry: RunRegistryEntry | undefined,\n isFinished: (taskId: string) => Promise<boolean>,\n timeoutMs: number,\n): Promise<void> {\n const finished: Promise<unknown>[] = [];\n for (const [taskId, record] of entry?.runScope?.get(BACKGROUND_RESULTS) ?? []) {\n if (!record.done && (await isFinished(taskId))) finished.push(record.settled);\n }\n if (finished.length === 0) return;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([Promise.all(finished), new Promise(resolve => (timer = setTimeout(resolve, timeoutMs)))]);\n } finally {\n clearTimeout(timer);\n }\n}\n","import { MastraError } from '../../../../error';\nimport type { Mastra } from '../../../../mastra';\nimport type { MastraMemory } from '../../../../memory/memory';\nimport type { RequestContext } from '../../../../request-context';\nimport { delay } from '../../../../utils';\nimport type { WorkflowRunState } from '../../../../workflows/types';\nimport { createStoredMessageLoader, isMemoryMessageRef } from '../../../message-list/memory-message-refs';\nimport type { DehydratedMessageListState, StoredMessageLoader } from '../../../message-list/memory-message-refs';\nimport type { SerializedMessageListState } from '../../../message-list/state';\nimport { getRunMessageRefs, peekRunMessageRefs, releaseRunMessageRefs } from '../../run-message-refs';\nimport { getRunRegistryEntry } from '../../run-registry';\nimport type { SerializableDurableState } from '../../types';\nimport { restoreRequestContext } from '../../utils/resolve-runtime';\n\ntype MessageListStateCarrier = { messageListState?: SerializedMessageListState };\ntype StoredMessageListStateCarrier = { messageListState?: DehydratedMessageListState };\n\n/** The run identity and services these helpers use. */\ntype RunParams = {\n getInitData(): unknown;\n mastra?: Mastra;\n requestContext?: RequestContext<any>;\n abortSignal?: AbortSignal;\n};\n\n/** The parts of a durable step's (or the loop predicate's) params these helpers use. */\ntype TranscriptParams = RunParams & { getState(keys?: readonly string[]): Promise<unknown> };\n\ntype WritableTranscriptParams = TranscriptParams & { setState(state: unknown): Promise<void> };\n\n/**\n * Where the serialized transcript (`messageListState`) lives between steps.\n *\n * The durable loop seeds it into workflow state once (`init-iteration-state`),\n * so every persisted snapshot carries a single copy in `value` instead of one\n * per step payload. Runs that never seeded it — those persisted before the\n * move, or workflows composing these steps without seeding — keep threading\n * it through step input/output unchanged.\n *\n * In workflow state, messages memory already stores (recalled, or saved by\n * this run) are kept as refs to their memory rows (see {@link MemoryMessageRefs}): reads restore them, writes\n * re-create them. Step payloads carry the full transcript while a step runs;\n * {@link dehydrateSnapshotTranscripts} swaps in refs when a snapshot is persisted.\n */\nexport async function readMessageListState(\n params: TranscriptParams,\n stepPayload: unknown,\n): Promise<SerializedMessageListState> {\n // Every durable run carries the transcript in at least one of the two;\n // workflow state wins.\n // A payload read back from a persisted snapshot can hold refs too.\n const stored =\n ((await params.getState(['messageListState'])) as StoredMessageListStateCarrier | undefined)?.messageListState ??\n (stepPayload as StoredMessageListStateCarrier | undefined)?.messageListState;\n if (!stored?.messages?.some(isMemoryMessageRef)) return stored as SerializedMessageListState;\n return hydrateMidRun(runTranscriptRefs(params), stored, params.abortSignal);\n}\n\n/**\n * Stores an updated transcript where this run keeps it. Returns the fields to\n * spread into the step output: nothing when it went to workflow state,\n * `{ messageListState }` when the run threads it through step payloads.\n */\nexport async function storeMessageListState(\n params: WritableTranscriptParams,\n messageListState: SerializedMessageListState,\n): Promise<MessageListStateCarrier> {\n const stored = (await params.getState(['messageListState'])) as StoredMessageListStateCarrier | undefined;\n if (stored?.messageListState === undefined) {\n return { messageListState };\n }\n await params.setState({ messageListState: await dehydrateMessageListState(params, messageListState) });\n return {};\n}\n\n/**\n * The transcript for code that reads and rewrites it in place across several\n * phases (the continuation predicate): restored once up front, then `write`\n * keeps the live copy and stores it back where it came from.\n */\nexport async function openMessageListState(\n params: TranscriptParams,\n stepPayload: MessageListStateCarrier,\n): Promise<{ read(): SerializedMessageListState; write(next: SerializedMessageListState): void }> {\n // The predicate can't call setState, so `write` edits the state object itself:\n // only the whole state is that object, a picked key would be a copy.\n const workflowState = (await params.getState()) as StoredMessageListStateCarrier | undefined;\n if (workflowState?.messageListState === undefined) {\n stepPayload.messageListState = await readMessageListState(params, stepPayload);\n return {\n read: () => stepPayload.messageListState as SerializedMessageListState,\n write: next => {\n stepPayload.messageListState = next;\n },\n };\n }\n const run = runTranscriptRefs(params);\n const { state } = (params.getInitData() ?? {}) as RunIdentity;\n let current = await hydrateMidRun(run, workflowState.messageListState, params.abortSignal);\n return {\n read: () => current,\n write: next => {\n current = next;\n // The messages the run recalled were restored (or verified) on the way\n // in, and saved ones were recorded when saved, so storing needs no reads.\n workflowState.messageListState = state?.fixedMemory ? run.refs.dehydrate(next) : next;\n },\n };\n}\n\nlet midRunLoadRetryDelaysMs: readonly number[] = [500, 2_000, 8_000];\n\n/** Test hook: replaces the waits between mid-run load retries. Returns a restore function. */\nexport function __setMidRunLoadRetryDelaysForTests(delays: readonly number[]): () => void {\n const previous = midRunLoadRetryDelaysMs;\n midRunLoadRetryDelaysMs = delays;\n return () => {\n midRunLoadRetryDelaysMs = previous;\n };\n}\n\n/**\n * Restores refs inside a running step or the loop predicate. A step without\n * this process's loaded rows (another worker, an evicted cache entry) reads\n * them from memory storage after the iteration's tools already ran, so a\n * failure here would end the run with no way to retry it. Transient storage\n * errors are retried for about ten seconds first. Every caller reads before\n * doing any work, so a retry repeats nothing.\n */\nasync function hydrateMidRun(\n run: ReturnType<typeof runTranscriptRefs>,\n stored: DehydratedMessageListState,\n abortSignal: AbortSignal | undefined,\n): Promise<SerializedMessageListState> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await run.refs.hydrate(stored, run.load, run);\n } catch (error) {\n const wait = midRunLoadRetryDelaysMs[attempt];\n // A missing memory store won't appear on a retry.\n const permanent = error instanceof MastraError && error.id === 'AGENT_MEMORY_MESSAGE_REF_UNRESOLVABLE';\n if (wait === undefined || permanent || abortSignal?.aborted) throw error;\n run.logger?.warn('Could not load recalled messages from memory storage; retrying', {\n runId: run.runId,\n attempt: attempt + 1,\n error,\n });\n await delay(wait, abortSignal);\n }\n }\n}\n\n/** The transcript as workflow state stores it. */\nexport async function dehydrateMessageListState(params: RunParams, messageListState: SerializedMessageListState) {\n // Function or inherited memory can resolve to another store on resume, where refs would not\n // resolve, so only fixed memory gets refs.\n const { state } = (params.getInitData() ?? {}) as RunIdentity;\n if (!state?.fixedMemory) return messageListState;\n const run = runTranscriptRefs(params);\n await run.refs.verify(messageListState, run.load, run.logger);\n return run.refs.dehydrate(messageListState);\n}\n\n/**\n * Loads the recalled messages a persisted run stores as refs before it resumes\n * or recovers, dropping any this process verified earlier so the run picks up\n * edits or deletions made in memory meanwhile. Called before anything runs, so\n * a memory storage failure leaves the run as it was; the steps then restore the\n * transcript from the rows loaded here.\n */\nexport async function loadMessageListStateForResume(params: RunParams & { state: unknown }): Promise<void> {\n releaseMessageListState(params);\n const stored = (params.state as StoredMessageListStateCarrier | undefined)?.messageListState;\n if (stored === undefined) return;\n const run = runTranscriptRefs(params);\n await run.refs.hydrate(stored, run.load, run);\n}\n\n/** Restores the refs in a transcript read straight from a persisted snapshot. */\nexport async function hydrateMessageListState(\n params: RunParams,\n stored: DehydratedMessageListState,\n): Promise<SerializedMessageListState> {\n const run = runTranscriptRefs(params);\n return run.refs.hydrate(stored, run.load, run);\n}\n\n/**\n * Replaces messages memory already stores with refs in the transcript copies a\n * persisted snapshot carries outside workflow state: the run input, step\n * payloads and outputs, and the evented engine's `__state` mirror. Without\n * this every checkpoint rewrites the conversation once per copy (#26600).\n * Never reads storage; anything not yet saved stays inline. Copy-on-write.\n */\nexport function dehydrateSnapshotTranscripts(snapshot: WorkflowRunState): WorkflowRunState {\n const context = snapshot.context as Record<string, unknown> | undefined;\n const input = context?.input as { state?: SerializableDurableState } | undefined;\n const refs = input?.state?.fixedMemory ? peekRunMessageRefs(snapshot.runId) : undefined;\n if (!context || !refs) return snapshot;\n const withRefs = (carrier: unknown) => {\n const state = (carrier as MessageListStateCarrier | undefined)?.messageListState;\n if (!state?.messages) return carrier;\n const next = refs.dehydrate(state);\n return next === state ? carrier : { ...(carrier as object), messageListState: next };\n };\n let changed = false;\n const nextContext: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(context)) {\n let next = value;\n if (key === 'input' || key === '__state') {\n next = withRefs(value);\n } else if (value && typeof value === 'object') {\n const step = value as { payload?: unknown; output?: unknown };\n const payload = withRefs(step.payload);\n const output = withRefs(step.output);\n if (payload !== step.payload || output !== step.output) next = { ...step, payload, output };\n }\n changed ||= next !== value;\n nextContext[key] = next;\n }\n // Workflow state was dehydrated when written, which can predate the save.\n const value = withRefs(snapshot.value) as WorkflowRunState['value'];\n if (!changed && value === snapshot.value) return snapshot;\n return { ...snapshot, value, context: (changed ? nextContext : context) as WorkflowRunState['context'] };\n}\n\n/** Loads stored messages of the run by id from the run's memory. */\nexport function loadRunStoredMessages(params: RunParams): StoredMessageLoader {\n return runTranscriptRefs(params).load;\n}\n\n/** Frees this process's verified rows once the run has read its transcript for the last time. */\nexport function releaseMessageListState(params: RunParams): void {\n const { runId } = (params.getInitData() ?? {}) as RunIdentity;\n releaseRunMessageRefs(runId);\n}\n\ntype RunIdentity = {\n runId?: string;\n agentId?: string;\n requestContextEntries?: Record<string, unknown>;\n state?: SerializableDurableState;\n};\n\nfunction runTranscriptRefs(params: RunParams) {\n // Both the outer loop's and the iteration workflow's init data carry the\n // run identity.\n const run = (params.getInitData() ?? {}) as RunIdentity;\n const refs = getRunMessageRefs(run.runId);\n let memory: Promise<MastraMemory | undefined> | undefined;\n const load: StoredMessageLoader = async ids =>\n createStoredMessageLoader(await (memory ??= runMemory(params, run)))(ids);\n return { refs, load, runId: run.runId, logger: params.mastra?.getLogger?.() };\n}\n\n/** The run's memory: the live instance in this process, else re-resolved from the agent. */\nasync function runMemory(params: RunParams, run: RunIdentity): Promise<MastraMemory | undefined> {\n const memory = run.runId ? getRunRegistryEntry(run.runId, params.mastra)?.memory : undefined;\n if (memory || !params.mastra || !run.agentId) return memory;\n const agent = params.mastra.getAgentById(run.agentId);\n return agent.getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext) });\n}\n","import { MastraFGAPermissions } from '../../../auth/ee';\nimport type { IMastraLogger } from '../../../logger';\nimport { noopLogger } from '../../../logger/noop-logger';\nimport { commitToolResult } from '../../../loop/shared/steps/tool-result-commit-core';\nimport { TOOL_ABORT_NOTICE } from '../../../loop/shared/tool-abort-grace';\nimport type { Mastra } from '../../../mastra';\nimport type { MastraMemory } from '../../../memory/memory';\nimport { createObservabilityContext } from '../../../observability';\nimport type { TracingContext } from '../../../observability';\nimport type { OutputResult } from '../../../processors';\nimport { StructuredOutputProcessor } from '../../../processors/processors/structured-output';\nimport { ProcessorRunner } from '../../../processors/runner';\nimport { RequestContext, withoutLiveRequestKeys } from '../../../request-context';\nimport { toStandardSchema } from '../../../schema';\nimport {\n persistProcessorDataChunk,\n resolveOutputMessageSkippingCompletionChecks,\n resolveProcessorWriterMessageId,\n} from '../../../stream/base/output';\nimport { createOutputHandler } from '../../../stream/base/output-format-handlers';\nimport type { ChunkType } from '../../../stream/types';\nimport type { Agent } from '../../agent';\nimport { convertMessages, coreContentToString, MessageList } from '../../message-list';\nimport type { SerializedMessageListState } from '../../message-list/state';\nimport { isTerminalToolInvocationState } from '../../message-list/utils/tool-invocation-state';\nimport { undoSavedResponseMessages } from '../../save-queue/undo-saved-response-messages';\nimport { restoreRunAgentScopes } from '../../scopes';\nimport { TripWire } from '../../trip-wire';\nimport type { StructuredOutputOptions } from '../../types';\nimport { isDurableAgentLike } from '../../types';\nimport { assertExecutionOwned, isExecutionFenceError } from '../execution-fence';\nimport { authorizeDurableMemory, getDurableMemoryAuthorizationChecks } from '../memory-fga';\nimport { getRunRegistryEntry } from '../run-registry';\nimport { toLiveStructuredOutputSchema } from '../structured-output-null-transform';\nimport type { DurableAgenticWorkflowInput, RunRegistryEntry } from '../types';\nimport { resolveRuntimeDependencies } from '../utils/resolve-runtime';\nimport { foldBackgroundResults } from './shared/background-results';\nimport { hydrateMessageListState } from './shared/message-list-state';\n\ntype GenerateThreadTitleArgs = Parameters<NonNullable<RunRegistryEntry['generateThreadTitle']>>[0];\ntype AnyAgent = Agent<any, any, any, any>;\n\nexport interface DurableFinishSideEffectsOptions {\n runId: string;\n initData: DurableAgenticWorkflowInput;\n messageListState: SerializedMessageListState;\n mastra?: Mastra;\n requestContext?: RequestContext;\n tracingContext?: TracingContext;\n logger?: IMastraLogger;\n outputResult?: OutputResult;\n /**\n * The current response message id. Signals, goals and isTaskComplete rotate it during\n * the run, so `initData.messageId` can name an earlier reply. Defaults to that id.\n */\n messageId?: string;\n}\n\nexport interface DurableFinishSideEffectsResult {\n messageListState: SerializedMessageListState;\n outputText: string;\n /**\n * True when processOutputResult changed `outputText`, including emptying it. Only then should\n * callers apply `outputText` to the run's last step: otherwise the step's own text stands,\n * e.g. the narration of a final tool step whose last message has no text.\n */\n outputTextChanged: boolean;\n titleGeneration?: Promise<void>;\n /**\n * Set when this stream() run should emit a `data-thread-title` chunk (`generateTitle.emitEvent`).\n * Resolves with the saved title, or undefined when none was generated. Callers await it\n * before FINISH so the chunk lands first, matching the in-process loop.\n */\n titleForStream?: Promise<string | undefined>;\n /** Chunks from the `structuredOutput.model` structuring pass, to publish before FINISH. */\n structuredOutputChunks?: ChunkType[];\n /**\n * Chunks output processors wrote with `writer.custom()` in processOutputResult. Publish them\n * marked output-processed, after `structuredOutputChunks` and before the tripwire or FINISH,\n * matching the in-process loop.\n */\n outputResultChunks?: ChunkType[];\n /** Set when an output processor aborted in processOutputResult; nothing was persisted. */\n tripwire?: {\n reason: string;\n processorId?: string;\n retry?: boolean;\n metadata?: unknown;\n };\n}\n\nfunction restoreRequestContext(\n entries: Record<string, unknown> | undefined,\n fallback: RequestContext | undefined,\n): RequestContext {\n if (!entries) return fallback ?? new RequestContext();\n\n const restored = new RequestContext<unknown>(fallback?.entries());\n // The snapshot's token and signed-in user belong to whoever started the run;\n // the live ones in `fallback` are kept.\n for (const [key, value] of Object.entries(withoutLiveRequestKeys(entries))) restored.set(key, value);\n restoreRunAgentScopes(restored);\n return restored;\n}\n\nfunction resolveOutputText(messageList: MessageList): string {\n const responseMessages = messageList.get.response.db();\n const hasCompletionCheckMessages = responseMessages.some(message => message.content?.metadata?.completionResult);\n if (hasCompletionCheckMessages) {\n const lastRealMessage = responseMessages.findLast(message => !message.content?.metadata?.completionResult);\n const converted = lastRealMessage ? convertMessages([lastRealMessage]).to('AIV4.Core') : [];\n const lastConverted = converted.at(-1);\n return lastConverted ? coreContentToString(lastConverted.content) : '';\n }\n\n const converted = messageList.get.response.aiV4.core();\n const lastResponseMessage = converted.at(-1);\n return lastResponseMessage ? coreContentToString(lastResponseMessage.content) : '';\n}\n\n/**\n * Run the side effects that happen after the durable agentic loop reaches its\n * terminal state. Every durable engine calls this before emitting its finish\n * event so remote workers provide the same behavior as the built-in engine.\n *\n * The returned state is the SAME MessageList that output processors mutated\n * and memory persistence flushed. Callers must use it in their final output;\n * rebuilding from the pre-processor state would discard redactions and other\n * processOutputResult changes.\n */\nexport async function runDurableFinishSideEffects({\n runId,\n initData,\n messageListState,\n mastra,\n requestContext,\n tracingContext,\n logger,\n outputResult,\n messageId = initData.messageId,\n}: DurableFinishSideEffectsOptions): Promise<DurableFinishSideEffectsResult> {\n const effectiveLogger = logger ?? mastra?.getLogger?.() ?? noopLogger;\n const durableState = initData.state;\n\n // A connect() worker has a separate process-local registry. Rebuild the\n // agent's runtime dependencies when the terminal step cannot see the\n // processor pipeline or the memory save queue prepared by stream().\n let registryEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n // resolveRuntimeDependencies only writes its rebuild back into the registry when it\n // rehydrated from Mastra, so an already-hydrated entry that was seeded without a save\n // queue would still be missing one afterwards. Keep what it returns and prefer that.\n let rebuiltSaveQueueManager: RunRegistryEntry['saveQueueManager'] | undefined;\n let rebuiltMemory: MastraMemory | undefined;\n const needsProcessorRebuild = registryEntry?.outputProcessors === undefined;\n const needsMemoryRebuild = !!durableState?.threadId && !registryEntry?.saveQueueManager;\n if ((needsProcessorRebuild || needsMemoryRebuild) && mastra) {\n try {\n const resolved = await resolveRuntimeDependencies({\n mastra,\n runId,\n agentId: initData.agentId,\n // initData read back from a snapshot may keep saved messages as refs.\n input: { ...initData, messageListState },\n logger: effectiveLogger,\n });\n rebuiltSaveQueueManager = resolved.saveQueueManager;\n rebuiltMemory = resolved.memory;\n registryEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n } catch (error) {\n effectiveLogger.error('[DurableAgent] Failed to rebuild finish-time dependencies', {\n agentId: initData.agentId,\n runId,\n error,\n });\n }\n }\n\n const effectiveRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext);\n // Snapshots drop MastraMemory (it holds a live instance), but memory processors read\n // memoryConfig (e.g. readOnly) from it. Restore it from durable state when it's missing.\n if (!effectiveRequestContext.has('MastraMemory') && durableState?.threadId) {\n effectiveRequestContext.set('MastraMemory', {\n thread: { id: durableState.threadId },\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n });\n }\n // Deserialize into the run's existing MessageList when there is one. MastraModelOutput\n // holds that instance and reads it during final processing, so swapping in a new one\n // would leave the stream reporting pre-processor messages.\n const messageList = (\n registryEntry?.messageList ??\n new MessageList({\n threadId: durableState?.threadId,\n resourceId: durableState?.resourceId,\n })\n ).deserialize(messageListState);\n if (registryEntry) {\n registryEntry.messageList = messageList;\n }\n // A background result that landed after the last background check is still a placeholder here.\n await foldBackgroundResults(registryEntry, messageList);\n\n // The caller-side MastraModelOutput only sees the finish event after this step has\n // persisted messages, and remote/recovered runs have no caller at all. Attach the\n // validated object here so the saved assistant message matches plain Agent output.\n // Like Agent, this runs before output processors so processors that persist the turn\n // themselves (observational memory) save the object too.\n // This mirrors createObjectStreamTransformer's finalize: truncated finishes never validate,\n // and failures follow errorStrategy. Prefer the live config (keeps Zod refinements/transforms\n // and non-JSON fallback values). Remote and recovered runs only have the persisted config,\n // which is what cross-process observers use too.\n const structuredOutput = initData.options?.structuredOutput;\n const structuredOutputText = resolveOutputText(messageList);\n const liveStructuredOutput = registryEntry?.structuredOutput;\n const structuredOutputSchema =\n liveStructuredOutput?.schema ??\n (structuredOutput?.schema\n ? toLiveStructuredOutputSchema(structuredOutput.schema, structuredOutput.nullToUndefined)\n : undefined);\n let structuredOutputChunks: ChunkType[] | undefined;\n // The structuring model reads tool calls and results too, so a tool-only answer still qualifies.\n const structuringParts = structuredOutput?.hasStructuringModel ? responseStreamParts(messageList) : undefined;\n if (structuredOutputSchema && (structuredOutputText.trim() || structuringParts?.length)) {\n const finishReason = outputResult?.finishReason;\n const truncated = finishReason === 'length' || finishReason === 'content-filter';\n const errorStrategy = liveStructuredOutput ? liveStructuredOutput.errorStrategy : structuredOutput?.errorStrategy;\n const fallbackValue = liveStructuredOutput ? liveStructuredOutput.fallbackValue : structuredOutput?.fallbackValue;\n let value: unknown;\n if (structuredOutput?.hasStructuringModel) {\n // Like Agent's StructuredOutputProcessor: the main model answered in text, so a\n // separate structuring model turns that answer into the object.\n const structuringModel = liveStructuredOutput?.model ?? structuredOutput.structuringModelConfig?.originalConfig;\n // Never structure partial text from an aborted or failed turn.\n const failed = finishReason === 'abort' || finishReason === 'error';\n if (structuringModel && !truncated && !failed) {\n structuredOutputChunks = await runStructuringPass({\n options: {\n ...(liveStructuredOutput ?? {}),\n schema: liveStructuredOutput?.schema ?? toStandardSchema(structuredOutput.schema!),\n model: structuringModel as any,\n instructions: liveStructuredOutput?.instructions ?? structuredOutput.instructions,\n jsonPromptInjection: liveStructuredOutput?.jsonPromptInjection ?? structuredOutput.jsonPromptInjection,\n errorStrategy,\n fallbackValue,\n } as StructuredOutputOptions<any>,\n mastra,\n agentId: initData.agentId,\n messageList,\n streamParts: structuringParts!,\n requestContext: effectiveRequestContext,\n logger: effectiveLogger,\n });\n const objectChunk = structuredOutputChunks.findLast(chunk => chunk.type === 'object-result');\n value = objectChunk?.type === 'object-result' ? objectChunk.object : undefined;\n } else if (!structuringModel) {\n effectiveLogger.warn('[DurableAgent] structuredOutput.model is not available on this worker', { runId });\n }\n } else {\n const result = truncated\n ? undefined\n : await createOutputHandler({ schema: structuredOutputSchema }).validateAndTransformFinal(structuredOutputText);\n value = result?.success ? result.value : errorStrategy === 'fallback' ? fallbackValue : undefined;\n }\n const lastAssistantMessage = messageList.get.response\n .db()\n .findLast(message => message.role === 'assistant' && !message.content?.metadata?.completionResult);\n if (value !== undefined && lastAssistantMessage) {\n lastAssistantMessage.content.metadata = {\n ...lastAssistantMessage.content.metadata,\n structuredOutput: value,\n };\n }\n }\n\n // Output processors persist messages too (MessageHistory saves the response\n // in processOutputResult), so a superseded execution must stop here, before\n // either memory write path, and never reach the finish event (#23734). This\n // check uses the live `requestContext`: the snapshot entries never carry the\n // execution id.\n const assertOwned = () => assertExecutionOwned({ runId, agentId: initData.agentId, requestContext, mastra });\n await assertOwned();\n\n // A signal drained on the last allowed step rotates the id, then the loop stops before any\n // reply uses it. Attach data to the final reply instead of saving it as its own message.\n // Resolved before processors run so their own writes can't become the fallback.\n const responses = messageList.get.response.db();\n const replyMessageId = responses.some(message => message.id === messageId)\n ? messageId\n : (resolveOutputMessageSkippingCompletionChecks(messageList)?.id ?? messageId);\n\n // This step has no pubsub (remote engines call it too), so chunks are buffered for the\n // caller. Non-transient ones go into the MessageList now so the flush below saves them.\n const outputResultChunks: ChunkType[] = [];\n const outputResultWriter = {\n custom: async (\n data: { type: string; data?: unknown; transient?: boolean },\n writerOptions?: { messageId?: string },\n ) => {\n persistProcessorDataChunk(messageList, writerOptions?.messageId ?? replyMessageId, data);\n outputResultChunks.push(data as ChunkType);\n },\n };\n\n const outputTextBeforeProcessing = resolveOutputText(messageList);\n\n // Keep this MessageList for every later phase. ProcessorRunner applies\n // returned message arrays back onto it, including removals and replacements.\n if (registryEntry?.outputProcessors?.length) {\n try {\n let agent: AnyAgent | undefined = registryEntry.agent;\n if (!agent && mastra) {\n try {\n const registered = mastra.getAgentById(initData.agentId);\n agent = isDurableAgentLike(registered) && registered.agent !== registered ? registered.agent : registered;\n } catch {\n agent = undefined;\n }\n }\n\n const runner = new ProcessorRunner({\n inputProcessors: registryEntry.inputProcessors ?? [],\n outputProcessors: registryEntry.outputProcessors,\n errorProcessors: registryEntry.errorProcessors ?? [],\n logger: effectiveLogger,\n agentName: initData.agentName ?? initData.agentId,\n agent,\n processorStates: registryEntry.processorStates,\n });\n await runner.runOutputProcessors(\n messageList,\n createObservabilityContext(tracingContext),\n effectiveRequestContext,\n 0,\n outputResultWriter,\n outputResult,\n );\n } catch (error) {\n if (error instanceof TripWire) {\n // Match Agent: a tripwire rejects the answer, so skip persistence and title generation,\n // and remove any response messages this run already saved.\n await undoSavedResponseMessages({\n memory: registryEntry?.memory ?? rebuiltMemory,\n threadId: durableState?.threadId,\n memoryConfig: durableState?.memoryConfig,\n messageList,\n saveQueueManager: registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager,\n logger: effectiveLogger,\n runId,\n });\n const outputText = resolveOutputText(messageList);\n return {\n messageListState: messageList.serialize(),\n outputText,\n outputTextChanged: outputText !== outputTextBeforeProcessing,\n outputResultChunks,\n tripwire: {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n },\n };\n }\n effectiveLogger.warn('[DurableAgent] Error running output processors', { runId, error });\n // Ordinary history can retry through the strict queue flush below. OM owns\n // its final write and skips that flush, so its failure must propagate here.\n if (durableState?.observationalMemory) throw error;\n }\n }\n\n // SaveQueueManager may reclassify flushed response messages as persisted\n // memory, so resolve the final response text before persistence runs.\n const outputText = resolveOutputText(messageList);\n const outputTextChanged = outputText !== outputTextBeforeProcessing;\n\n const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;\n const memory = registryEntry?.memory ?? rebuiltMemory;\n const authorizeMemory =\n durableState?.threadId && durableState.resourceId\n ? (permission: Parameters<typeof authorizeDurableMemory>[1]['permission']) =>\n authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {\n mastra,\n user: effectiveRequestContext.get('user'),\n threadId: durableState.threadId!,\n resourceId: durableState.resourceId!,\n agentId: initData.agentId,\n requestContext: effectiveRequestContext,\n permission,\n actor: initData.options?.actor,\n })\n : undefined;\n\n if (\n saveQueueManager &&\n memory &&\n durableState?.threadId &&\n durableState?.resourceId &&\n !durableState.observationalMemory &&\n !durableState.memoryConfig?.readOnly\n ) {\n await authorizeMemory!(MastraFGAPermissions.MEMORY_WRITE);\n if (!durableState.threadExists) await authorizeMemory!(MastraFGAPermissions.MEMORY_READ);\n try {\n if (!durableState.threadExists) {\n await memory.createThread?.({\n threadId: durableState.threadId,\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n });\n }\n\n await saveQueueManager.flushMessages(messageList, durableState.threadId, durableState.memoryConfig, {\n beforePersist: assertOwned,\n throwOnError: true,\n });\n } catch (error) {\n if (isExecutionFenceError(error)) throw error;\n effectiveLogger.error('[DurableAgent] Error persisting messages', {\n runId,\n threadId: durableState.threadId,\n error,\n });\n throw error;\n }\n }\n\n let titleGeneration: Promise<void> | undefined;\n let titleForStream: Promise<string | undefined> | undefined;\n\n // Same exclusions as the persistence block above: an observational-memory run writes no\n // messages here, and titling it would create a thread row holding a title and nothing else.\n if (\n durableState?.threadId &&\n durableState?.resourceId &&\n !durableState.observationalMemory &&\n !durableState.memoryConfig?.readOnly\n ) {\n const titleArgs: GenerateThreadTitleArgs = {\n threadId: durableState.threadId,\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n messageListState: messageList.serialize(),\n requestContext: effectiveRequestContext,\n tracingContext,\n };\n\n const generateThreadTitle = registryEntry?.generateThreadTitle;\n await authorizeMemory!(MastraFGAPermissions.MEMORY_READ);\n await authorizeMemory!(MastraFGAPermissions.MEMORY_WRITE);\n const savedTitle = (async (): Promise<string | undefined> => {\n if (generateThreadTitle) {\n return generateThreadTitle(titleArgs);\n } else if (mastra) {\n const agent = mastra.getAgentById(initData.agentId);\n const titleMemory = memory ?? (await agent.getMemory({ requestContext: effectiveRequestContext }));\n if (titleMemory) {\n return generateDurableThreadTitle({ agent, memory: titleMemory, ...titleArgs });\n }\n }\n return undefined;\n })().catch(error => {\n effectiveLogger.warn('[DurableAgent] Error generating thread title', { runId, error });\n return undefined;\n });\n\n if (registryEntry?.streamThreadTitle) titleForStream = savedTitle;\n\n // The user callback runs after the title is saved but never holds FINISH.\n const onTitleGenerated = registryEntry?.onTitleGenerated;\n titleGeneration = savedTitle\n .then(async title => {\n if (title && onTitleGenerated) await onTitleGenerated(title);\n })\n .catch(error => {\n effectiveLogger.error('[DurableAgent] Error in onTitleGenerated callback', { runId, error });\n });\n }\n\n return {\n messageListState: messageList.serialize(),\n outputText,\n outputTextChanged,\n titleGeneration,\n titleForStream,\n structuredOutputChunks,\n outputResultChunks,\n };\n}\n\n/**\n * What a total deadline saves: the steps that completed in time, plus the step in flight. A step cut off\n * mid-stream contributes the text it already streamed, which never reached the step processors. A step cut off\n * while its tools ran is kept whole, with the tool results that came back in time or during the deadline's grace\n * window and any call still running saved as aborted.\n */\nexport function deadlineMessageListState(\n entry: RunRegistryEntry,\n fallback: SerializedMessageListState,\n): { messageListState: SerializedMessageListState; cutOffText?: string } {\n if (entry.streamedStepText) {\n return { messageListState: entry.completedStepsState ?? fallback, cutOffText: entry.streamedStepText.join('') };\n }\n const settled = entry.settledToolResults;\n if (settled?.length && entry.messageList) {\n // JSON round-trip: the live list keeps mutating, and its metadata can hold functions.\n const inFlight = new MessageList().deserialize(JSON.parse(JSON.stringify(entry.messageList.serialize())));\n for (const result of settled) {\n commitToolResult({\n messageList: inFlight,\n outcome: result.outcome,\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n toolArgs: result.args,\n approval: result.approval,\n providerMetadata: result.providerMetadata,\n });\n }\n // A sibling call still running past the grace window is saved as aborted, so the results\n // that did come back are not dropped with it.\n const unsettled = inFlight.get.response\n .db()\n .flatMap(message => message.content.parts ?? [])\n .filter(part => part.type === 'tool-invocation' && !isTerminalToolInvocationState(part.toolInvocation.state));\n for (const part of unsettled) {\n if (part.type !== 'tool-invocation') continue;\n commitToolResult({\n messageList: inFlight,\n outcome: { kind: 'result', result: TOOL_ABORT_NOTICE },\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n toolArgs: part.toolInvocation.args,\n });\n }\n return { messageListState: inFlight.serialize() };\n }\n return { messageListState: entry.completedStepsState ?? fallback };\n}\n\n/**\n * Give the output processors (and with them memory) their one pass when a total deadline ends a\n * durable run. The run never reaches its finish step, so this runs over what the deadline saves\n * (see `deadlineMessageListState`), as the default loop's deadline pass does.\n */\nexport async function runDurableDeadlineOutputPass({\n runId,\n initData,\n messageListState,\n cutOffText,\n entry,\n mastra,\n tracingContext,\n logger,\n}: {\n runId: string;\n initData: Pick<\n DurableAgenticWorkflowInput,\n 'runId' | 'agentId' | 'agentName' | 'messageId' | 'state' | 'options' | 'requestContextEntries'\n >;\n messageListState: SerializedMessageListState;\n cutOffText?: string;\n entry: RunRegistryEntry;\n mastra?: Mastra;\n /** The run's agent span, so the deadline pass shows in the run's trace as the finish pass does. */\n tracingContext?: TracingContext;\n logger: IMastraLogger;\n}): Promise<void> {\n const durableState = initData.state;\n const requestContext = restoreRequestContext(initData.requestContextEntries, entry.requestContext);\n if (!requestContext.has('MastraMemory') && durableState?.threadId) {\n requestContext.set('MastraMemory', {\n thread: { id: durableState.threadId },\n resourceId: durableState.resourceId,\n memoryConfig: durableState.memoryConfig,\n });\n }\n const memoryContext = requestContext.get('MastraMemory') as\n | { thread?: { id?: string }; resourceId?: string; memoryConfig?: { readOnly?: boolean } }\n | undefined;\n // A read-only run writes nothing to memory, at the deadline either.\n if (durableState?.memoryConfig?.readOnly || memoryContext?.memoryConfig?.readOnly) return;\n\n // The output processors save the turn (MessageHistory) to the thread the run or its request context\n // names, so the caller needs write access to each first. A denial skips the whole save.\n const resourceId = durableState?.resourceId ?? memoryContext?.resourceId;\n if (entry.memory && resourceId) {\n const threadIds = new Set([durableState?.threadId, memoryContext?.thread?.id].filter(Boolean) as string[]);\n try {\n for (const threadId of threadIds) {\n // The run's cached grant covers only its own thread; a thread the request context points at is checked anew.\n const checks = threadId === durableState?.threadId ? getDurableMemoryAuthorizationChecks(entry) : new Map();\n await authorizeDurableMemory(checks, {\n mastra,\n user: requestContext.get('user'),\n threadId,\n resourceId,\n agentId: initData.agentId,\n requestContext,\n permission: MastraFGAPermissions.MEMORY_WRITE,\n actor: initData.options?.actor,\n });\n }\n } catch (authError) {\n logger.warn('[DurableAgent] Memory write denied at the total deadline, the turn is not saved', {\n runId,\n error: authError,\n });\n return;\n }\n }\n\n const messageList = new MessageList({\n threadId: durableState?.threadId,\n resourceId: durableState?.resourceId,\n }).deserialize(\n // A resumed run's persisted input keeps messages memory already stores as refs (a recovered run's\n // crash-time transcript is hydrated already). Defensive: refs only reach here when a resumed run's\n // deadline fires before its first step snapshot with no settled tool results, which no test drives.\n await hydrateMessageListState({ getInitData: () => initData, mastra, requestContext }, messageListState),\n );\n // Untargeted processor data lands on the reply, as at finish; resolved before the cut-off text is added.\n const replyMessageId = resolveOutputMessageSkippingCompletionChecks(messageList)?.id ?? initData.messageId;\n let inFlightMessageId: string | undefined;\n if (cutOffText?.trim()) {\n messageList.add({ role: 'assistant', content: [{ type: 'text', text: cutOffText }] }, 'response', {\n merge: false,\n });\n inFlightMessageId = messageList.get.response.db().at(-1)!.id;\n }\n\n if (entry.outputProcessors?.length) {\n const runner = new ProcessorRunner({\n inputProcessors: entry.inputProcessors ?? [],\n outputProcessors: entry.outputProcessors,\n errorProcessors: entry.errorProcessors ?? [],\n logger,\n agentName: initData.agentName ?? initData.agentId,\n agent: entry.agent,\n processorStates: entry.processorStates,\n });\n // Data parts a step processor writes for the cut-off text, whether it names that message or not, are\n // held until the message is written back: the write-back replaces it, and would drop parts merged into it.\n let heldDataChunks:\n | { data: { type: string; data?: unknown; transient?: boolean }; messageId?: string }[]\n | undefined;\n const writer = {\n custom: async (\n data: { type: string; data?: unknown; transient?: boolean },\n writerOptions?: { messageId?: string },\n ) => {\n if (heldDataChunks && (!writerOptions?.messageId || writerOptions.messageId === inFlightMessageId)) {\n heldDataChunks.push({ data, messageId: writerOptions?.messageId });\n } else {\n persistProcessorDataChunk(\n messageList,\n resolveProcessorWriterMessageId(messageList, replyMessageId, writerOptions?.messageId),\n data,\n );\n }\n },\n };\n if (inFlightMessageId) {\n heldDataChunks = [];\n // The cut-off text never reached the step processors (redaction, refusal handling...).\n // Run them over that message alone: the rest of the turn already went through them.\n try {\n const stepList = messageList.clone();\n stepList.removeByIds(\n stepList.get.all\n .db()\n .map(message => message.id)\n .filter(id => id !== inFlightMessageId),\n );\n await runner.runProcessOutputStep({\n steps: [],\n messages: stepList.get.all.db(),\n messageList: stepList,\n stepNumber: 0,\n finishReason: 'error',\n text: cutOffText,\n ...createObservabilityContext(tracingContext),\n requestContext,\n writer,\n });\n messageList.removeByIds([inFlightMessageId]);\n for (const message of stepList.get.all.db()) messageList.add(message, 'response', { merge: false });\n } catch (stepError) {\n // Fail closed: keep the completed steps rather than save unprocessed text. The result processors\n // then read the text of the completed steps only.\n messageList.removeByIds([inFlightMessageId]);\n logger.warn('[DurableAgent] Output step processors failed on the text cut off at the total deadline', {\n runId,\n error: stepError,\n });\n }\n for (const { data, messageId } of heldDataChunks) {\n // A part aimed at the cut-off message lands on it if it survived the write-back,\n // otherwise on the message an untargeted write would reach.\n const target =\n messageId && messageList.get.all.db().some(message => message.id === messageId)\n ? messageId\n : resolveProcessorWriterMessageId(messageList, replyMessageId);\n persistProcessorDataChunk(messageList, target, data);\n }\n heldDataChunks = undefined;\n }\n try {\n await runner.runOutputProcessors(\n messageList,\n createObservabilityContext(tracingContext),\n requestContext,\n 0,\n writer,\n {\n text: resolveOutputText(messageList),\n usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n finishReason: 'error',\n steps: [],\n },\n );\n } catch (processorError) {\n // A tripwire rejects the turn, as it does at finish: remove response messages already saved.\n if (processorError instanceof TripWire) {\n await undoSavedResponseMessages({\n memory: entry.memory,\n threadId: durableState?.threadId,\n memoryConfig: durableState?.memoryConfig,\n messageList,\n saveQueueManager: entry.saveQueueManager,\n logger,\n runId,\n });\n return;\n }\n logger.warn('[DurableAgent] Error running output processors at the total deadline', {\n runId,\n error: processorError,\n });\n if (durableState?.observationalMemory) return;\n }\n }\n\n if (\n !entry.saveQueueManager ||\n !entry.memory ||\n !durableState?.threadId ||\n !durableState.resourceId ||\n durableState.observationalMemory\n ) {\n return;\n }\n await entry.saveQueueManager.flushMessages(messageList, durableState.threadId, durableState.memoryConfig, {\n throwOnError: true,\n });\n}\n\nclass StructuringPassError extends Error {\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n this.name = 'StructuringPassError';\n }\n}\n\n/**\n * Rebuild the chunks the structuring prompt reads (text, tool calls and results) from the\n * run's response messages; the durable finish step has no in-memory chunk history.\n */\nfunction responseStreamParts(messageList: MessageList): ChunkType[] {\n const parts: ChunkType[] = [];\n for (const message of messageList.get.response.db()) {\n if (message.role !== 'assistant' || message.content?.metadata?.completionResult) continue;\n for (const part of message.content?.parts ?? []) {\n if (part.type === 'text') {\n parts.push({ type: 'text-delta', payload: { id: '', text: part.text } } as ChunkType);\n } else if (part.type === 'tool-invocation') {\n const { toolCallId, toolName, args } = part.toolInvocation;\n parts.push({ type: 'tool-call', payload: { toolCallId, toolName, args } } as ChunkType);\n if (part.toolInvocation.state === 'result') {\n parts.push({\n type: 'tool-result',\n payload: { toolCallId, toolName, result: part.toolInvocation.result },\n } as ChunkType);\n }\n }\n }\n }\n return parts;\n}\n\n/**\n * Run Agent's StructuredOutputProcessor once against the finished turn and collect the\n * chunks it would have streamed (object deltas and the final `object-result`).\n */\nasync function runStructuringPass({\n options,\n mastra,\n agentId,\n messageList,\n streamParts,\n requestContext,\n logger,\n}: {\n options: StructuredOutputOptions<any>;\n mastra?: Mastra;\n agentId: string;\n messageList: MessageList;\n streamParts: ChunkType[];\n requestContext: RequestContext;\n logger: IMastraLogger;\n}): Promise<ChunkType[]> {\n const chunks: ChunkType[] = [];\n try {\n const processor = new StructuredOutputProcessor({ ...options, logger });\n if (mastra) {\n processor.__registerMastra(mastra);\n if (options.useAgent) {\n try {\n processor.setAgent(mastra.getAgentById(agentId) as AnyAgent);\n } catch {\n // Fall back to the processor's internal structuring agent.\n }\n }\n }\n const state: Record<string, unknown> = { controller: { enqueue: (chunk: ChunkType) => chunks.push(chunk) } };\n await processor.processOutputStream({\n part: { type: 'finish' } as ChunkType,\n state,\n streamParts,\n messageList,\n requestContext,\n abort: (() => {\n throw new Error('abort is not supported in the durable structuring pass');\n }) as any,\n retryCount: 0,\n } as any);\n // Under errorStrategy 'strict' the processor records the failure and aborts in\n // processOutputStep (Agent retries there). The finish step cannot retry, so fail the run.\n processor.processOutputStep({\n state,\n messages: [],\n abort: ((reason: string, opts?: { metadata?: { error?: unknown } }) => {\n throw new StructuringPassError(reason, opts?.metadata?.error);\n }) as any,\n } as any);\n } catch (error) {\n if (error instanceof StructuringPassError || (options.errorStrategy ?? 'strict') === 'strict') throw error;\n logger.error('[DurableAgent] Structured output structuring pass failed', { error });\n }\n return chunks;\n}\n\n/**\n * Generate a durable thread title from messages belonging to that thread.\n * This is standalone so a remote worker can call it with the agent and memory\n * it rebuilt from its own Mastra instance.\n */\nexport async function generateDurableThreadTitle({\n agent,\n memory,\n threadId,\n resourceId,\n memoryConfig,\n messageListState,\n requestContext,\n tracingContext,\n}: GenerateThreadTitleArgs & { agent: AnyAgent; memory: MastraMemory }): Promise<string | undefined> {\n const thread = await memory.getThreadById({ threadId });\n const mergedConfig = memory.getMergedThreadConfig(memoryConfig);\n const { shouldGenerate, model, instructions, minMessages } = agent.resolveTitleGenerationConfig(\n mergedConfig.generateTitle,\n );\n if (!shouldGenerate || thread?.title) return undefined;\n\n const titleMessageList = new MessageList().deserialize(messageListState);\n const uiMessages = agent.filterUiMessagesByThread(titleMessageList, threadId, titleMessageList.get.all.ui());\n if (uiMessages.length < (minMessages ?? 1)) return undefined;\n\n const userMessage = agent.getMostRecentUserMessage(uiMessages);\n if (!userMessage) return undefined;\n\n const title = await agent.genTitle(\n userMessage,\n requestContext ?? new RequestContext(),\n createObservabilityContext(tracingContext),\n model,\n instructions,\n uiMessages,\n );\n if (!title) return undefined;\n\n // genTitle is a model round trip, so another writer may have created the thread in the\n // meantime. Re-read before falling back to createThread, which upserts the whole row and\n // would drop metadata that writer stored.\n const currentThread = thread ?? (await memory.getThreadById({ threadId }));\n\n if (currentThread) {\n await memory.updateThread({\n id: threadId,\n title,\n metadata: currentThread.metadata ?? {},\n memoryConfig,\n });\n } else {\n await memory.createThread({\n threadId,\n resourceId,\n memoryConfig,\n title,\n });\n }\n return title;\n}\n","import type { MastraScorer, MastraScorerEntry } from '../../../../evals/base';\nimport { runScorer } from '../../../../evals/hooks';\nimport type { Mastra } from '../../../../mastra';\nimport { createObservabilityContext } from '../../../../observability';\nimport { RequestContext } from '../../../../request-context';\nimport { MessageList } from '../../../message-list';\nimport type { StoredMessageLoader } from '../../../message-list/memory-message-refs';\nimport type { DurableAgenticLoopOutput, DurableAgenticWorkflowInput } from '../../types';\n\nexport interface ExecuteDurableAgentScorersParams {\n /** Workflow init data, carrying the serialized scorer config and run identity. */\n initData: DurableAgenticWorkflowInput;\n /** The run's final output, carrying the response messages to score. */\n finalOutput: Pick<DurableAgenticLoopOutput, 'messageListState'>;\n mastra?: Mastra;\n requestContext?: RequestContext;\n tracingContext?: Parameters<typeof createObservabilityContext>[0];\n /** Loads response messages the run pruned from its transcript (kept there by id only) from memory. */\n loadStoredMessages?: StoredMessageLoader;\n /**\n * Scorer instances parked in-process for this run (see `setRunScorerInstances`), keyed like\n * `initData.scorers`. They take precedence over name resolution so a scorer\n * passed at call time (or via `defaultOptions.scorers`) runs even when it is\n * not registered on Mastra (#27579).\n */\n scorerInstances?: Record<string, MastraScorer>;\n}\n\n/**\n * Run an agent's configured scorers after a durable run completes.\n *\n * Every durable engine needs this, so it lives here rather than inside one\n * engine's workflow builder: the Inngest engine shipped without scorers purely\n * because its builder was a copy that missed a step core later added. Sharing\n * the implementation means a scorer change lands on every engine at once.\n *\n * Scoring is fire-and-forget and must never affect the run: scorers come from\n * the in-process run when available, otherwise they are resolved by\n * name from the Mastra instance (so this is safe on a worker in another\n * process), and anything that goes wrong is logged and skipped.\n */\nexport async function executeDurableAgentScorers({\n initData,\n finalOutput,\n mastra,\n requestContext,\n tracingContext,\n loadStoredMessages,\n scorerInstances,\n}: ExecuteDurableAgentScorersParams): Promise<void> {\n const scorers = initData.scorers;\n if (!scorers || Object.keys(scorers).length === 0) {\n return;\n }\n\n const logger = mastra?.getLogger?.();\n\n // Messages as they stood before generation are the scorer's input.\n const inputMessageList = new MessageList();\n inputMessageList.deserialize(initData.messageListState);\n\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 const outputMessageList = new MessageList();\n outputMessageList.deserialize(finalOutput.messageListState);\n let scorerOutput: Awaited<ReturnType<MessageList['getRunResponseMessages']>>;\n try {\n scorerOutput = await outputMessageList.getRunResponseMessages(loadStoredMessages);\n } catch (error) {\n // Scoring is observability, not execution: never fail a run over it.\n logger?.warn?.('Skipped scorers: could not load pruned response messages', {\n error,\n runId: initData.runId,\n });\n return;\n }\n\n const resolveContext = requestContext ?? new RequestContext();\n\n for (const [scorerKey, scorerEntry] of Object.entries(scorers)) {\n const { scorerName, sampling, filter } = scorerEntry;\n\n try {\n // Scorers are serialized by name. `getScorerById` searches by id-or-name\n // without throwing on the common path, so try it first, then fall back to\n // the registration-key-keyed `getScorer` for older configs.\n let scorer: MastraScorer | undefined = scorerInstances?.[scorerKey];\n if (!scorer) {\n try {\n scorer = mastra?.getScorerById?.(scorerName) as MastraScorer | undefined;\n } catch {\n scorer = undefined;\n }\n }\n if (!scorer) {\n try {\n scorer = 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 const scorerObject: MastraScorerEntry = {\n scorer,\n sampling,\n filter,\n };\n\n runScorer({\n mastra,\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 // Scoring is observability, not execution: never fail a run over it.\n logger?.warn?.(`Error executing scorer ${scorerName}`, {\n error,\n runId: initData.runId,\n scorerKey,\n });\n }\n }\n}\n","import { z } from 'zod';\n\nimport { CONTINUATION_STOP_CAUSES } from '../../../../loop/shared/continuation-core';\nimport type { SpanTermination } from '../../../../observability/types/outcome';\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 * Returns the path of the first value that would not survive a JSON round trip\n * (functions, symbols, bigints, non-finite numbers, class instances, cycles, and\n * `undefined` array items), or undefined if the value is JSON-safe. Undefined\n * object properties are allowed (JSON drops them), and so are Dates: the workflow\n * snapshot codec round-trips them.\n */\nfunction findNonJsonSafePath(value: unknown, path: string, ancestors: Set<object>): string | undefined {\n if (value === null || value === undefined) return undefined;\n const type = typeof value;\n if (type === 'string' || type === 'boolean') return undefined;\n if (type === 'number') return Number.isFinite(value) ? undefined : path || '<root>';\n if (type !== 'object') return path || '<root>';\n if (value instanceof Date) return undefined;\n // Only objects on the current path form a cycle; shared references are fine.\n if (ancestors.has(value as object)) return path || '<root>';\n ancestors.add(value as object);\n try {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const itemPath = `${path}[${i}]`;\n if (value[i] === undefined) return itemPath;\n const bad = findNonJsonSafePath(value[i], itemPath, ancestors);\n if (bad) return bad;\n }\n return undefined;\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return path || '<root>';\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const bad = findNonJsonSafePath(child, path ? `${path}.${key}` : key, ancestors);\n if (bad) return bad;\n }\n return undefined;\n } finally {\n ancestors.delete(value as object);\n }\n}\n\nexport function isJsonSafe(value: unknown): boolean {\n return findNonJsonSafePath(value, '', new Set()) === undefined;\n}\n\n/**\n * Schema for the serialized durable options carried in workflow input. These\n * options cross step boundaries (and processes) as JSON, so live objects such\n * as Zod schemas must be converted before they get here — otherwise they are\n * silently mangled by the round trip.\n */\nexport const durableOptionsSchema = z.any().superRefine((value, ctx) => {\n const badPath = findNonJsonSafePath(value, '', new Set());\n if (badPath) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Durable agent options must be JSON-safe; found a non-serializable value at options.${badPath}`,\n });\n }\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 settings: 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 * Type for accumulated usage. Keys stay present in memory so the value can be\n * passed to usage consumers, while JSON serialization may omit unknown values.\n */\nexport type AccumulatedUsage = {\n inputTokens: number | undefined;\n outputTokens: number | undefined;\n totalTokens: number | undefined;\n cachedInputTokens?: number;\n cacheCreationInputTokens?: number;\n reasoningTokens?: number;\n};\n\n/**\n * Schema for accumulated usage across iterations\n */\nexport const accumulatedUsageSchema = z.object({\n inputTokens: z.number().optional(),\n outputTokens: z.number().optional(),\n totalTokens: z.number().optional(),\n cachedInputTokens: z.number().optional(),\n cacheCreationInputTokens: z.number().optional(),\n reasoningTokens: z.number().optional(),\n}) as z.ZodType<AccumulatedUsage>;\n\n/**\n * Provider id and serving model of one response.\n */\nexport const responseRecordSchema = z.object({ id: z.string().optional(), modelId: z.string().optional() });\n\nexport type ResponseRecord = z.infer<typeof responseRecordSchema>;\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: durableOptionsSchema,\n state: z.any(),\n messageId: z.string(),\n inputTripwire: z\n .object({\n reason: z.string(),\n retry: z.boolean().optional(),\n processorId: z.string().optional(),\n metadata: z.unknown().optional(),\n })\n .optional(),\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 // Absent when the run keeps the transcript in workflow state.\n messageListState: z.any().optional(),\n // Immutable untagged system-message baseline captured before the first\n // iteration. Each model attempt restores it before input-step processors run.\n initialUntaggedSystemMessages: z.array(z.any()).optional(),\n toolsMetadata: z.array(z.any()),\n modelConfig: z.any(),\n options: durableOptionsSchema,\n state: z.any(),\n messageId: z.string(),\n // JSON-safe snapshot of the caller's requestContext.entries(), carried\n // across every iteration so steps that rebuild runtime state from the Mastra\n // instance resolve with the same request context on iteration N as on\n // iteration 1. Dropping it here silently falls back to an empty context.\n requestContextEntries: z.record(z.string(), z.any()).optional(),\n inputTripwire: baseDurableAgenticInputSchema.shape.inputTripwire,\n // Iteration tracking\n iterationCount: z.number(),\n // Absent when the run keeps its step records in workflow state.\n accumulatedSteps: z.array(z.any()).optional(),\n accumulatedUsage: accumulatedUsageSchema,\n // Identifies states whose usage accumulator preserves unknown counters. Older\n // states have no marker and may contain partial totals presented as complete.\n usageAggregationVersion: z.literal(1).optional(),\n // Last step result for continuation check\n lastStepResult: z.any().optional(),\n // Step-finish waits here until the loop's continuation policy resolves.\n deferredStepFinishChunk: 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 the total deadline aborted a tool call — the loop stops and the run ends as the deadline\n deadlineTimeout: z.object({ timeoutType: z.literal('total'), timeoutMs: z.number() }).optional(),\n // Set when abort() stopped a tool call — the loop stops and the run ends as aborted\n runAborted: 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 // The response messages the run's step-finish events have sent (see agent/streams/response-messages.ts)\n responseMessagesCursor: z\n .object({\n producer: z.string(),\n seq: z.number(),\n fingerprints: z.array(z.string()),\n wholeListSize: z.number().optional(),\n sentSinceWholeList: z.number().optional(),\n })\n .optional(),\n // Span data, carried unchanged so every iteration shares one trace\n agentSpanData: z.any().optional(),\n modelSpanData: z.any().optional(),\n // First chunk clock, carried so the final step can end the generation and AGENT_RUN with it\n completionStartTime: z.coerce.date().optional(),\n // Time to first token of the inference that streamed that chunk, carried the same way\n timeToFirstTokenMs: z.number().optional(),\n // Provider id and model of the latest response, carried the same way\n lastResponse: responseRecordSchema.optional(),\n // How the run ended, as decided at the runtime boundary. Carried in the state so the\n // final step can end the root spans with the real outcome on a worker that never held\n // the deciding process's run-registry entry.\n tracingStopCause: z.enum(CONTINUATION_STOP_CAUSES).optional(),\n tracingTermination: z.custom<SpanTermination>().optional(),\n tracingDelegationFailure: z.custom<SpanTermination>().optional(),\n});\n\n/**\n * Type for the base iteration state\n */\nexport type BaseIterationState = z.infer<typeof baseIterationStateSchema>;\n","import type { LanguageModelUsage, StepTripwireData } from '../../../../stream/types';\nimport type { DurableAgenticExecutionOutput, RunRegistryEntry } from '../../types';\nimport type { AccumulatedUsage, BaseIterationState } from './schemas';\n\ninterface SpanClocks {\n completionStartTime?: Date | string;\n timeToFirstTokenMs?: number;\n}\n\n/**\n * The first-chunk clocks for spans rebuilt from a run-start snapshot. A\n * resumed segment keeps them on the run registry beside its fresh spans; the\n * originals keep them in the loop state. Undefined when none was captured yet.\n */\nexport function carriedSpanClocks(\n registry:\n | Pick<RunRegistryEntry, 'resumeModelSpanData' | 'resumeCompletionStartTime' | 'resumeTimeToFirstTokenMs'>\n | undefined,\n state: SpanClocks,\n): { completionStartTime?: Date; timeToFirstTokenMs?: number } | undefined {\n const clocks: SpanClocks = registry?.resumeModelSpanData\n ? { completionStartTime: registry.resumeCompletionStartTime, timeToFirstTokenMs: registry.resumeTimeToFirstTokenMs }\n : state;\n const attributes = {\n ...(clocks.completionStartTime ? { completionStartTime: new Date(clocks.completionStartTime) } : {}),\n ...(clocks.timeToFirstTokenMs !== undefined ? { timeToFirstTokenMs: clocks.timeToFirstTokenMs } : {}),\n };\n return Object.keys(attributes).length ? attributes : undefined;\n}\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 *\n * Main accumulates full `DefaultStepResult` objects; durable serializes this\n * reduced record across step boundaries instead. `content` is the step's model\n * content, the same value stopWhen and `stream.steps` see. It is absent on\n * records written before it was added, where `buildDurableStepContent`\n * rebuilds it from `text`/`toolCalls`/`toolResults`. Other fields of\n * `DefaultStepResult` (`response`, etc.) are still not carried.\n */\nexport interface StepRecord {\n text?: string;\n content?: unknown[];\n toolCalls?: unknown[];\n toolResults?: unknown[];\n usage?: LanguageModelUsage;\n finishReason?: string;\n tripwire?: StepTripwireData;\n}\n\n/**\n * Calculate accumulated usage from current state and new execution output.\n */\nexport function calculateAccumulatedUsage(\n currentUsage: AccumulatedUsage,\n executionUsage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n cachedInputTokens?: number;\n cacheCreationInputTokens?: number;\n reasoningTokens?: number;\n },\n): AccumulatedUsage {\n const accumulate = (current: number | undefined, next: number | undefined) =>\n current !== undefined && next !== undefined ? current + next : undefined;\n\n const usage: AccumulatedUsage = {\n inputTokens: accumulate(currentUsage.inputTokens, executionUsage?.inputTokens),\n outputTokens: accumulate(currentUsage.outputTokens, executionUsage?.outputTokens),\n totalTokens: accumulate(currentUsage.totalTokens, executionUsage?.totalTokens),\n };\n // Only emit detail fields once some step reported them, so providers without caching don't show a misleading 0\n for (const key of ['cachedInputTokens', 'cacheCreationInputTokens', 'reasoningTokens'] as const) {\n const current = currentUsage[key];\n const step = executionUsage?.[key];\n if (current !== undefined || step !== undefined) {\n usage[key] = (current ?? 0) + (step ?? 0);\n }\n }\n return usage;\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 content: executionOutput.output.content,\n toolCalls: executionOutput.output.toolCalls,\n // Tracing facts stay off the step records, which `stream.steps` and the finish payload expose.\n toolResults: executionOutput.toolResults?.map(\n ({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, ...result }) => result,\n ),\n usage: executionOutput.output.usage,\n finishReason: executionOutput.stepResult.reason,\n tripwire: executionOutput.stepResult.tripwire,\n };\n}\n\n/**\n * An output processor can hold a tool result past its tool-call step and emit\n * it when a later stream ends. The tool-call step recorded it as hidden; now\n * that it was emitted, callbacks report it again.\n */\nfunction withReleasedToolResults<T extends StepRecord>(steps: T[], released?: string[]): T[] {\n if (!released?.length) return steps;\n const ids = new Set(released);\n return steps.map(step => {\n if (!step.toolResults?.some(result => isHeldResult(result, ids))) return step;\n return {\n ...step,\n toolResults: step.toolResults.map(result => {\n if (!isHeldResult(result, ids)) return result;\n const { resultHidden: _resultHidden, ...rest } = result as { resultHidden?: boolean };\n return rest;\n }),\n };\n });\n}\n\nfunction isHeldResult(result: unknown, ids: Set<string>): boolean {\n const record = result as { toolCallId?: string; resultHidden?: boolean } | undefined;\n return !!record?.resultHidden && !!record.toolCallId && ids.has(record.toolCallId);\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(\n input: IterationStateUpdateInput,\n): BaseIterationState & Required<Pick<BaseIterationState, 'accumulatedSteps'>> {\n const { currentState, executionOutput } = input;\n const previousSteps = currentState.accumulatedSteps ?? [];\n\n // Legacy states with completed steps cannot prove whether their numeric totals\n // include every provider measurement. Preserve the zero identity only for a\n // pre-first-step state; otherwise migrate the accumulator to unknown.\n const currentUsage =\n currentState.usageAggregationVersion === 1 || previousSteps.length === 0\n ? currentState.accumulatedUsage\n : {\n ...currentState.accumulatedUsage,\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n const signalPreempted = executionOutput.stepResult.signalPreempted === true;\n const newUsage = signalPreempted\n ? currentState.accumulatedUsage\n : calculateAccumulatedUsage(currentUsage, executionOutput.output.usage);\n const lastStepResult = { ...executionOutput.stepResult };\n delete lastStepResult.request;\n\n return {\n runId: currentState.runId,\n agentId: currentState.agentId,\n agentName: currentState.agentName,\n messageListState: executionOutput.messageListState,\n initialUntaggedSystemMessages: currentState.initialUntaggedSystemMessages,\n toolsMetadata: currentState.toolsMetadata,\n modelConfig: currentState.modelConfig,\n options: currentState.options,\n state: executionOutput.state,\n messageId: executionOutput.messageId,\n // Carried, not recomputed: the request context is fixed for the run, and\n // the steps that rebuild from Mastra have no other source for it.\n requestContextEntries: currentState.requestContextEntries,\n inputTripwire: signalPreempted ? currentState.inputTripwire : undefined,\n iterationCount: currentState.iterationCount + (signalPreempted ? 0 : 1),\n accumulatedSteps: signalPreempted\n ? previousSteps\n : [\n ...withReleasedToolResults(previousSteps, executionOutput.releasedToolResultIds),\n buildStepRecord(executionOutput),\n ],\n accumulatedUsage: newUsage,\n usageAggregationVersion: signalPreempted ? currentState.usageAggregationVersion : 1,\n lastStepResult,\n deferredStepFinishChunk: executionOutput.deferredStepFinishChunk,\n backgroundTaskPending: executionOutput.backgroundTaskPending,\n delegationBailed: executionOutput.delegationBailed,\n deadlineTimeout: executionOutput.deadlineTimeout ?? currentState.deadlineTimeout,\n runAborted: executionOutput.runAborted ?? currentState.runAborted,\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 // Set by the predicate after it publishes a step-finish, like pendingFeedbackStop.\n responseMessagesCursor: currentState.responseMessagesCursor,\n // Carry span identity forward unchanged so every iteration shares one trace.\n agentSpanData: currentState.agentSpanData,\n modelSpanData: currentState.modelSpanData,\n // First inference wins; later iterations never overwrite it. Both values travel\n // together, so state saved with only the clock never gains a later step's number.\n ...(currentState.completionStartTime\n ? { completionStartTime: currentState.completionStartTime, timeToFirstTokenMs: currentState.timeToFirstTokenMs }\n : {\n completionStartTime: executionOutput.completionStartTime,\n timeToFirstTokenMs: executionOutput.timeToFirstTokenMs,\n }),\n // The latest iteration's response, even when it has none, as in the main loop: a run\n // whose final step is aborted or rejected mid-stream ends with no response on the span.\n lastResponse: signalPreempted ? currentState.lastResponse : executionOutput.response,\n // Both belong to the iteration whose lastStepResult the final step classifies.\n tracingTermination: executionOutput.tracingTermination,\n tracingDelegationFailure: executionOutput.tracingDelegationFailure,\n };\n}\n","import type { BaseIterationState } from './schemas';\n\ntype AccumulatedSteps = NonNullable<BaseIterationState['accumulatedSteps']>;\n\ntype StepsCarrier = { accumulatedSteps?: AccumulatedSteps };\n\ntype StateParams = { getState(keys?: readonly string[]): Promise<unknown> };\n\n/**\n * Where the run's step records (`accumulatedSteps`) live between steps. Same\n * rule as the transcript (see `readMessageListState`): the durable loop seeds\n * them into workflow state once (`init-iteration-state`), so a persisted\n * snapshot carries one copy (in `value`) instead of one per step payload. Runs\n * that never seeded them — those persisted before the move, or workflows\n * composing these steps without seeding — keep threading them through step\n * input/output unchanged.\n */\nexport function readAccumulatedSteps(workflowState: unknown, stepPayload: unknown): AccumulatedSteps {\n return (\n (workflowState as StepsCarrier | undefined)?.accumulatedSteps ??\n (stepPayload as StepsCarrier | undefined)?.accumulatedSteps ??\n []\n );\n}\n\n/** Loads the run's step records, and nothing else from workflow state. */\nexport async function loadAccumulatedSteps(params: StateParams, stepPayload: unknown): Promise<AccumulatedSteps> {\n return readAccumulatedSteps(await params.getState(['accumulatedSteps']), stepPayload);\n}\n\n/**\n * Stores updated step records where this run keeps them. Returns the fields to\n * spread into the step output: nothing when they went to workflow state,\n * `{ accumulatedSteps }` when the run threads them through step payloads.\n */\nexport async function storeAccumulatedSteps(\n params: StateParams & { setState(state: unknown): Promise<void> },\n accumulatedSteps: AccumulatedSteps,\n): Promise<{ accumulatedSteps?: AccumulatedSteps }> {\n const stored = (await params.getState(['accumulatedSteps'])) as StepsCarrier | undefined;\n if (stored?.accumulatedSteps === undefined) {\n return { accumulatedSteps };\n }\n await params.setState({ accumulatedSteps });\n return {};\n}\n","import { normalizeToolCallConcurrency } from '../../../../loop/workflows/agentic-execution/tool-call-concurrency';\nimport { 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' | 'toolName' | 'requireApproval' | 'hasSuspendSchema'>[];\n}): number {\n if (options?.requireToolApproval) {\n return 1;\n }\n\n // Step-stamped capability flags cover tools that input processors added for\n // this step (e.g. via ToolSearchProcessor). Those tools never appear in the\n // run-start `toolsMetadata`, so the metadata lookups below cannot see them.\n // The stamps are persisted with the tool calls, so this stays correct across\n // cold durable resumes (issue #24377).\n if (toolCalls?.some(tc => tc.requireApproval || tc.hasSuspendSchema)) {\n return 1;\n }\n\n const { limit, strategy } = normalizeToolCallConcurrency(options?.toolCallConcurrency);\n\n let consideredTools: SerializableToolMetadata[];\n if (strategy === 'called') {\n // Opt-in: consider only the tools the model actually called this step. A\n // batch that never called a suspend/approval tool cannot suspend this step,\n // so it may run at the configured concurrency.\n const calledNames = new Set((toolCalls ?? []).map(tc => tc.toolName).filter((name): name is string => !!name));\n consideredTools = (toolsMetadata ?? []).filter(tool => calledNames.has(tool.name));\n } else {\n // Default: consider the step's effective active tool set (a registered\n // suspend/approval tool forces sequential even if the model skipped it).\n const stamped = toolCalls?.find(tc => tc.activeTools !== undefined);\n const activeTools = stamped ? stamped.activeTools : options?.activeTools;\n consideredTools =\n activeTools === undefined || activeTools === null\n ? (toolsMetadata ?? [])\n : (toolsMetadata ?? []).filter(tool => activeTools.includes(tool.name));\n }\n\n if (consideredTools.some(tool => tool.hasSuspendSchema || tool.requireApproval)) {\n return 1;\n }\n\n return limit > 0 ? limit : DurableAgentDefaults.TOOL_CALL_CONCURRENCY;\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { checkBackgroundTasks } from '../../../../loop/shared/steps/background-task-check-core';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { DurableStepIds } from '../../constants';\nimport { getRunRegistryEntry, globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\nimport { createRunMessageList } from '../../utils/run-message-list';\nimport {\n foldBackgroundResults,\n hasAppliedBackgroundResults,\n settleFinishedBackgroundResults,\n} from '../shared/background-results';\nimport { readMessageListState, storeMessageListState } from '../shared/message-list-state';\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. Behavior lives in the shared\n * `checkBackgroundTasks` core; this glue owns registry/init-data access, the\n * durable wait gate, and pubsub emission.\n *\n * The durable wait gate differs from the main loop's on purpose: the regular\n * agent can skip waiting because background tool-result chunks are pushed\n * directly into the live ReadableStream controller — that works even after\n * this step returns. The durable agent emits tool-result chunks via pubsub,\n * and the subscription is torn down when the stream closes. If this step\n * returned without waiting, the workflow would finish, FINISH would fire,\n * cleanup would run, and the subscriber would be gone before the background\n * task could deliver its result. Therefore the durable agent must always\n * wait when tasks are running — using the configured waitTimeoutMs, or a 1 s\n * default to keep the workflow (and pubsub) alive. It only signals pending\n * without blocking on retryCount 0 when an explicit timeout is configured\n * (meaning the caller drives continuation externally).\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 if (typedInput.stepResult?.signalPreempted && !typedInput.stepResult.isContinued) return typedInput;\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 = getRunRegistryEntry(runId, params.mastra);\n const bgManager = registryEntry?.backgroundTaskManager;\n const waitTimeoutMs = registryEntry?.backgroundTasksConfig?.waitTimeoutMs ?? bgManager?.config?.waitTimeoutMs;\n\n const outcome = await checkBackgroundTasks({\n bgManager,\n runId,\n agentId,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n skipWait: initData.options?.skipBgTaskWait,\n retryCount,\n resolveWaitMs: rc => (rc === 0 && waitTimeoutMs ? undefined : (waitTimeoutMs ?? 1000)),\n emitChunk: chunk => {\n if (!pubsub) return;\n return emitChunkEvent(pubsub, runId, chunk as any);\n },\n });\n\n // A task's status turns terminal before its onResult hook runs, so wait for the hooks of\n // finished tasks. Cancelled tasks never call it.\n if (bgManager) {\n await settleFinishedBackgroundResults(\n registryEntry,\n async taskId => {\n // A failed read only skips the wait for this task; its result still folds in if its hook has run.\n const status = (await bgManager.getTask(taskId).catch(() => undefined))?.status;\n return status === 'completed' || status === 'failed' || status === 'timed_out';\n },\n waitTimeoutMs ?? 1000,\n );\n }\n // onResult wrote finished results into the tool-call step's message list, not into the\n // transcript in workflow state that the next model call reads.\n let output = typedInput;\n if (hasAppliedBackgroundResults(registryEntry)) {\n const transcript = await readMessageListState(params, typedInput);\n const list = createRunMessageList({ mastra: params.mastra }).deserialize(transcript);\n if (await foldBackgroundResults(registryEntry, list)) {\n output = { ...typedInput, ...(await storeMessageListState(params, list.serialize())) };\n }\n }\n\n switch (outcome.status) {\n case 'pass-through':\n case 'timeout':\n return output;\n case 'pending':\n return { ...output, backgroundTaskPending: true };\n case 'completed':\n if (output.stepResult) {\n return {\n ...output,\n backgroundTaskPending: true,\n stepResult: { ...output.stepResult, isContinued: true },\n };\n }\n return { ...output, backgroundTaskPending: true };\n }\n },\n });\n}\n","import type { ReadableStream as NodeReadableStream } from 'node:stream/web';\nimport type { LanguageModelV2Prompt } from '@ai-sdk/provider-v5';\nimport type { ToolChoice, ToolSet } from '@internal/ai-sdk-v5';\nimport { expandDurableSteps } from '@internal/core/durable';\nimport { z } from 'zod';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../../../error';\nimport { serializeError } from '../../../../events/codec/error';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { validateModelTimeoutSettings } from '../../../../llm/model/model-settings';\nimport { mergeProviderOptions } from '../../../../llm/model/provider-options';\nimport { resolveApiProviderId } from '../../../../llm/model/router';\nimport { resolveResponseModelId } from '../../../../llm/model/server-side-fallback';\nimport type { SharedProviderOptions } from '../../../../llm/model/shared.types';\nimport { ConsoleLogger } from '../../../../logger';\nimport { LOCAL_MODEL_REQUEST_KEY, STEP_MODEL_MESSAGES_KEY } from '../../../../loop/run-scope-keys';\nimport { applyAutoResumeSystemMessage } from '../../../../loop/shared/auto-resume-system-message';\nimport { backgroundOutcomesInPrompt, snapshotBackgroundOutcomes } from '../../../../loop/shared/background-outcomes';\nimport { buildLlmPromptArgs } from '../../../../loop/shared/build-llm-prompt-args';\nimport { composeStepInput } from '../../../../loop/shared/compose-step-input';\nimport { agentLoopTermination, executionFailureTermination } from '../../../../loop/shared/execution-outcome';\nimport { injectBackgroundTaskPrompt } from '../../../../loop/shared/inject-background-task-prompt';\nimport { trackOpenReasoning, watchInterruptibleStream } from '../../../../loop/shared/interruptible-stream';\nimport { buildMemoryHeaders, mergeLlmCallHeaders } from '../../../../loop/shared/merge-llm-call-headers';\nimport { persistUnavailableAttachments } from '../../../../loop/shared/persist-unavailable-attachments';\nimport { readToolResultFromMessageList } from '../../../../loop/shared/read-tool-result';\nimport { recordTerminalErrorMessage } from '../../../../loop/shared/record-terminal-error-message';\nimport { snapshotSignalOutcome } from '../../../../loop/shared/signal-outcome';\nimport { STEP_CONTENT_CHUNK_TYPES } from '../../../../loop/shared/step-content-chunk-types';\nimport { processAndEmitChunk } from '../../../../loop/shared/steps/process-chunk-core';\nimport { TERMINAL_FINISH_REASONS } from '../../../../loop/shared/terminal-finish-reasons';\nimport { applyToolPayloadTransformToChunk } from '../../../../loop/shared/tool-payload-transform';\nimport { getAbortReason, isMastraTimeoutError } from '../../../../loop/timeout';\nimport type { MastraTimeoutError } from '../../../../loop/timeout';\nimport { buildMessagesFromChunks } from '../../../../loop/workflows/agentic-execution/build-messages-from-chunks';\nimport type { CollectedChunk } from '../../../../loop/workflows/agentic-execution/build-messages-from-chunks';\nimport { getToolResultInvocationState } from '../../../../loop/workflows/agentic-execution/provider-tool-result-state';\nimport { endPendingProviderToolSpan } from '../../../../loop/workflows/agentic-execution/provider-tool-spans';\nimport type { PendingProviderToolCall } from '../../../../loop/workflows/agentic-execution/provider-tool-spans';\nimport type { Mastra } from '../../../../mastra';\nimport { createRunScope } from '../../../../mastra/run-scope';\nimport type {\n AIModelGenerationSpan,\n ExportedSpan,\n IModelSpanTracker,\n AnySpan,\n Span,\n SpanType,\n} from '../../../../observability';\nimport { EntityType, createObservabilityContext } from '../../../../observability';\nimport type { SpanTermination } from '../../../../observability/types/outcome';\nimport { extractUsageMetrics } from '../../../../observability/usage';\nimport { executeWithContextSync, getRootExportSpan } from '../../../../observability/utils';\nimport type { CachedLLMStepResponse } from '../../../../processors';\nimport { PrepareStepProcessor } from '../../../../processors/processors/prepare-step';\nimport { resolveMaxProcessorRetries } from '../../../../processors/retry-budget';\nimport type { ProcessorState } from '../../../../processors/runner';\nimport { ProcessorRunner } from '../../../../processors/runner';\nimport type { ProcessorLateSignalSink } from '../../../../processors/send-signal';\nimport {\n needsTrailingAssistantGuard,\n removeTrailingAssistantGuardContinuations,\n} from '../../../../processors/trailing-assistant-guard';\nimport { getToolDefinitionsForTracing } from '../../../../stream/aisdk/v5/compat/prepare-tools';\nimport { execute, sendsNativeResponseFormat } from '../../../../stream/aisdk/v5/execute';\nimport { MastraModelOutput, persistProcessorDataChunk } from '../../../../stream/base/output';\nimport type { ChunkType, TextDeltaPayload, ToolCallPayload } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport { withToolPayloadTransformProviderMetadata } from '../../../../tools/payload-transform';\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, makeProcessorCoreTool } from '../../../../utils';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport type { ExecuteFunctionParams } from '../../../../workflows/step';\nimport type { DefaultEngineType } from '../../../../workflows/types';\nimport { createStep } from '../../../../workflows/workflow';\nimport { isDownloadAssetsError } from '../../../message-list/prompt/download-assets';\nimport { startRunStep } from '../../../run-lease-fence';\nimport { createSignal } from '../../../signals';\nimport { TripWire } from '../../../trip-wire';\nimport { isSupportedLanguageModel } from '../../../utils';\nimport { ensureRemoteAbortListener, readRunDeadline } from '../../abort-transport';\nimport { DurableStepIds } from '../../constants';\nimport { ExecutionFence, getExecutionOwnershipGuard } from '../../execution-fence';\nimport { endRunSpansWithError, getRunRegistryEntry, markRunActive } from '../../run-registry';\nimport {\n createStepStartChunk,\n emitChunkEvent,\n emitIterationStartEvent,\n publishStepStartChunk,\n} from '../../stream-adapter';\nimport type { DurableAgenticWorkflowInput, DurableLLMStepOutput, DurableToolCallInput } from '../../types';\nimport { resolveRuntimeDependencies, resolveModelFromListEntry } from '../../utils/resolve-runtime';\nimport { createRunMessageList } from '../../utils/run-message-list';\nimport { loadAccumulatedSteps } from '../shared/accumulated-steps';\nimport { carriedSpanClocks } from '../shared/iteration-state';\nimport { readMessageListState, storeMessageListState } from '../shared/message-list-state';\nimport { baseIterationStateSchema, durableOptionsSchema, responseRecordSchema } from '../shared/schemas';\n\n/**\n * Detect a run-level budget expiry (`modelSettings.timeout.totalMs`, #21724\n * parity port). Total timeouts must surface as run *failures* — not clean\n * aborts and never retries/fallbacks — matching the main loop, where the\n * total-timeout race rejects the stream with the `MastraTimeoutError`.\n *\n * Step budgets (`timeoutType: 'step'`) are deliberately excluded: they are\n * handled inside the shared `execute()` (no same-model retry, fall back to\n * the next model) and must not kill the whole run.\n */\nfunction resolveTotalTimeoutAbort(signal: AbortSignal | undefined, error?: Error): MastraTimeoutError | undefined {\n const reason = getAbortReason(signal);\n if (isMastraTimeoutError(reason) && reason.timeoutType === 'total') return reason;\n if (isMastraTimeoutError(error) && error.timeoutType === 'total') return error;\n return undefined;\n}\n\nclass DurableOutputProcessorError extends Error {\n constructor(error: unknown) {\n super(error instanceof Error ? error.message : String(error), { cause: error });\n this.name = 'DurableOutputProcessorError';\n }\n}\n\nclass DurableChunkPublishError extends Error {\n constructor(error: unknown) {\n super(error instanceof Error ? error.message : String(error), { cause: error });\n this.name = 'DurableChunkPublishError';\n }\n}\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 initialUntaggedSystemMessages: z.array(z.any()).optional(),\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 settings: 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: durableOptionsSchema,\n state: z.any(),\n messageId: z.string(),\n // JSON-safe request context snapshot, forwarded from iteration state so the\n // rebuild-from-Mastra path resolves the model and tools with the caller's\n // context rather than an empty one.\n requestContextEntries: z.record(z.string(), z.any()).optional(),\n inputTripwire: baseIterationStateSchema.shape.inputTripwire,\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 // First-chunk clock carried from earlier iterations (first write wins)\n completionStartTime: z.coerce.date().optional(),\n // Time to first token of the inference that streamed that chunk, carried the same way\n timeToFirstTokenMs: z.number().optional(),\n // Step index for continuation (step: 0, 1, 2, ...)\n stepIndex: z.number().optional(),\n signalPreempted: z.boolean().optional(),\n // Step results from previous iterations, passed to processor hooks as `steps`\n accumulatedSteps: z.array(z.any()).optional(),\n});\n\n/**\n * Output schema for the durable LLM execution step.\n *\n * Declared for type/schema honesty: no engine validates step outputs today\n * (`validateInputs: false` in both loop builders, no output-side validation\n * in the workflows engine), but Zod would strip undeclared fields if\n * validation is ever (re-)enabled — declare new output fields here.\n */\nconst durableLLMOutputSchema = z.object({\n // Absent when the run keeps the transcript in workflow state.\n messageListState: z.any().optional(),\n text: z.string().optional(),\n // Element shape mirrors DurableToolCallInput / the tool-call step's input schema.\n toolCalls: z.array(\n z.object({\n toolCallId: z.string(),\n toolName: z.string(),\n args: z.record(z.string(), z.any()).optional(),\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 requireApproval: z.boolean().optional(),\n hasSuspendSchema: z.boolean().optional(),\n stepSpanData: z.any().optional(),\n }),\n ),\n stepResult: z.object({\n reason: z.string(),\n warnings: z.array(z.any()),\n isContinued: z.boolean(),\n signalPreempted: z.boolean().optional(),\n totalUsage: z.any().optional(),\n tripwire: z.any().optional(),\n messageId: z.string().optional(),\n }),\n metadata: z.any(),\n processorRetryCount: z.number().optional(),\n processorRetryFeedback: z.string().optional(),\n releasedToolResultIds: z.array(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 // Deferred step-finish chunk carried until the loop predicate has resolved\n // the actual continuation decision.\n deferredStepFinishChunk: z.any().optional(),\n // When this step's inference streamed its first chunk; the loop keeps the first one\n completionStartTime: z.coerce.date().optional(),\n // Time to first token of the inference that streamed that chunk; kept with it\n timeToFirstTokenMs: z.number().optional(),\n // Provider id and serving model of the response, only when the provider sent one\n response: responseRecordSchema.optional(),\n // Outcome of a step that ended the run itself, carried to the final step through the state\n tracingTermination: z.custom<SpanTermination>().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\ntype LLMExecutionParams = ExecuteFunctionParams<\n unknown,\n z.infer<typeof durableLLMInputSchema>,\n z.infer<typeof durableLLMOutputSchema>,\n unknown,\n unknown,\n DefaultEngineType\n>;\n\ntype StepLifetime = { closed: boolean };\n\n/** Close on failure too, so retained callbacks never write to an abandoned step. */\nfunction withStepLifetime<Params, Result>(execute: (params: Params, lifetime: StepLifetime) => Promise<Result>) {\n return async (params: Params): Promise<Result> => {\n const lifetime = { closed: false };\n try {\n return await execute(params, lifetime);\n } finally {\n lifetime.closed = true;\n }\n };\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: withStepLifetime(async (params: LLMExecutionParams, stepLifetime) => {\n const { inputData, mastra, tracingContext, requestContext, abortSignal } = params;\n const ownership = getExecutionOwnershipGuard(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 & z.infer<typeof durableLLMInputSchema>;\n const { agentId, messageId, options: execOptions } = typedInput;\n const runId = typedInput.runId;\n const logger = mastra?.getLogger?.();\n if (pubsub) await emitIterationStartEvent(pubsub, runId, inputData.stepIndex ?? 0);\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, messageListState: await readMessageListState(params, typedInput) },\n requestContext,\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 // Serialization ends this list's writable lifetime, before asynchronous\n // storage begins. Later sends must use the run queue, whose drain owns\n // transcript insertion, message rotation and the single stream echo.\n const storeStepTranscript = () => {\n stepLifetime.closed = true;\n return storeMessageListState(params, messageList.serialize());\n };\n const signalOwner = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const enqueuePendingSignal = signalOwner?.enqueuePendingSignal;\n const lateSignalSink: ProcessorLateSignalSink | undefined = enqueuePendingSignal\n ? {\n isClosed: () => stepLifetime.closed,\n send: async signalInput => {\n // Threadless runs have no thread-runtime queue. Keep their signals\n // on the live run entry; the next LLM step drains it identically.\n if (\n !signalOwner ||\n getRunRegistryEntry(runId, mastra as Mastra | undefined) !== signalOwner ||\n (signalOwner.executionFence &&\n (ExecutionFence.getLocalActive(runId) !== signalOwner.executionFence ||\n signalOwner.executionFence.isLost())) ||\n signalOwner.abortSignal?.aborted\n ) {\n throw new Error(`Cannot send processor signal: run ${runId} is no longer active`);\n }\n if (typedInput.state?.threadId && typedInput.state?.resourceId) return enqueuePendingSignal(signalInput);\n const signal = createSignal(signalInput);\n (signalOwner.pendingProcessorSignals ??= []).push(signal);\n return signal;\n },\n }\n : undefined;\n\n // 1a-bis. Become responsive to abort requests from other processes. The\n // caller that owns `abort()` may live on a different pod entirely, so\n // without this the run has no way to hear it. Must happen before the\n // abort check below so a request that arrives mid-step is honoured.\n // A transport failure here costs remote abortability, not the run itself,\n // so it is logged rather than thrown.\n if (pubsub) {\n try {\n await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(requestContext));\n } catch (error) {\n ownership?.throwIfLost();\n logger?.warn?.('Failed to subscribe to cross-process abort requests', {\n runId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n let request: any = {};\n\n // Emit error + step-finish chunks and return a bail response. This\n // mirrors the regular agent which sets stepResult.reason = 'error' and\n // emits a deferred error chunk rather than crashing the loop. Used by\n // the exhausted-models path and by run-level timeout expiry (#21724).\n let terminateAttemptSpans: ((termination: SpanTermination) => void) | undefined;\n let tracingTermination: SpanTermination | undefined;\n const recordTermination = (termination: SpanTermination) => {\n tracingTermination = termination;\n // The registry copy keeps older @mastra/inngest finalizers working in-process.\n const registry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n if (registry) registry.tracingTermination = termination;\n };\n const emitFatalErrorBail = async (\n fatalError: Error,\n modelId: string,\n signalPreempted = false,\n ): Promise<DurableLLMStepOutput> => {\n ownership?.throwIfLost();\n // Even an empty failing request must replace the previous step's request.\n getRunRegistryEntry(runId, mastra as Mastra | undefined)?.runScope?.set(LOCAL_MODEL_REQUEST_KEY, request);\n const usage = {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n // This bail returns a finish result. Record the failure now, but let finalization\n // end the roots with accumulated usage and output, including on evented workers.\n const termination = executionFailureTermination(fatalError);\n recordTermination(termination);\n terminateAttemptSpans?.(termination);\n // A total timeout can tear down the workflow before its finish mapping runs.\n endRunSpansWithError(runId, fatalError, {\n endSpan: isMastraTimeoutError(fatalError) && fatalError.timeoutType === 'total',\n });\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 // Serialize explicitly: a raw Error JSON-stringifies to `{}` on plain\n // transports, which destroys the producer stack and makes crashes\n // unattributable on the consumer side. Own fields (statusCode, ...)\n // are kept so the caller sees the full provider error.\n payload: { error: serializeError(fatalError) },\n });\n\n if (!signalPreempted) {\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: { reason: 'error', isContinued: false },\n output: { usage },\n metadata: {},\n },\n });\n }\n }\n\n return {\n ...(await storeStepTranscript()),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'error',\n warnings: [],\n isContinued: false,\n ...(signalPreempted ? { signalPreempted: true } : {}),\n },\n metadata: { modelId },\n state: typedInput.state,\n tracingTermination,\n } satisfies DurableLLMStepOutput;\n };\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 selectedAbortSignal = getRunRegistryEntry(runId, mastra as Mastra | undefined)?.abortSignal ?? abortSignal;\n const executionAbortSignalEarly = ownership?.composeSignal(selectedAbortSignal) ?? selectedAbortSignal;\n ownership?.throwIfLost();\n if (executionAbortSignalEarly?.aborted) {\n // A run-level budget expiry between iterations (e.g. while a tool\n // call was running) must fail the run, not settle it as a clean\n // abort (#21724).\n const earlyTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly);\n if (earlyTimeout) {\n return emitFatalErrorBail(\n earlyTimeout,\n typedInput.modelConfig?.modelId ?? 'unknown',\n inputData.signalPreempted === true,\n );\n }\n return {\n ...(await storeStepTranscript()),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'abort',\n warnings: [],\n isContinued: false,\n ...(inputData.signalPreempted ? { signalPreempted: true } : {}),\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, with a serialized fallback for\n // separate workers. Emit a tripwire chunk and bail before calling the model.\n const registryTripwire =\n getRunRegistryEntry(runId, mastra as Mastra | undefined)?.tripwire ?? typedInput.inputTripwire;\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 = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n if (entry) entry.tripwire = undefined;\n recordTermination(agentLoopTermination({ tripwire: registryTripwire }));\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 ...(await storeStepTranscript()),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n warnings: [],\n isContinued: false,\n },\n metadata: {},\n state: typedInput.state,\n tracingTermination,\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 // Agent-level maxRetries rides on serialized options (there is\n // no modelList entry to carry it for single-model agents).\n maxRetries: typedInput.options?.agentMaxRetries ?? 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 // Errors recovered inside this ladder (per-attempt retry / model\n // rotation) are never emitted as chunks, so output processors only ever\n // see the attempt that succeeds; only the terminal exhausted-models\n // error is published. Main needed an explicit guard to keep recovered\n // errors away from processors (#21738) — durable is immune by\n // construction, don't port that guard here.\n let lastError: Error | undefined;\n let skipUnavailableAttachments = false;\n const maxProcessorRetries = resolveMaxProcessorRetries({\n maxProcessorRetries: typedInput.options?.maxProcessorRetries,\n hasErrorProcessors: Boolean(getRunRegistryEntry(runId, mastra as Mastra | undefined)?.errorProcessors?.length),\n hasConfiguredErrorProcessors: Boolean(typedInput.options?.hasErrorProcessors),\n agentId,\n logger,\n });\n\n // Hoisted: a retry must keep the id an error processor rotated to.\n let currentMessageId = messageId;\n const rotateResponseMessageId = () => {\n currentMessageId = messageList.rotateResponseMessageId(currentMessageId);\n return currentMessageId;\n };\n\n // Input queued while this step's model request has produced only reasoning cancels\n // the request (not the run), and the step returns so the loop asks again with that input.\n const signalRegistry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const interruption = new AbortController();\n let interruptionOutcome: SpanTermination = { outcome: 'interrupted', stopReason: 'signal_received' };\n let interruptible = false;\n signalRegistry?.stopStepSignalListener?.();\n const stopListening = signalRegistry?.subscribePendingSignals?.(signals => {\n if (interruptible && !executionAbortSignalEarly?.aborted && !interruption.signal.aborted) {\n interruptionOutcome = {\n outcome: 'interrupted',\n stopReason: 'signal_received',\n stopReasonContext: snapshotSignalOutcome(signals),\n };\n interruption.abort(new Error('Interrupted by a queued signal'));\n }\n });\n if (signalRegistry) signalRegistry.stopStepSignalListener = stopListening;\n const throwIfInterrupted = () => {\n ownership?.throwIfLost();\n if (interruption.signal.aborted) throw interruption.signal.reason;\n };\n const openReasoningIds = new Set<string>();\n // Each durable attempt opens its own MODEL_STEP; a cancelled one ends both its spans here.\n let endAttemptSpans: (() => void) | undefined;\n // The attempt's first-chunk clocks. Every step output returned after the model call\n // carries them, since the finalizer ends the rebuilt spans with the loop state's copy.\n let recordClocks: (() => { completionStartTime?: Date; timeToFirstTokenMs?: number }) | undefined;\n // Ends the attempt's inference span with the error before a retry or fallback opens its own.\n let failInference: ((error: Error) => void) | undefined;\n const finishInterruptedRequest = async (error: unknown, modelId: string): Promise<DurableLLMStepOutput> => {\n ownership?.throwIfLost();\n stopListening?.();\n endAttemptSpans?.();\n for (const state of signalRegistry?.processorStates?.values() ?? []) {\n state.streamParts.splice(processorPartCounts.get(state) ?? 0);\n }\n if (pubsub) {\n for (const id of openReasoningIds) {\n await emitChunkEvent(\n pubsub,\n runId,\n { type: 'reasoning-end', runId, from: ChunkFrom.AGENT, payload: { id } },\n true,\n );\n }\n }\n const totalTimeout = resolveTotalTimeoutAbort(\n executionAbortSignalEarly,\n error instanceof Error ? error : undefined,\n );\n if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, true);\n return {\n ...(await storeStepTranscript()),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'other',\n warnings: [],\n isContinued: executionAbortSignalEarly?.aborted !== true,\n signalPreempted: true,\n },\n metadata: { modelId },\n state: typedInput.state,\n ...recordClocks?.(),\n };\n };\n // Processor retries are read from the step history: each rejected step is recorded with\n // finishReason 'retry' and the tripwire that rejected it. Only consecutive retries count.\n // API-error retries happen inside this step and add to the same count, as in Agent.\n const previousSteps = await loadAccumulatedSteps(params, inputData);\n let processorRetryCount = 0;\n for (let i = previousSteps.length - 1; i >= 0 && previousSteps[i]?.finishReason === 'retry'; i--) {\n processorRetryCount++;\n }\n const lastStep = previousSteps.at(-1);\n const processorRetryFeedback = lastStep?.finishReason === 'retry' ? lastStep.tripwire?.reason : undefined;\n\n // The abort reason from a processor-requested retry goes at the end of the conversation\n // as a reminder signal (mirrors the main loop). The response message id is rotated first\n // so the retry streams into a new message after the signal.\n if (processorRetryFeedback) {\n rotateResponseMessageId();\n const feedbackSignal = messageList.addSignal(\n createSignal({\n type: 'reactive',\n tagName: 'system-reminder',\n contents: processorRetryFeedback,\n }),\n );\n if (pubsub) {\n await emitChunkEvent(pubsub, runId, feedbackSignal.toDataPart());\n }\n }\n const initialEchoes = signalRegistry?.initialSignalEchoes?.splice(0) ?? [];\n // Pre-run signals join the first request, as before. Later requests also take signals\n // queued since the loop's last drain: they arrived before this step subscribed, so they\n // could not interrupt it, and this is the request they would restart.\n const isFirstRequest = (inputData.stepIndex ?? 0) === 0 && !inputData.signalPreempted;\n const queuedSignals = [\n ...((inputData.stepIndex ?? 0) === 0 ? (signalRegistry?.drainPendingSignals?.('pre-run') ?? []) : []),\n ...(isFirstRequest ? [] : (signalRegistry?.drainPendingSignals?.('pending') ?? [])),\n ...(signalRegistry?.pendingProcessorSignals?.splice(0) ?? []),\n ];\n if (queuedSignals.length) rotateResponseMessageId();\n const admittedSignals = queuedSignals.map(signal => messageList.addSignal(signal));\n // Subscribed before the drain above, so nothing queued in between is missed.\n interruptible = true;\n const processorPartCounts = new Map<ProcessorState, number>(\n [...(signalRegistry?.processorStates?.values() ?? [])].map(state => [state, state.streamParts.length]),\n );\n if (pubsub) {\n for (const signal of [...initialEchoes, ...admittedSignals]) {\n await emitChunkEvent(pubsub, runId, signal.toDataPart());\n }\n }\n // Mirror Agent: later iterations continue the same assistant message behind a step-start\n // boundary, so sequential tool steps aren't replayed as parallel calls (#26332).\n // What a total deadline that cuts this step off saves: the list as it enters the step. That is the\n // completed steps plus what was added between steps (completion-check feedback, signals).\n const deadlineEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n if (deadlineEntry?.timeoutTotalMs) {\n deadlineEntry.completedStepsState = JSON.parse(JSON.stringify(messageList.serialize()));\n }\n const iterationBoundary = previousSteps.length > 0 ? messageList.openStepBoundary().boundary : undefined;\n let terminalAttemptContext:\n | {\n recordTerminalError: (error: unknown) => void;\n }\n | undefined;\n\n for (let modelIndex = 0; modelIndex < modelList.length; modelIndex++) {\n const modelEntry = modelList[modelIndex]!;\n // Same precedence as the in-process loop (llm-execution-step.ts): an\n // explicitly configured agent-level maxRetries wins; otherwise the\n // call-time modelSettings.maxRetries applies. Serialized fallback-list\n // entries always carry a folded per-model value, so they keep it.\n const entryConfigured = hasModelList || (typedInput.options?.agentMaxRetriesConfigured ?? false);\n const maxRetries = entryConfigured\n ? modelEntry.maxRetries || 0\n : (typedInput.options?.modelSettings?.maxRetries ?? modelEntry.maxRetries ?? 0);\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n ownership?.throwIfLost();\n request = {};\n // Capture this attempt before processors can rotate the active id. The\n // fallback callback covers failures before a stream can materialize;\n // it resolves currentMessageId only when the terminal error is known.\n const attemptMessageId = currentMessageId;\n terminalAttemptContext = {\n recordTerminalError: error => {\n recordTerminalErrorMessage({\n messageList,\n attemptId: attemptMessageId,\n activeId: currentMessageId,\n error,\n });\n },\n };\n\n // Declared outside the try so the outer catch can persist\n // already-streamed partial output on abort (#22593). Assigned inside\n // once streaming state exists; undefined means nothing streamed yet.\n const textDeltas: string[] = [];\n let materializeStreamedMessages: (() => void) | undefined;\n let removeAttemptAbortListener: (() => void) | undefined;\n let deferredStepFinishChunk: any = null;\n const prepareDeferredStepFinishChunk = ({\n reason,\n isContinued,\n tripwire,\n }: {\n reason?: DurableLLMStepOutput['stepResult']['reason'];\n isContinued: boolean;\n tripwire?: DurableLLMStepOutput['stepResult']['tripwire'];\n }) => {\n if (!deferredStepFinishChunk) return undefined;\n\n deferredStepFinishChunk = {\n ...deferredStepFinishChunk,\n payload: {\n ...deferredStepFinishChunk.payload,\n ...(reason === 'retry' && tripwire ? { processorRetryFeedback: tripwire.reason } : {}),\n stepResult: {\n ...deferredStepFinishChunk.payload?.stepResult,\n ...(reason ? { reason } : {}),\n isContinued,\n ...(reason === 'retry' && tripwire\n ? {\n retryReason: tripwire.reason,\n retryMetadata: tripwire.metadata,\n retryProcessorId: tripwire.processorId,\n }\n : {}),\n },\n ...(tripwire ? { output: { ...deferredStepFinishChunk.payload?.output, steps: [{ tripwire }] } } : {}),\n },\n };\n return deferredStepFinishChunk;\n };\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 // 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 // Per-entry settings shallow-merge over call-time settings, timeout\n // fields included — same precedence as the in-process loop.\n const entrySettings = modelEntry.config.settings;\n let currentModelSettings: Record<string, unknown> = {\n ...execOptions.modelSettings,\n ...entrySettings,\n ...(execOptions.modelSettings?.timeout || entrySettings?.timeout\n ? { timeout: { ...execOptions.modelSettings?.timeout, ...entrySettings?.timeout } }\n : {}),\n };\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 = (getRunRegistryEntry(runId, mastra as Mastra | undefined)?.resumeModelSpanData ??\n inputData.modelSpanData) as ExportedSpan<SpanType.MODEL_GENERATION> | undefined;\n // Rebuilt spans come from the run-start snapshot, so re-apply the carried\n // first-chunk clocks before the tracker sees them; otherwise a later\n // step would overwrite them mid-run. The loop state carries the originals'\n // clocks; a resumed segment has fresh spans, so its clocks live on the\n // registry beside them.\n const resumeRegistry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const carriedClocks = carriedSpanClocks(resumeRegistry, inputData);\n const withCarriedClocks = <T extends ExportedSpan<SpanType.MODEL_GENERATION | SpanType.AGENT_RUN>>(\n data: T,\n ): T => {\n // Both values travel together; a span that already has the clock keeps its pair.\n if (!carriedClocks?.completionStartTime || data.attributes?.completionStartTime) return data;\n return { ...data, attributes: { ...data.attributes, ...carriedClocks } };\n };\n recordClocks = () => {\n const completionStartTime = modelSpanTracker?.getCompletionStartTime?.();\n const timeToFirstTokenMs = modelSpanTracker?.getTimeToFirstTokenMs?.();\n if (\n resumeRegistry?.resumeModelSpanData &&\n completionStartTime &&\n !resumeRegistry.resumeCompletionStartTime\n ) {\n resumeRegistry.resumeCompletionStartTime = completionStartTime;\n resumeRegistry.resumeTimeToFirstTokenMs = timeToFirstTokenMs;\n }\n return { completionStartTime, timeToFirstTokenMs };\n };\n const modelSpan = inputModelSpanData\n ? (observability?.rebuildSpan(withCarriedClocks(inputModelSpanData)) as AIModelGenerationSpan | undefined)\n : undefined;\n\n // On remote engines (Inngest) the step's tracingContext span is not part of the\n // exported trace, so parent client-tool spans on the rebuilt AGENT_RUN span instead.\n const inputAgentSpanData = (getRunRegistryEntry(runId, mastra as Mastra | undefined)?.resumeAgentSpanData ??\n inputData.agentSpanData) as ExportedSpan<SpanType.AGENT_RUN> | undefined;\n const agentRunSpan = inputAgentSpanData\n ? (observability?.rebuildSpan(withCarriedClocks(inputAgentSpanData)) as AnySpan | undefined)\n : undefined;\n\n // Create model span tracker for MODEL_STEP and MODEL_CHUNK spans\n const modelSpanTracker: IModelSpanTracker | undefined = modelSpan?.createTracker({\n agentRunSpan: agentRunSpan as Span<SpanType.AGENT_RUN> | undefined,\n });\n const recordProcessedChunk = (chunk: ChunkType) => {\n try {\n modelSpanTracker?.recordChunk?.(chunk);\n } catch {\n // Optional tracing must not prevent accepted output from reaching the caller.\n }\n };\n failInference = error => modelSpanTracker?.failInference?.(error);\n // Older observability releases expose only the step snapshot API.\n // Preserve their cleanup path without requiring a package upgrade.\n const endAttempt = (termination: SpanTermination) => {\n if (modelSpanTracker?.endAttempt) {\n modelSpanTracker.endAttempt(termination);\n } else {\n const stepData = modelSpanTracker?.exportCurrentStep();\n if (stepData) observability?.rebuildSpan(stepData)?.end(termination);\n }\n };\n endAttemptSpans = () => {\n modelSpanTracker?.interruptInference?.(interruptionOutcome);\n endAttempt(interruptionOutcome);\n };\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.stepIndex ?? 0;\n modelSpanTracker?.setStepIndex(stepIndex);\n // The logical step includes input processors, even when they reject\n // the attempt before any provider request is made.\n modelSpanTracker?.startStep();\n terminateAttemptSpans = termination => {\n endAttempt(termination);\n };\n const endTripwireSpans = (\n cause: TripWire | NonNullable<Parameters<typeof agentLoopTermination>[0]['tripwire']>,\n ) => {\n const termination = agentLoopTermination({\n tripwire:\n cause instanceof TripWire\n ? {\n reason: cause.message,\n processorId: cause.processorId,\n retry: cause.options?.retry,\n metadata: cause.options?.metadata,\n }\n : cause,\n });\n recordTermination(termination);\n endAttempt(termination);\n };\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 &&\n !structuredOutputConfig?.structuringModelConfig &&\n !structuredOutputConfig?.hasStructuringModel\n ? {\n schema: structuredOutputConfig.schema,\n jsonPromptInjection: structuredOutputConfig.jsonPromptInjection,\n instructions: structuredOutputConfig.instructions,\n }\n : undefined;\n\n const registryEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const selectedRunAbortSignal = registryEntry?.abortSignal ?? abortSignal;\n if (selectedRunAbortSignal) {\n const endAbortedAttempt = () => {\n const reason = getAbortReason(selectedRunAbortSignal);\n terminateAttemptSpans?.(\n isMastraTimeoutError(reason)\n ? executionFailureTermination(reason)\n : { outcome: 'abort', stopReason: 'caller_cancelled' },\n );\n };\n selectedRunAbortSignal.addEventListener('abort', endAbortedAttempt, { once: true });\n removeAttemptAbortListener = () => selectedRunAbortSignal.removeEventListener('abort', endAbortedAttempt);\n if (selectedRunAbortSignal.aborted) endAbortedAttempt();\n }\n const runAbortSignal = ownership?.composeSignal(selectedRunAbortSignal) ?? selectedRunAbortSignal;\n const executionAbortSignal = stopListening\n ? runAbortSignal\n ? AbortSignal.any([runAbortSignal, interruption.signal])\n : interruption.signal\n : runAbortSignal;\n const baseInputProcessors = registryEntry?.inputProcessors ?? resolvedInputProcessors ?? [];\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 const llmRequestInputProcessors =\n registryEntry?.llmRequestInputProcessors ??\n registryEntry?.inputProcessors ??\n resolvedLlmRequestInputProcessors ??\n resolvedInputProcessors ??\n [];\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\n // Match the plain loop: per-step system-message overrides are scoped\n // to one model attempt, while tagged processor-owned buckets remain.\n messageList.replaceAllSystemMessages(\n typedInput.initialUntaggedSystemMessages ?? messageList.getSystemMessages(),\n );\n\n if (needsTrailingAssistantGuard(currentModel, stepInputProcessors)) {\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 lateSignalSink,\n inputProcessors: stepInputProcessors,\n outputProcessors: effectiveOutputProcessors,\n errorProcessors: registryEntry?.errorProcessors ?? [],\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n agent: registryEntry?.agent,\n processorStates: registryEntry?.processorStates,\n });\n try {\n const processInputStepResult = await runner.runProcessInputStep({\n llmRequestProcessorIds: ProcessorRunner.getLLMRequestProcessorIds(llmRequestInputProcessors),\n messageList,\n stepNumber: stepIndex,\n steps: expandDurableSteps(previousSteps),\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 tools: currentTools,\n toolChoice: currentToolChoice,\n providerOptions: currentProviderOptions,\n activeTools: currentActiveTools,\n modelSettings: currentModelSettings,\n structuredOutput: structuredOutput as any,\n retryCount: processorRetryCount,\n abortSignal: runAbortSignal,\n writer: inputStepWriter,\n });\n ownership?.throwIfLost();\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] = makeProcessorCoreTool(\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 agentId,\n requestContext,\n workspace: registryEntry?.workspace,\n requireApproval: (tool as any).requireApproval,\n backgroundConfig: (tool as any).background,\n agentBackgroundConfig: registryEntry?.backgroundTasksConfig,\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 Boolean(registryEntry?.backgroundTaskManager),\n );\n } else {\n convertedTools[name] = tool as CoreTool;\n }\n }\n currentTools = convertedTools as unknown as ToolSet;\n if (registryEntry) {\n // Keep the full toolset this step started from so the NEXT step\n // (via resolveRuntimeDependencies) and its processors see the\n // complete catalog. Without this, a processor that withholds\n // tools (ToolSearchProcessor with includeResolvedTools) would\n // shrink the registry to `search_tools` on step 1 and the tool\n // it auto-loaded could never surface on step 2 (issue #22933).\n registryEntry.baseTools = tools;\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 } else if (registryEntry?.baseTools) {\n // No processor narrowed this step, so the model sees the full\n // toolset; make the tool-call step resolve from the same set\n // instead of a previous step's narrowed snapshot.\n registryEntry.tools = registryEntry.baseTools;\n }\n } catch (error) {\n ownership?.throwIfLost();\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 const tripwire = {\n reason: error.message,\n retry: error.options?.retry,\n metadata: error.options?.metadata,\n processorId: error.processorId,\n };\n endTripwireSpans(error);\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 ...(await storeStepTranscript()),\n text: '',\n toolCalls: [],\n stepResult: {\n reason: 'tripwire' as const,\n tripwire,\n warnings: [],\n isContinued: false,\n },\n metadata: {\n modelId: currentModel.modelId,\n },\n state: typedInput.state,\n tracingTermination,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processInputStep processors:', error);\n throw error;\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 skipUnavailableAttachments,\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 // `skipBgTaskWait` marks an `untilIdle` inner run, the only reader of these outcomes. Taken\n // before the prompt is built so an outcome that lands meanwhile is never counted as sent.\n const backgroundOutcomes = typedInput.options?.skipBgTaskWait\n ? snapshotBackgroundOutcomes(messageList)\n : undefined;\n let inputMessages = (await llmPromptForModel(messageListPromptArgs)) as LanguageModelV2Prompt;\n const builtPrompt = inputMessages;\n // Identify OM's prompt message by its source ID and position before request\n // processors run. Equal text in real user messages is not synthetic context.\n const dbMessages = messageList.get.all.db();\n const continuationIndex = dbMessages.findIndex(message => message.id === 'om-continuation');\n let omContinuationPrompt: LanguageModelV2Prompt[number] | undefined;\n if (continuationIndex !== -1) {\n const precedingMessages = createRunMessageList({ mastra });\n precedingMessages.add(dbMessages.slice(0, continuationIndex), 'input');\n const precedingUserCount = precedingMessages.get.all.aiV5\n .model()\n .filter(message => message.role === 'user' && message.content.length > 0).length;\n omContinuationPrompt = inputMessages.filter(message => message.role === 'user')[precedingUserCount];\n // Keep source identity in supported Mastra metadata so request processors\n // can clone or reorder messages without changing their prompt shape.\n if (omContinuationPrompt) {\n omContinuationPrompt.providerOptions = {\n ...omContinuationPrompt.providerOptions,\n mastra: { ...omContinuationPrompt.providerOptions?.mastra, messageId: 'om-continuation' },\n };\n }\n }\n removeTrailingAssistantGuardContinuations(messageList);\n await persistUnavailableAttachments({\n messageList,\n memory: getRunRegistryEntry(runId, mastra as Mastra | undefined)?.memory,\n readOnly: typedInput.state?.memoryConfig?.readOnly,\n logger,\n });\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,\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 let cachedResponse: CachedLLMStepResponse | undefined;\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 llmRequestInputProcessors.length > 0\n ? new ProcessorRunner({\n lateSignalSink,\n inputProcessors: llmRequestInputProcessors,\n outputProcessors: [],\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n agent: registryEntry?.agent,\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 apiProviderId: await resolveApiProviderId(currentModel),\n messageList,\n workspace: registryEntry?.workspace,\n stepNumber: inputData.stepIndex ?? 0,\n steps: expandDurableSteps(previousSteps),\n retryCount: processorRetryCount,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: requestStepWriter,\n abortSignal: runAbortSignal,\n });\n ownership?.throwIfLost();\n inputMessages = requestStepResult.prompt;\n cachedResponse = requestStepResult.response;\n } catch (error) {\n ownership?.throwIfLost();\n if (error instanceof TripWire) {\n endTripwireSpans(error);\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 ...(await storeStepTranscript()),\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 tracingTermination,\n } satisfies DurableLLMStepOutput;\n }\n logger?.error?.('Error in processLLMRequest processors:', error);\n throw error;\n }\n }\n\n // Share the effective prompt with agent tools without putting it on the wire.\n // OM's synthetic continuation is not part of the parent's conversation.\n const delegationMessages = omContinuationPrompt\n ? inputMessages.filter(\n message =>\n message !== omContinuationPrompt &&\n message.providerOptions?.mastra?.messageId !== 'om-continuation',\n )\n : inputMessages;\n if (registryEntry) {\n registryEntry.runScope ??= createRunScope();\n registryEntry.runScope.set(STEP_MODEL_MESSAGES_KEY, delegationMessages);\n }\n // A cached reply may come from a different prompt under a custom cache key, so it never\n // counts as having answered a background result.\n const backgroundResultTaskIds =\n backgroundOutcomes && !cachedResponse\n ? backgroundOutcomesInPrompt(backgroundOutcomes, builtPrompt, inputMessages)\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 rawResponse: any = {};\n const toolCalls: DurableToolCallInput[] = [];\n let finishReason: string = 'stop';\n let usage: any = { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined };\n let responseMetadata: any = {};\n // Tracks whether this attempt produced any actual model output.\n // Used to detect a zero-output stream that finishes with reason\n // 'other' (#21897, ported from the regular loop's #22273 fix).\n let hasStepContent = false;\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 pendingProviderToolCallsByToolCallId = new Map<string, PendingProviderToolCall>();\n // Guards against a re-delivered tool-result minting a second span for the same call.\n const materializedProviderToolCallIds = new Set<string>();\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 = resolveAgentRunFallback(tracingContext.currentSpan as AnySpan);\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 resolveAgentRunFallback = (span: AnySpan): AnySpan =>\n span.type === ('agent_run' as string)\n ? span\n : ((agentRunSpan ?? (span as any).findParent?.('agent_run') ?? span) as AnySpan);\n\n const recordProviderToolCall = ({\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 = pendingProviderToolCallsByToolCallId.get(toolCallId);\n if (existingEntry) {\n if (args !== undefined && existingEntry.args === undefined) {\n existingEntry.args = args;\n }\n return;\n }\n\n pendingProviderToolCallsByToolCallId.set(toolCallId, {\n toolName,\n args,\n startTime: new Date(),\n toolDescription: (toolDef as { description?: string } | undefined)?.description,\n fallbackParentSpan: resolveAgentRunFallback(tracingContext.currentSpan),\n });\n };\n\n const cleanupToolObservabilitySpans = (flushPendingProviderToolCalls: boolean) => {\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 if (flushPendingProviderToolCalls) {\n for (const [toolCallId, pending] of pendingProviderToolCallsByToolCallId.entries()) {\n endPendingProviderToolSpan({ toolCallId, pending, parentSpan: pending.fallbackParentSpan, logger });\n }\n }\n pendingProviderToolCallsByToolCallId.clear();\n };\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 tools /\n // availableTools / toolChoice reflect per-step mutations.\n // availableTools is derived from the serialized definitions so the\n // two can't disagree. 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 // Skipped when tracing is off or the trace was not sampled (a\n // no-op span still hands out a tracker). The prompt is passed at\n // creation so MODEL_INFERENCE records what this call sent.\n const inferenceTools = modelSpanTracker?.getTracingContext()?.currentSpan?.isValid\n ? getToolDefinitionsForTracing({\n tools: currentTools,\n toolChoice: currentToolChoice,\n activeTools: currentActiveTools,\n specificationVersion: currentModel.specificationVersion,\n stripToolsWhenNone: sendsNativeResponseFormat(structuredOutput, currentModel),\n })\n : undefined;\n modelSpanTracker?.setInferenceContext?.({\n parameters: currentModelSettings as Record<string, unknown> | undefined,\n providerOptions: currentProviderOptions as Record<string, unknown> | undefined,\n availableTools: inferenceTools?.map(tool => tool.name) ?? [],\n tools: inferenceTools,\n toolChoice: currentToolChoice,\n responseFormat: structuredOutput ? 'json_schema' : undefined,\n });\n // A queued signal that arrived during the processors cancels this request\n // before the model is called, and invalid timeout settings from a\n // processor fail it before the call too, so the step must not name a\n // model in either case (same order as the in-process loop). A cached\n // response replays without invoking the model, so it records no model either.\n throwIfInterrupted();\n validateModelTimeoutSettings(currentModelSettings?.timeout);\n modelSpanTracker?.startInference?.({\n request: {},\n inputMessages,\n messageId: currentMessageId,\n ...(cachedResponse ? {} : { modelId: currentModel.modelId, provider: currentModel.provider }),\n });\n let inferenceStartedAt: number | undefined;\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 // What a total deadline saves of this attempt if it cuts the step off: the text as published.\n if (registryEntry?.timeoutTotalMs) registryEntry.streamedStepText = [];\n\n // Materialize collected chunks into the messageList via the same\n // helper the regular Agent uses, preserving reasoning spans\n // (#19365) and modelId/provider/traceId metadata (#19891).\n // Called on the success path AND both abort returns: the\n // serialized messageListState is the only channel to finalize-run\n // persistence, so skipping this on abort would drop\n // already-streamed partial output (#22593). Keep this attempt's\n // materialization id stable if an error processor later rotates the\n // active id before the terminal-error branch runs.\n const materializationMessageId = currentMessageId;\n materializeStreamedMessages = () => {\n ownership?.throwIfLost();\n if (interruption.signal.aborted) return;\n const responseModelId = currentModel.modelId ?? responseMetadata?.modelId;\n const responseTraceId = getRootExportSpan(\n modelSpanTracker?.getTracingContext()?.currentSpan ?? tracingContext?.currentSpan,\n )?.externalTraceId;\n const responseModelMetadata =\n responseModelId || currentModel.provider || responseTraceId\n ? {\n metadata: {\n ...(responseModelId ? { modelId: responseModelId } : {}),\n ...(currentModel.provider ? { provider: currentModel.provider } : {}),\n ...(responseTraceId ? { traceId: responseTraceId } : {}),\n },\n }\n : undefined;\n const builtMessages = buildMessagesFromChunks({\n chunks: collectedChunks,\n messageId: materializationMessageId,\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 terminalAttemptContext = {\n recordTerminalError: error => {\n materializeStreamedMessages?.();\n recordTerminalErrorMessage({\n messageList,\n attemptId: materializationMessageId,\n activeId: currentMessageId,\n error,\n });\n },\n };\n\n // 10. Execute LLM call (or replay cached response)\n let modelResult: ReturnType<typeof execute>;\n if (cachedResponse) {\n interruptible = false;\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 const releaseModelCallActivity = markRunActive(runId);\n try {\n inferenceStartedAt = Date.now();\n modelResult = executeWithContextSync({\n span: modelSpanTracker?.getTracingContext()?.currentSpan,\n fn: () =>\n 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?.({\n request,\n inputMessages,\n warnings,\n messageId: currentMessageId,\n });\n },\n }),\n });\n } finally {\n releaseModelCallActivity();\n }\n }\n\n const providerStream =\n stopListening && !cachedResponse\n ? watchInterruptibleStream(\n modelResult as unknown as NodeReadableStream<ChunkType>,\n interruption.signal,\n () => (interruptible = false),\n )\n : modelResult;\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: providerStream 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 rawBaseStream = outputStream._getBaseStream();\n const baseStream = modelSpanTracker?.recordChunk\n ? (modelSpanTracker.wrapInferenceStream?.(rawBaseStream) ?? rawBaseStream)\n : rawBaseStream;\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?.recordChunk\n ? stepBoundaryStream\n : (modelSpanTracker?.wrapStream(stepBoundaryStream) ?? stepBoundaryStream);\n\n // ── processToolResult support for provider-executed results (#14282 parity port) ──\n // Provider-executed tool results (same-stream or deferred) never reach\n // the tool-call step (the passthrough gate skips client execution), so\n // this is their only processToolResult site — mirrors the main loop's\n // llm-execution tool-result case. Lazy: most streams carry no\n // provider tool results.\n let toolResultTripwire: TripWire | null = null;\n let outputStreamBlocked = false;\n // Tool results of earlier steps a processor held until this stream ended.\n const releasedToolResultIds: string[] = [];\n let toolResultRunner: ProcessorRunner | undefined;\n const getToolResultRunner = (): ProcessorRunner => {\n toolResultRunner ??= new ProcessorRunner({\n lateSignalSink,\n inputProcessors: [],\n outputProcessors: effectiveOutputProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n agent: registryEntry?.agent,\n processorStates: registryEntry?.processorStates,\n });\n return toolResultRunner;\n };\n // Persist non-transient data-* chunks into the workflow-side\n // messageList before streaming them (#19375 parity, same as the\n // outputStepWriter below).\n const toolResultChunkWriter = pubsub\n ? {\n custom: async (\n data: { type: string; data?: unknown; transient?: boolean },\n writerOptions?: { messageId?: string },\n ) => {\n ownership?.throwIfLost();\n persistProcessorDataChunk(messageList, writerOptions?.messageId ?? currentMessageId, data);\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n const outputStreamWriter = pubsub\n ? {\n custom: async (\n data: { type: string; data?: unknown; transient?: boolean },\n writerOptions?: { messageId?: string },\n ) => {\n ownership?.throwIfLost();\n persistProcessorDataChunk(messageList, writerOptions?.messageId ?? currentMessageId, data);\n try {\n await emitChunkEvent(pubsub, runId, data as any, true);\n } catch (error) {\n ownership?.throwIfLost();\n throw new DurableChunkPublishError(error);\n }\n },\n }\n : undefined;\n\n const releaseStreamActivity = markRunActive(runId);\n // A run that loses its thread lease while this request streams lets the request finish before it stops.\n const settleRequest = startRunStep(registryEntry);\n try {\n let stepStartEmitted = false;\n // Stream driver — deliberate, permanent divergence from the\n // main loop: main commits chunks to\n // the message list and then emits them into its request-scoped\n // in-process stream; durable publishes to pubsub FIRST because\n // consumers are cross-process and must see chunks live, while\n // the authoritative commits land after the stream completes\n // (buildMessagesFromChunks below; tool results later in\n // llm-mapping, across a serialization boundary). Don't reorder\n // to match main — emit-after-commit would require buffering the\n // whole step.\n for await (const rawChunk of trackedStream) {\n ownership?.throwIfLost();\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 // Published directly to pubsub — deliberate divergence from\n // the main loop, which injects step-start into its\n // request-scoped in-process pipeline via onResult\n // (#16687/#17370). That injection point cannot exist here\n // (durable steps serialize at their boundaries), and porting\n // it would double-emit lifecycle chunks. When this producer holds the\n // run's output processors, it runs them on step-start itself and\n // publishes it marked processed, like every other chunk: a consumer\n // sharing those processor states would otherwise hold a step-start\n // that arrives after the step's held parts were released (#28231).\n // Without them (process hop), consumers run processors on it.\n // Keep the full model request out of the durable event stream; the helper\n // preserves the canonical payload shape with an empty `request` object.\n if (!stepStartEmitted && pubsub) {\n stepStartEmitted = true;\n const stepStartChunk = createStepStartChunk(runId, {\n stepId: DurableStepIds.LLM_EXECUTION,\n messageId: currentMessageId,\n startedAt: inferenceStartedAt,\n modelId: currentModel.modelId,\n provider: currentModel.provider,\n warnings,\n ...(backgroundResultTaskIds.length > 0 ? { backgroundResultTaskIds } : {}),\n });\n if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) {\n try {\n await processAndEmitChunk(stepStartChunk, {\n runner: getToolResultRunner(),\n processorStates: registryEntry.processorStates,\n // No tracing context: the consumer pipeline owns the\n // processor spans. A model-step context here would end the\n // consumer's span and open one under the model step.\n observabilityContext: createObservabilityContext(),\n requestContext,\n messageList,\n streamWriter: outputStreamWriter,\n emitChunk: async chunk => {\n if (chunk.type === 'tripwire') {\n endTripwireSpans(chunk.payload);\n outputStreamBlocked = true;\n }\n try {\n if (chunk.type === 'step-start') {\n await publishStepStartChunk(pubsub, runId, chunk, true, inputData.stepIndex ?? 0);\n } else {\n await emitChunkEvent(pubsub, runId, chunk, true);\n }\n } catch (error) {\n ownership?.throwIfLost();\n throw new DurableChunkPublishError(error);\n }\n },\n onProcessorError: error => {\n throwIfInterrupted();\n if (error instanceof DurableChunkPublishError) {\n throw error.cause;\n }\n throw new DurableOutputProcessorError(error);\n },\n });\n } catch (error) {\n ownership?.throwIfLost();\n throwIfInterrupted();\n if (error instanceof DurableOutputProcessorError) {\n const processorError = error.cause instanceof Error ? error.cause : error;\n terminalAttemptContext?.recordTerminalError(processorError);\n return emitFatalErrorBail(processorError, currentModel.modelId);\n }\n throw error;\n }\n if (outputStreamBlocked) {\n break;\n }\n } else {\n await publishStepStartChunk(pubsub, runId, stepStartChunk, undefined, inputData.stepIndex ?? 0);\n }\n }\n\n // ── Deferred provider-executed tool results (#14282 parity port) ──\n // When a provider tool is deferred (e.g. Anthropic web_search called\n // alongside a client tool), the tool-call arrives in step N and is\n // committed to the messageList as state:'call'; the tool-result only\n // arrives in step N+1's stream. Patch the existing call part to\n // state:'result' here so the real data reaches durable history —\n // without this the invocation stays 'call' forever (the tool-call\n // step's passthrough gate skips client execution for provider tools).\n // For same-stream results no matching part exists yet, so\n // updateToolInvocation returns false and buildMessagesFromChunks\n // handles the merge from the mutated collected chunk.\n //\n // Run processToolResult BEFORE the raw result is emitted, collected,\n // or persisted — this engine emits eagerly, so the hook must run\n // pre-emission to honor the \"scan before history / next LLM call\"\n // guarantee and so streaming clients see the post-processor value.\n // Presence check (not truthiness): a tool legitimately returning\n // `null` still triggers processors.\n //\n // `transformTools` / `deferredEnrichedChunk` are hoisted above the\n // patch block because deferred-result patching needs the payload\n // transform to run BEFORE `updateToolInvocation`: the enrichment\n // below builds a NEW clientChunk object (it never mutates\n // rawChunk), so reading `rawChunk.metadata` at patch time would\n // always see undefined and silently drop the transcript transform\n // state for deferred results (L18b residual). The client-emission\n // path reuses the enriched chunk so the transform runs once.\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 let deferredEnrichedChunk: typeof rawChunk | undefined;\n // Partial provider results (e.g. OpenAI image_generation partial images) are only\n // streamed; the final result is processed, saved and ends the provider span.\n if (\n rawChunk.type === 'tool-result' &&\n rawChunk.payload &&\n !rawChunk.payload.preliminary &&\n 'result' in (rawChunk.payload as any)\n ) {\n const resultPayload = rawChunk.payload as any;\n const resultToolDef = resolveToolDef(resultPayload.toolName);\n const resultProviderExecuted = inferProviderExecuted(resultPayload.providerExecuted, resultToolDef);\n\n if (effectiveOutputProcessors.length > 0) {\n try {\n await getToolResultRunner().runProcessToolResult({\n steps: expandDurableSteps(previousSteps),\n messages: messageList.get.all.db(),\n messageList,\n stepNumber: previousSteps.length,\n toolName: resultPayload.toolName,\n toolCallId: resultPayload.toolCallId,\n toolArgs: resultPayload.args,\n result: resultPayload.result,\n providerExecuted: resultProviderExecuted,\n requestContext,\n retryCount: processorRetryCount,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: toolResultChunkWriter,\n abortSignal: runAbortSignal,\n });\n ownership?.throwIfLost();\n // Sync any processor mutation (via messageList.updateToolInvocation)\n // back into the chunk so the emitted client chunk and the\n // collected chunk both carry the post-processor value.\n const postProcessorResult = readToolResultFromMessageList(messageList, resultPayload.toolCallId);\n if (postProcessorResult !== undefined && postProcessorResult !== resultPayload.result) {\n resultPayload.result = postProcessorResult;\n }\n } catch (error) {\n ownership?.throwIfLost();\n if (error instanceof TripWire) {\n logger?.warn?.('Tool result processor tripwire triggered', {\n reason: error.message,\n processorId: error.processorId,\n retry: error.options?.retry,\n });\n // Stop consuming the stream: the raw result is never emitted,\n // collected, or persisted. The post-stream join below emits\n // the tripwire chunk and bails with reason 'tripwire'.\n toolResultTripwire = error;\n break;\n }\n logger?.error?.('Error in processToolResult processors:', error);\n throw error;\n }\n }\n\n // Run the payload transform now (post-processor value already\n // synced into the payload) so the patch below can persist the\n // transform's transcript state. Same policy/tools inputs as the\n // client-emission enrichment further down, which reuses this\n // chunk instead of transforming again.\n if (registryEntry?.toolPayloadTransform || transformTools) {\n deferredEnrichedChunk = await applyToolPayloadTransformToChunk(rawChunk, {\n policy: registryEntry?.toolPayloadTransform,\n tools: transformTools,\n logger: logger as any,\n });\n }\n\n // Patch the deferred tool-call to state:'result' with the\n // (possibly post-processor-mutated) value. Args/result stay\n // raw — display-layer transforms live only in the transform\n // metadata, applied to the transcript at drain time.\n messageList.updateToolInvocation({\n type: 'tool-invocation',\n toolInvocation: {\n toolCallId: resultPayload.toolCallId,\n toolName: resultPayload.toolName,\n args: resultPayload.args,\n ...getToolResultInvocationState(resultPayload),\n },\n providerMetadata: withToolPayloadTransformProviderMetadata(\n resultPayload.providerMetadata,\n (deferredEnrichedChunk as { metadata?: Record<string, unknown> } | undefined)?.metadata,\n ),\n providerExecuted: resultProviderExecuted,\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 // Deferred tool-result chunks were already enriched in the patch\n // block above (`deferredEnrichedChunk`) — reuse that result so\n // the transform is applied exactly once per chunk.\n const clientChunk =\n deferredEnrichedChunk ??\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 recordProviderToolCall({\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 recordProviderToolCall({\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 client-visible chunks ('finish' was rewritten to 'step-finish' above).\n // Skip 'response-metadata' to match the regular agent, which consumes it\n // internally without exposing it on fullStream. Skip 'error' chunks because\n // retry/fallback handles them internally; when all models are exhausted the\n // fatal error is propagated via emitError (mirrors the regular agent's\n // deferredErrorChunk pattern).\n //\n // Defer 'step-finish' until the loop predicate resolves whether the run continues.\n // Carry it through llm-mapping so tool-result chunks are emitted first, matching the\n // regular agent's ordering (tool-result → step-finish).\n // Set when output processors ran on this chunk: the processed chunk\n // (what the client received), or null when a processor dropped it.\n let processedChunk: typeof clientChunk | null | undefined;\n if (rawChunk.type === 'step-finish') {\n recordProcessedChunk(rawChunk);\n registryEntry?.runScope?.set(LOCAL_MODEL_REQUEST_KEY, request);\n }\n if (pubsub && rawChunk.type !== 'error' && rawChunk.type !== 'response-metadata') {\n if (rawChunk.type === 'step-finish') {\n // The rewritten provider 'finish' chunk carries no response metadata;\n // add it so onStepFinish/onFinish report the provider's response id\n // and model, as the regular agent does.\n const { id, timestamp, modelId } = responseMetadata;\n deferredStepFinishChunk = {\n ...clientChunk,\n payload: {\n ...clientChunk.payload,\n metadata: {\n ...(id !== undefined ? { id } : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n ...clientChunk.payload?.metadata,\n modelId: clientChunk.payload?.metadata?.modelId || modelId || model.modelId,\n },\n },\n };\n } else if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) {\n try {\n processedChunk = await processAndEmitChunk(clientChunk, {\n runner: getToolResultRunner(),\n processorStates: registryEntry.processorStates,\n observabilityContext: createObservabilityContext(\n modelSpanTracker?.getTracingContext() ?? tracingContext,\n ),\n requestContext,\n messageList,\n streamWriter: outputStreamWriter,\n emitChunk: async chunk => {\n // processAndEmitChunk publishes a tripwire chunk only when a processor blocks.\n if (chunk.type === 'tripwire') {\n endTripwireSpans(chunk.payload);\n outputStreamBlocked = true;\n }\n recordProcessedChunk(chunk);\n trackOpenReasoning(chunk, openReasoningIds);\n try {\n await emitChunkEvent(pubsub, runId, chunk, true);\n } catch (error) {\n ownership?.throwIfLost();\n throw new DurableChunkPublishError(error);\n }\n },\n onProcessorError: error => {\n throwIfInterrupted();\n if (error instanceof DurableChunkPublishError) {\n throw error.cause;\n }\n throw new DurableOutputProcessorError(error);\n },\n });\n } catch (error) {\n ownership?.throwIfLost();\n throwIfInterrupted();\n if (error instanceof DurableOutputProcessorError) {\n const processorError = error.cause instanceof Error ? error.cause : error;\n // Keep already-published output and the error record; the failing chunk was never collected.\n terminalAttemptContext?.recordTerminalError(processorError);\n return emitFatalErrorBail(processorError, currentModel.modelId);\n }\n throw error;\n }\n // A blocked chunk ends the stream: it is never collected, and later chunks are never published.\n if (outputStreamBlocked) {\n break;\n }\n } else {\n // Without producer-side processors, only record content when\n // none are configured; another worker may own those processors.\n if (effectiveOutputProcessors.length === 0) recordProcessedChunk(clientChunk);\n trackOpenReasoning(clientChunk, openReasoningIds);\n await emitChunkEvent(pubsub, runId, clientChunk);\n }\n }\n\n // Collect every chunk for post-stream message building and the\n // processLLMResponse hook. Collect every chunk an output processor\n // didn't drop — reasoning parts (including empty spans with\n // providerMetadata carrying OpenAI itemIds) are required to\n // correctly reconstruct the assistant message and preserve\n // pairing with subsequent tool-calls (#19365). When output\n // processors ran, persist the processed payload so memory holds\n // exactly what the client streamed (default-loop parity, #26335);\n // otherwise the raw payload. Metadata comes from the client\n // chunk: the payload transform is purely additive metadata\n // (`mastra.toolPayloadTransform`), and buildMessagesFromChunks\n // layers it into the persisted providerMetadata so transcript\n // targets apply on recall (L18b). Internal state below (tool\n // args, finish reason, usage) still reads the raw chunk.\n ownership?.throwIfLost();\n if (processedChunk !== null) {\n const persistedChunk = processedChunk ?? rawChunk;\n collectedChunks.push({\n type: persistedChunk.type,\n payload: 'payload' in persistedChunk ? persistedChunk.payload : undefined,\n metadata: (clientChunk as { metadata?: Record<string, unknown> }).metadata,\n });\n // The step's text is transcript, not internal state: build it from the same\n // chunk memory stores so a redacted reply is never returned unredacted.\n if (persistedChunk.type === 'text-delta') {\n const text = (persistedChunk.payload as TextDeltaPayload).text;\n textDeltas.push(text);\n registryEntry?.streamedStepText?.push(text);\n }\n }\n\n if (STEP_CONTENT_CHUNK_TYPES.has(rawChunk.type)) {\n hasStepContent = true;\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 '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: runAbortSignal,\n });\n } catch (error) {\n ownership?.throwIfLost();\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: runAbortSignal,\n });\n } catch (error) {\n ownership?.throwIfLost();\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 // Stamp approval/suspension capability from the step's *effective* tool\n // set. Processor-injected tools (e.g. ToolSearchProcessor) never appear\n // in the run-start `toolsMetadata`, so without this stamp the durable\n // foreach concurrency gate cannot see that the call can suspend for\n // approval (issue #24377). The stamp is persisted with the call, so it\n // stays correct across cold resumes.\n const effectiveTool = (\n currentTools as\n | Record<string, { requireApproval?: unknown; hasSuspendSchema?: unknown } | undefined>\n | undefined\n )?.[payload.toolName];\n toolCalls.push({\n toolCallId: payload.toolCallId,\n toolName: payload.toolName,\n args: payload.args,\n providerMetadata: payload.providerMetadata,\n providerExecuted: payload.providerExecuted,\n output: payload.output,\n activeTools: currentActiveTools ?? null,\n ...(effectiveTool?.requireApproval ? { requireApproval: true } : {}),\n ...(effectiveTool?.hasSuspendSchema ? { hasSuspendSchema: true } : {}),\n });\n break;\n }\n\n case 'tool-result': {\n const payload = rawChunk.payload as any;\n if (payload.preliminary) break;\n // The result determines which MODEL_STEP owns the provider tool call, so\n // the PROVIDER_TOOL_CALL span is created now, backdated to the tool-call chunk.\n const pending = pendingProviderToolCallsByToolCallId.get(payload.toolCallId);\n if (pending) {\n endPendingProviderToolSpan({\n toolCallId: payload.toolCallId,\n pending,\n parentSpan: modelSpanTracker?.getTracingContext()?.currentSpan ?? pending.fallbackParentSpan,\n result: { output: payload.result, isError: payload.isError },\n logger,\n });\n pendingProviderToolCallsByToolCallId.delete(payload.toolCallId);\n materializedProviderToolCallIds.add(payload.toolCallId);\n } else if (\n tracingContext?.currentSpan &&\n !materializedProviderToolCallIds.has(payload.toolCallId)\n ) {\n // Deferred result: the call arrived in a previous 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 // startTime is result time, not the call time: the call was observed in a\n // previous invocation whose in-memory state (including its timestamp) does\n // not survive the invocation boundary.\n endPendingProviderToolSpan({\n toolCallId: payload.toolCallId,\n pending: {\n toolName: payload.toolName,\n args: spanInput,\n startTime: new Date(),\n toolDescription: (resultToolDef2 as { description?: string } | undefined)?.description,\n },\n parentSpan:\n modelSpanTracker?.getTracingContext()?.currentSpan ??\n resolveAgentRunFallback(tracingContext.currentSpan),\n result: { output: payload.result, isError: payload.isError },\n logger,\n });\n materializedProviderToolCallIds.add(payload.toolCallId);\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\n // A provider can end the stream with finishReason 'error' without ever\n // enqueueing an error part (e.g. Google reports MALFORMED_FUNCTION_CALL\n // this way). Throw so the shared retry / error-processor / fallback path\n // sees it, matching the regular loop.\n if (finishReason === 'error') {\n const rawReason = payload.stepResult?.rawReason;\n throw new MastraError({\n id: 'AGENT_STREAM_ERROR',\n text: rawReason\n ? `Agent stream finished with finishReason \"error\" (provider reported \"${rawReason}\") but no error payload was provided`\n : 'Agent stream finished with finishReason \"error\" but no error payload was provided',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n details: {\n runId,\n ...(rawReason && { rawFinishReason: rawReason }),\n },\n });\n }\n\n // A provider can close the stream cleanly with finishReason 'other'\n // without producing any output (e.g. @ai-sdk/openai defaults to\n // 'other' when the SSE stream ends before a response.completed\n // event arrives). With a completion checker configured the loop\n // would re-issue the identical request and spin until maxSteps\n // (issue #21897, ported from the regular loop's #22273 fix).\n // Throw so the shared retry / error-processor / fallback path\n // treats it as a stream error and retries boundedly. A finish\n // with reason 'other' that DID produce output continues as usual.\n if (finishReason === 'other' && !hasStepContent) {\n const rawReason = payload.stepResult?.rawReason;\n throw new MastraError({\n id: 'AGENT_STREAM_ERROR',\n text: rawReason\n ? `Agent stream finished with finishReason \"other\" (provider reported \"${rawReason}\") without producing any output`\n : 'Agent stream finished with finishReason \"other\" without producing any output',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n details: {\n runId,\n ...(rawReason && { rawFinishReason: rawReason }),\n },\n });\n }\n break;\n }\n\n case 'response-metadata': {\n const payload = rawChunk.payload as any;\n // Providers may split metadata across several chunks, so keep\n // earlier values for fields a chunk omits.\n responseMetadata = {\n id: payload.id ?? responseMetadata.id,\n timestamp: payload.timestamp ?? responseMetadata.timestamp,\n modelId: payload.modelId ?? responseMetadata.modelId,\n headers: payload.headers ?? responseMetadata.headers,\n };\n break;\n }\n\n case 'error': {\n const payload = rawChunk.payload as any;\n // Pass the provider error through unchanged (keeps statusCode,\n // isRetryable, responseBody, ...) so error processors and the\n // caller see the same error the regular engine surfaces.\n if (payload?.error instanceof Error) {\n throw payload.error;\n }\n const errorMessage = payload?.error?.message || payload?.message || 'LLM execution error';\n const errorObj = new Error(errorMessage, { cause: payload?.error ?? payload });\n // Keep the producer's stack so crashes stay attributable to their real throw site.\n if (typeof payload?.error?.stack === 'string') {\n errorObj.stack = payload.error.stack;\n }\n // Retain the producer's error name so classification (e.g. AbortError) survives transport.\n if (typeof payload?.error?.name === 'string' && payload.error.name) {\n errorObj.name = payload.error.name;\n }\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 // Release parts output processors still hold (e.g. a partial\n // BatchPartsProcessor batch) so a stream ending mid-batch keeps its tail.\n if (\n pubsub &&\n !outputStreamBlocked &&\n !executionAbortSignal?.aborted &&\n effectiveOutputProcessors.length > 0 &&\n registryEntry?.processorStates\n ) {\n const released = await getToolResultRunner().flushHeldParts(\n registryEntry.processorStates,\n createObservabilityContext(modelSpanTracker?.getTracingContext() ?? tracingContext),\n requestContext,\n messageList,\n 0,\n outputStreamWriter,\n );\n for (const r of released) {\n if (r.blocked) {\n outputStreamBlocked = true;\n endTripwireSpans({\n reason: r.reason || 'Output processor blocked content',\n processorId: r.processorId,\n metadata: r.tripwireOptions?.metadata,\n });\n await emitChunkEvent(\n pubsub,\n runId,\n {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n reason: r.reason || 'Output processor blocked content',\n retry: r.tripwireOptions?.retry,\n metadata: r.tripwireOptions?.metadata,\n processorId: r.processorId,\n },\n },\n true,\n );\n break;\n }\n if (r.part == null) continue;\n trackOpenReasoning(r.part, openReasoningIds);\n await emitChunkEvent(pubsub, runId, r.part, true);\n if (r.part.type === 'tool-result') releasedToolResultIds.push(r.part.payload.toolCallId);\n collectedChunks.push({\n type: r.part.type,\n payload: 'payload' in r.part ? r.part.payload : undefined,\n metadata: (r.part as { metadata?: Record<string, unknown> }).metadata,\n });\n if (r.part.type === 'text-delta') textDeltas.push(r.part.payload.text);\n }\n }\n throwIfInterrupted();\n interruptible = false;\n stopListening?.();\n // Clean up any unclosed observability spans after successful stream completion.\n // Pending provider tool calls are only flushed on terminal steps — when the loop\n // continues, the deferred result creates the real span in a later invocation.\n cleanupToolObservabilitySpans(!(toolCalls.length > 0 && finishReason !== 'stop'));\n } catch (error) {\n ownership?.throwIfLost();\n // This attempt is over: whatever processors still hold from it must not be\n // released alongside a retry's parts or after an abort.\n if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) {\n const kept = await getToolResultRunner().discardHeldParts(registryEntry.processorStates);\n if (pubsub) {\n for (const part of kept) await emitChunkEvent(pubsub, runId, part, true);\n }\n }\n throwIfInterrupted();\n cleanupToolObservabilitySpans(true);\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, endSpan: false });\n } else if (modelSpan) {\n modelSpan.error({ error: errorObj, endSpan: false });\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 // A run-level budget expiry (#21724) is a failure, not a clean\n // abort: rethrow so the outer catch routes it to the fatal\n // error path (no retry, no fallback, error chunk emitted).\n const innerTimeout = resolveTotalTimeoutAbort(executionAbortSignal, errorObj);\n if (innerTimeout) {\n throw innerTimeout;\n }\n\n const isAbort = executionAbortSignal?.aborted === true || errorObj.name === 'AbortError';\n if (isAbort) {\n // Persist already-streamed partial output (#22593).\n materializeStreamedMessages();\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 ...(await storeStepTranscript()),\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 deferredStepFinishChunk: prepareDeferredStepFinishChunk({ reason: 'abort', isContinued: false }),\n ...recordClocks(),\n } satisfies DurableLLMStepOutput;\n }\n\n lastError = errorObj;\n\n // Try processAPIError before deciding retry/break\n const registryEntryInner = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const canRetryErrorInner = maxProcessorRetries !== undefined && processorRetryCount < maxProcessorRetries;\n // See the outer site below: the processor always runs, only the retry is gated.\n if (registryEntryInner?.errorProcessors?.length) {\n try {\n const runner = new ProcessorRunner({\n lateSignalSink,\n inputProcessors: registryEntryInner.inputProcessors ?? [],\n outputProcessors: registryEntryInner.outputProcessors ?? [],\n errorProcessors: registryEntryInner.errorProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n agent: registryEntryInner?.agent,\n processorStates: registryEntryInner.processorStates,\n });\n const { retry } = await runner.runProcessAPIError({\n error: lastError,\n messages: messageList.get.all.db(),\n messageList,\n messageId: currentMessageId,\n rotateResponseMessageId,\n stepNumber: inputData.stepIndex ?? 0,\n steps: expandDurableSteps(previousSteps),\n retryCount: processorRetryCount,\n requestContext,\n });\n ownership?.throwIfLost();\n if (retry && canRetryErrorInner) {\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 ownership?.throwIfLost();\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 } finally {\n releaseStreamActivity();\n settleRequest();\n }\n\n ownership?.throwIfLost();\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, endSpan: false });\n } else if (modelSpan) {\n modelSpan.error({ error: streamErrorObj, endSpan: false });\n }\n\n // Mirror the iterator catch: a run-level budget expiry (#21724)\n // routes to the fatal error path via the outer catch.\n const streamErrorTimeout = resolveTotalTimeoutAbort(executionAbortSignal, streamErrorObj);\n if (streamErrorTimeout) {\n throw streamErrorTimeout;\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 // Persist already-streamed partial output (#22593).\n materializeStreamedMessages();\n return {\n ...(await storeStepTranscript()),\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 deferredStepFinishChunk: prepareDeferredStepFinishChunk({ reason: 'abort', isContinued: false }),\n ...recordClocks(),\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 // A processToolResult tripwire fired mid-stream (#14282 parity port):\n // the raw provider tool result was never emitted nor persisted. Join\n // the shared tripwire bail path (mirrors processLLMResponse below).\n // A blocked output-stream chunk joins the same path; its tripwire\n // chunk was already published by processAndEmitChunk.\n if (toolResultTripwire || outputStreamBlocked) {\n if (toolResultTripwire) endTripwireSpans(toolResultTripwire);\n if (toolResultTripwire && pubsub) {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n processorId: toolResultTripwire.processorId,\n reason: toolResultTripwire.message,\n retry: toolResultTripwire.options?.retry,\n metadata: toolResultTripwire.options?.metadata,\n },\n });\n }\n return {\n ...(await storeStepTranscript()),\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 deferredStepFinishChunk: prepareDeferredStepFinishChunk({\n reason: 'tripwire',\n isContinued: false,\n }),\n ...recordClocks(),\n tracingTermination,\n } satisfies DurableLLMStepOutput;\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.stepIndex ?? 0,\n steps: expandDurableSteps(previousSteps),\n warnings,\n request,\n rawResponse,\n fromCache: false,\n retryCount: processorRetryCount,\n requestContext,\n tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,\n writer: requestStepWriter,\n abortSignal: runAbortSignal,\n });\n ownership?.throwIfLost();\n } catch (error) {\n ownership?.throwIfLost();\n if (error instanceof TripWire) {\n endTripwireSpans(error);\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 ...(await storeStepTranscript()),\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 deferredStepFinishChunk: prepareDeferredStepFinishChunk({\n reason: 'tripwire',\n isContinued: false,\n }),\n ...recordClocks(),\n tracingTermination,\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 materializeStreamedMessages();\n if (currentModel.provider && currentModel.modelId) {\n messageList.enrichLastStepStart(`${currentModel.provider}/${currentModel.modelId}`);\n }\n\n // 13. Determine if we should continue (has tool calls). Pending\n // tool calls must never override a terminal finish reason:\n // `error`, `length`, and `content-filter` all reproduce the same\n // failure/truncation/refusal when the request is re-sent, so the\n // loop would spin until maxSteps (#17893, #15717 parity port).\n //\n // Deliberate divergence from the main loop: treating\n // `stop` as terminal here IS reachable with tool calls — some\n // providers report finishReason 'stop' alongside tool calls, and\n // no upstream normalization rewrites it (`normalizeFinishReason`\n // in stream/aisdk/v5/transform.ts is format-only). Main's #17893\n // gate deliberately does NOT exclude `stop` (see\n // `hasPendingToolCalls` in loop/workflows/agentic-execution/\n // llm-execution-step.ts), so main runs the tools AND loops so the\n // model sees the results. Durable still executes the tools (the\n // tool-call foreach consumes `toolCalls` regardless of this flag)\n // and commits their results, but ends the loop without a\n // follow-up model step — unless a tool errors, in which case\n // llm-mapping's recovery override forces\n // continuation. Kept as-is: the narrow #17893 port deliberately\n // preserved durable's gating; converge only with a pinning test.\n const isContinued = toolCalls.length > 0 && !TERMINAL_FINISH_REASONS.includes(finishReason);\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 let processOutputStepTripwire: TripWire | undefined;\n if (effectiveOutputProcessors.length > 0) {\n const outputStepRunner = new ProcessorRunner({\n lateSignalSink,\n inputProcessors: [],\n outputProcessors: effectiveOutputProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n agent: registryEntry?.agent,\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 // Persist non-transient data-* chunks into the workflow-side\n // messageList (serialized into messageListState and flushed to\n // memory at finalize) before streaming them, mirroring the main\n // loop's outputWriter behavior (#19375 parity port).\n const outputStepWriter = pubsub\n ? {\n custom: async (\n data: { type: string; data?: unknown; transient?: boolean },\n writerOptions?: { messageId?: string },\n ) => {\n ownership?.throwIfLost();\n persistProcessorDataChunk(messageList, writerOptions?.messageId ?? currentMessageId, data);\n await emitChunkEvent(pubsub, runId, data as any);\n },\n }\n : undefined;\n\n try {\n await outputStepRunner.runProcessOutputStep({\n steps: expandDurableSteps(previousSteps),\n messages: messageList.get.all.db(),\n messageList,\n stepNumber: inputData.stepIndex ?? 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 retryCount: processorRetryCount,\n });\n ownership?.throwIfLost();\n } catch (error) {\n ownership?.throwIfLost();\n // No tripwire chunk here: the stream reader closes on one, which would drop\n // the retry and the finish chunk. The step result carries the tripwire instead.\n if (!(error instanceof TripWire)) throw error;\n processOutputStepTripwire = error;\n }\n }\n // The step processors ran over the streamed text and it is in the list; a deadline no longer cuts it off.\n // Publish the accepted step first, in the same tick, so a deadline before the mapping step's snapshot\n // still saves it (and never both the snapshot and the cut-off text). A rejected response is rolled\n // back below, so the step-start snapshot stays.\n if (registryEntry?.timeoutTotalMs && !processOutputStepTripwire) {\n registryEntry.completedStepsState = JSON.parse(JSON.stringify(messageList.serialize()));\n }\n if (registryEntry) registryEntry.streamedStepText = undefined;\n\n const retryRequested = processOutputStepTripwire?.options?.retry === true;\n const canRetry =\n typedInput.options?.maxProcessorRetries !== undefined &&\n processorRetryCount < typedInput.options.maxProcessorRetries;\n const shouldRetry = retryRequested && canRetry;\n\n // Remove the rejected response so the retry doesn't send it back to the model, and\n // so a rejection that ends the run isn't persisted or returned (issue #26048).\n if (processOutputStepTripwire) {\n messageList.rollbackToStepBoundary(materializationMessageId, iterationBoundary);\n }\n\n const stepTripwire = processOutputStepTripwire\n ? {\n reason: processOutputStepTripwire.message,\n retry: processOutputStepTripwire.options?.retry,\n metadata: processOutputStepTripwire.options?.metadata,\n processorId: processOutputStepTripwire.processorId,\n }\n : undefined;\n\n // 13.9. Prepare step-finish for post-decision emission.\n //\n // The durable continuation decision runs after this step and may override\n // the model's continuation state because of maxSteps, stopWhen, feedback,\n // signals, task-completion scorers, or goals. Carry the chunk through the\n // serialized iteration state so the predicate can stamp and emit the loop's\n // actual decision. Tool-calling steps still reach this point only after their\n // tool-result chunks have been emitted by tool-call.ts.\n // Build step content directly from the current step's data rather than\n // relying on messageList, which may contain response messages from\n // previous iterations after deserialization. The stream reader reads a\n // rejected step's tripwire from the chunk payload, like the main loop's.\n prepareDeferredStepFinishChunk({\n reason: processOutputStepTripwire ? (shouldRetry ? 'retry' : 'tripwire') : undefined,\n isContinued: shouldRetry || (!processOutputStepTripwire && isContinued),\n tripwire: stepTripwire,\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 =\n hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.exportCurrentStep() : undefined;\n const stepFinishPayload =\n hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.getPendingStepFinishPayload() : undefined;\n\n // 15. Build output\n const output: DurableLLMStepOutput = {\n ...(await storeStepTranscript()),\n // Serialized steps feed onFinish; rejected attempts must not contribute text.\n text: processOutputStepTripwire ? '' : textDeltas.join(''),\n // A rejected response's tool calls never run.\n toolCalls: processOutputStepTripwire ? [] : toolCalls,\n stepResult: {\n reason: (shouldRetry ? 'retry' : processOutputStepTripwire ? 'tripwire' : finishReason) as any,\n warnings,\n isContinued: shouldRetry || (!processOutputStepTripwire && isContinued),\n totalUsage: usage,\n headers: rawResponse?.headers,\n tripwire: stepTripwire,\n // The id may have rotated in this step (retry feedback, signals, processors);\n // the next iteration must continue and roll back that message, not the old one.\n messageId: currentMessageId,\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 },\n // Only a finished step has a step-finish chunk, so an aborted step records\n // none. Its metadata already defaults the model to the requested one, and\n // the serving model accounts for Anthropic server-side fallbacks, as the\n // main loop does.\n response: deferredStepFinishChunk\n ? {\n id: deferredStepFinishChunk.payload?.metadata?.id,\n modelId: resolveResponseModelId(\n deferredStepFinishChunk.payload?.metadata?.providerMetadata,\n deferredStepFinishChunk.payload?.metadata?.modelId,\n ),\n }\n : undefined,\n state: typedInput.state,\n // Pass span data so tool calls can be children of model_step\n modelSpanData:\n hasToolCalls && !processOutputStepTripwire\n ? (modelSpan?.snapshot?.() ?? modelSpan?.exportSpan())\n : undefined,\n stepSpanData,\n stepFinishPayload,\n // Carry step-finish through the iteration so the loop predicate can\n // stamp and emit the actual post-policy continuation decision.\n deferredStepFinishChunk: deferredStepFinishChunk ?? undefined,\n ...recordClocks(),\n ...(releasedToolResultIds.length ? { releasedToolResultIds } : {}),\n tracingTermination,\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 || processOutputStepTripwire) {\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 ...agentLoopTermination({\n stopCause: 'model_finished',\n finishReason,\n tripwire: stepTripwire,\n }),\n output: {\n text: textDeltas.join(''),\n toolCalls: [],\n },\n attributes: {\n usage: extractUsageMetrics(\n pendingPayload.output?.usage,\n pendingPayload.metadata?.providerMetadata,\n ),\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 ownership?.throwIfLost();\n if (interruption.signal.aborted) return finishInterruptedRequest(error, modelEntry.config.modelId);\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 = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const selectedOuterAbortSignal = outerRegistryEntry?.abortSignal ?? abortSignal;\n const outerAbortSignal = ownership?.composeSignal(selectedOuterAbortSignal) ?? selectedOuterAbortSignal;\n\n // A run-level budget expiry (#21724) is a hard failure: no retry\n // on the same model, no fallback to the next one (the budget is\n // shared across the whole run, so another attempt would start\n // already-expired), and no clean-abort masking. Persist partial\n // output, then bail through the shared fatal error path.\n const totalTimeout = resolveTotalTimeoutAbort(outerAbortSignal, lastError);\n if (totalTimeout) {\n materializeStreamedMessages?.();\n return emitFatalErrorBail(totalTimeout, modelEntry.config.modelId);\n }\n\n const isAbort = outerAbortSignal?.aborted === true || lastError.name === 'AbortError';\n if (isAbort) {\n terminateAttemptSpans?.({ outcome: 'abort', stopReason: 'caller_cancelled' });\n // Return a clean output instead of throwing so the workflow\n // engine doesn't crash. Persist already-streamed partial output\n // first (#22593) — errors thrown after the stream loop (e.g. a\n // response processor rethrown at the processLLMResponse call)\n // land here without passing through the inner catch.\n materializeStreamedMessages?.();\n return {\n ...(await storeStepTranscript()),\n text: textDeltas.join(''),\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 deferredStepFinishChunk: prepareDeferredStepFinishChunk({ reason: 'abort', isContinued: false }),\n ...recordClocks?.(),\n } satisfies DurableLLMStepOutput;\n }\n\n const modelId = modelEntry.config.modelId;\n failInference?.(lastError);\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 = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const canRetryError = maxProcessorRetries !== undefined && processorRetryCount < maxProcessorRetries;\n // The processor always runs so it can observe (and report) the terminal\n // failure; only the retry itself is gated by the budget. This matches the\n // non-durable loop path in loop/workflows/agentic-execution/llm-execution-step.ts.\n if (registryEntry?.errorProcessors?.length) {\n try {\n const runner = new ProcessorRunner({\n lateSignalSink,\n inputProcessors: registryEntry.inputProcessors ?? [],\n outputProcessors: registryEntry.outputProcessors ?? [],\n errorProcessors: registryEntry.errorProcessors,\n logger: logger as any,\n agentName: typedInput.agentName ?? typedInput.agentId,\n agent: registryEntry?.agent,\n processorStates: registryEntry.processorStates,\n });\n const { retry } = await runner.runProcessAPIError({\n error: lastError,\n messages: messageList.get.all.db(),\n messageList,\n messageId: currentMessageId,\n rotateResponseMessageId,\n stepNumber: inputData.stepIndex ?? 0,\n steps: expandDurableSteps(previousSteps),\n retryCount: processorRetryCount,\n requestContext,\n tracingContext,\n });\n ownership?.throwIfLost();\n if (retry && canRetryError) {\n processorRetryCount++;\n // Error processor retry should NOT consume a model retry attempt.\n attempt--;\n continue;\n }\n } catch (processorError) {\n ownership?.throwIfLost();\n logger?.debug?.(`processAPIError handler failed: ${processorError}`, { runId });\n }\n }\n\n // Nothing recovered an attachment download failure. Rather than failing the\n // turn (and every later turn that replays the same history), retry the last\n // model once with unavailable attachments replaced by a placeholder.\n if (\n attempt >= maxRetries &&\n modelIndex === modelList.length - 1 &&\n !skipUnavailableAttachments &&\n isDownloadAssetsError(lastError)\n ) {\n logger?.warn?.('Could not download an attachment; retrying without unavailable attachments', {\n runId,\n error: lastError.message,\n });\n skipUnavailableAttachments = true;\n attempt--;\n continue;\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 } finally {\n removeAttemptAbortListener?.();\n }\n } // end retry loop\n } // end model loop\n\n // All models exhausted (or the run-level budget expired) - emit error +\n // step-finish chunks and return a bail response.\n const fatalError =\n lastError ?? new Error('Exhausted all fallback models and reached the maximum number of retries.');\n\n // Materialize only the final attempt before serializing MessageList. Its\n // callback preserves partial parts and model metadata, then appends the\n // Mastra-only error part; recovered attempts never reach this branch.\n // Must run before emitFatalErrorBail, which serializes the list.\n terminalAttemptContext?.recordTerminalError(fatalError);\n\n return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? 'unknown');\n }),\n });\n}\n","import type { JSONSchema7 } from 'json-schema';\nimport type { ScoringFilter } from '../../../evals/predicate';\nimport type { MastraLanguageModel } from '../../../llm/model/shared.types';\nimport type { ToolCallConcurrency } from '../../../loop/types';\nimport type { MemoryConfig } from '../../../memory/types';\nimport { getSpanErrorOrigin } from '../../../observability/error-count';\nimport type { SpanErrorOrigin } from '../../../observability/error-count';\nimport type { CoreTool } from '../../../tools/types';\nimport { boundedStringify } from '../../../utils/safe-stringify';\nimport type { MessageList } from '../../message-list';\nimport type { AgentModelManagerConfig } from '../../types';\nimport type {\n SerializableClientTool,\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 const settings = serializeModelSettings(entry.modelSettings);\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 ...(settings ? { settings } : {}),\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 {\n scorer: { name: string } | string;\n sampling?: { type: 'none' } | { type: 'ratio'; rate: number };\n filter?: ScoringFilter;\n }\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 // Filters are plain JSON (declarative predicates), so they survive the\n // snapshot round-trip by value with no name-based re-resolution.\n if (entry.filter) {\n scorerEntry.filter = entry.filter;\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 fixedMemory?: 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 fixedMemory: params.fixedMemory,\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];\n if (typeof value === 'number' && Number.isFinite(value)) {\n (out as Record<string, unknown>)[key] = 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;\n }\n\n // Execution time budgets (#21724). `totalMs` re-arms the run-level budget on\n // cold resume/recovery (see DurableAgent.recover()); `stepMs`/`firstChunkMs`\n // bound each model call inside the shared execute wrapper, which receives\n // these serialized settings on the durable path. Only positive finite\n // numbers survive, mirroring validateModelTimeoutSettings.\n if (source.timeout && typeof source.timeout === 'object') {\n const timeoutSource = source.timeout as Record<string, unknown>;\n const timeout: NonNullable<SerializableModelSettings['timeout']> = {};\n for (const key of ['totalMs', 'stepMs', 'firstChunkMs'] as const) {\n const value = timeoutSource[key];\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) {\n timeout[key] = value;\n }\n }\n if (Object.keys(timeout).length > 0) {\n out.timeout = timeout;\n }\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 * Snapshot call-time client tools from their converted CoreTools so a worker in\n * another process can rebuild them. Provider tools (no JSON input schema to\n * carry) are skipped.\n */\nexport function serializeClientTools(\n clientTools: Record<string, unknown> | undefined,\n tools: Record<string, CoreTool>,\n): Record<string, SerializableClientTool> | undefined {\n if (!clientTools) return undefined;\n const out: Record<string, SerializableClientTool> = {};\n for (const name of Object.keys(clientTools)) {\n const tool = tools[name];\n if (\n !tool ||\n (tool as { type?: string }).type === 'provider-defined' ||\n (tool as { type?: string }).type === 'provider'\n ) {\n continue;\n }\n const meta = serializeToolMetadata(name, tool);\n out[name] = {\n id: meta.id,\n description: meta.description,\n inputSchema: meta.inputSchema,\n requireApproval: meta.requireApproval,\n };\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Collect the tool names from call-time toolsets so a cross-process worker can\n * detect that they are unavailable.\n */\nexport function serializeToolsetToolNames(\n toolsets: Record<string, Record<string, unknown> | undefined> | undefined,\n): string[] | undefined {\n if (!toolsets) return undefined;\n const names = new Set<string>();\n for (const toolset of Object.values(toolsets)) {\n for (const name of Object.keys(toolset ?? {})) names.add(name);\n }\n return names.size > 0 ? [...names] : undefined;\n}\n\n/**\n * Extract serializable options from agent execution options\n */\nexport function serializeDurableOptions(options: {\n clientTools?: SerializableDurableOptions['clientTools'];\n toolsetToolNames?: string[];\n maxSteps?: number;\n toolChoice?: any;\n activeTools?: string[];\n modelSettings?: SerializableModelSettings | Record<string, unknown>;\n agentMaxRetries?: number;\n agentMaxRetriesConfigured?: boolean;\n requireToolApproval?: boolean;\n toolCallConcurrency?: ToolCallConcurrency;\n autoResumeSuspendedTools?: boolean;\n maxProcessorRetries?: number;\n includeRawChunks?: boolean;\n returnScorerData?: boolean;\n hasErrorProcessors?: boolean;\n emptyErrorProcessorOverride?: boolean;\n providerOptions?: SerializableDurableOptions['providerOptions'];\n structuredOutput?: SerializableDurableOptions['structuredOutput'];\n skipBgTaskWait?: boolean;\n disableBackgroundTasks?: boolean;\n backgroundTaskPolicy?: SerializableDurableOptions['backgroundTaskPolicy'];\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 clientTools: options.clientTools,\n toolsetToolNames: options.toolsetToolNames,\n maxSteps: options.maxSteps,\n toolChoice: serializedToolChoice,\n activeTools: options.activeTools,\n modelSettings: serializeModelSettings(options.modelSettings),\n agentMaxRetries: options.agentMaxRetries,\n agentMaxRetriesConfigured: options.agentMaxRetriesConfigured,\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 emptyErrorProcessorOverride: options.emptyErrorProcessorOverride,\n providerOptions: options.providerOptions,\n structuredOutput: options.structuredOutput,\n skipBgTaskWait: options.skipBgTaskWait,\n disableBackgroundTasks: options.disableBackgroundTasks,\n backgroundTaskPolicy: options.backgroundTaskPolicy,\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 agentVersionId?: 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 inputTripwire?: DurableAgenticWorkflowInput['inputTripwire'];\n}): DurableAgenticWorkflowInput {\n // Unsupported metadata must not discard the terminal rejection itself.\n const metadataJson = params.inputTripwire ? boundedStringify(params.inputTripwire.metadata) : undefined;\n const inputTripwire = params.inputTripwire\n ? {\n reason: params.inputTripwire.reason,\n retry: params.inputTripwire.retry,\n processorId: params.inputTripwire.processorId,\n ...(metadataJson === undefined ? {} : { metadata: JSON.parse(metadataJson) }),\n }\n : undefined;\n\n return {\n __workflowKind: 'durable-agent',\n runId: params.runId,\n agentId: params.agentId,\n agentName: params.agentName,\n agentVersionId: params.agentVersionId,\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 inputTripwire,\n };\n}\n\n/**\n * Serialize an error for workflow state\n */\nexport function serializeError(error: unknown): {\n name: string;\n message: string;\n stack?: string;\n __mastraSpanErrorOrigin?: SpanErrorOrigin;\n} {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n __mastraSpanErrorOrigin: getSpanErrorOrigin(error),\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 { z } from 'zod';\nimport { MastraFGAPermissions } from '../../../../auth/ee';\nimport { executeAdoptedBackgroundOperation } from '../../../../background-tasks/adoption';\nimport type { ToolBackgroundConfig } from '../../../../background-tasks/types';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { STEP_MODEL_MESSAGES_KEY } from '../../../../loop/run-scope-keys';\nimport { approvalResumeSchema } from '../../../../loop/shared/approval-schema';\nimport { takeDelegationFailure } from '../../../../loop/shared/delegation-outcome';\nimport { normalizeModelOutput } from '../../../../loop/shared/normalize-model-output';\nimport { readToolResultFromMessageList } from '../../../../loop/shared/read-tool-result';\nimport { dispatchBackgroundTool } from '../../../../loop/shared/steps/background-dispatch-core';\nimport {\n applyBackgroundToolExecution,\n applyBackgroundToolResult,\n} from '../../../../loop/shared/steps/background-task-result-core';\nimport { executeToolCall } from '../../../../loop/shared/steps/execute-tool-core';\nimport { processAndEmitChunk } from '../../../../loop/shared/steps/process-chunk-core';\nimport {\n computeModelOutputProviderMetadata,\n readModelOutput,\n resolveModelOutputAfterToolResultProcessors,\n snapshotToolResult,\n hasToolResultProcessor,\n withAgentWorkflowToolMarker,\n} from '../../../../loop/shared/steps/tool-result-commit-core';\nimport type { ToolResultCommitOutcome } from '../../../../loop/shared/steps/tool-result-commit-core';\nimport {\n ownToolCallSuspendData,\n resolveFrameworkSuspendedToolIdentity,\n} from '../../../../loop/shared/suspended-tool-run-id';\nimport type { ResolvedSuspendedToolIdentity } from '../../../../loop/shared/suspended-tool-run-id';\nimport { TOOL_ABORT_NOTICE } from '../../../../loop/shared/tool-abort-grace';\nimport { applyToolPayloadTransformToChunk } from '../../../../loop/shared/tool-payload-transform';\nimport { isMastraTimeoutError } from '../../../../loop/timeout';\nimport {\n INTERNAL_APPROVAL_KEYS,\n runBeforeApprovalChecks,\n} from '../../../../loop/workflows/agentic-execution/tool-approval-verdict';\nimport type { Mastra } from '../../../../mastra';\nimport type { MastraMemory } from '../../../../memory/memory';\nimport type { MemoryConfig } from '../../../../memory/types';\nimport { EntityType, SpanType, createObservabilityContext } from '../../../../observability';\nimport type { ExportedSpan, ObservabilityContext, SpanTermination } from '../../../../observability';\nimport { compactStopReasonContext } from '../../../../observability/outcome-schema';\nimport type { ProcessorState } from '../../../../processors';\nimport { BACKGROUND_WORK_CONTEXT } from '../../../../processors/background-work-signals';\nimport { isProcessorWorkflow } from '../../../../processors/is-processor-workflow';\nimport { ProcessorRunner } from '../../../../processors/runner';\nimport type { RequestContext } from '../../../../request-context';\nimport { persistProcessorDataChunk } from '../../../../stream/base/output';\nimport type { ChunkType } from '../../../../stream/types';\nimport { ChunkFrom } from '../../../../stream/types';\nimport {\n getTransformedToolPayload,\n hasTransformedToolPayload,\n withToolPayloadTransformProviderMetadata,\n} from '../../../../tools/payload-transform';\nimport { findProviderToolByName } from '../../../../tools/provider-tool-utils';\nimport { ToolStream } from '../../../../tools/stream';\nimport { getToolTitle } from '../../../../tools/tool-title';\nimport {\n getModelFacingValidationError,\n resolveToolOutputValidationSchema,\n validateToolOutput,\n} from '../../../../tools/validation';\nimport type { ModelFacingValidationError } from '../../../../tools/validation';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport type { SuspendOptions } from '../../../../workflows/step';\nimport { defineLazyWriter } from '../../../../workflows/utils';\nimport { createStep } from '../../../../workflows/workflow';\nimport { stopGoalActivity } from '../../../goal';\nimport type { MessageList } from '../../../message-list';\nimport type { MastraDBMessage } from '../../../message-list/state/types';\nimport { startRunStep } from '../../../run-lease-fence';\nimport type { SaveQueueManager } from '../../../save-queue';\nimport { resolveDeclineReason } from '../../../tool-approval';\nimport { TripWire } from '../../../trip-wire';\nimport { ensureRemoteAbortListener, readRunDeadline } from '../../abort-transport';\nimport { DurableStepIds } from '../../constants';\nimport {\n assertExecutionNotSuperseded,\n assertExecutionNotSupersededInStorage,\n assertExecutionOwned,\n getExecutionOwnershipGuard,\n isExecutionFenceError,\n runFencedToClaim,\n} from '../../execution-fence';\nimport { authorizeDurableMemory, getDurableMemoryAuthorizationChecks } from '../../memory-fga';\nimport { clearResumeInFlight, getRunRegistryEntry, globalRunRegistry, markRunActive } from '../../run-registry';\nimport { emitSuspendedEvent, emitChunkEvent } from '../../stream-adapter';\nimport type {\n DurableToolCallInput,\n DurableToolCallOutput,\n DurableLLMStepOutput,\n SerializableDurableOptions,\n AgentSuspendedEventData,\n RunRegistryEntry,\n} from '../../types';\nimport {\n rebuildRunToolsFromMastra,\n resolveTool,\n restoreRequestContext,\n toolRequiresApproval,\n} from '../../utils/resolve-runtime';\nimport { createRunMessageList } from '../../utils/run-message-list';\nimport { serializeError } from '../../utils/serialize-state';\nimport { recordBackgroundResult } from '../shared/background-results';\nimport { carriedSpanClocks } from '../shared/iteration-state';\nimport { readMessageListState } from '../shared/message-list-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()).optional(),\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 // Stamps from the step's *effective* tool set so the durable foreach\n // concurrency gate can see approval/suspension capability that the run-start\n // `toolsMetadata` lacks (e.g. tools added by input processors, issue #24377).\n requireApproval: z.boolean().optional(),\n hasSuspendSchema: z.boolean().optional(),\n // Exported MODEL_STEP span so the TOOL_CALL nests under the LLM call\n stepSpanData: z.any().optional(),\n // First-chunk clock of the step that produced this call, for ending spans on suspend\n completionStartTime: z.coerce.date().optional(),\n // Time to first token of the same step, used the same way\n timeToFirstTokenMs: z.number().optional(),\n // Model usage of the step that produced this call, reported on its suspension chunk\n stepUsage: z.any().optional(),\n});\n\n/**\n * Output schema for the durable tool call step.\n *\n * NOTE on field declarations: nothing strips undeclared fields today — both\n * loop builders run with `validateInputs: false` and the workflows engine has\n * no output-side validation — so undeclared fields still cross step\n * boundaries at runtime. Every field the step emits is declared anyway for\n * type/schema honesty and so the contract survives if validation is ever\n * (re-)enabled (e.g. by the Phase 2 evented port, which may use different\n * validation defaults). If validation is enabled, an undeclared field would\n * be silently stripped at the boundary — declare new output fields here.\n */\nconst serializedErrorSchema = z.object({\n name: z.string(),\n message: z.string(),\n stack: z.string().optional(),\n __mastraSpanErrorOrigin: z\n .object({\n traceId: z.string(),\n spanId: z.string(),\n occurrenceId: z.string(),\n attemptId: z.string().optional(),\n })\n .optional(),\n});\n\nconst durableToolCallOutputSchema = durableToolCallInputSchema.extend({\n result: z.any().optional(),\n modelOutputComputed: z.boolean().optional(),\n mappingError: serializedErrorSchema.optional(),\n // Set when execution was interrupted by request abort (not a tool error); no result/error\n // so the mapping step leaves the call incomplete.\n // Mirrors the non-durable tool-call output schema.\n aborted: z.boolean().optional(),\n // Set when a processToolResult processor blocked the result via tripwire; no result\n // crosses the boundary and the mapping step leaves the call incomplete.\n resultBlocked: z.boolean().optional(),\n // Set when an output processor dropped the tool-result chunk. The model still\n // gets the result; callbacks must not report a result the stream never emitted.\n resultHidden: z.boolean().optional(),\n tripwire: z\n .object({\n reason: z.string(),\n retry: z.boolean().optional(),\n metadata: z.unknown().optional(),\n processorId: z.string().optional(),\n })\n .optional(),\n error: serializedErrorSchema.optional(),\n // Approval decision for a `requireApproval` tool; a declined call carries its\n // `output-denied` marker across the boundary in this field.\n approval: z\n .object({\n id: z.string(),\n approved: z.boolean(),\n reason: z.string().optional(),\n })\n .optional(),\n // Non-transient data-* chunks emitted by output processors via writer.custom()\n // during this tool call. The tool-call step's messageList is a local copy whose\n // mutations don't cross the step boundary, so these are carried on the output\n // record and persisted into the authoritative messageList by the mapping step\n // (#19375 parity port).\n processorDataParts: z\n .array(\n z.object({\n type: z.string(),\n data: z.any().optional(),\n id: z.string().optional(),\n messageId: z.string().optional(),\n }),\n )\n .optional(),\n // Payload-transform metadata captured from the emitted tool-result/tool-error\n // chunk (L18b): merged into providerMetadata by the mapping step before\n // commitToolResult so transcript/display targets apply on recall.\n transformMetadata: z.record(z.string(), z.any()).optional(),\n // Set when a delegation onDelegationComplete hook called ctx.bail() during\n // this tool call. Carried on the step output (not requestContext) because\n // the evented engine rehydrates a fresh RequestContext per step, so the\n // wrapper's by-reference flag write never reaches the mapping step there.\n delegationBailed: z.boolean().optional(),\n // Why that delegation failed, carried the same way for the root spans' outcome.\n tracingDelegationFailure: z.custom<SpanTermination>().optional(),\n // Set when the total deadline aborted this tool call. Carried on the step\n // output so a later step on another worker, which may never have received\n // the abort request, still ends the run as the deadline.\n deadlineTimeout: z.object({ timeoutType: z.literal('total'), timeoutMs: z.number() }).optional(),\n // Set when abort() stopped this tool call; carried for the same reason.\n runAborted: z.boolean().optional(),\n});\n\n/**\n * Marks a tool call the run was stopped during, however the tool settled: the total deadline or\n * abort(). The next step may run on a worker that never received the abort request, so the mark\n * travels on the step output. An abort only this execution saw (lost ownership) is not the run's.\n */\nfunction runStopOf(\n signal: AbortSignal | undefined,\n runSignal: AbortSignal | undefined,\n): { deadlineTimeout?: DurableToolDeadlineTimeout; runAborted?: true } {\n if (!signal?.aborted || !runSignal?.aborted) return {};\n const reason: unknown = runSignal.reason;\n if (isMastraTimeoutError(reason)) {\n return reason.timeoutType === 'total'\n ? { deadlineTimeout: { timeoutType: 'total', timeoutMs: reason.timeoutMs } }\n : {};\n }\n return { runAborted: true };\n}\n\ntype DurableToolDeadlineTimeout = { timeoutType: 'total'; timeoutMs: number };\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 *\n * Skips entirely when memoryConfig.readOnly is set, mirroring the readOnly\n * guard on the durable finish path — a readOnly run shouldn't get a thread\n * created or messages written just because it happened to suspend mid-run.\n */\nasync function flushMessagesBeforeSuspension({\n saveQueueManager,\n messageList,\n memory,\n threadId,\n resourceId,\n memoryConfig,\n threadExists,\n onThreadCreated,\n beforePersist,\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 beforePersist?: () => Promise<void>;\n}): Promise<boolean> {\n if (!saveQueueManager || !messageList || !threadId || memoryConfig?.readOnly) {\n return true;\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, { beforePersist, throwOnError: true });\n return true;\n } catch (error) {\n // A superseded execution must not suspend the run it no longer owns.\n if (isExecutionFenceError(error)) throw error;\n // Otherwise don't throw — suspension should proceed even if flush fails\n return false;\n }\n}\n\nclass DurableOutputProcessorError extends Error {\n constructor(error: unknown) {\n super(error instanceof Error ? error.message : String(error), { cause: error });\n this.name = 'DurableOutputProcessorError';\n }\n}\n\nclass DurableChunkPublishError extends Error {\n constructor(error: unknown) {\n super(error instanceof Error ? error.message : String(error), { cause: error });\n this.name = 'DurableChunkPublishError';\n }\n}\n\n/**\n * Run a tool-result or tool-error chunk through the run's output processor\n * pipeline and emit it (or a tripwire when blocked) via pubsub. Returns the\n * processed chunk, or `null` if a processor blocked it. `onEmit` sees every\n * chunk emitted, including parts a processor stashed for reprocessing.\n *\n * Thin glue over the shared per-chunk pipeline core; mirrors the regular\n * 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 observabilityContext?: ObservabilityContext,\n collectDataPart?: (part: { type: string; data?: unknown; messageId?: string }) => void,\n onEmit?: (chunk: ChunkType) => void,\n): Promise<ChunkType | null> {\n const runner =\n registryEntry?.outputProcessors?.length && registryEntry.processorStates\n ? new ProcessorRunner({\n inputProcessors: [],\n outputProcessors: registryEntry.outputProcessors,\n logger,\n agentName,\n agent: registryEntry.agent,\n processorStates: registryEntry.processorStates,\n })\n : undefined;\n\n return processAndEmitChunk(chunk, {\n runner,\n processorStates: registryEntry?.processorStates as Map<string, ProcessorState> | undefined,\n observabilityContext,\n requestContext: registryEntry?.requestContext,\n messageList,\n streamWriter: pubsub\n ? {\n custom: async (\n data: { type: string; data?: unknown; transient?: boolean },\n writerOptions?: { messageId?: string },\n ) => {\n // Collect non-transient data-* chunks for persistence by the\n // mapping step (#19375 parity port); transient chunks stay\n // stream-only.\n if (data.type.startsWith('data-') && !data.transient) {\n collectDataPart?.({ type: data.type, data: data.data, messageId: writerOptions?.messageId });\n }\n try {\n await emitChunkEvent(pubsub, runId, data as ChunkType);\n } catch (error) {\n throw new DurableChunkPublishError(error);\n }\n },\n }\n : undefined,\n emitChunk: async c => {\n if (pubsub) {\n // Mark chunks the processors ran on so the stream consumer doesn't run\n // them again. Without a runner (no processors, or none in this process)\n // the chunk goes out unmarked and the consumer processes it.\n try {\n await emitChunkEvent(pubsub, runId, c, !!runner);\n } catch (error) {\n throw new DurableChunkPublishError(error);\n }\n }\n onEmit?.(c);\n },\n onProcessorError: error => {\n // Publication failures keep the callers' non-fatal emission path.\n if (error instanceof DurableChunkPublishError) {\n throw error.cause;\n }\n throw new DurableOutputProcessorError(error);\n },\n // The finish chunk that normally ends stream-processor spans never reaches\n // this pipeline, so end the spans opened for this chunk here.\n endSpansAfterProcessing: true,\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 *\n * Deliberate divergence from the main loop: main cannot pause its\n * request-scoped loop, so pending client tools ride the finish payload for\n * browser-side handling and results come back on a follow-up request (#21688\n * family). Durable has first-class suspension — the whole workflow parks at\n * this step and resumes with the decision/result — so none of main's\n * pending-tool plumbing applies here.\n */\nexport function createDurableToolCallStep() {\n return createStep({\n id: DurableStepIds.TOOL_CALL,\n inputSchema: durableToolCallInputSchema,\n outputSchema: durableToolCallOutputSchema,\n execute: async params => {\n const {\n inputData,\n mastra,\n suspend,\n resumeData: workflowResumeData,\n requestContext,\n actor,\n getInitData,\n getStepResultAsync,\n } = params;\n\n const ownership = getExecutionOwnershipGuard(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 const suspendData = ownToolCallSuspendData(params.suspendData, toolCallId);\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 // Non-transient data-* chunks emitted by output processors or tools via\n // writer.custom() during this tool call. This step's messageList is a\n // local copy whose mutations don't cross the step boundary, so parts are\n // collected here and carried on the output record for the mapping step\n // to persist into the authoritative messageList (#19375 parity port).\n const processorDataParts: Array<{ type: string; data?: unknown; id?: string; messageId?: string }> = [];\n const collectProcessorDataPart = (part: { type: string; data?: unknown; id?: string; messageId?: string }) => {\n ownership?.throwIfLost();\n processorDataParts.push(part);\n };\n\n const resumeData = resumeDataFromArgs ?? workflowResumeData;\n // Approval decisions are read from the serialized resume payload — never\n // from live in-memory policy objects. Main's #20487 bug (a live\n // `requireToolApproval` policy that didn't survive serialization let\n // declined tools execute) cannot occur here by construction.\n const approvalDecision =\n workflowResumeData != null &&\n typeof workflowResumeData === 'object' &&\n typeof (workflowResumeData as Record<string, unknown>).approved === 'boolean'\n ? (workflowResumeData as { approved: boolean; reason?: string })\n : undefined;\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 completionStartTime?: Date | string;\n timeToFirstTokenMs?: number;\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 = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;\n const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;\n // Rebuilt spans come from the run-start snapshot, so end them with the clocks\n // their segment captured: the loop state's (or this step's, on the first\n // iteration) for the originals.\n const attributes = carriedSpanClocks(\n reg,\n initData.completionStartTime\n ? { completionStartTime: initData.completionStartTime, timeToFirstTokenMs: initData.timeToFirstTokenMs }\n : {\n completionStartTime: typedInput.completionStartTime,\n timeToFirstTokenMs: typedInput.timeToFirstTokenMs,\n },\n );\n if (typedInput.stepSpanData) {\n obs.rebuildSpan(typedInput.stepSpanData as ExportedSpan<SpanType.MODEL_STEP>)?.end({\n output,\n outcome: 'suspend',\n stopReason: info.reason === 'approval' ? 'approval_required' : null,\n stopReasonContext:\n info.reason === 'approval'\n ? compactStopReasonContext('approval_required', {\n toolCallId: info.toolCallId,\n toolName: info.toolName,\n })\n : null,\n });\n }\n if (modelSpanData) {\n obs.rebuildSpan(modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION>)?.end({\n output,\n attributes,\n outcome: 'suspend',\n stopReason: info.reason === 'approval' ? 'approval_required' : null,\n stopReasonContext:\n info.reason === 'approval'\n ? compactStopReasonContext('approval_required', {\n toolCallId: info.toolCallId,\n toolName: info.toolName,\n })\n : null,\n });\n }\n if (agentSpanData) {\n obs.rebuildSpan(agentSpanData as ExportedSpan<SpanType.AGENT_RUN>)?.end({\n output,\n attributes,\n outcome: 'suspend',\n stopReason: info.reason === 'approval' ? 'approval_required' : null,\n stopReasonContext:\n info.reason === 'approval'\n ? compactStopReasonContext('approval_required', {\n toolCallId: info.toolCallId,\n toolName: info.toolName,\n })\n : null,\n });\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 // Provider-executed tools are handled entirely by the stream path\n // (tool-call and tool-result chunks in llm-execution.ts), so skip client\n // execution — mirrors the non-durable tool-call step. When the provider\n // already delivered the output in the same stream, thread it through as\n // the result; a deferred result (e.g. Anthropic web_search resolving in\n // a later stream) must not fall through to client execution, which would\n // try to run the provider tool client-side and fail with\n // ToolNotFoundError. The deferred result is patched into the messageList\n // by llm-execution's tool-result handling when it arrives in a later\n // stream (#14282 parity port).\n if (providerExecuted) {\n return {\n ...typedInput,\n ...(output !== undefined ? { 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 let registryEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const registryModel = registryEntry?.model as { __metadataOnly?: boolean } | undefined;\n const hasAuthoritativeToolSnapshot =\n !!registryEntry &&\n registryEntry.isPlaceholder !== true &&\n !!registryModel &&\n registryModel.__metadataOnly !== true &&\n (registryEntry.baseTools !== undefined || registryEntry.tools !== undefined);\n const observability = (mastra as Mastra | undefined)?.observability?.getSelectedInstance({ requestContext });\n\n // Tracing context for per-chunk PROCESSOR_RUN spans: the run's AGENT_RUN span (live\n // in-process, rebuilt cross-process). Without it they export as orphan trace roots.\n const processorAgentSpanData = registryEntry?.resumeAgentSpanData ?? initData.agentSpanData;\n const processorAgentSpan =\n registryEntry?.resumeAgentSpan ??\n registryEntry?.agentSpan ??\n (processorAgentSpanData && observability\n ? observability.rebuildSpan(processorAgentSpanData as ExportedSpan<SpanType.AGENT_RUN>)\n : undefined);\n const processorObservabilityContext = processorAgentSpan\n ? createObservabilityContext({ currentSpan: processorAgentSpan })\n : undefined;\n\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 // RequestContext the rebuilt tools were built with (their closures\n // capture it) — checked for the delegation bail flag after execution.\n let rebuiltRequestContext: RequestContext | undefined;\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 // Cross-process fallback: workspace/skill tools are per-request closures\n // never registered at the Mastra-instance level, so the registry lookups 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 //\n // The same rebuild is ALSO the only source of a SaveQueueManager. `createInngestAgent`\n // registers one on the run-registry entry, but only in the process that called `stream()`;\n // the connect() worker that actually runs the loop has an empty registry, so\n // `registryEntry?.saveQueueManager` is undefined there. Without it\n // `flushMessagesBeforeSuspension()` early-returns and the suspend metadata written by\n // `addToolMetadata()` is never persisted — a reloading client then sees no pending approval\n // even though the run is parked. So rebuild when the save queue is missing too, not just\n // when the tool is.\n //\n // Gated on `state?.threadId`: an agent without memory legitimately has no SaveQueueManager\n // (see preparation.ts — it is only built when `memory` is set), and the flush requires a\n // threadId regardless. Without this guard every tool call on a memoryless durable run would\n // pay for a full rebuild to obtain something that can neither exist nor be used.\n const needsSaveQueueForFlush = !registryEntry?.saveQueueManager && !!state?.threadId;\n // A persistence-only rebuild restores tools and the save queue, but not processors.\n const needsProcessorPipeline = !registryEntry?.outputProcessors || !registryEntry.processorStates;\n if (((!tool && !hasAuthoritativeToolSnapshot) || needsSaveQueueForFlush || needsProcessorPipeline) && 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 requestContext,\n rehydrateProcessors: true,\n logger,\n });\n if (rebuilt) {\n registryEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n rebuiltTools = rebuilt.tools;\n rebuiltWorkspace = rebuilt.workspace;\n rebuiltMemory = rebuilt.memory;\n rebuiltSaveQueueManager = rebuilt.saveQueueManager;\n rebuiltRequestContext = rebuilt.requestContext;\n // Keep an already-resolved tool: we may have rebuilt purely to obtain the\n // SaveQueueManager, and the registry's instance is the live per-request closure.\n // A hydrated registry's per-step snapshot is authoritative, so a tool omitted\n // from it must not be restored from the agent's full toolset.\n if (!tool && !hasAuthoritativeToolSnapshot) {\n tool = rebuiltTools[toolName] as typeof tool;\n }\n if (!tool && !hasAuthoritativeToolSnapshot) {\n tool = findProviderToolByName(rebuiltTools as any, toolName) as typeof tool;\n }\n if (!tool && !hasAuthoritativeToolSnapshot) {\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 // Mastra-wide lookup runs only after a cold worker's rebuilt agent tools\n // miss: tool ids are not unique across agents, so a global lookup first\n // could execute another agent's same-id tool. A hydrated registry's\n // per-step snapshot is authoritative and must not fall back to this full\n // catalog when prepareStep or an input processor omitted a tool.\n if (!tool && !hasAuthoritativeToolSnapshot) {\n tool = resolveTool(toolName, mastra as Mastra);\n }\n\n if (!tool && !hasAuthoritativeToolSnapshot && 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 // 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 =\n effectiveActiveTools ??\n Object.keys(\n hasAuthoritativeToolSnapshot ? (registryEntry?.tools ?? {}) : (rebuiltTools ?? registryEntry?.tools ?? {}),\n );\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 // Preserve parse failure as a tool error, before approval hooks or argument spreading.\n if (args === null || args === undefined) {\n const error = serializeError(\n new Error(\n `Tool \"${toolName}\" received invalid arguments — the provided JSON could not be parsed. Please provide valid JSON arguments.`,\n ),\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 { ...typedInput, error };\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 const toolPayloadTransform =\n getRunRegistryEntry(runId, mastra as Mastra | undefined)?.toolPayloadTransform ??\n Object.values(mastra?.listAgents?.() ?? {})\n .find(agent => agent.id === initData.agentId)\n ?.getToolPayloadTransform?.() ??\n mastra?.getToolPayloadTransform?.();\n let threadExists = state?.threadExists ?? false;\n\n const toolsForTransform = getRunRegistryEntry(runId, mastra as Mastra | undefined)?.tools ?? rebuiltTools;\n const messageList: MessageList | undefined = getRunRegistryEntry(\n runId,\n mastra as Mastra | undefined,\n )?.messageList;\n // Hold suspension chunks/events until the engine has saved the suspended\n // snapshot, when the running engine supports that (#26435).\n const publishAfterPersist = async (publish: () => Promise<void>) => {\n const entry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n // Once the new suspension is saved, a later resume of the tool call is a decision on\n // that suspension, not a duplicate. Clearing earlier would let a duplicate approval\n // of the previous gate approve the new one (#27365).\n const resumedToolCallId = entry?.resumeToolCallId;\n const clearAndPublish = async () => {\n if (resumedToolCallId !== undefined) clearResumeInFlight(runId, resumedToolCallId);\n await publish();\n };\n const pending = entry?.pendingSuspensionEvents;\n if (pending) pending.push(clearAndPublish);\n else await clearAndPublish();\n };\n let resumeMessageList = messageList;\n // Observational memory loads history in the LLM step, which a cold resume skips.\n // Recover the persisted invocation before clearing or replacing its metadata.\n const hasInvocation = (msg: MastraDBMessage) =>\n msg.role === 'assistant' &&\n (msg.content?.parts ?? []).some(\n part => part?.type === 'tool-invocation' && part.toolInvocation?.toolCallId === toolCallId,\n );\n if (\n workflowResumeData !== undefined &&\n memory &&\n state?.threadId &&\n !messageList?.get.all.db().some(hasInvocation)\n ) {\n const { messages } = await memory.recall({\n threadId: state.threadId,\n resourceId: state.resourceId,\n perPage: false,\n });\n if (messageList) {\n const invocation = [...messages].reverse().find(hasInvocation);\n if (invocation) messageList.add(invocation, 'memory');\n } else if (messages.length) {\n resumeMessageList = createRunMessageList({\n mastra,\n threadId: state.threadId,\n resourceId: state.resourceId,\n }).add(messages, 'memory');\n }\n }\n // Replayed step transcripts supply context only, not messages to persist.\n let contextMessageList = messageList;\n if (!contextMessageList) {\n const llmOutput = await getStepResultAsync?.<DurableLLMStepOutput>(DurableStepIds.LLM_EXECUTION);\n const messageListState = await readMessageListState(params, llmOutput ?? {});\n if (messageListState) {\n contextMessageList = createRunMessageList({\n mastra,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n }).deserialize(messageListState);\n }\n }\n\n // Every flush from this step re-checks run ownership inside the save\n // queue, so a superseded execution cannot write memory (#23734).\n const assertOwned = () =>\n assertExecutionOwned({ runId, agentId: initData.agentId, requestContext, mastra: mastra as Mastra });\n // Background-task hooks can fire after the execution settled and\n // released its claim; their writes only stop once another execution\n // claimed the run.\n const assertNotSuperseded = () =>\n assertExecutionNotSuperseded({ runId, agentId: initData.agentId, requestContext, mastra: mastra as Mastra });\n // A late suspension gets that rule only with ownership in storage: a released lease can't show\n // whether another execution claimed and finished the run since, so a lease keeps the strict check.\n const assertSuspensionNotSuperseded = () =>\n assertExecutionNotSupersededInStorage({\n runId,\n agentId: initData.agentId,\n requestContext,\n mastra: mastra as Mastra,\n });\n // Those writes carry the run's claim, so storage rejects one that lands after a successor\n // raised the memory fence, even though it passed the check above (#30182).\n const claimFenceArgs = {\n requestContext,\n runId,\n memoryStore: async () => memory?.storage.getStore('memory'),\n };\n\n // Remote workers have no registry message list; persist updates through the recovered resume list.\n const doFlush = async (messagesToFlush = messageList ?? resumeMessageList, beforePersist = assertOwned) => {\n if (!messagesToFlush && processorDataParts.length) {\n const invocation = [...(contextMessageList?.get.all.db() ?? [])].reverse().find(hasInvocation);\n if (invocation) {\n // Replayed context is not new output. Seed only the invocation that owns the\n // questions, so adding data parts marks that one message for persistence.\n messagesToFlush = createRunMessageList({\n mastra,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n }).add(invocation, 'memory');\n }\n }\n if (\n saveQueueManager &&\n messagesToFlush &&\n memory &&\n state?.threadId &&\n state.resourceId &&\n !state.memoryConfig?.readOnly\n ) {\n const authorizationRequestContext =\n registryEntry?.requestContext ?? restoreRequestContext(initData.requestContextEntries, requestContext);\n const authorizeMemory = (permission: Parameters<typeof authorizeDurableMemory>[1]['permission']) =>\n authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {\n mastra: mastra as Mastra | undefined,\n user: authorizationRequestContext.get('user'),\n threadId: state.threadId!,\n resourceId: state.resourceId!,\n agentId: initData.agentId,\n requestContext: authorizationRequestContext,\n permission,\n actor: agentOptions.actor,\n });\n await authorizeMemory(MastraFGAPermissions.MEMORY_WRITE);\n if (!threadExists) await authorizeMemory(MastraFGAPermissions.MEMORY_READ);\n }\n let flushedDataParts: typeof processorDataParts = [];\n if (messagesToFlush && processorDataParts.length) {\n const invocation = [...messagesToFlush.get.all.db()].reverse().find(hasInvocation);\n if (invocation) {\n flushedDataParts = processorDataParts.splice(0);\n for (const part of flushedDataParts) {\n persistProcessorDataChunk(messagesToFlush, part.messageId ?? invocation.id, part);\n }\n }\n }\n const flushed = await flushMessagesBeforeSuspension({\n saveQueueManager,\n messageList: messagesToFlush,\n memory,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n memoryConfig: state?.memoryConfig,\n threadExists,\n onThreadCreated: () => {\n threadExists = true;\n },\n beforePersist,\n });\n if (!flushed) {\n logger?.warn?.('Failed to persist messages before durable tool suspension', {\n runId,\n toolCallId,\n });\n // Keep the parts for the mapping step to persist if this save did not land.\n processorDataParts.unshift(...flushedDataParts);\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 // Prefer the live in-process request context. On a cross-process worker\n // (or a resume after restart) the registry is empty, so fall back to the\n // persisted `requestContextEntries` snapshot — the same source the tool\n // rebuild uses — so context-aware approval predicates still see the\n // request scope captured when the run started.\n const approvalRequestContext =\n registryEntry?.requestContext ?? restoreRequestContext(initData.requestContextEntries, requestContext);\n const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {\n toolName,\n requestContext: Object.fromEntries(\n [...approvalRequestContext.entries()].filter(([key]) => !INTERNAL_APPROVAL_KEYS.has(key)),\n ),\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 delegatedRunId?: string;\n delegatedToolCallId?: string;\n delegatedToolName?: string;\n approvalToolName?: string;\n approvalArgs?: unknown;\n }) => {\n const metadataMessageList = messageList ?? resumeMessageList;\n if (!metadataMessageList) return;\n const metadataKey = opts.type === 'suspension' ? 'suspendedTools' : 'pendingToolApprovals';\n const entry = {\n toolCallId,\n toolName: opts.approvalToolName ?? toolName,\n args: opts.approvalArgs ?? args,\n ...(opts.approvalToolName ? { parentToolName: toolName, parentArgs: args } : {}),\n type: opts.type,\n // `runId` is the outer resumable durable run. When a delegated\n // sub-agent/workflow suspends, its inner suspended run is preserved\n // separately as `delegatedRunId` so the resume leg can recover it\n // (mirrors the regular engine's tool-call-step metadata shape).\n runId,\n ...(opts.delegatedRunId && opts.delegatedRunId !== runId ? { delegatedRunId: opts.delegatedRunId } : {}),\n // The delegate's own tool call that paused. Resume stays keyed on `toolCallId`.\n ...(opts.delegatedToolCallId ? { delegatedToolCallId: opts.delegatedToolCallId } : {}),\n ...(opts.delegatedToolName ? { delegatedToolName: opts.delegatedToolName } : {}),\n ...(opts.type === 'suspension' ? { suspendPayload: opts.suspendPayload } : {}),\n ...(opts.resumeSchema ? { resumeSchema: opts.resumeSchema } : {}),\n };\n\n const carriesToolCall = (msg: any) =>\n msg.role === 'assistant' &&\n (msg.content?.parts ?? []).some(\n (part: any) => part?.type === 'tool-invocation' && part.toolInvocation?.toolCallId === toolCallId,\n );\n\n const responseMessages = metadataMessageList.get.response.db();\n const lastAssistantMessage = [...responseMessages].reverse().find(carriesToolCall);\n if (lastAssistantMessage?.content) {\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] = entry;\n return;\n }\n\n // The response view is empty: a sibling parallel tool call already\n // suspended and its pre-suspension flush drained the unsaved response\n // messages. Without a fallback this sibling's entry is silently lost\n // and only the first suspension survives in persisted metadata. Merge\n // the entry into the assistant message that carries this tool call via\n // updateMessageMetadataByToolCallId, which also re-marks the message\n // unsaved so the following flush persists this write too.\n const allMessages = metadataMessageList.get.all.db();\n const target = [...allMessages].reverse().find(carriesToolCall);\n if (!target?.content) {\n logger?.warn?.(\n `[DurableAgent] addToolMetadata could not find an assistant message for tool call ${toolCallId} (${toolName}); ${metadataKey} entry was not persisted.`,\n );\n return;\n }\n const existingMeta =\n typeof target.content.metadata === 'object' && target.content.metadata !== null\n ? (target.content.metadata as Record<string, any>)\n : {};\n const existingEntries = (existingMeta[metadataKey] ?? {}) as Record<string, any>;\n metadataMessageList.updateMessageMetadataByToolCallId(toolCallId, {\n [metadataKey]: { ...existingEntries, [toolCallId]: entry },\n });\n };\n\n const removeToolMetadata = async (\n target: { toolCallId?: string; toolName: string; runId?: string },\n type: 'suspension' | 'approval',\n ) => {\n if (!resumeMessageList) return;\n\n const metadataKey = type === 'suspension' ? 'suspendedTools' : 'pendingToolApprovals';\n const expectedPartType = type === 'suspension' ? 'data-tool-call-suspended' : 'data-tool-call-approval';\n const entryMatches = (entry: any, fallbackToolCallId?: string): boolean => {\n const entryToolCallId = typeof entry?.toolCallId === 'string' ? entry.toolCallId : fallbackToolCallId;\n const entryToolName = entry?.parentToolName ?? entry?.toolName;\n const entryRunId = type === 'approval' ? entry?.delegatedRunId : (entry?.delegatedRunId ?? entry?.runId);\n if (target.toolCallId) return entryToolCallId === target.toolCallId;\n return entryToolName === target.toolName && !!target.runId && entryRunId === target.runId;\n };\n\n const changedMessages = [];\n let matchedEntry: Record<string, any> | undefined;\n for (const message of resumeMessageList.get.all.db()) {\n if (message.role !== 'assistant') continue;\n\n let messageChanged = false;\n const metadata =\n typeof message.content.metadata === 'object' && message.content.metadata !== null\n ? (message.content.metadata as Record<string, any>)\n : undefined;\n const entries = metadata?.[metadataKey] as Record<string, any> | undefined;\n if (entries) {\n for (const [key, entry] of Object.entries(entries)) {\n if (entryMatches(entry, key)) {\n matchedEntry ??= { ...entry, toolCallId: entry?.toolCallId ?? key };\n delete entries[key];\n messageChanged = true;\n }\n }\n if (Object.keys(entries).length === 0) delete metadata![metadataKey];\n }\n\n message.content.parts = message.content.parts?.map(part => {\n if (part.type !== expectedPartType || !entryMatches(part.data)) return part;\n matchedEntry ??= { ...(part.data as Record<string, any>) };\n if ((part.data as { resumed?: boolean }).resumed) return part;\n messageChanged = true;\n return { ...part, data: { ...(part.data as any), resumed: true } };\n });\n\n if (messageChanged) changedMessages.push(message);\n }\n\n if (changedMessages.length > 0) {\n resumeMessageList.add(changedMessages, 'response');\n await doFlush(resumeMessageList);\n }\n // Live counterpart of the persisted `resumed: true` marker (mirrors the base tool-call step).\n if (matchedEntry && pubsub) {\n // Re-run the original approval/suspension display transform so the ack never re-exposes redacted payloads.\n const displayed = await applyToolPayloadTransformToChunk(\n {\n type: type === 'approval' ? ('tool-call-approval' as const) : ('tool-call-suspended' as const),\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: matchedEntry.toolCallId ?? toolCallId,\n // Delegated approvals store the inner tool's name; policies select redaction by it.\n toolName: matchedEntry.toolName ?? toolName,\n args: matchedEntry.args,\n ...(type === 'suspension' ? { suspendPayload: matchedEntry.suspendPayload } : {}),\n resumeSchema: matchedEntry.resumeSchema,\n },\n metadata: undefined as Record<string, any> | undefined,\n },\n {\n policy: toolPayloadTransform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n await emitChunkEvent(pubsub, runId, {\n type: 'tool-call-resumed',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: matchedEntry.toolCallId ?? toolCallId,\n toolName: matchedEntry.toolName ?? toolName,\n kind: type,\n args: displayed.payload.args,\n ...(typeof matchedEntry.delegatedToolCallId === 'string'\n ? { delegatedToolCallId: matchedEntry.delegatedToolCallId }\n : {}),\n ...(typeof matchedEntry.delegatedToolName === 'string'\n ? { delegatedToolName: matchedEntry.delegatedToolName }\n : {}),\n ...(type === 'suspension' ? { suspendPayload: (displayed.payload as any).suspendPayload } : {}),\n resumeSchema: displayed.payload.resumeSchema,\n },\n ...(displayed.metadata ? { metadata: displayed.metadata } : {}),\n });\n }\n };\n\n const suspendedForApproval =\n suspendData != null &&\n typeof suspendData === 'object' &&\n (suspendData as { type?: unknown }).type === 'approval';\n const isFreshCall = suspendData === undefined;\n const approvalGated = suspendedForApproval || (requiresApproval && isFreshCall);\n\n if (approvalGated && !approvalDecision && isFreshCall) {\n const rejection = await runBeforeApprovalChecks({\n tool,\n input: args,\n context: { toolCallId, toolName, requestContext: approvalRequestContext, workspace, actor },\n logger: logger as any,\n });\n if (rejection) {\n const result = rejection.output;\n // A failed input check here is Mastra's own validation error. Map it now, in this\n // process: llm-mapping only sees the serialized copy, which lost the marker.\n const validationError = getModelFacingValidationError(result);\n const mappingTool = getRunRegistryEntry(runId, mastra as Mastra | undefined)?.tools?.[toolName] ?? tool;\n const validationErrorOutput =\n validationError && mappingTool.toModelOutput\n ? {\n providerMetadata: (await computeModelOutputProviderMetadata({\n tool: mappingTool,\n toolName,\n toolCallId,\n result,\n validationError,\n existingProviderMetadata: typedInput.providerMetadata as Record<string, unknown> | undefined,\n })) as typeof typedInput.providerMetadata,\n modelOutputComputed: true,\n }\n : undefined;\n if (pubsub) {\n try {\n const resultChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-result' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId,\n toolName,\n args,\n result,\n ...(validationErrorOutput ? { providerMetadata: validationErrorOutput.providerMetadata } : {}),\n providerExecuted,\n },\n },\n {\n policy: toolPayloadTransform,\n toolTransform: (tool as { transform?: any })?.transform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n await processChunkThroughOutputProcessors(\n resultChunk,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n processorObservabilityContext,\n collectProcessorDataPart,\n );\n } catch (emitError) {\n if (emitError instanceof DurableOutputProcessorError) {\n throw emitError;\n }\n logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);\n }\n }\n return {\n ...typedInput,\n result,\n ...(validationErrorOutput ?? {}),\n ...(processorDataParts.length ? { processorDataParts } : {}),\n };\n }\n }\n\n if (approvalGated && !approvalDecision) {\n // Persist active goal time before exposing the approval wait.\n await stopGoalActivity({ agentId: initData.agentId, runId });\n\n // Add approval metadata to message before persisting\n addToolMetadata({ type: 'approval', resumeSchema: approvalResumeSchema });\n\n // Flush messages before suspension\n await doFlush();\n\n // Emit approval chunk via PubSub (mirrors base agent's controller.enqueue).\n // Apply the tool payload transform first so display targets never see raw\n // args on the approval prompt (parity with the main loop's approval chunk).\n if (pubsub) {\n const approvalChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-call-approval' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId,\n toolName,\n args,\n resumeSchema: approvalResumeSchema,\n updatedAt: Date.now(),\n usage: typedInput.stepUsage,\n },\n },\n {\n policy: toolPayloadTransform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n await publishAfterPersist(() => emitChunkEvent(pubsub, runId, approvalChunk));\n }\n\n // Emit suspended event for the stream adapter\n if (pubsub) {\n await publishAfterPersist(() =>\n emitSuspendedEvent(pubsub, runId, {\n toolCallId,\n toolName,\n args,\n type: 'approval',\n resumeSchema: approvalResumeSchema,\n }),\n );\n }\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 // Delegated identity is trusted only after it is tied to framework-persisted\n // suspension state. The suspend payload remains the primary per-tool-call source.\n // Resolved before the decline short-circuit so a declined delegated approval\n // reaches the suspended sub-agent instead of being denied here (#26994).\n const isResumableTool = toolName?.startsWith('agent-') || toolName?.startsWith('workflow-');\n const needsRunIdLookup = isResumableTool && resumeData !== undefined;\n // Nullish model data follows the framework resume path; false, 0, and empty strings remain\n // valid model payloads. A workflow approval decision always wins over model-supplied data.\n const hasModelResumeData = resumeDataFromArgs != null && !(approvalGated && approvalDecision);\n const resolvedSuspensionIdentity: ResolvedSuspendedToolIdentity | undefined = needsRunIdLookup\n ? resolveFrameworkSuspendedToolIdentity({\n toolCallId,\n toolName,\n resumeSource: hasModelResumeData ? 'model' : 'framework',\n modelSuppliedSuspendedToolCallId: hasModelResumeData ? args?.suspendedToolCallId : undefined,\n modelSuppliedSuspendedToolRunId: hasModelResumeData ? args?.suspendedToolRunId : undefined,\n suspendData,\n messages: messageList?.get.all.db() ?? [],\n })\n : undefined;\n const suspendedToolRunId = resolvedSuspensionIdentity?.runId;\n // When the delegation tool is itself approval-gated, an approval decision is\n // ambiguous: it can answer this step's pre-execution gate or a delegated approval\n // raised mid-execution by the sub-agent. Only the delegated suspend payload carries\n // `requireToolApproval`, so require it plus a framework-resolved inner run id —\n // never a historical delegation found for a local gate.\n const isDelegatedApprovalResume =\n approvalGated &&\n !!approvalDecision &&\n !!(suspendData as { requireToolApproval?: unknown } | undefined)?.requireToolApproval &&\n resolvedSuspensionIdentity?.type === 'approval' &&\n !!suspendedToolRunId;\n\n // Check if resuming from approval. Without the `approvalGated` guard,\n // generic resume data that happens to contain an `approved` field (e.g. from\n // context.agent.suspend()) would be misinterpreted as an approval response.\n if (approvalGated && approvalDecision) {\n // Remove approval metadata since we're resuming (either approved or declined)\n await removeToolMetadata({ toolCallId, toolName }, 'approval');\n\n // A delegated decline is the sub-agent's decision to act on; only a decline of\n // this step's own gate is denied locally.\n if (!approvalDecision.approved && !isDelegatedApprovalResume) {\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 // Also emit a terminal `tool-output-denied` chunk so live stream subscribers\n // resolve the pending tool call (issue #20880) — persistence alone is not enough.\n const approval = {\n id: toolCallId,\n approved: false as const,\n reason: resolveDeclineReason(approvalDecision),\n };\n if (pubsub) {\n try {\n const deniedChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-output-denied' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, approval },\n },\n {\n policy: toolPayloadTransform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n // Processes through output processors and emits (or emits a tripwire when blocked).\n await processChunkThroughOutputProcessors(\n deniedChunk as ChunkType,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n processorObservabilityContext,\n collectProcessorDataPart,\n );\n } catch (emitError) {\n if (emitError instanceof DurableOutputProcessorError) {\n throw emitError;\n }\n logger?.warn?.(`[DurableAgent] Failed to emit tool-output-denied chunk for ${toolName}: ${emitError}`);\n }\n }\n return {\n ...typedInput,\n approval,\n ...(processorDataParts.length ? { processorDataParts } : {}),\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 approvalGated && approvalDecision?.approved === true\n ? ({ approval: { id: toolCallId, approved: true as const } } as const)\n : undefined;\n\n // Check if resuming from in-execution suspension. Once the approval gate has\n // resolved, all later resume data belongs to the tool's own suspension schema.\n const isResumingFromSuspension = resumeData !== undefined && !approvalGated;\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 const isAgentTool = toolName?.startsWith('agent-');\n if ('_background' in cleanedArgs) {\n delete (cleanedArgs as any)._background;\n }\n\n // Parity with the regular loop (tool-call-step.ts): stamp the caller's\n // thread/resource identity onto agent-tool args so the sub-agent wrapper\n // derives `${resourceId}-${agentName}` instead of falling back to the\n // parent agent's id (issue #23903). Always overwrite — LLM-hallucinated\n // ids must not leak into sub-agents. In the durable world the scope\n // context doesn't exist; serialized workflow state is its equivalent.\n if (toolName?.startsWith('agent-') && 'prompt' in cleanedArgs) {\n cleanedArgs.threadId = state?.threadId;\n cleanedArgs.resourceId = state?.resourceId;\n }\n\n delete cleanedArgs.suspendedToolRunId;\n delete cleanedArgs.suspendedToolCallId;\n\n // Mirror the non-durable step: a bare `{ approved }` belongs to the gate and is\n // dropped, but an approval carrying extra keys is caller data for the tool.\n const hasCustomApprovalResumeData =\n approvalGated &&\n typeof resumeData === 'object' &&\n resumeData !== null &&\n 'approved' in resumeData &&\n Object.keys(resumeData).length > 1;\n if ((isResumingFromSuspension || isDelegatedApprovalResume) && suspendedToolRunId) {\n cleanedArgs.suspendedToolRunId = suspendedToolRunId;\n }\n\n if (isResumingFromSuspension) {\n // Auto-resume re-calls a plain tool under a new toolCallId and names the original via\n // `suspendedToolCallId`; resolve it so the original entry is cleared (mirrors tool-call-step.ts).\n const plainResumeIdentity =\n !isResumableTool && hasModelResumeData\n ? resolveFrameworkSuspendedToolIdentity({\n toolCallId,\n toolName,\n resumeSource: 'model',\n modelSuppliedSuspendedToolCallId: args?.suspendedToolCallId,\n modelSuppliedSuspendedToolRunId: args?.suspendedToolRunId,\n suspendData,\n messages: messageList?.get.all.db() ?? [],\n })\n : undefined;\n const cleanupTarget = isResumableTool\n ? resolvedSuspensionIdentity\n : (plainResumeIdentity ?? { toolCallId, toolName });\n if (cleanupTarget) {\n await removeToolMetadata(cleanupTarget, resolvedSuspensionIdentity?.type ?? 'suspension');\n }\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 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 // A tool step can run on a worker whose LLM step ran elsewhere, so it subscribes to abort\n // requests too. Otherwise a deadline or abort() published while the tool runs never reaches it.\n // Only a real entry: a cold worker without one keeps no registry state. Called on every tool\n // step rather than keyed on the signal: a step whose subscribe failed earlier retries it, and a\n // warm worker re-arms the deadline this segment carries. The listener reuses the entry's\n // controller; a signal with no controller behind it would be replaced, so leave it alone.\n if (\n pubsub &&\n registryEntry &&\n !registryEntry.isPlaceholder &&\n (!registryEntry.abortSignal || registryEntry.abortController)\n ) {\n try {\n await ensureRemoteAbortListener(pubsub, runId, mastra as Mastra | undefined, readRunDeadline(requestContext));\n registryEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined) ?? registryEntry;\n } catch (error) {\n logger?.warn?.('Failed to subscribe to cross-process abort requests', {\n runId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\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 = ownership?.composeSignal(registryEntry?.abortSignal) ?? registryEntry?.abortSignal;\n\n // A queued step must not start tool side effects after its run has stopped.\n if (toolAbortSignal?.aborted) {\n return {\n ...typedInput,\n result: TOOL_ABORT_NOTICE,\n aborted: true,\n ...runStopOf(toolAbortSignal, registryEntry?.abortSignal),\n };\n }\n\n // Provide outputWriter so context.writer.write() / context.writer.custom()\n // emit chunks through pubsub (matching the regular agent's tool streaming).\n // Non-transient data-* chunks are also collected for persistence, as the\n // regular agent does for tool-written data parts (#25122).\n const outputWriter = pubsub\n ? async (chunk: any) => {\n const dataPart = chunk?.type === 'tool-output' ? chunk.payload?.output : chunk;\n if (typeof dataPart?.type === 'string' && dataPart.type.startsWith('data-') && !dataPart.transient) {\n collectProcessorDataPart({\n type: dataPart.type,\n data: dataPart.data,\n id: dataPart.id,\n messageId: dataPart.messageId,\n });\n }\n await emitChunkEvent(pubsub, runId, chunk as ChunkType);\n }\n : undefined;\n\n let delegationMessages = registryEntry?.runScope?.get(STEP_MODEL_MESSAGES_KEY);\n if (isAgentTool && !delegationMessages && contextMessageList) {\n // Cold workers must exclude synthetic context by ID before model conversion drops IDs.\n const delegationList = createRunMessageList({ mastra });\n delegationList.add(\n contextMessageList.get.all.db().filter(message => message.id !== 'om-continuation'),\n 'input',\n );\n delegationMessages = delegationList.get.all.aiV5.prompt();\n }\n\n const toolOptionsWithoutWriter = {\n toolCallId,\n messages: isAgentTool ? (delegationMessages ?? []) : (contextMessageList?.get.input.aiV5.model() ?? []),\n getMessages: messageList ? () => messageList.get.all.db() : undefined,\n workspace,\n requestContext,\n mcp: registryEntry?.mcp,\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 // Delegated approval decisions (approve or decline) must also flow to the wrapper\n // tool: it only resumes the inner suspended run when resumeData is present.\n resumeData: isDelegatedApprovalResume\n ? workflowResumeData\n : isResumingFromSuspension || hasCustomApprovalResumeData\n ? resumeData\n : undefined,\n suspendedToolRunId,\n // The payload this tool call suspended with (see `toolCallSuspended` below), so a\n // resumed tool can continue from its own state — mirrors the non-durable step.\n ...(isResumingFromSuspension &&\n suspendData != null &&\n typeof suspendData === 'object' &&\n 'toolCallSuspended' in suspendData\n ? { suspendPayload: (suspendData as { toolCallSuspended?: unknown }).toolCallSuspended }\n : {}),\n ...(toolAbortSignal ? { abortSignal: toolAbortSignal } : {}),\n outputWriter,\n // In-execution suspend callback — allows tools to suspend mid-execution\n suspend: (suspendPayload: any, suspendOptions?: SuspendOptions) =>\n suspendToolCall(suspendPayload, suspendOptions, assertOwned),\n };\n // `beforePersist` guards the suspension's memory writes. A background\n // task can suspend after the run settled and released its claim, so with\n // ownership in storage it passes the post-settlement check instead of the\n // strict one (#30182).\n const suspendToolCall = async (\n suspendPayload: any,\n suspendOptions: SuspendOptions | undefined,\n beforePersist: typeof assertOwned,\n ) => {\n wasSuspended = true;\n // When a delegated sub-agent requests approval, the delegation tool\n // wrapper passes its inner suspended run id via `suspendOptions.runId`\n // (see the agent-tool wrapper's `suspend(..., { runId, isAgentSuspend })`).\n // Persist it with the approval so the resume leg targets that inner\n // run instead of restarting the sub-agent from scratch.\n const delegatedRunId =\n typeof suspendOptions?.runId === 'string' && suspendOptions.runId !== runId\n ? suspendOptions.runId\n : undefined;\n // Set by the agent-tool wrapper when a delegated sub-agent paused: the sub-agent's own\n // tool call. Carried alongside the delegation call, which stays the resume key. Ignored\n // unless the wrapper raised the pause, so a plain tool's suspend options can't set it.\n const fromDelegate = suspendOptions?.isAgentSuspend === true;\n const delegatedToolCallId =\n fromDelegate && typeof suspendOptions?.delegatedToolCallId === 'string'\n ? suspendOptions.delegatedToolCallId\n : undefined;\n const delegatedToolName =\n fromDelegate && typeof suspendOptions?.delegatedToolName === 'string'\n ? suspendOptions.delegatedToolName\n : undefined;\n if (suspendOptions?.requireToolApproval) {\n const innerApproval =\n typeof suspendOptions.requireToolApproval === 'object' && suspendOptions.requireToolApproval\n ? suspendOptions.requireToolApproval\n : typeof suspendPayload?.requireToolApproval === 'object' && suspendPayload?.requireToolApproval\n ? suspendPayload.requireToolApproval\n : null;\n\n const approvalToolName = innerApproval?.toolName ?? toolName;\n const approvalArgs = innerApproval?.args !== undefined ? innerApproval.args : args;\n\n // Tool is requesting approval during execution\n await stopGoalActivity({ agentId: initData.agentId, runId });\n\n // Add approval metadata to message before persisting\n addToolMetadata({\n type: 'approval',\n resumeSchema: approvalResumeSchema,\n delegatedRunId,\n delegatedToolCallId,\n delegatedToolName,\n ...(innerApproval ? { approvalToolName, approvalArgs } : {}),\n });\n\n await doFlush(undefined, beforePersist);\n\n if (pubsub) {\n const approvalChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-call-approval' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId,\n toolName: approvalToolName,\n args: approvalArgs,\n ...(delegatedToolCallId ? { delegatedToolCallId } : {}),\n ...(delegatedToolName ? { delegatedToolName } : {}),\n resumeSchema: approvalResumeSchema,\n updatedAt: Date.now(),\n usage: typedInput.stepUsage,\n },\n },\n {\n policy: toolPayloadTransform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n await publishAfterPersist(() => emitChunkEvent(pubsub, runId, approvalChunk));\n }\n\n if (pubsub) {\n await publishAfterPersist(() =>\n emitSuspendedEvent(pubsub, runId, {\n toolCallId,\n toolName: approvalToolName,\n args: approvalArgs,\n type: 'approval',\n resumeSchema: approvalResumeSchema,\n }),\n );\n }\n\n endSpansAsSuspended({ toolCallId, toolName: approvalToolName, reason: 'approval' });\n\n return suspend(\n {\n type: 'approval',\n requireToolApproval: { toolCallId, toolName: approvalToolName, args: approvalArgs },\n // Persist the inner suspended run id in the workflow snapshot,\n // partitioned per tool call (resumeLabel = toolCallId), so the\n // resume leg can recover it even if message metadata is stale.\n ...(delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}),\n },\n { resumeLabel: toolCallId },\n );\n }\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 // Add suspension metadata to message before persisting\n addToolMetadata({\n type: 'suspension',\n suspendPayload,\n resumeSchema: suspendOptions?.resumeSchema,\n delegatedRunId,\n delegatedToolCallId,\n delegatedToolName,\n });\n\n await doFlush(undefined, beforePersist);\n\n if (pubsub) {\n const suspensionChunk = await applyToolPayloadTransformToChunk(\n {\n type: 'tool-call-suspended' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId,\n toolName,\n ...(delegatedToolCallId ? { delegatedToolCallId } : {}),\n ...(delegatedToolName ? { delegatedToolName } : {}),\n suspendPayload,\n args,\n resumeSchema: suspendOptions?.resumeSchema,\n usage: typedInput.stepUsage,\n },\n },\n {\n policy: toolPayloadTransform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n await publishAfterPersist(() => emitChunkEvent(pubsub, runId, suspensionChunk));\n await publishAfterPersist(() => emitSuspendedEvent(pubsub, runId, suspendedEventData));\n }\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 // Persist the inner suspended run id in the workflow snapshot,\n // partitioned per tool call (resumeLabel = toolCallId), so the\n // resume leg continues the delegate's suspended run instead of\n // restarting it (#20496; mirrors the approval branch above).\n ...(delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}),\n },\n { resumeLabel: toolCallId },\n );\n };\n // Raw `Tool` instances resolved from the Mastra registry (the cross-process\n // fallback path) are not wrapped by CoreToolBuilder, so they only get a\n // `writer` from here — mirrors the non-durable tool-call-step. Registry tools\n // go through CoreToolBuilder, which builds its own ToolStream, so this one is\n // created only if the tool actually reads it.\n const toolOptions = defineLazyWriter(\n toolOptionsWithoutWriter,\n () => new ToolStream({ prefix: 'tool', callId: toolCallId, name: toolName, runId }, outputWriter),\n );\n\n // Live-attempt barrier only. Durable recovery must use persisted task and\n // transcript state because this Promise does not survive workflow replay.\n // `validationError` is read from the result in `onResult`, in the process that ran the\n // task, so an awaited call can map its result after the stored copy dropped the marker.\n let resolveReconciliation!: (outcome: { error?: unknown; validationError?: ModelFacingValidationError }) => void;\n const reconciliationComplete = new Promise<{ error?: unknown; validationError?: ModelFacingValidationError }>(\n resolve => {\n resolveReconciliation = resolve;\n },\n );\n // Marked here so a later step needn't resolve the tool to know it ran a workflow (#30219).\n const backgroundResultMetadata = (taskId: string, status: 'running' | 'completed' | 'failed') =>\n withAgentWorkflowToolMarker(\n {\n ...typedInput.providerMetadata,\n mastra: {\n ...(typeof typedInput.providerMetadata?.mastra === 'object' ? typedInput.providerMetadata.mastra : {}),\n backgroundTask: { taskId, status },\n },\n },\n tool,\n );\n // Background task dispatch via the shared dispatch ladder with the\n // durable policy: steps replay under at-least-once redelivery, so an\n // already-running task is restarted to reattach hooks and\n // ladder failures degrade to sync execution to preserve forward\n // progress across transport/store boundaries.\n const bgOutcome = await dispatchBackgroundTool({\n existingRunningTask: 'restart',\n dispatchFailure: 'fallback-to-sync',\n backgroundTaskManager: bgManager,\n agentBackgroundConfig: bgConfig,\n managerConfig: bgManager?.config,\n toolBackgroundConfig: toolBgConfig,\n llmBgOverrides,\n args: cleanedArgs,\n toolName,\n toolCallId,\n agentId: initData.agentId,\n threadId: state?.threadId,\n resourceId: state?.resourceId,\n runId,\n // Only a resume of a previously-suspended call may reattach to a\n // suspended background task; a fresh call must dispatch its own.\n resumeData: isResumingFromSuspension ? resumeData : undefined,\n logger: logger as any,\n adoptPersistedTask: true,\n emitTaskStarted: async task => {\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 taskContext: info => ({\n executor: {\n execute: async (taskArgs: any, taskContext: any) => {\n const taskId = info.getTaskId()!;\n const execution = await executeAdoptedBackgroundOperation({\n taskId,\n disposition: info.disposition === 'awaited' ? 'awaited' : 'deferred',\n abortSignal: taskContext?.abortSignal ?? toolAbortSignal,\n execute: background =>\n tool.execute!(taskArgs, {\n ...toolOptions,\n isBackgroundTask: true,\n abortSignal: taskContext?.abortSignal ?? toolAbortSignal,\n background,\n [BACKGROUND_WORK_CONTEXT]: {\n originRunId: runId,\n originToolCallId: toolCallId,\n taskId,\n invocationKind: isAgentTool ? 'agent' : 'tool',\n disposition: info.disposition === 'awaited' ? 'awaited' : 'deferred',\n },\n ...(taskContext?.resumeData !== undefined\n ? { resumeData: taskContext.resumeData, suspendPayload: taskContext.suspendPayload }\n : {}),\n // Framework-resolved delegated run id recovered from persisted\n // suspension state (#23739) — never the model-authored one.\n suspendedToolRunId: taskContext?.suspendedToolRunId,\n suspend: async (data?: unknown, options?: SuspendOptions) => {\n // The run may have settled and stopped fencing its writes. The suspension's\n // memory save carries the run's claim, so storage rejects it once a successor\n // raised the memory fence, even when it lands after the ownership check (#30182).\n await runFencedToClaim(claimFenceArgs, () =>\n suspendToolCall(data, options, assertSuspensionNotSuperseded),\n );\n return taskContext?.suspend?.(data, options);\n },\n outputWriter: async (chunk: any) => {\n await taskContext?.onProgress?.(chunk);\n return toolOptions.outputWriter?.(chunk);\n },\n } as any),\n onCancelError: error => logger?.warn('Failed to cancel adopted background operation', error),\n });\n\n if (!execution.adopted) {\n return execution.result;\n }\n\n const outputValidation = validateToolOutput(\n resolveToolOutputValidationSchema(tool),\n execution.result,\n toolName,\n false,\n );\n return outputValidation.error ?? outputValidation.data;\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 != null)) {\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 title: getToolTitle(tool),\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 // Match the awaited step result below: a void result is reported as null.\n result:\n info.disposition === 'awaited' && chunk.payload.result === undefined\n ? null\n : chunk.payload.result,\n providerMetadata: backgroundResultMetadata(chunk.payload.taskId, 'completed'),\n providerExecuted,\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 providerMetadata: backgroundResultMetadata(chunk.payload.taskId, 'failed'),\n },\n });\n }\n } catch {\n // PubSub may be closed — ignore\n }\n },\n\n onResult: async (params: any) => {\n if (!messageList) {\n if (info.disposition === 'awaited') {\n const error = new Error('Cannot reconcile an awaited background task without a message list');\n resolveReconciliation({ error });\n throw error;\n }\n resolveReconciliation({});\n return;\n }\n\n try {\n // Resolve the mapping tool at completion time: the registry entry\n // may have been rebuilt (or expired) if the task finished after a\n // process restart.\n const liveEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const mappingTool = liveEntry?.tools?.[toolName] ?? tool;\n const baseProviderMetadata = withAgentWorkflowToolMarker(typedInput.providerMetadata, mappingTool);\n // Resolve the tool-level transform from the live registry at\n // completion, since the entry may have been rebuilt after dispatch.\n // Use the same resolved run/agent/Mastra policy as the other chunks.\n const transformForTranscript = async (result: unknown) => {\n const failed = params.status === 'failed';\n const transformCarrier = await applyToolPayloadTransformToChunk(\n {\n type: failed ? 'tool-error' : 'tool-result',\n payload: {\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n args: cleanedArgs,\n ...(failed ? { error: params.error } : { result: params.result }),\n },\n metadata: {} as Record<string, any>,\n },\n {\n policy: toolPayloadTransform,\n toolTransform: (mappingTool as { transform?: any })?.transform,\n tools: toolsForTransform,\n logger: logger as any,\n transformInput: {\n providerMetadata: typedInput.providerMetadata as Record<string, unknown> | undefined,\n },\n },\n );\n const transcriptArgsTransform = getTransformedToolPayload(\n transformCarrier.metadata,\n 'transcript',\n 'input-available',\n );\n const transcriptResultTransform = getTransformedToolPayload(\n transformCarrier.metadata,\n 'transcript',\n failed ? 'error' : 'output-available',\n );\n return {\n transcriptArgs: hasTransformedToolPayload(transcriptArgsTransform)\n ? transcriptArgsTransform.transformed\n : cleanedArgs,\n transcriptResult: hasTransformedToolPayload(transcriptResultTransform)\n ? transcriptResultTransform.transformed\n : result,\n providerMetadata: withToolPayloadTransformProviderMetadata(\n baseProviderMetadata as any,\n transformCarrier.metadata,\n ) as any,\n };\n };\n const toModelOutput = mappingTool.toModelOutput;\n // Later steps apply this result again (see below); they reuse these instead of calling the tool's hooks twice.\n let transcript: ReturnType<typeof transformForTranscript> | undefined;\n let modelOutput: Promise<unknown> | undefined;\n const applyTo = (list: MessageList, flush: () => Promise<void>) =>\n applyBackgroundToolResult({\n params,\n currentRunId: runId,\n hasResumeData: resumeData != null,\n args: cleanedArgs,\n messageList: list,\n approvalGrant: approvalGrant as Record<string, unknown> | undefined,\n baseProviderMetadata: baseProviderMetadata as any,\n transformForTranscript: result => (transcript ??= transformForTranscript(result)),\n toModelOutput:\n toModelOutput && (output => (modelOutput ??= Promise.resolve().then(() => toModelOutput(output)))),\n // Respect a custom idGenerator for the fallback appended message —\n // parity with main, which reads generateId from its run scope.\n generateId: mastra ? () => (mastra as Mastra).generateId() : undefined,\n logger: logger as any,\n flush,\n });\n await applyTo(messageList, async () => {\n const threadId = state?.threadId;\n if (saveQueueManager && threadId && !state?.memoryConfig?.readOnly) {\n // Like a late suspend, the result can land after the run settled: the write carries its claim.\n await runFencedToClaim(claimFenceArgs, () =>\n saveQueueManager.flushMessages(messageList, threadId, state.memoryConfig, {\n beforePersist: assertNotSuperseded,\n }),\n );\n }\n });\n if (info.disposition !== 'awaited' && liveEntry) {\n // Later steps rebuild the transcript from workflow state; they apply this result too.\n recordBackgroundResult(liveEntry, params.taskId, params.toolCallId, reconciliationComplete).apply =\n list => applyTo(list, async () => {});\n }\n resolveReconciliation({\n validationError:\n params.status === 'completed' ? getModelFacingValidationError(params.result) : undefined,\n });\n if (info.disposition !== 'awaited' && state?.threadId && state?.resourceId) {\n const owner = Object.values(mastra?.listAgents?.() ?? {}).find(agent => agent.id === initData.agentId);\n void owner?.__notifyBackgroundTaskFinished({\n threadId: state.threadId,\n resourceId: state.resourceId,\n taskId: params.taskId,\n toolCallId: params.toolCallId,\n toolName: params.toolName,\n status: params.status === 'failed' ? 'failed' : 'completed',\n requestContext:\n registryEntry?.requestContext ??\n restoreRequestContext(initData.requestContextEntries, requestContext),\n });\n }\n } catch (error) {\n resolveReconciliation({ error });\n throw error;\n }\n },\n\n onExecution: async (params: any) => {\n if (!messageList) return;\n\n await applyBackgroundToolExecution({\n params,\n args: cleanedArgs,\n messageList,\n transformChunk: chunk =>\n applyToolPayloadTransformToChunk(chunk, {\n policy: toolPayloadTransform,\n tools: toolsForTransform,\n logger: logger as any,\n }),\n });\n\n // Flush to storage so the metadata update (especially an open suspension)\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 // A superseded execution skips the write. The hook runs outside this\n // step (the background-task manager calls it), so the error is not\n // rethrown: that would fail the task instead of stopping the step.\n const threadId = state?.threadId;\n if (saveQueueManager && threadId && !state?.memoryConfig?.readOnly) {\n try {\n await runFencedToClaim(claimFenceArgs, () =>\n saveQueueManager.flushMessages(messageList, threadId, state.memoryConfig, {\n beforePersist: assertNotSuperseded,\n }),\n );\n } catch (error) {\n if (!isExecutionFenceError(error)) throw error;\n logger?.debug?.('[DurableAgent] Skipped background-task metadata flush: execution superseded', {\n runId,\n toolCallId: params.toolCallId,\n });\n }\n }\n },\n\n onComplete: toolBgConfig?.onComplete ?? bgConfig?.onTaskComplete,\n onFailed: toolBgConfig?.onFailed ?? bgConfig?.onTaskFailed,\n }),\n });\n\n if (bgOutcome.status !== 'sync') {\n if (bgOutcome.disposition === 'awaited') {\n let completedTask: Awaited<ReturnType<typeof bgOutcome.waitForCompletion>>;\n try {\n completedTask = await bgOutcome.waitForCompletion({ abortSignal: toolAbortSignal });\n } catch (error) {\n if (!toolAbortSignal?.aborted || error !== toolAbortSignal.reason) throw error;\n return {\n ...typedInput,\n args: cleanedArgs,\n result: TOOL_ABORT_NOTICE,\n aborted: true,\n ...runStopOf(toolAbortSignal, registryEntry?.abortSignal),\n };\n }\n // Cancellation deregisters the task context without calling onResult, so there is no reconciliation to await.\n let reconciledValidationError: ModelFacingValidationError | undefined;\n if (completedTask.status !== 'cancelled') {\n const reconciliation = await reconciliationComplete;\n if (reconciliation.error) {\n throw reconciliation.error;\n }\n reconciledValidationError = reconciliation.validationError;\n }\n\n if (completedTask.status !== 'completed') {\n throw new Error(\n completedTask.error?.message ??\n `Background task ${completedTask.status.replace('_', ' ')}: ${completedTask.id}`,\n );\n }\n\n return {\n ...typedInput,\n args: cleanedArgs,\n // Normalize a void result to null like executeToolCall does, so the loop continues.\n result: completedTask.result === undefined ? null : completedTask.result,\n providerMetadata: backgroundResultMetadata(bgOutcome.taskId, 'completed'),\n // Map a validation error here: llm-mapping only sees the stored copy, which lost the marker.\n ...(reconciledValidationError\n ? {\n providerMetadata: await computeModelOutputProviderMetadata({\n tool: getRunRegistryEntry(runId, mastra as Mastra | undefined)?.tools?.[toolName] ?? tool,\n toolName,\n toolCallId,\n result: completedTask.result,\n validationError: reconciledValidationError,\n existingProviderMetadata: backgroundResultMetadata(bgOutcome.taskId, 'completed'),\n }),\n modelOutputComputed: true,\n }\n : {}),\n ...(bgOutcome.status === 'started' ? (approvalGrant ?? {}) : {}),\n ...(processorDataParts.length ? { processorDataParts } : {}),\n };\n }\n\n // Lets the background check wait for this task's result to be applied once it finishes.\n const dispatchEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n if (dispatchEntry) recordBackgroundResult(dispatchEntry, bgOutcome.taskId, toolCallId, reconciliationComplete);\n\n if (bgOutcome.status === 'started') {\n // Return placeholder result so the LLM can continue\n return {\n ...typedInput,\n args: cleanedArgs,\n result: bgOutcome.placeholder,\n providerMetadata: backgroundResultMetadata(bgOutcome.taskId, 'running'),\n ...(approvalGrant ?? {}),\n };\n }\n return {\n ...typedInput,\n args: cleanedArgs,\n result: bgOutcome.placeholder,\n providerMetadata: backgroundResultMetadata(bgOutcome.taskId, 'running'),\n };\n }\n\n // Read-and-clear the delegation bail signal (`ctx.bail()` from an\n // onDelegationComplete hook). The sub-agent tool wrapper writes the\n // flag by-reference to the RequestContext instance captured when the\n // tool was BUILT — the registry's live instance in-process, or the\n // context restored by rebuildRunToolsFromMastra cross-process. On the\n // evented engine every step rehydrates its own RequestContext copy from\n // its event payload, so that write never reaches the llm-mapping step's\n // instance and bail used to cost one extra LLM turn (G3). Consuming the\n // flag here — same process and same instances as tool execution — and\n // carrying it on the serializable step output stops the loop in the\n // same iteration on every engine.\n const consumeDelegationBailSignal = ():\n | { delegationBailed: true; tracingDelegationFailure?: SpanTermination }\n | undefined => {\n let bailed = false;\n let failure: SpanTermination | undefined;\n for (const rc of [registryEntry?.requestContext, rebuiltRequestContext, requestContext]) {\n if (rc?.get('__mastra_delegationBailed')) {\n bailed = true;\n rc.set('__mastra_delegationBailed', false);\n failure = takeDelegationFailure(rc) ?? failure;\n }\n }\n if (!bailed) return undefined;\n // The run-registry copy keeps older @mastra/inngest finalizers working in-process.\n if (registryEntry) registryEntry.tracingDelegationFailure = failure;\n return { delegationBailed: true, ...(failure ? { tracingDelegationFailure: failure } : {}) };\n };\n let mappingFailure: { error: unknown } | undefined;\n\n // A run that loses its thread lease while this call runs lets it finish before it stops. The step stays\n // running until the tool body settles, even after the abort grace hands control back to the loop.\n const settleRunTool = startRunStep(registryEntry);\n let outcomeRecorded!: () => void;\n const outcomeRecordedPromise = new Promise<void>(resolve => (outcomeRecorded = resolve));\n // An outcome that settles in time is recorded for the deadline save only after mapping and the output\n // processors, below. The run step stays open until then, so a deadline in between waits for it.\n let recordedAtStepEnd = false;\n let stepEnded = false;\n try {\n try {\n ownership?.throwIfLost();\n } catch (error) {\n settleRunTool();\n throw error;\n }\n const outcome = await executeToolCall({\n tool: tool as any,\n args: cleanedArgs,\n toolOptions,\n toolCallId,\n toolName,\n abortSignal: toolAbortSignal,\n // Past a total deadline the outcome is still needed (recorded below); the step stops right after.\n assertNotBailedOut: () => {\n if (!registryEntry?.executionFence?.deadlineError) ownership?.throwIfLost();\n },\n // Run-activity tracking brackets live execution (durable-only bookkeeping).\n acquireExecution: () => markRunActive(runId),\n // Settles once the tool body has settled and its outcome below is recorded where needed, which the deadline save waits for.\n onToolSettled: () =>\n void outcomeRecordedPromise.then(() => {\n if (!recordedAtStepEnd || stepEnded) settleRunTool();\n }),\n logger: logger as any,\n })\n .then(async settled => {\n // The total deadline ended the run while this call ran, so the call's own commit is rejected\n // below. Leave the result where the deadline save looks for it, before the call reads as settled.\n // A call that failed in time is left there too: its step merges only once every sibling settles.\n if (\n registryEntry?.executionFence?.deadlineError ||\n (registryEntry?.timeoutTotalMs && settled.status === 'error')\n ) {\n // processToolResult hooks can redact or block a result, and they do not run past the deadline.\n // When one could apply, save only the abort notice so the raw value never reaches memory.\n const resultProcessed = registryEntry.outputProcessors?.some(processor =>\n isProcessorWorkflow(processor)\n ? processor.__processToolResult !== false\n : typeof processor.processToolResult === 'function',\n );\n let lateOutcome: ToolResultCommitOutcome =\n settled.status === 'error'\n ? {\n kind: 'error',\n errorText: settled.error instanceof Error ? settled.error.message : String(settled.error),\n }\n : {\n kind: 'result',\n result: settled.status === 'aborted' || resultProcessed ? TOOL_ABORT_NOTICE : settled.result,\n };\n // The transform metadata makes transcript transforms apply to the saved result on recall.\n // When it cannot be computed, save only the abort notice so the raw value never reaches memory.\n let lateTransformMetadata: DurableToolCallOutput['transformMetadata'];\n try {\n const chunk = await applyToolPayloadTransformToChunk(\n settled.status === 'error'\n ? {\n type: 'tool-error' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: { toolCallId, toolName, args, error: serializeError(settled.error) },\n }\n : {\n type: 'tool-result' as const,\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId,\n toolName,\n args,\n result: lateOutcome.result,\n providerMetadata: typedInput.providerMetadata,\n providerExecuted,\n },\n },\n {\n transformInput: { args, providerMetadata: typedInput.providerMetadata },\n policy: toolPayloadTransform,\n toolTransform: (tool as { transform?: any })?.transform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n lateTransformMetadata = (chunk as { metadata?: Record<string, any> })\n .metadata as DurableToolCallOutput['transformMetadata'];\n } catch (transformError) {\n logger?.warn?.(`[DurableAgent] Failed to transform the late result of ${toolName}: ${transformError}`);\n lateOutcome = { kind: 'result', result: TOOL_ABORT_NOTICE };\n }\n let lateProviderMetadata = withToolPayloadTransformProviderMetadata(\n typedInput.providerMetadata as Record<string, any> | undefined,\n lateTransformMetadata,\n );\n // Save what toModelOutput returns, so the next turn sends the model the mapped output, not the raw result.\n // When mapping fails, save only the abort notice.\n if (\n settled.status === 'success' &&\n lateOutcome.kind === 'result' &&\n lateOutcome.result !== TOOL_ABORT_NOTICE\n ) {\n try {\n lateProviderMetadata = await computeModelOutputProviderMetadata({\n tool: getRunRegistryEntry(runId, mastra as Mastra | undefined)?.tools?.[toolName] ?? tool,\n toolName,\n toolCallId,\n result: settled.rawResult,\n validationError: getModelFacingValidationError(settled.rawResult),\n existingProviderMetadata: lateProviderMetadata,\n parentSpan: stepSpan,\n });\n } catch (mappingError) {\n logger?.warn?.(`[DurableAgent] Failed to map the late result of ${toolName}: ${mappingError}`);\n lateOutcome = { kind: 'result', result: TOOL_ABORT_NOTICE };\n }\n }\n (registryEntry.settledToolResults ??= []).push({\n toolCallId,\n toolName,\n args: cleanedArgs,\n outcome: lateOutcome,\n ...(approvalGrant ?? {}),\n providerMetadata: lateProviderMetadata,\n });\n } else if (registryEntry?.timeoutTotalMs) {\n recordedAtStepEnd = true;\n }\n return settled;\n })\n .finally(outcomeRecorded);\n\n ownership?.throwIfLost();\n if (outcome.status === 'error') {\n // Route through the catch below so error serialization and the\n // tool-error chunk emission stay on the single existing path.\n throw outcome.error;\n }\n\n let result = outcome.status === 'aborted' ? TOOL_ABORT_NOTICE : outcome.result;\n\n // Compute model-facing output while invocation-scoped execution metadata is still available.\n // Durable step outputs are serialized before the LLM mapping step, which strips symbols and\n // other non-JSON side channels used by tools such as MCP structured-output tools. Map from\n // the raw pre-serialization result for the same reason.\n let providerMetadata = typedInput.providerMetadata;\n let modelOutputComputed: boolean | undefined;\n const mappingTool = getRunRegistryEntry(runId, mastra as Mastra | undefined)?.tools?.[toolName] ?? tool;\n const toModelOutput = mappingTool.toModelOutput;\n // Read in the process that ran the tool, before the result is serialized.\n const validationError =\n outcome.status === 'success' ? getModelFacingValidationError(outcome.rawResult) : undefined;\n if (toModelOutput && outcome.status === 'success' && validationError) {\n // Mastra's own validation errors skip the mapper, as on the main engine.\n modelOutputComputed = true;\n providerMetadata = (await computeModelOutputProviderMetadata({\n tool: mappingTool,\n toolName,\n toolCallId,\n result: outcome.rawResult,\n validationError,\n existingProviderMetadata: providerMetadata as Record<string, unknown> | undefined,\n parentSpan: stepSpan,\n })) as typeof providerMetadata;\n } else if (toModelOutput && outcome.status === 'success') {\n modelOutputComputed = true;\n const mappingSpan = stepSpan?.createChildSpan({\n type: SpanType.MAPPING,\n name: `tool output mapping: '${toolName}'`,\n entityType: EntityType.TOOL,\n entityId: toolName,\n entityName: toolName,\n input: outcome.rawResult,\n attributes: {\n mappingType: 'toModelOutput',\n toolCallId,\n },\n });\n try {\n const modelOutput = normalizeModelOutput(await toModelOutput(outcome.rawResult));\n mappingSpan?.end({ output: modelOutput });\n\n if (modelOutput != null) {\n const existingMastra = (providerMetadata as any)?.mastra;\n providerMetadata = {\n ...providerMetadata,\n mastra: { ...existingMastra, modelOutput },\n };\n }\n } catch (mappingError) {\n mappingSpan?.error({ error: mappingError as Error, endSpan: true });\n mappingFailure = { error: mappingError };\n throw mappingError;\n }\n }\n // Mark results of an agent's workflow tools here, like the mapping above:\n // llm-mapping may run where the run registry, and so the tool, is gone (#30219).\n if (outcome.status === 'success') {\n providerMetadata = withAgentWorkflowToolMarker(providerMetadata, mappingTool);\n }\n\n // Run processToolResult hooks before the tool-result chunk is emitted.\n // In this engine subscribers receive tool-result chunks HERE, at\n // tool-call time — running the hook later in llm-mapping would protect\n // only the transcript after the raw value had already reached the\n // stream. Processors mutate via messageList.updateToolInvocation, but\n // llm-mapping re-derives the transcript from the llm-execution snapshot\n // plus the serialized step outputs, so the processed value must travel\n // through the returned `result` field. Requires a live messageList,\n // so a cross-process resume skips this hook; the chunk pipeline below\n // still runs with the rebuilt output processors.\n if (!wasSuspended && registryEntry?.outputProcessors?.length && registryEntry.processorStates && messageList) {\n const resultProcessorRunner = new ProcessorRunner({\n inputProcessors: [],\n outputProcessors: registryEntry.outputProcessors,\n logger,\n agentName: initData.agentId,\n agent: registryEntry.agent,\n processorStates: registryEntry.processorStates,\n });\n const resultBeforeProcessors = result;\n const resultSnapshotBeforeProcessors =\n mappingTool?.toModelOutput && hasToolResultProcessor(registryEntry.outputProcessors)\n ? snapshotToolResult(resultBeforeProcessors)\n : undefined;\n let processorsSucceeded = false;\n try {\n await resultProcessorRunner.runProcessToolResult({\n // The accumulated StepResult[] is not reconstructable at\n // tool-call time in this engine (only serialized iteration state\n // exists), so hooks that inspect prior steps see an empty array.\n steps: [],\n stepNumber: 0,\n messages: messageList.get.all.db(),\n messageList,\n toolName,\n toolCallId,\n toolArgs: cleanedArgs,\n result,\n modelOutput: readModelOutput(providerMetadata),\n ...(processorObservabilityContext ?? {}),\n requestContext: registryEntry.requestContext,\n retryCount: 0,\n writer: pubsub\n ? {\n custom: async (\n data: { type: string; data?: unknown; transient?: boolean },\n writerOptions?: { messageId?: string },\n ) => {\n if (data.type.startsWith('data-') && !data.transient) {\n collectProcessorDataPart({\n type: data.type,\n data: data.data,\n messageId: writerOptions?.messageId,\n });\n }\n await emitChunkEvent(pubsub, runId, data as ChunkType);\n },\n }\n : undefined,\n abortSignal: toolAbortSignal,\n });\n ownership?.throwIfLost();\n // Sync any processor mutation back so the emitted chunk and the\n // serialized step output both carry the post-processor value.\n const postProcessorResult = readToolResultFromMessageList(messageList, toolCallId);\n if (postProcessorResult !== undefined && postProcessorResult !== result) {\n result = postProcessorResult;\n }\n processorsSucceeded = true;\n } catch (processorError) {\n ownership?.throwIfLost();\n if (processorError instanceof TripWire) {\n // Blocked: emit a tripwire chunk instead of the tool-result and\n // leave the call incomplete (no result). llm-mapping skips\n // `resultBlocked` entries the way it skips `aborted` ones, so\n // the invocation stays in 'call' state — mirroring the main\n // loop, where a tripwire skips both commit and emission.\n const tripwire = {\n reason: processorError.message || 'Tool result blocked by processor',\n retry: processorError.options?.retry,\n metadata: processorError.options?.metadata,\n processorId: processorError.processorId,\n };\n if (pubsub) {\n try {\n await emitChunkEvent(pubsub, runId, {\n type: 'tripwire',\n runId,\n from: ChunkFrom.AGENT,\n payload: tripwire,\n } as ChunkType);\n } catch (emitError) {\n logger?.warn?.(`[DurableAgent] Failed to emit tripwire chunk for ${toolName}: ${emitError}`);\n }\n }\n return {\n ...typedInput,\n resultBlocked: true,\n tripwire,\n ...(processorDataParts.length ? { processorDataParts } : {}),\n };\n }\n // A non-tripwire processor failure must not kill the run in this\n // engine (run and stream lifecycles are decoupled) — but it must\n // fail closed: continuing with the raw result would leak the\n // unprocessed value past a throwing redaction processor. The\n // regular loop rethrows here (runToolResultProcessors), so no\n // engine emits or persists the raw value; this engine substitutes\n // an error placeholder for both emission and persistence and\n // keeps the run alive.\n logger?.warn?.(`[DurableAgent] processToolResult failed for tool \"${toolName}\": ${processorError}`);\n result = { error: 'Tool result processing failed' };\n // The mapped output came from the unprocessed value; the model must not read it either.\n if (providerMetadata?.mastra && 'modelOutput' in providerMetadata.mastra) {\n const { modelOutput: _unprocessed, ...mastra } = providerMetadata.mastra;\n providerMetadata = { ...providerMetadata, mastra };\n }\n }\n\n // Carry a model output a processor rewrote (or a re-mapping of the result it\n // rewrote) into the emitted chunk and the serialized step output. Outside the\n // try so a failing `toModelOutput` fails the run, as it does before the hook.\n if (processorsSucceeded && outcome.status === 'success') {\n let resolvedProviderMetadata: typeof providerMetadata;\n try {\n resolvedProviderMetadata = (await resolveModelOutputAfterToolResultProcessors({\n messageList,\n tool: mappingTool,\n toolName,\n toolCallId,\n resultBeforeProcessors,\n resultSnapshotBeforeProcessors,\n providerMetadata,\n // Read from `outcome.rawResult` above, before the result was serialized.\n validationError,\n parentSpan: stepSpan,\n })) as typeof providerMetadata;\n } catch (mappingError) {\n mappingFailure = { error: mappingError };\n throw mappingError;\n }\n ownership?.throwIfLost();\n if (resolvedProviderMetadata !== providerMetadata) {\n providerMetadata = resolvedProviderMetadata;\n modelOutputComputed = true;\n }\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 let transformMetadata: DurableToolCallOutput['transformMetadata'];\n let resultEmitted = false;\n let resultHidden = false;\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, providerMetadata, providerExecuted },\n },\n {\n transformInput: { args, providerMetadata: typedInput.providerMetadata },\n policy: toolPayloadTransform,\n toolTransform: (tool as { transform?: any })?.transform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n // Capture the transform metadata for the step output (L18b) —\n // this step's messageList is a local copy, so llm-mapping layers\n // it into the persisted providerMetadata from the output record.\n transformMetadata = (resultChunk as { metadata?: Record<string, any> })\n .metadata as DurableToolCallOutput['transformMetadata'];\n // Runs through output processors (tripwire/blocking/redaction) and emits\n await processChunkThroughOutputProcessors(\n resultChunk,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n processorObservabilityContext,\n collectProcessorDataPart,\n chunk => {\n if (chunk.type === 'tool-result' && chunk.payload.toolCallId === toolCallId) resultEmitted = true;\n },\n );\n } catch (emitError) {\n ownership?.throwIfLost();\n if (emitError instanceof DurableOutputProcessorError) {\n throw emitError;\n }\n logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);\n }\n // A processor can drop the result or stash it and emit it right\n // after, and publishing can fail; only a published result counts.\n resultHidden = !resultEmitted;\n }\n\n // Its step merges only once every sibling settles; a total deadline before then saves it from here.\n // A result hidden from the stream is still saved, as the step's merge does.\n if (registryEntry?.timeoutTotalMs && !wasSuspended) {\n (registryEntry.settledToolResults ??= []).push({\n toolCallId,\n toolName,\n args: cleanedArgs,\n outcome: { kind: 'result', result },\n ...(approvalGrant ?? {}),\n providerMetadata: withToolPayloadTransformProviderMetadata(\n providerMetadata as Record<string, any> | undefined,\n transformMetadata,\n ),\n });\n }\n\n return {\n ...typedInput,\n providerMetadata,\n result,\n ...(outcome.status === 'aborted' ? { aborted: true } : {}),\n ...runStopOf(toolAbortSignal, registryEntry?.abortSignal),\n modelOutputComputed,\n ...(resultHidden ? { resultHidden: true } : {}),\n ...(approvalGrant ?? {}),\n ...(processorDataParts.length ? { processorDataParts } : {}),\n ...(transformMetadata ? { transformMetadata } : {}),\n ...consumeDelegationBailSignal(),\n };\n } catch (error) {\n // The deadline took the run while a call that returned in time was still being mapped or\n // processed: save it as cut off, never with its unprocessed result or as a failure. The run's\n // abort reason marks the deadline before `deadlineError` does: that is set only once the\n // replacement claim is in place, and the call can return while it is still being acquired.\n const deadlineReason = registryEntry?.abortSignal?.reason;\n if (\n registryEntry &&\n recordedAtStepEnd &&\n (registryEntry.executionFence?.deadlineError ||\n (isMastraTimeoutError(deadlineReason) && deadlineReason.timeoutType === 'total')) &&\n ownership?.isLost() &&\n !registryEntry.settledToolResults?.some(settled => settled.toolCallId === toolCallId)\n ) {\n (registryEntry.settledToolResults ??= []).push({\n toolCallId,\n toolName,\n args: cleanedArgs,\n outcome: { kind: 'result', result: TOOL_ABORT_NOTICE },\n });\n }\n ownership?.throwIfLost();\n if (mappingFailure?.error === error) {\n return {\n ...typedInput,\n mappingError: serializeError(error),\n ...runStopOf(toolAbortSignal, registryEntry?.abortSignal),\n };\n }\n // Output processor failures and authorization denials must fail the run\n // instead of being serialized as recoverable tool errors.\n if (\n error instanceof DurableOutputProcessorError ||\n (error instanceof Error && error.name === 'FGADeniedError')\n ) {\n throw error;\n }\n const toolError = serializeError(error);\n\n // Emit tool-error chunk (non-fatal — error result is returned regardless)\n let errorTransformMetadata: DurableToolCallOutput['transformMetadata'];\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: toolPayloadTransform,\n toolTransform: (tool as { transform?: any })?.transform,\n tools: toolsForTransform,\n logger: logger as any,\n },\n );\n // Capture the transform metadata for the step output (L18b) — see\n // the tool-result path above.\n errorTransformMetadata = (errorChunk as { metadata?: Record<string, any> })\n .metadata as DurableToolCallOutput['transformMetadata'];\n // Runs through output processors (tripwire/blocking/redaction) and emits\n await processChunkThroughOutputProcessors(\n errorChunk,\n registryEntry,\n pubsub,\n runId,\n initData.agentId,\n logger,\n messageList,\n processorObservabilityContext,\n collectProcessorDataPart,\n );\n } catch (emitError) {\n ownership?.throwIfLost();\n if (emitError instanceof DurableOutputProcessorError) {\n throw emitError;\n }\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 ...(processorDataParts.length ? { processorDataParts } : {}),\n ...(errorTransformMetadata ? { transformMetadata: errorTransformMetadata } : {}),\n ...runStopOf(toolAbortSignal, registryEntry?.abortSignal),\n // A hook may bail on a FAILED delegation too (success: false).\n ...consumeDelegationBailSignal(),\n };\n } finally {\n stepEnded = true;\n if (recordedAtStepEnd) settleRunTool();\n }\n },\n });\n}\n","import { compactDurableStepContent } from '@internal/core/durable';\nimport { z } from 'zod';\nimport { MastraFGAPermissions } from '../../../../auth/ee';\nimport { agentLoopTermination, executionFailureTermination } from '../../../../loop/shared/execution-outcome';\nimport {\n commitToolResult,\n computeModelOutputProviderMetadata,\n} from '../../../../loop/shared/steps/tool-result-commit-core';\nimport { TOOL_CALL_TERMINAL_FINISH_REASONS } from '../../../../loop/shared/terminal-finish-reasons';\nimport { getAbortReason, isMastraTimeoutError } from '../../../../loop/timeout';\nimport type { Mastra } from '../../../../mastra';\nimport type { SpanType, ExportedSpan, SpanTermination } from '../../../../observability';\nimport { getSpanErrorOrigin, setSpanErrorOrigin } from '../../../../observability/error-count';\nimport { extractUsageMetrics } from '../../../../observability/usage';\nimport { persistProcessorDataChunk } from '../../../../stream/base/output';\nimport { withToolPayloadTransformProviderMetadata } from '../../../../tools/payload-transform';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableStepIds } from '../../constants';\nimport { assertExecutionOwned, isExecutionFenceError } from '../../execution-fence';\nimport { authorizeDurableMemory, getDurableMemoryAuthorizationChecks } from '../../memory-fga';\nimport { getRunRegistryEntry } from '../../run-registry';\nimport type {\n DurableLLMStepOutput,\n DurableToolCallOutput,\n DurableAgenticExecutionOutput,\n DurableAgenticWorkflowInput,\n SerializableDurableState,\n} from '../../types';\nimport { rebuildRunToolsFromMastra } from '../../utils/resolve-runtime';\nimport { readMessageListState, storeMessageListState } from '../shared/message-list-state';\nimport { responseRecordSchema } from '../shared/schemas';\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 // Absent when the run keeps the transcript in workflow state.\n messageListState: z.any().optional(),\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 content: z.array(z.any()).optional(),\n }),\n state: z.any(),\n delegationBailed: z.boolean().optional(),\n tracingDelegationFailure: z.custom<SpanTermination>().optional(),\n tracingTermination: z.custom<SpanTermination>().optional(),\n deadlineTimeout: z.object({ timeoutType: z.literal('total'), timeoutMs: z.number() }).optional(),\n runAborted: z.boolean().optional(),\n processorRetryCount: z.number().optional(),\n processorRetryFeedback: z.string().optional(),\n releasedToolResultIds: z.array(z.string()).optional(),\n deferredStepFinishChunk: z.any().optional(),\n completionStartTime: z.coerce.date().optional(),\n timeToFirstTokenMs: z.number().optional(),\n response: responseRecordSchema.optional(),\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, getInitData } = 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 // Reuse the run's existing MessageList when the in-process registry has\n // one (same pattern as resolve-runtime and finalize-run) so external\n // consumers holding a reference to it — e.g. the stream adapter's\n // MastraModelOutput, which reads it for scoringData — keep seeing state\n // updates. A fresh instance here would orphan those references.\n const registryEntry = getRunRegistryEntry(_runId, mastra as Mastra | undefined);\n const terminalBackgroundParts = new Map<string, { restore: (list: MessageList) => void; taskId: string }>();\n const captureTerminalBackgroundParts = () => {\n for (const message of registryEntry?.messageList?.get.all.db() ?? []) {\n for (const part of message.content.parts) {\n if (part.type !== 'tool-invocation') continue;\n const backgroundTask = part.providerMetadata?.mastra?.backgroundTask;\n if (\n backgroundTask &&\n typeof backgroundTask === 'object' &&\n 'taskId' in backgroundTask &&\n (backgroundTask.status === 'completed' || backgroundTask.status === 'failed') &&\n toolResults.some(\n result =>\n result.toolCallId === part.toolInvocation.toolCallId &&\n (\n result.providerMetadata as\n | { mastra?: { backgroundTask?: { taskId?: string; status?: string } } }\n | undefined\n )?.mastra?.backgroundTask?.taskId === backgroundTask.taskId &&\n (result.providerMetadata as { mastra?: { backgroundTask?: { status?: string } } } | undefined)?.mastra\n ?.backgroundTask?.status === 'running',\n )\n ) {\n const toolCallId = part.toolInvocation.toolCallId;\n const backgroundTaskEntry = (\n message.content.metadata?.backgroundTasks as Record<string, unknown> | undefined\n )?.[toolCallId];\n terminalBackgroundParts.set(toolCallId, {\n restore: list => {\n list.updateToolInvocation(part, {\n mode: 'stream',\n ...(backgroundTaskEntry ? { backgroundTasks: { [toolCallId]: backgroundTaskEntry } } : {}),\n });\n },\n taskId: backgroundTask.taskId as string,\n });\n }\n }\n }\n };\n captureTerminalBackgroundParts();\n const snapshot = await readMessageListState(params, llmOutput);\n // Hydration may yield while a background task completes. Capture the live\n // terminal part again before deserializing the older workflow snapshot.\n captureTerminalBackgroundParts();\n const messageList = (\n registryEntry?.messageList ??\n new MessageList({\n threadId: state.threadId,\n resourceId: state.resourceId,\n })\n ).deserialize(snapshot);\n for (const { restore } of terminalBackgroundParts.values()) {\n restore(messageList);\n }\n\n if (llmOutput.stepResult.signalPreempted) {\n return {\n ...(await storeMessageListState(params, messageList.serialize())),\n messageId,\n stepResult: llmOutput.stepResult,\n toolResults: [],\n output: {\n text: '',\n toolCalls: [],\n usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n steps: [],\n },\n state,\n } satisfies DurableAgenticExecutionOutput;\n }\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 // A pending client-side / HITL call: no result, no error, not provider-executed and\n // not a resolved denial. The client answers it on a follow-up request, so it must\n // stay in `call` state, must not appear as a tool result anywhere, and must end the\n // turn — the durable counterpart of the non-durable llm-mapping-step's\n // `hasPendingHITL` (issue #23295).\n //\n // Aborted calls also lack a result/error but were cancelled, not awaiting input,\n // so they must not count as a HITL suspension (mirrors the non-durable predicate's\n // `!tc.aborted`). Tripwire-blocked calls (`resultBlocked`) are resolved by policy,\n // not awaiting a client answer; keep the existing continuation decision.\n const isPendingClientCall = (toolResult: (typeof toolResults)[number]) =>\n toolResult.result === undefined &&\n !toolResult.error &&\n !toolResult.aborted &&\n !toolResult.resultBlocked &&\n !toolResult.providerExecuted &&\n !isDeniedApproval(toolResult);\n\n // 2. Add tool results to message list\n // Look up tools from the in-process registry for toModelOutput support\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?.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 const runStopped = toolResults.some(result => result.deadlineTimeout || result.runAborted);\n for (const toolResult of toolResults) {\n const backgroundTask = (\n toolResult.providerMetadata as\n | { mastra?: { backgroundTask?: { taskId?: string; status?: string } } }\n | undefined\n )?.mastra?.backgroundTask;\n captureTerminalBackgroundParts();\n const terminalPart = terminalBackgroundParts.get(toolResult.toolCallId);\n if (backgroundTask?.status === 'running' && terminalPart && terminalPart.taskId === backgroundTask.taskId) {\n terminalPart.restore(messageList);\n continue;\n }\n if (toolResult.mappingError) {\n // Cancellation of this call or a sibling takes precedence over a mapping failure.\n if (runStopped) continue;\n const mappingError = new Error(toolResult.mappingError.message);\n mappingError.name = toolResult.mappingError.name;\n mappingError.stack = toolResult.mappingError.stack;\n const origin = getSpanErrorOrigin(toolResult.mappingError);\n if (origin) setSpanErrorOrigin(mappingError, origin);\n throw mappingError;\n }\n\n // Only executed calls carry a cancellation notice. An aborted call with\n // no result must not be recorded as a fabricated successful output.\n if (toolResult.aborted && toolResult.result === undefined) {\n continue;\n }\n\n // A processToolResult processor blocked this result via tripwire at\n // tool-call time: a tripwire chunk was emitted instead of the\n // tool-result, and no result crossed the boundary. Leave the\n // invocation incomplete, mirroring the main loop's tripwire handling\n // (commit and emission both skipped).\n if (toolResult.resultBlocked) {\n continue;\n }\n\n // Provider-executed results are already committed by llm-execution's\n // buildMessagesFromChunks when the result arrives in-stream; committing\n // here again would overwrite that entry with the serialized copy (and\n // clobber the providerMetadata captured from the live stream chunk).\n // A deferred provider result (no output yet) has nothing to commit.\n // Mirrors the non-durable llm-mapping-step's providerExecuted gate.\n if (toolResult.providerExecuted) {\n continue;\n }\n\n if (isDeniedApproval(toolResult)) {\n commitToolResult({\n messageList,\n outcome: {\n kind: 'denied',\n approval: {\n id: toolResult.approval!.id,\n approved: false,\n reason: toolResult.approval!.reason,\n },\n },\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolArgs: toolResult.args,\n });\n continue;\n }\n\n // Recording a pending call as a `result` would overwrite the invocation with an\n // undefined value and feed the model a fabricated tool output on the next turn.\n if (isPendingClientCall(toolResult)) {\n continue;\n }\n\n // Compute toModelOutput for successful tool results (Bug 9 parity).\n // Start from the existing providerMetadata so tools without a mapper\n // preserve their metadata. Results that already carry a mapped output\n // from tool-call.ts (`modelOutputComputed`) are not recomputed: the\n // serialization boundary is why tool-call maps eagerly, and this step\n // only covers results that crossed the boundary unmapped (background\n // completion, provider fallback).\n let providerMetadata: Record<string, unknown> | undefined = toolResult.providerMetadata as\n | Record<string, unknown>\n | undefined;\n if (\n !toolResult.error &&\n !toolResult.aborted &&\n toolResult.result != null &&\n !toolResult.providerExecuted &&\n !toolResult.modelOutputComputed\n ) {\n providerMetadata = await computeModelOutputProviderMetadata({\n tool: registryTools?.[toolResult.toolName] as\n | { toModelOutput?: (output: unknown) => unknown }\n | undefined,\n toolName: toolResult.toolName,\n toolCallId: toolResult.toolCallId,\n result: toolResult.result,\n existingProviderMetadata: toolResult.providerMetadata as Record<string, unknown> | undefined,\n parentSpan: stepSpan,\n });\n }\n\n // Layer the tool-payload-transform metadata captured at emission time\n // on top (L18b). The tool-call step's messageList is a local copy, so\n // the chunk-level metadata travels on the output record and is merged\n // into the persisted providerMetadata here — matching the main loop's\n // llm-mapping, which reads it off the live chunk. Without it,\n // transcript-target transforms would not apply to the persisted\n // args/result on recall.\n if (toolResult.transformMetadata) {\n providerMetadata = withToolPayloadTransformProviderMetadata(\n providerMetadata,\n toolResult.transformMetadata,\n ) as Record<string, unknown> | undefined;\n }\n\n // A mapper may have yielded while a background result settled.\n captureTerminalBackgroundParts();\n const settledPart = terminalBackgroundParts.get(toolResult.toolCallId);\n if (backgroundTask?.status === 'running' && settledPart && settledPart.taskId === backgroundTask.taskId) {\n settledPart.restore(messageList);\n continue;\n }\n\n // A tool error must be recorded as `output-error` with the message in\n // `errorText` so the transcript/adapters read it as a failure rather than\n // a normal result. Successful results keep `state: 'result'` + `result`.\n // The approval decision for an approved approval-gated tool is preserved\n // so it round-trips on recall as `approval: { approved: true }`.\n commitToolResult({\n messageList,\n outcome: toolResult.error\n ? { kind: 'error', errorText: toolResult.error.message }\n : { kind: 'result', result: toolResult.result },\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolArgs: toolResult.args,\n approval: toolResult.approval,\n providerMetadata: providerMetadata as any,\n fallbackAppend: true,\n });\n }\n }\n\n // 2a. Persist processor-emitted data-* chunks (#19375 parity port).\n // The tool-call step's messageList is a local copy whose mutations don't\n // cross the step boundary, so non-transient data-* chunks emitted by\n // output processors during tool execution travel on the output record\n // and are committed here, into the messageList that gets serialized and\n // flushed to memory. Runs for every entry — including aborted/blocked/\n // provider-executed calls skipped by the commit loop above — because in\n // the main loop persistence happens at emission time, before any\n // tripwire or abort can intervene.\n for (const toolResult of toolResults) {\n for (const part of toolResult.processorDataParts ?? []) {\n persistProcessorDataChunk(messageList, part.messageId ?? messageId, part);\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 //\n // Durable runs tools first (the tool-call foreach is unconditional), so\n // this override IS its tool-error recovery path: a step that finished\n // with `stop` (which durable otherwise treats as terminal) whose tool\n // result errored still continues. It does not trump `error`, `length`\n // or `content-filter`, matching the main loop: asking again repeats the\n // failure, truncation, or refusal (#29518). Both sides are pinned by\n // malformed-tool-args-terminal-finish.scenario.test.ts.\n const recoverFromToolErrors =\n toolResults.some(r => r.error !== undefined) &&\n !TOOL_CALL_TERMINAL_FINISH_REASONS.has(llmOutput.stepResult.reason);\n // A pending client call ends the turn so the client can answer it. Without this the\n // loop re-invoked the model on a result nobody produced.\n const hasPendingHITL = toolResults.some(isPendingClientCall);\n const tripwire = toolResults.find(r => r.tripwire)?.tripwire;\n const isContinued = hasPendingHITL ? false : recoverFromToolErrors ? true : llmOutput.stepResult.isContinued;\n\n // Check if any delegation hook called ctx.bail(). The primary channel\n // is the tool-call step's serializable output: the hook writes the flag\n // by-reference to the RequestContext the tool was built with, which the\n // tool-call step consumes in-process and carries as `delegationBailed`\n // on its output — the only channel that survives the evented engine's\n // per-step RequestContext rehydration (G3). The requestContext read is\n // kept as a fallback for same-process paths where the flag lands on\n // this step's own instance.\n let delegationBailed = toolResults.some(r => r?.delegationBailed === true);\n if (requestContext?.get('__mastra_delegationBailed')) {\n delegationBailed = true;\n requestContext.set('__mastra_delegationBailed', false);\n }\n // Keep the first failure, so a later bail with no failure can't hide it.\n const tracingDelegationFailure = toolResults.find(r => r?.tracingDelegationFailure)?.tracingDelegationFailure;\n\n // A tool the total deadline aborted, possibly on another worker, ends the run as the deadline.\n const deadlineTimeout = toolResults.find(r => r?.deadlineTimeout)?.deadlineTimeout;\n // abort() stopped a tool, possibly on a worker the next step never hears from.\n const runAborted = toolResults.some(r => r?.runAborted === true);\n\n // 4. Carry the deferred step-finish after tool-result chunks have been\n // emitted. The loop predicate adds step content and emits it after resolving\n // continuation policy, avoiding duplicate tool results in persisted snapshots.\n const deferredChunk = llmOutput.deferredStepFinishChunk as any;\n const deferredStepFinishChunk = deferredChunk\n ? {\n ...deferredChunk,\n payload: {\n ...deferredChunk.payload,\n stepResult: {\n ...deferredChunk.payload?.stepResult,\n isContinued,\n },\n },\n }\n : undefined;\n\n // 5. Build the output\n const serializedMessageList = messageList.serialize();\n // This step and its tool results are complete; a total deadline from here on saves up to this point.\n // A copy, since the serialized state shares parts with the live list the next step appends to.\n // JSON rather than structuredClone: message metadata can hold callbacks, which have no place in memory.\n // Only runs with a total deadline read it, so others skip the copy.\n if (registryEntry?.timeoutTotalMs) {\n registryEntry.completedStepsState = JSON.parse(JSON.stringify(serializedMessageList));\n registryEntry.settledToolResults = undefined;\n }\n const output: DurableAgenticExecutionOutput = {\n ...(await storeMessageListState(params, serializedMessageList)),\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: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n },\n steps: [], // Steps are accumulated at the loop level\n // Recorded on the step record; stopWhen reads it, and the deferred\n // step-finish chunk returns it as stream.steps content.\n content: compactDurableStepContent(\n messageList.get.response.aiV5.modelContent(\n -1,\n llmOutput.toolCalls.map(call => call.toolCallId),\n ),\n toolResults,\n ),\n },\n state: {\n ...state,\n threadExists: state.threadExists,\n },\n processorRetryCount: llmOutput.processorRetryCount,\n processorRetryFeedback: llmOutput.processorRetryFeedback,\n releasedToolResultIds: llmOutput.releasedToolResultIds,\n delegationBailed,\n tracingDelegationFailure,\n tracingTermination: llmOutput.tracingTermination,\n ...(deadlineTimeout ? { deadlineTimeout } : {}),\n ...(runAborted ? { runAborted } : {}),\n deferredStepFinishChunk,\n completionStartTime: llmOutput.completionStartTime,\n timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,\n response: llmOutput.response,\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 const signal = getRunRegistryEntry(_runId, mastra as Mastra | undefined)?.abortSignal ?? params.abortSignal;\n const abortReason = getAbortReason(signal);\n // A late run abort does not change completed tool work. Only calls\n // that actually observed cancellation interrupt this logical step.\n const interrupted = toolResults.some(result => result.aborted);\n const termination = interrupted\n ? isMastraTimeoutError(abortReason)\n ? executionFailureTermination(abortReason)\n : agentLoopTermination({ finishReason: 'abort' })\n : agentLoopTermination({\n stopCause: 'model_finished',\n finishReason: tripwire ? 'tripwire' : llmOutput.stepResult.reason,\n tripwire,\n });\n stepSpan.end({\n ...termination,\n ...(interrupted ? { outcome: 'interrupted' as const } : {}),\n output: {\n text: llmOutput.text,\n toolCalls: llmOutput.toolCalls,\n },\n attributes: {\n usage: extractUsageMetrics(pendingPayload?.output?.usage, pendingPayload?.metadata?.providerMetadata),\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?.getLogger?.()?.warn?.(`[DurableAgent] Failed to close model_step span: ${error}`);\n }\n }\n\n // savePerStep: persist this step before the loop continues, like the regular agent's\n // onStepFinish. The final step is saved by finalize-run. Observational memory saves on its\n // own, and a save here would corrupt its bookkeeping (same exclusion as finalize-run).\n if (\n isContinued &&\n state.savePerStep &&\n !state.observationalMemory &&\n !state.memoryConfig?.readOnly &&\n state.threadId &&\n state.resourceId\n ) {\n const authorizationEntry = getRunRegistryEntry(_runId, mastra as Mastra | undefined);\n const authorizationRequestContext = authorizationEntry?.requestContext ?? requestContext;\n const authorizeMemory = (permission: Parameters<typeof authorizeDurableMemory>[1]['permission']) =>\n authorizeDurableMemory(getDurableMemoryAuthorizationChecks(authorizationEntry), {\n mastra: mastra as Mastra | undefined,\n user: authorizationRequestContext?.get('user'),\n threadId: state.threadId!,\n resourceId: state.resourceId!,\n agentId: _agentId,\n requestContext: authorizationRequestContext,\n permission,\n actor: (getInitData?.() as DurableAgenticWorkflowInput | undefined)?.options?.actor,\n });\n await authorizeMemory(MastraFGAPermissions.MEMORY_WRITE);\n if (!state.threadExists) await authorizeMemory(MastraFGAPermissions.MEMORY_READ);\n try {\n // Re-read the entry: tool-call may have rebuilt the save queue into it. A connect()\n // worker in another process has none until something rebuilds it.\n let saveQueueManager = getRunRegistryEntry(_runId, mastra as Mastra | undefined)?.saveQueueManager;\n let memory = getRunRegistryEntry(_runId, mastra as Mastra | undefined)?.memory;\n if (!saveQueueManager && mastra) {\n const rebuilt = await rebuildRunToolsFromMastra({\n mastra: mastra as Mastra,\n runId: _runId,\n agentId: _agentId,\n state,\n requestContext,\n });\n saveQueueManager = rebuilt?.saveQueueManager;\n memory = rebuilt?.memory;\n }\n if (saveQueueManager) {\n if (!state.threadExists && memory) {\n const thread = await memory.getThreadById?.({ threadId: state.threadId });\n if (!thread) {\n await memory.createThread?.({\n threadId: state.threadId,\n resourceId: state.resourceId,\n memoryConfig: state.memoryConfig,\n });\n }\n output.state = { ...output.state, threadExists: true };\n }\n await saveQueueManager.flushMessages(messageList, state.threadId, state.memoryConfig, {\n beforePersist: () =>\n assertExecutionOwned({ runId: _runId, agentId: _agentId, requestContext, mastra: mastra as Mastra }),\n });\n }\n } catch (error) {\n if (isExecutionFenceError(error)) throw error;\n mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to save step: ${error}`);\n }\n }\n\n return output;\n },\n });\n}\n","import type { IMastraLogger } from '../../../logger';\nimport type { RequestContext } from '../../../request-context';\nimport type { AgentExecutionOptions } from '../../agent.types';\nimport type { SerializableDurableOptions } from '../types';\n\ntype PersistedCompletion = NonNullable<SerializableDurableOptions['isTaskComplete']>;\ntype CompletionPolicy = NonNullable<AgentExecutionOptions<any>['isTaskComplete']>;\n\n/**\n * Rebuild a run's `isTaskComplete` policy in a process that did not prepare it\n * (recovery after a restart, or a worker that runs the completion step).\n * Scorers and `onComplete` cannot be serialized, so only a policy taken from\n * the agent defaults can be restored, and only when the defaults still resolve\n * to the same scorers. Anything else logs a warning and returns undefined.\n */\nexport async function restoreCompletionPolicy({\n agent,\n persisted,\n requestContext,\n runId,\n logger,\n}: {\n agent: { getDefaultOptions(options?: { requestContext?: RequestContext }): unknown } | undefined;\n persisted: PersistedCompletion | undefined;\n requestContext: RequestContext;\n runId: string;\n logger?: IMastraLogger;\n}): Promise<CompletionPolicy | undefined> {\n if (!persisted) return undefined;\n\n let configured: CompletionPolicy | undefined;\n if (persisted.fromAgentDefaults && agent) {\n try {\n const defaults = (await agent.getDefaultOptions({ requestContext })) as AgentExecutionOptions<any> | undefined;\n configured = defaults?.isTaskComplete;\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Failed to resolve agent defaults for run ${runId}: ${error}`);\n }\n }\n\n const scorerIds = configured?.scorers?.map(scorer => scorer.id);\n if (\n !configured?.scorers ||\n !persisted.scorerIds ||\n JSON.stringify(scorerIds) !== JSON.stringify(persisted.scorerIds)\n ) {\n logger?.warn?.(`[DurableAgent] Cannot restore isTaskComplete for run ${runId}; completion checks will not run`);\n return undefined;\n }\n\n return {\n scorers: configured.scorers,\n onComplete: configured.onComplete,\n strategy: persisted.strategy,\n timeout: persisted.timeout,\n parallel: persisted.parallel,\n suppressFeedback: persisted.suppressFeedback,\n };\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { evaluateTaskCompletion } from '../../../../loop/shared/steps/is-task-complete-core';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { MessageList } from '../../../message-list';\nimport { DurableAgentDefaults, DurableStepIds } from '../../constants';\nimport { getRunRegistryEntry, globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\nimport type { SerializableDurableOptions } from '../../types';\nimport { restoreCustomContext, restoreRequestContext } from '../../utils/resolve-runtime';\nimport { restoreCompletionPolicy } from '../../utils/restore-completion';\nimport { loadAccumulatedSteps } from '../shared/accumulated-steps';\nimport { readMessageListState, storeMessageListState } from '../shared/message-list-state';\n\n/**\n * Create the durable isTaskComplete step. Behavior lives in the shared\n * `evaluateTaskCompletion` core; this glue owns registry/init-data access,\n * message-list rehydration/serialization, and projection back onto the\n * IterationState.\n *\n * The scorer instances + `onComplete` closure come from the in-process run\n * registry. They can't survive the wire, so a process that did not prepare\n * the run rebuilds a policy taken from the agent defaults, and warns and falls\n * back to `maxSteps` + `stopWhen` for one it cannot rebuild.\n */\nexport function createDurableIsTaskCompleteStep(defaultMaxSteps: number = DurableAgentDefaults.MAX_STEPS) {\n // The step is a pass-through over the IterationState — we update\n // `lastStepResult.isContinued` and `messageListState` when a verdict\n // requires it. We use `z.any()` instead of the iteration schema to avoid\n // 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 messageId?: string;\n iterationCount: number;\n /** Present only on runs that thread the transcript through step payloads. */\n messageListState?: any;\n /** Present only on runs that thread step records through step payloads. */\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; signalPreempted?: boolean };\n options?: { maxSteps?: number };\n backgroundTaskPending?: boolean;\n };\n if (state.lastStepResult?.signalPreempted) return state;\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 options?: Pick<SerializableDurableOptions, 'isTaskComplete'>;\n };\n\n const registryEntry = getRunRegistryEntry(state.runId, mastra);\n let policy = registryEntry?.isTaskComplete;\n // Preparation and recovery always set the key. Without it this process\n // never saw the run's policy, so rebuild it from the persisted shadow.\n if (initData.options?.isTaskComplete && !(registryEntry && 'isTaskComplete' in registryEntry)) {\n let agent: Parameters<typeof restoreCompletionPolicy>[0]['agent'];\n try {\n agent = initData.agentId ? mastra?.getAgentById(initData.agentId) : undefined;\n } catch {\n // Reported below as a policy that cannot be restored.\n }\n const restored = await restoreCompletionPolicy({\n agent,\n persisted: initData.options.isTaskComplete,\n requestContext: restoreRequestContext(initData.requestContextEntries, registryEntry?.requestContext),\n runId: state.runId,\n logger: mastra?.getLogger?.(),\n });\n if (registryEntry) registryEntry.isTaskComplete = restored;\n policy = restored;\n }\n // No scorers → nothing to grade.\n if (!policy?.scorers?.length) return state;\n\n // Build the message list lazily — only when the core actually grades\n // this iteration does it read the transcript / append feedback.\n const messageListState = await readMessageListState(params, state);\n let messageList: MessageList | undefined;\n const list = () => {\n if (!messageList) {\n messageList = new MessageList();\n messageList.deserialize(messageListState);\n }\n return messageList;\n };\n\n const lastStep = (await loadAccumulatedSteps(params, state)).at(-1);\n const outcome = await evaluateTaskCompletion({\n policy,\n // Durable steps replay under at-least-once redelivery: a\n // throwing scorer/callback would fail the step and be re-invoked\n // against the same state forever, so failures are logged and grading\n // is skipped. Chunk emission is post-verdict publish —\n // best-effort by the same argument.\n errorPolicy: 'best-effort',\n // Durable shipped the errored-iteration grading skip (#21897)\n // pre-extraction — keep it here.\n engineMode: 'durable',\n iteration: state.iterationCount,\n maxIterations: state.options?.maxSteps ?? defaultMaxSteps,\n llmSignaledDone: state.lastStepResult?.isContinued === false,\n stepReason: state.lastStepResult?.reason,\n backgroundTaskPending: state.backgroundTaskPending,\n toolCalls: lastStep?.toolCalls ?? [],\n toolResults: lastStep?.toolResults ?? [],\n currentText: lastStep?.text || '',\n messageList: list,\n runId: state.runId,\n agentId: initData.agentId,\n agentName: initData.agentName,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n customContext: restoreCustomContext(\n initData.requestContextEntries,\n registryEntry?.requestContext ?? params.requestContext,\n ),\n generateId: () => mastra?.generateId?.(),\n emitChunk: chunk => {\n if (!pubsub) return;\n return emitChunkEvent(pubsub, state.runId, chunk as any);\n },\n logger: mastra?.getLogger?.(),\n });\n\n if (!outcome.evaluated) {\n return state;\n }\n\n // Flip isContinued based on the verdict so the outer dowhile predicate\n // continues (not complete) or stops (complete), and persist the\n // (possibly feedback-extended) transcript back into serialized state.\n const nextState: typeof state = { ...state };\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: !outcome.complete,\n };\n }\n // The retry turn needs its own response message (the non-durable loop\n // switches to a fresh id too). Reusing the graded turn's id folds the\n // retry into that earlier message, ahead of the feedback.\n if (!outcome.complete && nextState.messageId) {\n nextState.messageId = list().rotateResponseMessageId(nextState.messageId);\n }\n Object.assign(nextState, await storeMessageListState(params, list().serialize()));\n return nextState;\n },\n });\n}\n","import { z } from 'zod';\nimport type { PubSub } from '../../../../events/pubsub';\nimport { evaluateGoal } from '../../../../loop/shared/steps/goal-core';\nimport type { ChunkType } from '../../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../../workflows/constants';\nimport { createStep } from '../../../../workflows/workflow';\nimport { getRunRegistryEntry, globalRunRegistry } from '../../run-registry';\nimport { emitChunkEvent } from '../../stream-adapter';\nimport { restoreCustomContext, restoreRequestContext } from '../../utils/resolve-runtime';\nimport { createRunMessageList } from '../../utils/run-message-list';\nimport { loadAccumulatedSteps } from '../shared/accumulated-steps';\nimport { readMessageListState, storeMessageListState } from '../shared/message-list-state';\n\n/**\n * Create the durable goal step.\n *\n * Behavior lives in the shared `evaluateGoal` core; this glue owns\n * registry/init-data access, request-context reconstruction, message-list\n * rehydration/serialization, and projection back onto the IterationState.\n *\n * The `goal` config (judge, scorer, tools closures) comes from the in-process\n * run registry — closures can't survive the wire, so cross-process engines\n * without this slot fall back to the agent's own config or skip goal\n * evaluation. The objective and its progress are isolated by thread and\n * loaded from storage inside the core.\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 /** Present only on runs that thread the transcript through step payloads. */\n messageListState?: any;\n messageId: string;\n /** Present only on runs that thread step records through step payloads. */\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; signalPreempted?: boolean };\n options?: { maxSteps?: number };\n backgroundTaskPending?: boolean;\n };\n if (state.lastStepResult?.signalPreempted) return state;\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 = getRunRegistryEntry(state.runId, mastra);\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 in the core.\n let goalConfig = registryEntry?.goal;\n if (!goalConfig && initData.agentId) {\n goalConfig = (mastra as any)?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();\n }\n\n // Rebuild requestContext from serialized entries for resolvers. The signed-in\n // user comes from the live run context, never from the run's starting request.\n const liveRequestContext = registryEntry?.requestContext ?? params.requestContext;\n const requestContext = restoreRequestContext(initData.requestContextEntries, liveRequestContext);\n const customContext = restoreCustomContext(initData.requestContextEntries, liveRequestContext);\n\n // No goal configured on the agent → nothing to judge.\n if (!goalConfig) return state;\n\n // Build the message list lazily — only when the core actually judges\n // this iteration does it read the transcript / append the feedback\n // signal. Memoized so the scorer context and signal injection share one\n // instance, which is then serialized back into state.\n const messageListState = await readMessageListState(params, state);\n let messageList: ReturnType<ReturnType<typeof createRunMessageList>['deserialize']> | undefined;\n const list = () => {\n if (!messageList) {\n messageList = createRunMessageList({ mastra }).deserialize(messageListState);\n }\n return messageList;\n };\n\n const lastStep = (await loadAccumulatedSteps(params, state)).at(-1);\n const outcome = await evaluateGoal({\n goal: goalConfig,\n stepReason: state.lastStepResult?.reason,\n backgroundTaskPending: state.backgroundTaskPending,\n isContinued: state.lastStepResult?.isContinued,\n toolCalls: lastStep?.toolCalls ?? [],\n toolResults: lastStep?.toolResults ?? [],\n currentText: lastStep?.text || '',\n runId: state.runId,\n agentId: initData.agentId,\n agentName: initData.agentName,\n threadId: initData.state?.threadId,\n resourceId: initData.state?.resourceId,\n customContext,\n mastra,\n requestContext,\n messageList: list,\n messageId: state.messageId,\n rotateMessageId: current => list().rotateResponseMessageId(current),\n writeSignal: pubsub\n ? async data => {\n await emitChunkEvent(pubsub, state.runId, data as ChunkType);\n }\n : undefined,\n emitChunk: chunk => {\n if (!pubsub) return;\n return emitChunkEvent(pubsub, state.runId, chunk as any);\n },\n });\n\n if (!outcome.evaluated) {\n return state;\n }\n\n const nextState: typeof state = { ...state };\n if (nextState.lastStepResult) {\n nextState.lastStepResult = {\n ...nextState.lastStepResult,\n isContinued: outcome.shouldContinue,\n };\n }\n if (outcome.kind === 'judged') {\n // The transcript gained the feedback signal (and the response message\n // id may have rotated) — persist both back into serialized state.\n nextState.messageId = outcome.messageId;\n Object.assign(nextState, await storeMessageListState(params, list().serialize()));\n }\n return nextState;\n },\n });\n}\n","import { z } from 'zod';\nimport { ErrorCategory, ErrorDomain, getErrorFromUnknown, MastraError } from '../../../error';\nimport type { PubSub } from '../../../events/pubsub';\nimport type { LoopContinuationPredicate } from '../../../loop/loop-builder';\nimport { AgenticLoopBuilder } from '../../../loop/loop-builder';\nimport type { LoopIterationState, LoopRuntime } from '../../../loop/loop-runtime';\nimport { decideContinuation } from '../../../loop/shared/continuation-core';\nimport { agentLoopTermination } from '../../../loop/shared/execution-outcome';\nimport { drainSignalsToTranscript } from '../../../loop/shared/steps/signal-drain-core';\nimport { getAbortReason, isMastraTimeoutError } from '../../../loop/timeout';\nimport { pruneAgentLoopSnapshot } from '../../../loop/workflows/prune-snapshot';\nimport type { StepResultReads } from '../../../loop/workflows/prune-snapshot';\nimport type { Mastra } from '../../../mastra';\nimport { InternalSpans } from '../../../observability';\nimport type { AIModelGenerationSpan, ExportedSpan, SpanType } from '../../../observability';\nimport { calculateObservedUsage, isUsageIncomplete } from '../../../observability/usage';\nimport { currentRunGeneration } from '../../../storage/run-fencing';\nimport { ChunkFrom } from '../../../stream/types';\nimport { PUBSUB_SYMBOL } from '../../../workflows/constants';\nimport { createEventedWorkflow, createWorkflow } from '../../../workflows/create';\nimport { markNonRedeliverable } from '../../../workflows/evented/helpers';\nimport { markFrameworkCondition } from '../../../workflows/framework-condition';\nimport type { ShouldPersistSnapshotFn } from '../../../workflows/types';\nimport { createStep } from '../../../workflows/workflow';\nimport { normalizeToolOutput } from '../../message-list/utils/unwrap-legacy-tool-output';\nimport { diffResponseMessages } from '../../streams/response-messages';\nimport type { ResponseMessagesCursor } from '../../streams/response-messages';\nimport { AGENT_STREAM_TOPIC, DURABLE_STOP_WHEN_ERROR_ID, DurableStepIds, DurableAgentDefaults } from '../constants';\nimport {\n getExecutionClaim,\n isExecutionFenceError,\n isForeignExecutionContext,\n watchExecutionLoss,\n withExecutionFence,\n} from '../execution-fence';\nimport { withExecutionStreamProducer } from '../execution-stream-publisher';\nimport { getRunRegistryEntry, globalRunRegistry, takeRunScorerInstances } from '../run-registry';\nimport { emitChunkEvent, emitFinishEvent, emitIterationCompleteEvent } from '../stream-adapter';\nimport type {\n DurableToolCallInput,\n DurableAgenticWorkflowInput,\n DurableAgenticExecutionOutput,\n DurableLLMStepOutput,\n DurableToolCallOutput,\n} from '../types';\nimport { createRunMessageList } from '../utils/run-message-list';\nimport { runDurableFinishSideEffects } from './finalize-run';\nimport {\n modelConfigSchema,\n modelListEntrySchema,\n durableAgenticOutputSchema,\n baseIterationStateSchema,\n durableOptionsSchema,\n createBaseIterationStateUpdate,\n resolveDurableToolCallConcurrency,\n executeDurableAgentScorers,\n dehydrateSnapshotTranscripts,\n hydrateMessageListState,\n loadRunStoredMessages,\n openMessageListState,\n readMessageListState,\n releaseMessageListState,\n dehydrateMessageListState,\n storeMessageListState,\n buildDeferredStepFinishChunk,\n durableStopConditionSteps,\n loadAccumulatedSteps,\n storeAccumulatedSteps,\n expandDurableSteps,\n carriedSpanClocks,\n} from './shared';\nimport {\n createDurableBackgroundTaskCheckStep,\n createDurableGoalStep,\n createDurableIsTaskCompleteStep,\n createDurableLLMExecutionStep,\n createDurableToolCallStep,\n createDurableLLMMappingStep,\n} from './steps';\n\nconst COLLECT_TOOL_RESULTS_STEP_ID = 'collect-tool-results';\n\n/**\n * The outer step that publishes FINISH. Recovery reads its saved status to tell\n * whether FINISH already went out before a crash.\n */\n\n/**\n * Copies step params with some fields overridden, keeping accessors intact.\n * A spread would invoke the lazy `writer` getter (see `defineLazyWriter`) and\n * allocate a ToolStream the step never uses.\n */\nfunction withParams<T extends object, O extends object>(params: T, overrides: O): Omit<T, keyof O> & O {\n const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(params);\n for (const [key, value] of Object.entries(overrides)) {\n descriptors[key] = { value, enumerable: true, configurable: true, writable: true };\n }\n return Object.defineProperties({}, descriptors) as Omit<T, keyof O> & O;\n}\n\nexport const MAP_FINAL_OUTPUT_STEP_ID = 'map-final-output';\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 * Which workflow execution engine runs the loop. `'evented'` builds both\n * the outer loop and the inner single-iteration workflow on the evented\n * execution engine (pubsub + WorkflowEventProcessor); `'default'` (the\n * default) uses the in-process default engine.\n */\n engine?: 'default' | 'evented';\n /**\n * Snapshot-persistence policy applied to both the outer agentic-loop\n * workflow and the inner single-iteration workflow. When omitted, the\n * factory keeps the historical policy of persisting\n * `pending | paused | suspended | running`.\n *\n * `DurableAgent.createWorkflow()` always injects a policy here — user\n * provided, or a recovery-aware default that persists `running` only when\n * `recovery.durableAgents: 'auto'` is configured.\n */\n shouldPersistSnapshot?: ShouldPersistSnapshotFn;\n /**\n * Sets `autoStorageVersion` on the outer loop workflow, so new runs are\n * stored as version 2 where the engine and store support it. The\n * iteration workflow's runs are nested, so they follow the outer run.\n */\n autoStorageVersion?: boolean;\n}\n\n/**\n * Historical default persistence policy for durable agent workflows.\n *\n * A persisted snapshot record supports both:\n * - `resumeStream()` after a suspend (records with status\n * `pending` / `paused` / `suspended`)\n * - boot-time recovery of orphaned RUNNING runs after a process restart,\n * via `DurableAgent.recoverActiveRuns()` — this requires the row to\n * actually be stamped `running` while the loop is 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 run (see\n * `persistStepUpdate` in workflows/handlers/entry.ts), so it is safe to\n * return true for `running` here.\n */\nexport const defaultShouldPersistSnapshot: ShouldPersistSnapshotFn = params => {\n return (\n params.workflowStatus === 'pending' ||\n params.workflowStatus === 'paused' ||\n params.workflowStatus === 'suspended' ||\n params.workflowStatus === 'running'\n );\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 // Exact stored version id the run resolved to at start time; resume()/recover()\n // read it from the persisted workflow input to pin the run to that version\n // (#22128). Absent for purely code-defined agents.\n agentVersionId: 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 // Serializable scorers configuration, resolved from Mastra by name at runtime\n scorers: z.record(z.string(), z.any()).optional(),\n options: durableOptionsSchema,\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 // Starting step index for continuation across iterations\n stepIndex: z.number().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 inputTripwire: baseIterationStateSchema.shape.inputTripwire,\n});\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\n/**\n * Compile-time contract check: the durable between-iterations state must stay\n * assignable to the engine-agnostic {@link LoopIterationState} shape that\n * shared continuation logic operates on (both loops converge on it).\n */\ntype SatisfiesLoopIterationState<T extends LoopIterationState> = T;\n\ntype IterationState = SatisfiesLoopIterationState<z.infer<typeof iterationStateSchema>>;\n\n/**\n * Durable resolution of the shared {@link LoopRuntime} contract. Live handles\n * (abort signal, `stopWhen`/`onIterationComplete` closures, the pre-bound\n * signal drain) come from the in-process run registry — closures can't cross\n * the wire — and the transport comes from the engine's predicate params.\n */\ninterface DurableLoopRuntime extends LoopRuntime {\n /** Always resolved on the durable loop: run options ?? builder default. */\n maxSteps: number;\n /** Present when the run streams through a pubsub transport. */\n pubsub?: PubSub;\n}\n\n/**\n * Whether a reader that attaches mid-run can read the run's earlier events. Steps publish on the\n * engine's bus, but `observe()` reads through the agent's own stream bus, which has no replay\n * when the agent was created with `cache: false`; both have to keep the topic.\n */\nfunction runTopicReplays(rt: DurableLoopRuntime): boolean {\n const topic = AGENT_STREAM_TOPIC(rt.runId);\n if (!rt.pubsub?.__replaysTopic(topic)) return false;\n // Not `getAgentById`, which reports a missing agent as an error; this runs on every step.\n const agent = Object.values(rt.mastra?.listAgents() ?? {}).find(registered => registered.id === rt.agentId);\n // An agent not registered here leaves the engine's bus to go by.\n const agentBus = (agent as { pubsub?: Partial<PubSub> } | undefined)?.pubsub;\n return agentBus?.__replaysTopic?.(topic) ?? true;\n}\n\n/**\n * Builds the durable agent loop on the shared `AgenticLoopBuilder` topology.\n *\n * The durable loop implements the same agentic loop pattern as the main loop\n * (LLM execution → tool-call foreach → mapping → background check → signal\n * drain → isTaskComplete → goal, wrapped in a dowhile) but flows all state\n * through workflow input/output so it is durable across process restarts and\n * execution engine replays.\n *\n * Migration status: every method is still a whole-method\n * override delegating to the durable step files. As the shared cores land,\n * these overrides shrink until only the runtime hooks remain (state\n * resolution via registry + serialized `messageListState`, pubsub chunk\n * transport, the evented `workflowFactory`, and snapshot policies).\n */\nexport class DurableAgenticLoopBuilder extends AgenticLoopBuilder {\n readonly #options?: DurableAgenticWorkflowOptions;\n readonly #maxSteps: number;\n readonly #shouldPersistSnapshot: ShouldPersistSnapshotFn;\n\n constructor(options?: DurableAgenticWorkflowOptions) {\n // No main-loop params: the durable loop resolves its runtime from the run\n // registry and serialized iteration state. Any base method that reads\n // `this.params` on this path throws (see AgenticLoopBuilder).\n super();\n this.#options = options;\n this.#maxSteps = options?.maxSteps ?? DurableAgentDefaults.MAX_STEPS;\n this.#shouldPersistSnapshot = options?.shouldPersistSnapshot ?? defaultShouldPersistSnapshot;\n }\n\n /**\n * Engine selection: EventedAgent opts into the evented execution engine;\n * DurableAgent stays on the default in-process engine.\n */\n protected override workflowFactory(): typeof createWorkflow {\n return this.#options?.engine === 'evented' ? createEventedWorkflow : createWorkflow;\n }\n\n /**\n * Engine-aware snapshot pruning. The `running`-only history strip (#20747)\n * keeps what a crash-restart reads back, including `stepResultReads`: steps\n * that read an earlier step's result via `getStepResultAsync` (reader → sources).\n * The evented engine also reads persisted step results during normal\n * execution, but the only such reads are the declared ones below, so the\n * strip keeps exactly what it reads. Retaining *all* terminal history instead\n * (the old blanket `retainRunningHistory`) copied every completed step's\n * payload/output and ballooned snapshots into a heap OOM on long runs\n * (COR-1431). What remains then stores messages memory already holds as refs\n * (see `dehydrateSnapshotTranscripts`).\n */\n protected pruneSnapshotHook(stepResultReads: StepResultReads = {}): typeof pruneAgentLoopSnapshot {\n return args => dehydrateSnapshotTranscripts(pruneAgentLoopSnapshot({ ...args, stepResultReads }));\n }\n\n // ── Runtime hooks ──────────────────────────────────────────────────────\n\n /**\n * Resolve the runtime from serialized iteration state + the run registry\n * (see {@link DurableLoopRuntime}). Cross-process engines (e.g. Inngest\n * after a worker restart) won't have a registry entry; every\n * registry-derived field is then undefined and the loop falls back to\n * maxSteps-only continuation.\n *\n * Callable from both the continuation predicate (inputData = iteration\n * state) and steps inside the iteration workflow (inputData = an\n * intermediate execution shape without run identity); the latter falls\n * back to init data, which inside the iteration workflow is the iteration\n * state itself.\n */\n protected override resolveRuntime(predicateParams: any): DurableLoopRuntime {\n const state = (predicateParams.inputData ?? {}) as Partial<IterationState>;\n const initData = predicateParams.getInitData() as DurableAgenticWorkflowInput;\n const mastra = predicateParams.mastra as Mastra | undefined;\n const runId = state.runId ?? initData.runId;\n const registryEntry = getRunRegistryEntry(runId, mastra as Mastra | undefined);\n const agentId = state.agentId ?? initData.agentId;\n const pubsub = predicateParams[PUBSUB_SYMBOL] as PubSub | undefined;\n return {\n runId,\n agentId,\n agentName: state.agentName ?? initData.agentName,\n threadId: initData?.state?.threadId,\n resourceId: initData?.state?.resourceId,\n maxSteps: state.options?.maxSteps ?? initData.options?.maxSteps ?? this.#maxSteps,\n mastra,\n logger: mastra?.getLogger?.(),\n abortSignal: registryEntry?.abortSignal,\n stopWhen: registryEntry?.stopWhen,\n onIterationComplete: registryEntry?.onIterationComplete,\n // runId is pre-bound at registry-entry creation; scope defaults to\n // 'pending' in the underlying stream runtime.\n drainPendingSignals: registryEntry?.drainPendingSignals,\n pubsub:\n pubsub &&\n withExecutionStreamProducer(pubsub, {\n runId,\n agentId,\n mastra,\n claim: getExecutionClaim(predicateParams.requestContext, runId),\n }),\n };\n }\n\n /**\n * TODO: always use pubsub, it's better\n * Chunk transport: publish through pubsub instead of enqueueing onto a live\n * stream controller. No-op when the run has no pubsub transport — callers\n * that must not consume input without a transport (signal drain) guard on\n * `pubsub` before draining.\n */\n protected override emitChunk(runtime: DurableLoopRuntime, chunk: unknown): void | Promise<void> {\n if (!runtime.pubsub) return;\n return emitChunkEvent(runtime.pubsub, runtime.runId, chunk as any);\n }\n\n // ── Step factories ─────────────────────────────────────────────────────\n // Tools and model are resolved from Mastra at runtime; the workflow is\n // created once at startup and reused for all runs.\n\n protected override llmExecutionStep() {\n return createDurableLLMExecutionStep();\n }\n\n /** Each tool call runs as its own step with suspend support. */\n protected override toolCallStep() {\n return createDurableToolCallStep();\n }\n\n protected override llmMappingStep() {\n return createDurableLLMMappingStep();\n }\n\n protected override backgroundTaskCheckStep() {\n return createDurableBackgroundTaskCheckStep();\n }\n\n /**\n * Mirrors the non-durable `signalDrainStep` which drains signals queued\n * during tool execution. Behavior lives in `drainSignalsToTranscript`\n * (shared with the main loop); this override owns the\n * serialization glue: the `MessageList` is materialized lazily from\n * serialized state only once signals actually arrive (drain-first\n * ordering), and re-serialized into the projected output. Signals are\n * appended to the transcript even without a pubsub transport (`emitChunk`\n * no-ops), matching prior behavior. Signals only queue in the process\n * running the agent, so other processes skip the step.\n */\n protected override signalDrainStep() {\n return createStep({\n id: `${DurableStepIds.AGENTIC_EXECUTION}-signal-drain`,\n inputSchema: z.any(),\n outputSchema: z.any(),\n execute: async stepParams => {\n const execOutput = stepParams.inputData as Record<string, any>;\n if (execOutput.stepResult?.signalPreempted && !execOutput.stepResult.isContinued) return execOutput;\n const rt = this.resolveRuntime(stepParams);\n if (!rt.drainPendingSignals) return execOutput;\n try {\n const messageListState = await readMessageListState(stepParams, execOutput);\n let drainList: ReturnType<typeof createRunMessageList> | undefined;\n const list = () => (drainList ??= createRunMessageList({ mastra: rt.mastra }).deserialize(messageListState));\n const outcome = await drainSignalsToTranscript({\n drainPendingSignals: rt.drainPendingSignals,\n rotateResponseMessageId: sealMessageId => list().rotateResponseMessageId(sealMessageId),\n addSignal: signal => list().addSignal(signal),\n emitChunk: chunk => this.emitChunk(rt, chunk),\n sealMessageId: execOutput.messageId,\n // Durable's shipped contract: drain is best-effort — redelivery\n // re-runs this site and signals stay queued on failure.\n errorPolicy: 'best-effort',\n logger: rt.logger,\n });\n if (!outcome.drained || !drainList) return execOutput;\n return {\n ...execOutput,\n ...(await storeMessageListState(stepParams, drainList.serialize())),\n messageId: outcome.nextMessageId,\n stepResult: {\n ...execOutput.stepResult,\n messageId: outcome.nextMessageId,\n // Aligned with the main loop's signal-drain step.\n reason: 'other',\n isContinued: true,\n },\n };\n } catch {\n // Best-effort: transcript mutations are local to this step's\n // drainList, so returning execOutput drops them cleanly.\n return execOutput;\n }\n },\n });\n }\n\n /**\n * 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 */\n protected override isTaskCompleteStep() {\n return createDurableIsTaskCompleteStep(this.#maxSteps);\n }\n\n /**\n * The goal evaluation step — mirrors the non-durable `createGoalStep`.\n * Runs after isTaskComplete so the goal judge sees whether isTaskComplete\n * already stopped the loop.\n */\n protected override goalStep() {\n return createDurableGoalStep();\n }\n\n // ── Composition ────────────────────────────────────────────────────────\n\n /**\n * 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 * This deliberately differs from the main loop, which resolves concurrency\n * once at loop build from the active tool set (#15978): the durable workflow\n * graph is built once and shared across runs, so anything per-run must be a\n * resolver evaluated at execution time.\n */\n override buildIterationWorkflow() {\n // Every step that calls a model, runs tools, or writes memory checks that\n // its execution still owns the run (#23734), so a superseded execution\n // stops at the next step boundary instead of overwriting the new owner.\n const llmExecutionStep = withExecutionFence(this.llmExecutionStep());\n const toolCallStep = withExecutionFence(this.toolCallStep());\n const llmMappingStep = withExecutionFence(this.llmMappingStep());\n const backgroundTaskCheckStep = withExecutionFence(this.backgroundTaskCheckStep());\n const signalDrainStep = withExecutionFence(this.signalDrainStep());\n const isTaskCompleteStep = withExecutionFence(this.isTaskCompleteStep());\n const goalStep = withExecutionFence(this.goalStep());\n const executeLLM = llmExecutionStep.execute;\n llmExecutionStep.execute = async stepParams => {\n // On abort this step stores both the transcript and the step records. On\n // storage v1 the default engine keeps only a step's last setState, so each\n // write carries the ones before it.\n let written: Record<string, unknown> = {};\n const params = withParams(stepParams, {\n setState: async (update: Record<string, unknown>) => {\n written = { ...written, ...update };\n await stepParams.setState(written);\n },\n });\n const llmOutput = await executeLLM(params);\n if (llmOutput && llmOutput.stepResult.reason === 'abort') {\n const initData = params.getInitData() as IterationState;\n // Preserve transcript, step records, usage and span bookkeeping, then\n // finish only this iteration. The outer loop still runs its normal\n // terminal side effects. `getState` includes this step's `setState`\n // changes, so each store builds on the state the previous one wrote.\n const executionOutput = await llmMappingStep.execute(\n withParams(params, {\n bail: params.bail<unknown>,\n inputData: {\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 );\n if (!executionOutput) return executionOutput;\n const { accumulatedSteps, ...update } = createBaseIterationStateUpdate({\n currentState: { ...initData, accumulatedSteps: await loadAccumulatedSteps(params, initData) },\n executionOutput,\n });\n return params.bail<IterationState>({\n ...update,\n ...(await storeAccumulatedSteps(params, accumulatedSteps)),\n modelList: initData.modelList,\n });\n }\n return llmOutput;\n };\n\n return (\n this.workflowFactory()({\n id: DurableStepIds.AGENTIC_EXECUTION,\n inputSchema: iterationStateSchema,\n outputSchema: iterationStateSchema,\n options: {\n // Injectable persistence policy (see DurableAgenticWorkflowOptions).\n // The default persists `pending | paused | suspended | running`;\n // `DurableAgent` injects a recovery-aware policy that persists\n // `running` only when crash recovery is enabled.\n shouldPersistSnapshot: this.#shouldPersistSnapshot,\n // When the effective policy excludes `running`, resume claims cannot\n // be written, so per-resume de-dup warnings would fire on every HITL\n // resume. The durable resume path serializes its own resumes, so\n // acknowledge unclaimed resumes. Harmless when `running` is persisted:\n // claims still land and de-dup still works.\n allowUnclaimedResumes: true,\n // A superseded execution must leave the stored run to its new owner\n // (the evented engine otherwise merges, marks failed, or deletes it).\n isOwnershipLostError: isExecutionFenceError,\n isForeignExecution: isForeignExecutionContext,\n watchExecutionLoss,\n // Agent-loop snapshots are pure resume artifacts — strip everything a\n // resume never reads. The declared reads below cover every\n // same-iteration step-result read (see pruneSnapshotHook).\n pruneSnapshot: this.pruneSnapshotHook({\n [toolCallStep.id]: [llmExecutionStep.id],\n [COLLECT_TOOL_RESULTS_STEP_ID]: [llmExecutionStep.id],\n }),\n validateInputs: false,\n // Deliberate divergence from the main loop (#21529): the workflow\n // engine's own step events repeatedly serialized cumulative\n // conversation state and paused the run between model steps.\n // Agent-stream lifecycle chunks are unaffected — llm-execution emits\n // step-start and llm-mapping emits the deferred step-finish straight\n // to pubsub. Main's in-process loop workflow pays no serialization\n // cost for engine step events, so it doesn't set this.\n emitStepEvents: false,\n // Default engine only: nested runs created by execute() reuse the\n // parent run's pubsub so inner events reach the outer subscriber.\n // On the evented engine this flag is a structural no-op — the engine\n // always publishes on the shared `mastra.pubsub`, and the agent's\n // CachingPubSub follows that bus (Phase 2 Item 5). Toggling it to\n // `false` changes nothing there.\n sharePubsub: true,\n // Generic boot-time restart must not re-drive agent loops — recovery\n // is owned by the dedicated opt-in path (`recovery.durableAgents:\n // 'auto'`) with leasing/fencing (issue #22598).\n autoRestartActiveRuns: false,\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 initialUntaggedSystemMessages: state.initialUntaggedSystemMessages,\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 requestContextEntries: state.requestContextEntries,\n inputTripwire: state.inputTripwire,\n stepIndex: state.iterationCount,\n signalPreempted: state.lastStepResult?.signalPreempted,\n // Processor hooks receive the running step list (#24293) — the\n // llm-execution step reads it for stepNumber/steps parity with\n // the main loop. Absent when the run keeps it in workflow state.\n accumulatedSteps: state.accumulatedSteps,\n agentSpanData: state.agentSpanData,\n modelSpanData: state.modelSpanData,\n completionStartTime: state.completionStartTime,\n timeToFirstTokenMs: state.timeToFirstTokenMs,\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 completionStartTime: llmOutput.completionStartTime,\n timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,\n // A suspended step never emits step-finish, so its usage rides on the suspension chunk.\n stepUsage: llmOutput.stepResult?.totalUsage,\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, getStepResultAsync, getInitData }) => {\n const toolResults = inputData as DurableToolCallOutput[];\n // Direct read of an earlier step: declared to pruneSnapshotHook above\n // so snapshot pruning keeps it for a crash-restart.\n const llmOutput = (await getStepResultAsync(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: llmOutput?.stepResult?.messageId ?? initData.messageId,\n state: llmOutput?.state ?? initData.state,\n };\n },\n { id: COLLECT_TOOL_RESULTS_STEP_ID },\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 params => {\n const executionOutput = params.inputData as DurableAgenticExecutionOutput;\n const initData = params.getInitData() as IterationState;\n\n // Use shared function for base state update\n const { accumulatedSteps, ...baseUpdate } = createBaseIterationStateUpdate({\n currentState: { ...initData, accumulatedSteps: await loadAccumulatedSteps(params, initData) },\n executionOutput,\n });\n\n // Extend with core-specific fields\n const newIterationState: IterationState = {\n ...baseUpdate,\n ...(await storeAccumulatedSteps(params, accumulatedSteps)),\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 }\n\n /**\n * The dowhile predicate: abort check, feedback two-phase stop, stopWhen\n * evaluation, delegation bail, inter-iteration signal drain, the\n * onIterationComplete hook, response-message boundary rotation, and the\n * iteration-complete observability event.\n */\n protected override buildContinuationPredicate(): LoopContinuationPredicate {\n return async (params: any) => {\n const state = params.inputData as IterationState;\n const steps = await loadAccumulatedSteps(params, state);\n const initData = params.getInitData() as DurableAgenticWorkflowInput;\n const rt = this.resolveRuntime(params);\n\n // Opened once per step; the abort exits below emit before it is opened.\n let transcript: Awaited<ReturnType<typeof openMessageListState>> | undefined;\n const emitStepFinish = async (isContinued: boolean) => {\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = isContinued;\n }\n\n const deferredChunk = buildDeferredStepFinishChunk({ ...state, accumulatedSteps: steps }, isContinued);\n state.deferredStepFinishChunk = undefined;\n if (!deferredChunk) return;\n\n // Carry the step's response messages so `onStepFinish(event).response.messages` and\n // `output.steps[i].response.messages` match the regular loop (#26780). Only the part that\n // changed since the previous step-finish is sent; readers rebuild the list. The cursor\n // travels with the iteration state, so a step on another worker continues it, and each\n // execution of the run (each claim: start, resume, recovery) starts over with the whole list.\n let nextCursor: ResponseMessagesCursor | undefined;\n try {\n const list = createRunMessageList({ mastra: rt.mastra }).deserialize(\n (transcript ?? (await openMessageListState(params, state))).read(),\n );\n const producer =\n getExecutionClaim(params.requestContext, state.runId)?.executionId ??\n `${state.runId}:${currentRunGeneration(state.runId) ?? 0}`;\n let cursor: ResponseMessagesCursor | { producer: string } =\n state.responseMessagesCursor?.producer === producer ? state.responseMessagesCursor : { producer };\n // A reader that attaches mid-run on a bus that keeps no history can only place whole lists.\n if ('fingerprints' in cursor && !runTopicReplays(rt)) {\n cursor = { ...cursor, fingerprints: [] };\n }\n const { diff, cursor: next } = diffResponseMessages(cursor, list.get.response.aiV5.model());\n deferredChunk.payload._durableResponseMessagesDiff = diff;\n nextCursor = next;\n } catch (error) {\n rt.logger?.warn?.(`[DurableAgent] Could not rebuild step-finish messages: ${error}`);\n }\n\n try {\n await this.emitChunk(rt, deferredChunk);\n if (nextCursor) state.responseMessagesCursor = nextCursor;\n } catch (error) {\n rt.logger?.warn?.(`[DurableAgent] Failed to emit deferred step-finish: ${error}`);\n // The event may have reached the log anyway: number the next one after it, and make it\n // the whole list so readers don't need to know which list this one gave.\n if (nextCursor) state.responseMessagesCursor = { ...nextCursor, fingerprints: [] };\n }\n };\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 (rt.abortSignal?.aborted) {\n // A run-level budget expiry (`modelSettings.timeout.totalMs`, #21724)\n // is a failure, not a cancellation. If the budget expired between\n // steps (e.g. inside a tool call), run one more llm-execution\n // iteration: its early abort guard routes total timeouts through the\n // fatal error path (error chunk + stepResult.reason 'error'), after\n // which this guard sees reason 'error' and stops the loop keeping\n // that reason intact.\n const abortReason = getAbortReason(rt.abortSignal);\n const isTotalTimeout = isMastraTimeoutError(abortReason) && abortReason.timeoutType === 'total';\n if (isTotalTimeout && state.lastStepResult?.reason !== 'error') {\n await emitStepFinish(true);\n return true;\n }\n // The parked step completed before the run-level abort was observed. Emit its own outcome\n // before recording the abort on loop state so consumers keep the completed step boundary.\n await emitStepFinish(state.lastStepResult?.isContinued === true);\n if (state.lastStepResult) {\n state.lastStepResult.reason = isTotalTimeout ? 'error' : 'abort';\n }\n return false;\n }\n\n // The transcript lives in workflow state, or on the iteration state for\n // runs that thread it through step payloads. Writes below land on\n // whichever object holds it; both persist into the next iteration.\n transcript = await openMessageListState(params, state);\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 // Runs before the continuation decision (matching the main loop) so\n // stopWhen still applies to a signal-forced turn.\n // Behavior shared with the main-loop predicate via\n // `drainSignalsToTranscript`; this site owns the pubsub guard (don't\n // consume signals without a transport to emit them on) and the\n // serialize/deserialize glue. Drain is best-effort: failures inside the\n // core resolve to `drained: false` and the next iteration runs with the\n // un-drained state.\n let drainForcedContinue = false;\n if (rt.pubsub && rt.drainPendingSignals) {\n try {\n let drainList: ReturnType<typeof createRunMessageList> | undefined;\n const list = () => (drainList ??= createRunMessageList({ mastra: rt.mastra }).deserialize(transcript.read()));\n const drainOutcome = await drainSignalsToTranscript({\n drainPendingSignals: rt.drainPendingSignals,\n rotateResponseMessageId: () => list().rotateResponseMessageId(),\n addSignal: signal => list().addSignal(signal),\n emitChunk: chunk => this.emitChunk(rt, chunk),\n // Durable's shipped contract: drain is best-effort — redelivery\n // re-runs this site and signals stay queued on failure.\n errorPolicy: 'best-effort',\n logger: rt.logger,\n });\n if (drainOutcome.drained && drainList) {\n state.messageId = drainOutcome.nextMessageId;\n transcript.write(drainList.serialize());\n\n // Force continuation — the LLM must see the injected signals\n if (state.lastStepResult) {\n state.lastStepResult.isContinued = true;\n }\n drainForcedContinue = true;\n }\n } catch {\n // serialize() is best-effort too; state keeps the pre-drain\n // messageListState if it throws.\n }\n }\n\n if (state.lastStepResult?.signalPreempted) return state.lastStepResult.isContinued === true;\n\n const runMaxSteps = rt.maxSteps;\n\n // Lazy message-list rehydration for the onIterationComplete hook: the\n // callback's messages snapshot and any injected feedback share one\n // instance, re-serialized into state when feedback lands. Only\n // deserialized when the hook actually runs.\n let callbackListInstance: ReturnType<typeof createRunMessageList> | undefined;\n const callbackList = () => {\n if (!callbackListInstance) {\n callbackListInstance = createRunMessageList({ mastra: rt.mastra });\n try {\n callbackListInstance.deserialize(transcript.read());\n } catch {\n // If deserialization fails, callback sees empty messages\n }\n }\n return callbackListInstance;\n };\n\n // Shared continuation decision: two-phase feedback stop, stopWhen (read\n // from the in-process registry — the predicate is a closure and can't\n // survive the wire; cross-process engines fall back to maxSteps only),\n // delegation bail, and the onIterationComplete ladder (see\n // `decideContinuation` for the per-engine policy). This engine (and\n // evented/inngest, which inherit through this builder) runs the\n // `durable` ladder — hard stops, gated stopWhen, and the two-phase\n // stop past stopWhen, all grounded in persisted step records under\n // at-least-once redelivery. `runMaxSteps` is always finite here, so\n // the default ladder's hasFiniteMaxSteps question never arises.\n const stopWhen = rt.stopWhen\n ? (Array.isArray(rt.stopWhen) ? rt.stopWhen : [rt.stopWhen]).map(condition => async (context: any) => {\n try {\n return await (condition as (context: any) => boolean | PromiseLike<boolean>)(context);\n } catch (error) {\n const originalError = getErrorFromUnknown(error);\n // A throwing predicate is deterministic; redelivering the event would only rerun it.\n throw markNonRedeliverable(\n new MastraError(\n {\n id: DURABLE_STOP_WHEN_ERROR_ID,\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: originalError.message,\n details: { name: originalError.name, message: originalError.message },\n },\n originalError,\n ),\n );\n }\n })\n : undefined;\n const decision = await decideContinuation({\n policy: { mode: 'durable' },\n pendingFeedbackStop: state.pendingFeedbackStop ?? false,\n llmWantsToContinue: state.lastStepResult?.isContinued === true || drainForcedContinue,\n // Processor retry steps re-run the same step, so only real LLM steps count against maxSteps.\n // Retries stay bounded by maxProcessorRetries.\n underMaxSteps: steps.filter(s => s.finishReason !== 'retry').length < runMaxSteps,\n steps: durableStopConditionSteps(steps),\n stopWhen,\n consumeDelegationBail: () => {\n if (state.delegationBailed) {\n // Reset the flag so it doesn't carry forward\n state.delegationBailed = false;\n return true;\n }\n return false;\n },\n backgroundTaskPending: state.backgroundTaskPending,\n onIterationComplete: rt.onIterationComplete,\n buildIterationContext: isFinal => {\n const lastStep = steps[steps.length - 1];\n return {\n iteration: steps.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: normalizeToolOutput(tr.result).output,\n error: tr.error,\n })),\n isFinal,\n finishReason: lastStep?.finishReason ?? 'unknown',\n runId: state.runId,\n threadId: rt.threadId,\n resourceId: rt.resourceId,\n agentId: rt.agentId,\n agentName: rt.agentName ?? rt.agentId,\n messages: callbackList().get.all.db(),\n };\n },\n injectFeedback: feedback => {\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 = rt.mastra?.generateId?.() ?? globalThis.crypto?.randomUUID?.() ?? `msg_${Date.now()}`;\n callbackList().add(\n {\n id: feedbackId,\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: { suppressFeedback: true },\n },\n format: 2,\n },\n } as any,\n 'response',\n );\n // Re-serialize the updated messageList\n transcript.write(callbackList().serialize());\n },\n logger: rt.logger,\n }).catch(async error => {\n if ((error as { id?: unknown })?.id !== DURABLE_STOP_WHEN_ERROR_ID) {\n await emitStepFinish(state.lastStepResult?.isContinued === true);\n }\n throw error;\n });\n\n state.pendingFeedbackStop = decision.nextPendingFeedbackStop;\n state.tracingStopCause = decision.stopCause;\n // Also on the registry, which the final step still falls back to.\n const tracingRegistry = getRunRegistryEntry(state.runId, rt.mastra);\n if (tracingRegistry) tracingRegistry.tracingStopCause = decision.stopCause;\n const isFinal = decision.isFinal;\n await emitStepFinish(!isFinal);\n\n // Like Agent, ordinary iterations keep the same response message; the next LLM step opens\n // a step-start boundary inside it (#26332).\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 (rt.pubsub) {\n const lastStep = steps[steps.length - 1];\n await emitIterationCompleteEvent(rt.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: rt.threadId,\n resourceId: rt.resourceId,\n agentId: initData.agentId,\n agentName: initData.agentName,\n });\n }\n\n return !isFinal;\n };\n }\n\n /**\n * The outer loop workflow: init iteration state → dowhile(single iteration,\n * continuation predicate) → finalize (output mapping, memory persistence,\n * finish event, span closure) → fire-and-forget scorers.\n */\n override build() {\n return (\n this.workflowFactory()({\n id: DurableStepIds.AGENTIC_LOOP,\n inputSchema: durableAgenticInputSchema,\n outputSchema: durableAgenticOutputSchema,\n options: {\n // Same injectable policy as the iteration workflow above.\n shouldPersistSnapshot: this.#shouldPersistSnapshot,\n // See the iteration workflow comment above — the effective\n // policy may exclude `running`, in which case resume claims cannot\n // be de-duplicated.\n allowUnclaimedResumes: true,\n // listSuspendedRuns() reads this row's status, so a resume must flip it\n // off `suspended` even when `running` checkpoints are skipped (#27619).\n persistResumeClaim: true,\n isOwnershipLostError: isExecutionFenceError,\n isForeignExecution: isForeignExecutionContext,\n watchExecutionLoss,\n // Agent-loop snapshots are pure resume artifacts — strip everything a\n // resume never reads. This loop reads iteration state from workflow\n // `value`, so it has no declared step-result reads (see pruneSnapshotHook).\n // Runs stored as v2 (see autoStorageVersion) skip this.\n pruneSnapshot: this.pruneSnapshotHook(),\n autoStorageVersion: this.#options?.autoStorageVersion,\n // Snapshots written up to the end reference this process's saved\n // rows, so release them only once the run has persisted its result.\n // A suspended run releases too: it may wait indefinitely, and on\n // resume `hydrate` reloads the rows it references from storage.\n onFinish: ({ getInitData }) => {\n releaseMessageListState({ getInitData });\n },\n validateInputs: false,\n // Engine step events off for the same reason as the iteration\n // workflow (#21529) — see singleIterationWorkflow.\n emitStepEvents: false,\n // Generic boot-time restart must not re-drive agent loops — recovery\n // is owned by the dedicated opt-in path (`recovery.durableAgents:\n // 'auto'`) with leasing/fencing (issue #22598).\n autoRestartActiveRuns: 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 params => {\n const { messageListState: inputMessageListState, ...input } =\n params.inputData as DurableAgenticWorkflowInput;\n // A restart reads the input back from a snapshot, which keeps saved messages as refs.\n const messageListState = await hydrateMessageListState(params, inputMessageListState);\n const initialMessageList = createRunMessageList({\n mastra: params.mastra as Mastra | undefined,\n }).deserialize(messageListState);\n // The transcript and the step records ride in workflow state from\n // here on: each persisted snapshot then holds one copy (in `value`)\n // rather than one per step payload. Steps read and update them\n // there. One write: on storage v1 the default engine keeps only a\n // step's last setState.\n await params.setState({\n accumulatedSteps: [],\n messageListState: await dehydrateMessageListState(params, messageListState),\n });\n const iterationState: IterationState = {\n ...input,\n initialUntaggedSystemMessages: initialMessageList.getSystemMessages(),\n iterationCount: 0,\n accumulatedUsage: {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n },\n usageAggregationVersion: 1,\n lastStepResult: undefined,\n };\n return iterationState;\n },\n { id: 'init-iteration-state' },\n )\n // Run the agentic loop with dowhile\n .dowhile(this.buildIterationWorkflow(), markFrameworkCondition(this.buildContinuationPredicate()))\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 runPubsub = (params as any)[PUBSUB_SYMBOL] as PubSub | undefined;\n const pubsub =\n runPubsub &&\n withExecutionStreamProducer(runPubsub, {\n runId: state.runId,\n agentId: state.agentId,\n mastra,\n claim: getExecutionClaim(requestContext, state.runId),\n });\n const logger = mastra?.getLogger?.();\n\n const storedSteps = await loadAccumulatedSteps(params, state);\n const steps = expandDurableSteps(storedSteps);\n\n // Extract final text from last step\n const lastStep = storedSteps[storedSteps.length - 1];\n let finalText = lastStep?.text;\n\n const messageListState = await readMessageListState(params, state);\n\n // Read before the finish side effects: saving moves messages out of the input/response\n // sets, and plain builds its finish envelope before saving too.\n const finalMessageList = createRunMessageList({}).deserialize(messageListState);\n const finishMessages = {\n all: finalMessageList.get.all.aiV5.model(),\n user: finalMessageList.get.input.aiV5.model(),\n nonUser: finalMessageList.get.response.aiV5.model(),\n };\n\n const finishResult = await runDurableFinishSideEffects({\n runId: state.runId,\n initData,\n messageListState,\n mastra: mastra as Mastra | undefined,\n requestContext,\n tracingContext,\n logger,\n messageId: state.messageId,\n outputResult: {\n text: finalText ?? '',\n usage: state.accumulatedUsage,\n finishReason: state.lastStepResult?.reason ?? 'unknown',\n steps,\n },\n });\n const textRewritten = !!lastStep && finishResult.outputTextChanged;\n if (lastStep && finishResult.outputTextChanged) {\n lastStep.text = finishResult.outputText;\n steps[steps.length - 1] = { ...steps[steps.length - 1]!, text: finishResult.outputText };\n finalText = finishResult.outputText;\n }\n\n const tripwire = finishResult.tripwire;\n if (pubsub && !tripwire) {\n for (const chunk of finishResult.structuredOutputChunks ?? []) {\n await emitChunkEvent(pubsub, state.runId, { ...chunk, runId: state.runId } as any);\n }\n }\n\n if (pubsub) {\n for (const chunk of finishResult.outputResultChunks ?? []) {\n await emitChunkEvent(pubsub, state.runId, chunk, true);\n }\n }\n\n if (tripwire && pubsub) {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'tripwire',\n runId: state.runId,\n from: ChunkFrom.AGENT,\n payload: tripwire,\n });\n }\n\n // generateTitle.emitEvent: hold FINISH until the title is saved, then stream it as a\n // transient chunk so consumers see it before the stream closes (as the in-process loop does).\n if (pubsub && !tripwire && finishResult.titleForStream) {\n const title = await finishResult.titleForStream;\n if (title && initData.state?.threadId) {\n await emitChunkEvent(pubsub, state.runId, {\n type: 'data-thread-title',\n data: { threadId: initData.state.threadId, title },\n transient: true,\n });\n }\n }\n\n const finalOutput = {\n messageListState: finishResult.messageListState,\n messageId: state.messageId,\n stepResult: tripwire\n ? { ...(state.lastStepResult ?? { warnings: [] }), reason: 'tripwire' as const, isContinued: false }\n : state.lastStepResult || {\n reason: 'stop',\n warnings: [],\n isContinued: false,\n },\n output: {\n text: finalText,\n usage: state.accumulatedUsage,\n // Saved with the run, so keep tool outputs compacted; the stream adapter expands them.\n steps: storedSteps,\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 messages: finishMessages,\n ...(textRewritten && { textRewritten }),\n });\n }\n\n // Keep title generation inside the workflow lifecycle so durable workers do not\n // abandon it, but wait only after FINISH has released stream/generate callers.\n await finishResult.titleGeneration;\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 = getRunRegistryEntry(initData.runId, mastra as Mastra | undefined);\n const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;\n const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;\n // Rebuilt spans end from snapshots taken at run start, so the clocks the\n // steps carried are applied here.\n const clocks = carriedSpanClocks(reg, state);\n // The state carries the facts across workers; the registry is the fallback for\n // runs whose snapshots predate those fields.\n const finishReason = finalOutput.stepResult?.reason;\n const stopCause = state.tracingStopCause ?? reg?.tracingStopCause;\n const recordedTermination = state.tracingTermination ?? reg?.tracingTermination;\n if (!stopCause && (finishReason === 'stop' || finishReason === 'tool-calls')) {\n logger?.warn?.(\n `[DurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`,\n );\n }\n const termination =\n ['tripwire', 'error'].includes(finishReason ?? '') && recordedTermination\n ? recordedTermination\n : agentLoopTermination({\n stopCause,\n delegationFailure: state.tracingDelegationFailure ?? reg?.tracingDelegationFailure,\n finishReason,\n tripwire: tripwire ?? state.lastStepResult?.tripwire,\n maxSteps: initData.options?.maxSteps,\n });\n if (observability) {\n if (modelSpanData) {\n const modelSpan =\n reg?.resumeModelSpan ??\n reg?.modelSpan ??\n (observability.rebuildSpan(modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION>) as\n | AIModelGenerationSpan\n | undefined);\n // Surface every tool call made during the run so exporters (e.g. PostHog)\n // see the same { toolCallId, toolName, args } shape as the in-process loop.\n const toolCalls = steps.flatMap(step =>\n ((step.toolCalls ?? []) as DurableToolCallInput[]).map(tc => ({\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n args: tc.args,\n })),\n );\n const usageIncomplete = isUsageIncomplete(state.accumulatedUsage);\n modelSpan?.createTracker()?.endGeneration({\n ...termination,\n output: { text: finalText, toolCalls: toolCalls.length ? toolCalls : undefined },\n attributes: {\n finishReason: finalOutput.stepResult?.reason,\n ...(usageIncomplete ? { usageIncomplete: true } : {}),\n ...clocks,\n responseId: state.lastResponse?.id,\n responseModel: state.lastResponse?.modelId,\n },\n usage: usageIncomplete ? calculateObservedUsage(steps) : state.accumulatedUsage,\n });\n }\n if (agentSpanData) {\n const agentSpan =\n reg?.resumeAgentSpan ??\n reg?.agentSpan ??\n observability.rebuildSpan(agentSpanData as ExportedSpan<SpanType.AGENT_RUN>);\n agentSpan?.end({\n ...termination,\n output: { text: finalText },\n ...(clocks ? { attributes: clocks } : {}),\n });\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_STEP_ID },\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 initData = getInitData() as DurableAgenticWorkflowInput;\n if (initData.scorers && Object.keys(initData.scorers).length > 0) {\n try {\n // Both transcripts may come back from a snapshot that keeps saved messages as refs.\n const [initial, final] = await Promise.all([\n hydrateMessageListState(params, initData.messageListState),\n hydrateMessageListState(params, inputData.messageListState),\n ]);\n void executeDurableAgentScorers({\n initData: { ...initData, messageListState: initial },\n finalOutput: { ...inputData, messageListState: final },\n mastra: mastra as Mastra | undefined,\n requestContext,\n tracingContext,\n loadStoredMessages: loadRunStoredMessages(params),\n scorerInstances: takeRunScorerInstances(initData.runId, mastra as Mastra | undefined),\n }).catch(error => mastra?.getLogger?.()?.warn?.(`[DurableAgent] Skipped scorers: ${error}`));\n } catch (error) {\n mastra?.getLogger?.()?.warn?.(`[DurableAgent] Skipped scorers: ${error}`);\n }\n }\n\n return inputData;\n },\n { id: 'execute-scorers' },\n )\n .commit()\n );\n }\n}\n","import type { DurableAgenticWorkflowOptions } from './durable-loop-builder';\nimport { DurableAgenticLoopBuilder } from './durable-loop-builder';\n\nexport type { DurableAgenticWorkflowOptions } from './durable-loop-builder';\nexport { defaultShouldPersistSnapshot } from './durable-loop-builder';\n\n/**\n * Composes the durable agentic workflow. The topology, workflow options, and\n * continuation predicate live on `DurableAgenticLoopBuilder` (which shares its\n * shape with the main loop's `AgenticLoopBuilder`); this wrapper preserves the\n * existing call surface.\n *\n * Note: tools and model are resolved from Mastra at runtime, so this workflow\n * is created once at startup and reused for all runs.\n */\nexport function createDurableAgenticWorkflow(options?: DurableAgenticWorkflowOptions) {\n return new DurableAgenticLoopBuilder(options).build();\n}\n","import { getErrorFromUnknown } from '../../error';\nimport type { PubSub } from '../../events/pubsub';\nimport type { IMastraLogger } from '../../logger';\nimport type { Mastra } from '../../mastra';\nimport type { ObservabilityContext } from '../../observability';\nimport type { RequestContext } from '../../request-context';\nimport type { MemoryStorage, WorkflowsStorage } from '../../storage';\nimport type { ShouldPersistSnapshotFn, WorkflowRunState, WorkflowRunStatus } from '../../workflows/types';\nimport { DURABLE_STOP_WHEN_ERROR_ID, DurableStepIds, markErrorForStreamRejection } from './constants';\nimport { ExecutionFence, fencePubSub, resolveLeaseProvider, supportsRunFencing } from './execution-fence';\nimport type { UntrackedRunLiveness } from './execution-fence';\nimport { withExecutionStreamProducer } from './execution-stream-publisher';\nimport { emitAbortEvent } from './stream-adapter';\nimport type { DurableAgenticWorkflowInput } from './types';\nimport { createDurableAgenticWorkflow } from './workflows/create-durable-agentic-workflow';\n\nexport type DurableWorkflow = ReturnType<typeof createDurableAgenticWorkflow>;\ntype DurableRun = Awaited<ReturnType<DurableWorkflow['createRun']>>;\nexport type ExecutionCompletion = { result: Awaited<ReturnType<DurableRun['start']>> } | { error: unknown };\nexport type ExecutionOutcome = { owner: 'agent'; status?: string; error?: Error } | { owner: 'workers'; error?: Error };\n\nconst unfencedStoresWarned = new WeakSet<WorkflowsStorage | MemoryStorage>();\n\nexport interface DurableWorkflowOptions {\n maxSteps?: number;\n workflowEngine: 'default' | 'evented';\n storesRunsInJournal: boolean;\n shouldPersistSnapshot?: ShouldPersistSnapshotFn;\n logger: IMastraLogger;\n guardrailLogger?: IMastraLogger;\n}\n\nexport class DurableExecutionEngine {\n #workflow: DurableWorkflow | null = null;\n #resolvedWorkflowEngine: 'default' | 'evented' | null = null;\n #warnedPersistencePolicy = false;\n /** Canceled parked runs whose abort terminal this process already published. */\n #canceledRunTerminals = new Set<string>();\n\n constructor(\n protected readonly id: string,\n protected mastra?: Mastra,\n ) {}\n registerMastra(mastra: Mastra): void {\n this.mastra = mastra;\n }\n get workflow(): DurableWorkflow | null {\n return this.#workflow;\n }\n\n raceFenceLoss<T>(operation: Promise<T>, executionFence: ExecutionFence): Promise<T> {\n const lost = new Promise<never>((_, reject) => executionFence.onLost(reject));\n // The loser of the race must not surface as an unhandled rejection.\n lost.catch(() => {});\n return Promise.race([operation, lost]);\n }\n\n /**\n * Record the abort of a parked run in shared storage, so a resume on any server\n * refuses it. The in-process resume fence only covers this process. The status\n * moves from `suspended` to `canceled` with a guarded write: a resume that claimed\n * the run first has already moved it to `running`, and that run is stopped by the\n * abort request instead. Stores that cannot enforce the guard atomically get the\n * same check on a best-effort basis, so a finished or running run is never marked\n * canceled. Stores without concurrent updates (some don't implement\n * `updateWorkflowState`) get the canceled status by rewriting the run's snapshot,\n * which every store supports. Resolves whether this call canceled the parked run.\n * Storage errors propagate: an abort acknowledged without this write would not stop\n * another server from resuming the run.\n */\n async cancelParkedRun(runId: string): Promise<boolean> {\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n if (!workflowsStore) return false;\n const workflowName = DurableStepIds.AGENTIC_LOOP;\n if (workflowsStore.supportsConcurrentUpdates()) {\n if ((await workflowsStore.loadWorkflowRunStatus({ workflowName, runId })) !== 'suspended') return false;\n const updated = await workflowsStore.updateWorkflowState({\n workflowName,\n runId,\n opts: { status: 'canceled', expectedStatus: 'suspended' },\n });\n return updated !== undefined;\n }\n const run = await workflowsStore.getWorkflowRunById({ runId, workflowName });\n const snapshot = typeof run?.snapshot === 'string' ? (JSON.parse(run.snapshot) as WorkflowRunState) : run?.snapshot;\n if (snapshot?.status !== 'suspended') return false;\n const written = await workflowsStore.persistWorkflowSnapshot({\n workflowName,\n runId,\n resourceId: run?.resourceId,\n snapshot: { ...snapshot, status: 'canceled' },\n expectedStatus: 'suspended',\n });\n return written !== false;\n }\n\n /**\n * Publish the abort terminal for a parked run this call just canceled. The bus is\n * shared, so observers on every server close now, whichever server later refuses\n * the approval. Only the call that won the cancel publishes. A failed publish does\n * not undo the abort: the cancel is already stored, and a refused resume on this\n * server retries the publish.\n */\n async announceCanceledRun(runId: string, pubsub: PubSub): Promise<void> {\n try {\n await this.publishCanceledRunTerminal(runId, pubsub);\n } catch (error) {\n this.mastra?.getLogger?.()?.warn?.(`Failed to publish the abort of canceled run ${runId}`, { runId, error });\n }\n }\n\n /**\n * Publish the abort terminal of a canceled run once per process. Reserved before the\n * publish, so concurrent callers publish once; released if the publish fails, so the\n * next caller retries it.\n */\n async publishCanceledRunTerminal(runId: string, pubsub: PubSub): Promise<void> {\n if (this.#canceledRunTerminals.has(runId)) return;\n this.#canceledRunTerminals.add(runId);\n if (this.#canceledRunTerminals.size > 1000) {\n this.#canceledRunTerminals.delete(this.#canceledRunTerminals.values().next().value!);\n }\n try {\n await emitAbortEvent(pubsub, runId, { steps: [], text: '' });\n } catch (error) {\n this.#canceledRunTerminals.delete(runId);\n throw error;\n }\n }\n\n async isRunCanceledInStorage(runId: string): Promise<boolean> {\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n const status = await workflowsStore?.loadWorkflowRunStatus({ workflowName: DurableStepIds.AGENTIC_LOOP, runId });\n return status === 'canceled';\n }\n\n async claimExecution(\n runId: string,\n mode: 'acquire' | 'recover' | 'takeover',\n pubsub: PubSub,\n logger: IMastraLogger,\n untrackedRun?: UntrackedRunLiveness,\n ): Promise<ExecutionFence> {\n const fence = await ExecutionFence.claim({\n leaseProvider: resolveLeaseProvider(pubsub),\n workflowsStore: await this.mastra?.getStorage()?.getStore('workflows'),\n agentId: this.id,\n runId,\n mode,\n untrackedRun,\n logger: logger,\n });\n return fence;\n }\n\n async warnIfUnfenced(\n store: WorkflowsStorage | MemoryStorage | undefined,\n domain: 'workflows' | 'memory',\n guardrailLogger: IMastraLogger | undefined,\n ): Promise<boolean> {\n if (!store || (await supportsRunFencing(store).catch(() => true))) return false;\n if (unfencedStoresWarned.has(store)) return true;\n unfencedStoresWarned.add(store);\n const consequence =\n domain === 'workflows'\n ? `Recovery can only tell that a run is still live through the pubsub lease, which works only when every instance shares the pubsub, and writes from an execution that lost its run are not rejected. A run recovered while it is still live can end with the stale execution's output.`\n : `When recovery takes a run over, the memory writes (messages, threads, working memory) of the execution that lost it are not rejected.`;\n guardrailLogger?.warn(\n `DurableAgent '${this.id}': the ${domain} store (${store.constructor.name}) can't fence run writes. ${consequence} ` +\n `Use a storage adapter that supports run fencing.`,\n );\n return true;\n }\n\n fenceRunPubSub(\n executionFence: ExecutionFence | undefined,\n abortController: AbortController | undefined,\n pubsub: PubSub,\n workflowEngine: 'default' | 'evented',\n logger: IMastraLogger,\n ): PubSub {\n if (executionFence)\n pubsub = withExecutionStreamProducer(pubsub, {\n runId: executionFence.runId,\n agentId: this.id,\n mastra: this.mastra,\n claim: executionFence.claim,\n });\n if (!executionFence || this.resolveWorkflowEngine(workflowEngine, logger) !== 'default') return pubsub;\n executionFence.onLost(error => {\n if (abortController && !abortController.signal.aborted) abortController.abort(error);\n });\n return fencePubSub(pubsub, executionFence);\n }\n\n async deleteRunSnapshots(runId: string, workflow: DurableWorkflow): Promise<void> {\n try {\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 resolveWorkflowEngine(workflowEngine: 'default' | 'evented', logger: IMastraLogger): 'default' | 'evented' {\n if (this.#resolvedWorkflowEngine) return this.#resolvedWorkflowEngine;\n let engine = workflowEngine;\n if (engine === 'evented' && !this.mastra) {\n engine = 'default';\n logger.warn(\n `EventedAgent '${this.id}' has no Mastra host; running on the default in-process engine. ` +\n `Register the agent on a Mastra instance (with storage) to get evented execution.`,\n );\n } else if (engine === 'evented') {\n // Read `stores` directly rather than `await getStore('workflows')`: engine\n // resolution is synchronous (`getWorkflow()` is), and `getStore()` is only\n // async by signature — it returns `this.stores?.[name]` without awaiting\n // init, so this sees exactly what the engine's own gate sees.\n const storage = this.mastra?.getStorage();\n const workflowsStore = storage?.stores?.workflows;\n if (workflowsStore && !(workflowsStore.supportsConcurrentUpdates?.() ?? false)) {\n engine = 'default';\n logger.warn(\n `EventedAgent '${this.id}' is registered with ${storage?.name ?? 'a'} storage, which does not apply concurrent ` +\n `workflow updates atomically (\\`supportsConcurrentUpdates()\\`); running the durable loop on the default ` +\n `in-process engine instead. In-flight runs will not resume on their own after a process restart. Use a ` +\n `storage adapter that supports atomic concurrent updates (for example @mastra/libsql, @mastra/pg or ` +\n `@mastra/mysql) to get evented execution.`,\n );\n }\n }\n this.#resolvedWorkflowEngine = engine;\n return engine;\n }\n\n async ensureEngineWorkersStarted(workflowEngine: 'default' | 'evented', logger: IMastraLogger): Promise<void> {\n if (this.resolveWorkflowEngine(workflowEngine, logger) === 'evented') {\n await this.mastra?.__ensureExecutionWorkersStarted();\n }\n }\n\n createWorkflow(options: DurableWorkflowOptions): ReturnType<typeof createDurableAgenticWorkflow> {\n return createDurableAgenticWorkflow({\n maxSteps: options.maxSteps,\n // Resolved, not raw: a hostless evented agent falls back to the default\n // in-process engine (see resolveWorkflowEngine).\n engine: this.resolveWorkflowEngine(options.workflowEngine, options.logger),\n shouldPersistSnapshot: this.resolveShouldPersistSnapshot(options.shouldPersistSnapshot),\n autoStorageVersion: options.storesRunsInJournal,\n });\n }\n\n readonly recoveryAwarePersistencePolicy: ShouldPersistSnapshotFn = ({ workflowStatus }) => {\n return (\n workflowStatus === 'pending' ||\n workflowStatus === 'paused' ||\n workflowStatus === 'suspended' ||\n (workflowStatus === 'running' &&\n (this.mastra?.recoveryConfig?.durableAgents === 'auto' || this.mastra?.__shuttingDown === true))\n );\n };\n\n getWorkflow(options: DurableWorkflowOptions) {\n if (!this.#workflow) {\n this.#workflow = this.createWorkflow(options);\n this.warnOnRiskyPersistencePolicy(options.shouldPersistSnapshot, options.guardrailLogger);\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 // Evented engine: the WorkflowEventProcessor resolves workflows by id\n // from Mastra's registries, so the loop workflow must be discoverable\n // there. Register it as an (unscoped) internal workflow — it's a\n // per-agent singleton. Without this, every run's events would be\n // unresolvable and the run would hang. Uses the resolved engine so\n // this stays consistent with the workflow instance just created.\n //\n // `distributed`: every process sharing this Mastra setup registers the\n // same loop, so a dedicated worker process can run it. Keeping its\n // events local would strand runs started in a process without workers.\n if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === 'evented') {\n this.mastra.__registerInternalWorkflow(this.#workflow, undefined, { distributed: true });\n }\n }\n }\n return this.#workflow;\n }\n\n warnOnRiskyPersistencePolicy(\n predicate: ShouldPersistSnapshotFn | undefined,\n guardrailLogger: IMastraLogger | undefined,\n ): void {\n if (this.#warnedPersistencePolicy) return;\n this.#warnedPersistencePolicy = true;\n if (!predicate) return;\n const probe = (workflowStatus: WorkflowRunStatus): boolean => {\n try {\n return predicate({ workflowStatus, stepResults: {} });\n } catch {\n // The predicate depends on data the probe can't fake — assume it\n // persists rather than emitting a false-positive warning.\n return true;\n }\n };\n if (!probe('suspended') || !probe('paused')) {\n guardrailLogger?.warn(\n `DurableAgent '${this.id}': the custom shouldPersistSnapshot policy does not persist 'suspended'/'paused' snapshots. ` +\n `Suspended runs cannot be resumed — human-in-the-loop flows will break.`,\n );\n }\n if (this.mastra?.recoveryConfig?.durableAgents === 'auto' && !probe('running')) {\n guardrailLogger?.warn(\n `DurableAgent '${this.id}': recovery.durableAgents is 'auto' but the custom shouldPersistSnapshot policy does not persist 'running' snapshots. ` +\n `In-flight runs of this agent are invisible to crash recovery (listActiveRuns/recoverActiveRuns).`,\n );\n }\n }\n workflowFailureError(workflowError: unknown, fallbackMessage: string): Error {\n const serialized = (workflowError ?? {}) as {\n code?: unknown;\n id?: unknown;\n message?: unknown;\n details?: { name?: unknown; message?: unknown };\n };\n if (serialized.code === DURABLE_STOP_WHEN_ERROR_ID || serialized.id === DURABLE_STOP_WHEN_ERROR_ID) {\n const error = new Error(\n typeof serialized.details?.message === 'string'\n ? serialized.details.message\n : typeof serialized.message === 'string'\n ? serialized.message\n : fallbackMessage,\n );\n error.name = typeof serialized.details?.name === 'string' ? serialized.details.name : 'Error';\n return markErrorForStreamRejection(error);\n }\n return new Error(typeof serialized.message === 'string' ? serialized.message : fallbackMessage);\n }\n workflowExecutionError(workflowError: unknown, fallbackMessage: string): Error {\n const serialized = (workflowError ?? {}) as { code?: unknown; id?: unknown };\n if (serialized.code === DURABLE_STOP_WHEN_ERROR_ID || serialized.id === DURABLE_STOP_WHEN_ERROR_ID) {\n return this.workflowFailureError(workflowError, fallbackMessage);\n }\n return getErrorFromUnknown(workflowError, { fallbackMessage });\n }\n async loadRunSnapshot(runId: string): Promise<WorkflowRunState | undefined> {\n const workflowsStore = await this.mastra?.getStorage()?.getStore('workflows');\n const persisted = await workflowsStore?.getWorkflowRunById({ runId, workflowName: DurableStepIds.AGENTIC_LOOP });\n return typeof persisted?.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted?.snapshot;\n }\n createRun(workflow: DurableWorkflow, options: Parameters<DurableWorkflow['createRun']>[0]): Promise<DurableRun> {\n return workflow.createRun(options);\n }\n\n releaseRun(workflow: DurableWorkflow, runId: string, run: DurableRun, status: string | undefined): void {\n if (status !== 'suspended' && workflow.runs.get(runId) === run) {\n workflow.runs.delete(runId);\n }\n }\n\n finishExecution(\n _runId: string,\n _executionFence: ExecutionFence | undefined,\n _sharedExecution: boolean,\n completion: ExecutionCompletion,\n ): ExecutionOutcome {\n if ('error' in completion) {\n return { owner: 'agent', error: this.workflowExecutionError(completion.error, 'Workflow execution failed') };\n }\n return {\n owner: 'agent',\n status: completion.result?.status,\n error:\n completion.result?.status === 'failed'\n ? this.workflowFailureError(completion.result.error, 'Workflow execution failed')\n : undefined,\n };\n }\n\n startRun(\n run: DurableRun,\n workflowInput: DurableAgenticWorkflowInput,\n requestContext: RequestContext | undefined,\n observabilityContext: ObservabilityContext,\n ) {\n return run.start({\n inputData: workflowInput,\n requestContext,\n actor: workflowInput.options?.actor,\n ...observabilityContext,\n });\n }\n resolveShouldPersistSnapshot(predicate?: ShouldPersistSnapshotFn): ShouldPersistSnapshotFn {\n return predicate ?? this.recoveryAwarePersistencePolicy;\n }\n prepareExecution(\n _pubsub: PubSub | undefined,\n _fence: ExecutionFence | undefined,\n _workflowEngine: 'default' | 'evented',\n _logger: IMastraLogger,\n _guardrailLogger: IMastraLogger | undefined,\n ): { sharedExecution: boolean; usesRunPubSub: boolean } {\n return { sharedExecution: false, usesRunPubSub: true };\n }\n}\n","import { MastraFGAPermissions } from '../../auth/ee';\nimport type { Mastra } from '../../mastra';\nimport { assertExecutionOwned } from './execution-fence';\nimport { authorizeDurableMemory, getDurableMemoryAuthorizationChecks } from './memory-fga';\nimport { getRunRegistryEntry } from './run-registry';\nimport type { DurableAgenticWorkflowInput } from './types';\n\n/**\n * Save the run's accepted input to memory through its in-process registry\n * entry, before the run starts. No-op when the entry lacks memory or a message\n * list, the thread is unknown, memory is read-only, or an input processor\n * tripped the run.\n * @internal\n */\nexport async function persistDurableRunInput(\n runId: string,\n workflowInput: Pick<DurableAgenticWorkflowInput, 'agentId' | 'state' | 'options'>,\n mastra: Mastra | undefined,\n): Promise<void> {\n const entry = getRunRegistryEntry(runId, mastra);\n const state = workflowInput.state;\n if (\n !entry?.saveQueueManager ||\n !entry.memory ||\n !entry.messageList ||\n !state?.threadId ||\n !state.resourceId ||\n state.memoryConfig?.readOnly ||\n entry.tripwire\n ) {\n return;\n }\n\n const requestContext = entry.requestContext;\n await authorizeDurableMemory(getDurableMemoryAuthorizationChecks(entry), {\n mastra,\n user: requestContext?.get('user'),\n threadId: state.threadId,\n resourceId: state.resourceId,\n agentId: workflowInput.agentId,\n requestContext,\n permission: MastraFGAPermissions.MEMORY_WRITE,\n actor: workflowInput.options?.actor,\n });\n // Input membership is also used by OM and tool context, not just persistence.\n // Save a copy so later consumers still see the accepted request; saves upsert by ID.\n const inputCopy = entry.messageList.clone();\n await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {\n throwOnError: true,\n beforePersist: () =>\n assertExecutionOwned({\n runId,\n agentId: workflowInput.agentId,\n mastra,\n requestContext,\n }),\n });\n // The save embedded the input on the copy. Carry that onto the live list so the finalize step\n // (the SemanticRecall processor, then the final flush) does not embed it again. A finalize on\n // another worker (evented, Inngest) never sees this list; it embeds the input once more into\n // the same rows, because row ids come from the message id.\n const embedded = entry.messageList.getEmbeddedMessages();\n for (const [messageId, textHash] of inputCopy.getEmbeddedMessages()) {\n embedded.set(messageId, textHash);\n }\n}\n","import type { StandardSchemaWithJSON } from '@mastra/schema-compat/schema';\nimport { MastraFGAPermissions } from '../../auth/ee';\nimport type { MastraFGAPermissionInput } from '../../auth/ee';\nimport type { AgentBackgroundConfig } from '../../background-tasks/types';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../../error';\nimport { validateModelTimeoutSettings } from '../../llm/model/model-settings';\nimport { mergeProviderOptions } from '../../llm/model/provider-options';\nimport type { MastraLanguageModel, MastraModelConfig } from '../../llm/model/shared.types';\nimport type { IMastraLogger } from '../../logger';\nimport { executionFailureTermination } from '../../loop/shared/execution-outcome';\nimport { withDefaultToolCallConcurrencyLimit } from '../../loop/workflows/agentic-execution/tool-call-concurrency';\nimport type { Mastra } from '../../mastra';\nimport type { MastraMemory } from '../../memory/memory';\nimport { isObservationalMemoryEnabled } from '../../memory/types';\nimport type { MemoryConfig, MemoryConfig as _MemoryConfig, StorageThreadType } from '../../memory/types';\nimport { EntityType, SpanType, createObservabilityContext, getOrCreateSpan } from '../../observability';\nimport type { AIModelGenerationSpan, ExportedSpan, Span } from '../../observability';\nimport type {\n InputProcessorOrWorkflow,\n LLMRequestProcessorOrWorkflow,\n OutputProcessorOrWorkflow,\n ErrorProcessorOrWorkflow,\n} from '../../processors';\nimport type { ProcessorState } from '../../processors/runner';\nimport { RequestContext, MASTRA_SCOPES_KEY, MASTRA_VERSIONS_KEY, mergeVersionOverrides } from '../../request-context';\nimport type { VersionOverrides } from '../../request-context';\nimport { getRequestContextInputValues } from '../../request-context/input-source';\nimport { asJsonSchema } from '../../stream/base/schema';\nimport { normalizeToolPayloadTransformPolicy } from '../../tools/payload-transform';\nimport type { CoreTool, ToolHooks, ToolPayloadTransformPolicy } from '../../tools/types';\nimport type { DynamicArgument } from '../../types';\nimport { boundedStringify, deepMerge } from '../../utils';\nimport type { Workspace } from '../../workspace';\nimport type { Agent } from '../agent';\nimport type { AgentExecutionOptions, DelegationConfig } from '../agent.types';\nimport { assertThreadOwnedByResource } from '../memory-thread-ownership';\nimport { MessageList } from '../message-list';\nimport type { MessageListInput } from '../message-list';\nimport { modelSpanAttributes } from '../model-span-attributes';\nimport { snapshotRequestContextEntries } from '../request-context-snapshot';\nimport { SaveQueueManager } from '../save-queue';\nimport { applyResolvedAgentScopes, incomingAgentScopes, resolveAgentScopes } from '../scopes';\nimport type { PendingSignalListener, AgentSignalInput, CreatedAgentSignal } from '../signals';\nimport { mastraDBMessageToSignal, signalSpanAttributes } from '../signals';\nimport { TripWire } from '../trip-wire';\nimport type {\n AgentInstructions,\n AgentMethodType,\n AgentModelManagerConfig,\n GoalConfig,\n ModelFallbackSettings,\n ToolsetsInput,\n ToolsInput,\n} from '../types';\nimport {\n applyClientToolModelOutput,\n fireClientToolOutputHooks,\n} from '../workflows/prepare-stream/client-tool-output-hooks';\nimport { authorizeDurableMemory } from './memory-fga';\nimport { recordRunSavedMessages } from './run-message-refs';\nimport { setRunScorerInstances } from './run-registry';\nimport { needsNullToUndefined, toLiveStructuredOutputSchema } from './structured-output-null-transform';\nimport type { DurableAgenticWorkflowInput, RunRegistryEntry, SerializableStructuredOutput } from './types';\nimport {\n createWorkflowInput,\n serializeClientTools,\n serializeModelConfig,\n serializeToolsetToolNames,\n} from './utils/serialize-state';\nimport { generateDurableThreadTitle } from './workflows/finalize-run';\nimport { isJsonSafe } from './workflows/shared/schemas';\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 maxRetries?: number;\n requestContextSchema?: StandardSchemaWithJSON<unknown>;\n getDefaultOptions(opts: { requestContext: RequestContext }): AgentExecutionOptions | Promise<AgentExecutionOptions>;\n getScopes?(opts: { requestContext: RequestContext; scopes?: string[] }): Promise<string[]>;\n getInstructions(opts: { requestContext: RequestContext }): AgentInstructions | Promise<AgentInstructions>;\n __getModelAndModelList(opts: { requestContext: RequestContext; model?: unknown }): Promise<{\n model: MastraLanguageModel;\n modelList: AgentModelManagerConfig[] | null;\n fallbackTimeouts: Array<ModelFallbackSettings['timeout'] | undefined>;\n }>;\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 backgroundTaskEnabled?: boolean;\n backgroundTaskPolicy?: AgentExecutionOptions<any>['backgroundTaskPolicy'];\n model?: MastraLanguageModel;\n }): Promise<Record<string, CoreTool>>;\n listInputProcessors(requestContext?: RequestContext): Promise<InputProcessorOrWorkflow[]>;\n listOutputProcessors(requestContext?: RequestContext): Promise<OutputProcessorOrWorkflow[]>;\n __resolveRunErrorProcessors(\n requestContext: RequestContext,\n overrides?: ErrorProcessorOrWorkflow[],\n ): Promise<{ errorProcessors: ErrorProcessorOrWorkflow[]; hasConfiguredErrorProcessors: boolean }>;\n getBackgroundTasksConfig(): AgentBackgroundConfig | undefined;\n getToolPayloadTransform?(): ToolPayloadTransformPolicy | undefined;\n __getDrainPendingSignals(): (runId: string, scope?: 'pending' | 'pre-run') => CreatedAgentSignal[];\n __getSubscribePendingSignals(): (runId: string, listener: PendingSignalListener) => () => void;\n __getEnqueuePendingSignal(): (\n target: { runId: string; resourceId?: string; threadId?: string },\n signalInput: AgentSignalInput,\n ) => Promise<CreatedAgentSignal>;\n __getGoalConfig(): GoalConfig | undefined;\n __hasFixedMemory(): boolean;\n __getMaxRetriesConfigured?(): boolean;\n __getMaxProcessorRetries?(): number | undefined;\n __listLLMRequestProcessors(\n requestContext?: RequestContext,\n errorProcessorOverrides?: ErrorProcessorOrWorkflow[],\n ): Promise<LLMRequestProcessorOrWorkflow[]>;\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 /**\n * The agent defaults `options` were resolved from. Function-based defaults can build new\n * scorers on every call, so recording whether the completion policy came from the defaults\n * must compare against this resolution rather than a fresh one.\n */\n resolvedDefaultOptions?: AgentExecutionOptions<OUTPUT>;\n /**\n * Whether agent scopes were already applied to `options` (DurableAgent does this itself).\n * When false, preparation resolves scopes so wrappers that call it directly honor them.\n */\n scopesResolved?: boolean;\n /**\n * The AGENT_RUN and MODEL_GENERATION spans a suspended run persisted when it started. A cold\n * resume passes them so the run keeps its own trace instead of opening a new one.\n */\n resumedSpanData?: { agentSpanData?: unknown; modelSpanData?: unknown };\n /**\n * Scopes the caller passed. When the property is absent, `options.scopes`; set it (even to\n * undefined) when `options` already include the agent defaults, so the Agent's own\n * `defaultOptions.scopes` are not treated as caller input.\n */\n callScopes?: string[];\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 resolvedDefaultOptions,\n scopesResolved = false,\n resumedSpanData,\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 let requestContext = providedRequestContext ?? new RequestContext();\n\n // 2a. Validate the request context against the agent's requestContextSchema,\n // mirroring Agent.stream()/generate(). Without this, schema violations are\n // silently ignored on the durable path.\n if (typedAgent.requestContextSchema) {\n const contextValues = getRequestContextInputValues(requestContext);\n const validation = await typedAgent.requestContextSchema['~standard'].validate(contextValues);\n\n if (validation.issues) {\n const errorMessages = validation.issues\n .map(e => {\n const pathStr = e.path?.map((p: any) => (typeof p === 'object' ? p.key : p)).join('.');\n return `- ${pathStr}: ${e.message}`;\n })\n .join('\\n');\n throw new MastraError({\n id: 'AGENT_REQUEST_CONTEXT_VALIDATION_FAILED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `Request context validation failed for agent '${publicAgentId}':\\n${errorMessages}`,\n details: {\n agentId: publicAgentId,\n agentName: publicAgentName,\n },\n });\n }\n }\n\n // 2a. 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 let defaultOptions: AgentExecutionOptions<OUTPUT> | undefined = resolvedDefaultOptions;\n const loadDefaultOptions = async () =>\n (defaultOptions ??= ((await typedAgent.getDefaultOptions({ requestContext })) ??\n {}) as AgentExecutionOptions<OUTPUT>);\n let execOptions: AgentExecutionOptions<OUTPUT> = optionsAreResolved\n ? (rawExecOptions ?? ({} as AgentExecutionOptions<OUTPUT>))\n : (deepMerge(\n withDefaultToolCallConcurrencyLimit(await loadDefaultOptions(), rawExecOptions) as Record<string, unknown>,\n (rawExecOptions ?? {}) as Record<string, unknown>,\n ) as AgentExecutionOptions<OUTPUT>);\n\n // An explicit `callScopes`, even undefined, means `options` already carry the Agent defaults.\n const callScopes = 'callScopes' in options ? options.callScopes : rawExecOptions?.scopes;\n\n // 2b. Resolve agent scopes for callers that did not (DurableAgent resolves its own).\n // Durable runs read identity from `memory` only, so nothing changes without scopes.\n if (!scopesResolved) {\n const defaultScopes = (await loadDefaultOptions()).scopes ?? [];\n const incoming = incomingAgentScopes({ requestContext, callScopes, defaultScopes, mastra });\n const agentScopes = typedAgent.getScopes\n ? await typedAgent.getScopes({ requestContext, scopes: incoming })\n : incoming;\n if (agentScopes.length || callScopes?.length || requestContext.has(MASTRA_SCOPES_KEY)) {\n const resolved = resolveAgentScopes({\n requestContext,\n agentScopes,\n incomingScopes: incoming,\n callScopes,\n memory: execOptions.memory,\n mastra,\n });\n execOptions = applyResolvedAgentScopes({ ...execOptions, requestContext }, resolved, requestContext);\n requestContext = execOptions.requestContext ?? requestContext;\n }\n }\n\n validateModelTimeoutSettings(execOptions.modelSettings?.timeout);\n\n if (execOptions.eagerToolExecution) {\n throw new Error('eagerToolExecution is not supported by durable agents');\n }\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 // Resolve and validate the complete model selection before durable preparation\n // can persist a thread or run user-defined processors, tools, or hooks.\n const { model, modelList, fallbackTimeouts } = await typedAgent.__getModelAndModelList({\n requestContext,\n model: (execOptions as { model?: DynamicArgument<MastraModelConfig> }).model,\n });\n if (!model) {\n throw new Error('Agent model not available');\n }\n for (const timeout of fallbackTimeouts) {\n validateModelTimeoutSettings(timeout);\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 const memoryAuthorizationChecks = new Map<MastraFGAPermissionInput, Promise<void>>();\n const authorizeMemory = (permission: MastraFGAPermissionInput) =>\n authorizeDurableMemory(memoryAuthorizationChecks, {\n mastra,\n user: requestContext.get('user'),\n threadId: threadId!,\n resourceId,\n agentId: publicAgentId,\n requestContext,\n permission,\n actor: execOptions?.actor,\n });\n if (memory && threadId && resourceId) {\n await authorizeMemory(MastraFGAPermissions.MEMORY_READ);\n const existingThread = await memory.getThreadById({ threadId });\n if (existingThread) {\n assertThreadOwnedByResource({ thread: existingThread, resourceId, agentName: publicAgentName });\n } else {\n await authorizeMemory(MastraFGAPermissions.MEMORY_WRITE);\n }\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: LLMRequestProcessorOrWorkflow[] = [];\n let outputProcessors: OutputProcessorOrWorkflow[] = [];\n let errorProcessors: ErrorProcessorOrWorkflow[] = [];\n let hasConfiguredErrorProcessors = false;\n\n inputProcessors = await typedAgent.listInputProcessors(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 // Error processors resolve after output processors. They resolve once:\n // call-time errorProcessors replace the resolved list, including the defaults,\n // and the request lane below reuses the result. `hasConfiguredErrorProcessors`\n // excludes framework defaults and gates the implicit retry-cap warning, since\n // the defaults self-limit.\n ({ errorProcessors, hasConfiguredErrorProcessors } = await typedAgent.__resolveRunErrorProcessors(\n requestContext,\n execOptions?.errorProcessors,\n ));\n // Uncombined processors for processLLMRequest — combined (workflow-wrapped)\n // processors are skipped by ProcessorRunner.runProcessLLMRequest.\n llmRequestInputProcessors = await typedAgent.__listLLMRequestProcessors(requestContext, errorProcessors);\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 startingSignal = signalSpanAttributes(messages);\n // A cold resume reattaches to the spans the run opened when it started (ended as `suspended`)\n // instead of opening a second root in a new trace. The resume then opens its own spans under them.\n // A run that recorded no span stays unrecorded. An unsampled run saved a no-op span (id `no-op`),\n // and rebuilding it would record spans the run never sampled.\n const { agentSpanData, modelSpanData } = resumedSpanData ?? {};\n const agentSpanId = (agentSpanData as { id?: unknown } | undefined)?.id;\n const resumedObservability =\n typeof agentSpanId === 'string' && agentSpanId !== 'no-op'\n ? mastra?.observability?.getSelectedInstance({ requestContext })\n : undefined;\n let resumedSpans: { agentSpan?: Span<SpanType.AGENT_RUN>; modelSpan?: AIModelGenerationSpan } | undefined;\n if (resumedSpanData) {\n resumedSpans = {};\n try {\n resumedSpans.agentSpan = resumedObservability?.rebuildSpan(agentSpanData as ExportedSpan<SpanType.AGENT_RUN>);\n if (modelSpanData) {\n resumedSpans.modelSpan = resumedObservability?.rebuildSpan(\n modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION>,\n ) as AIModelGenerationSpan | undefined;\n }\n } catch (error) {\n // Span bookkeeping must never block a resume, so a run whose spans cannot be rebuilt continues unrecorded.\n resumedSpans = {};\n (logger ?? mastra?.getLogger?.())?.warn?.(`[DurableAgent] Failed to rebuild the spans of run ${runId}: ${error}`);\n }\n }\n const agentSpan = resumedSpans\n ? resumedSpans.agentSpan\n : getOrCreateSpan({\n type: SpanType.AGENT_RUN,\n outcome: null,\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 ...modelSpanAttributes(model),\n ...(startingSignal ? { signal: startingSignal } : {}),\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 agent: agent as unknown as Agent<any, any, any, any>,\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 const inputProcessorError = new MastraError(\n {\n id: 'AGENT_INPUT_PROCESSOR_ERROR',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `[Agent:${publicAgentName}] - Input processor error`,\n },\n error,\n );\n // A rebuilt span ended when the run suspended. Ending it again would rewrite that record.\n if (!resumedSpans)\n agentSpan?.error({\n error: inputProcessorError,\n ...executionFailureTermination(inputProcessorError),\n endTree: true,\n });\n throw inputProcessorError;\n }\n }\n }\n\n // Snapshot the request context AFTER input processors have run so their\n // writes reach the durable run (#23904) — cross-process engines rebuild the\n // context from these entries via restoreRequestContext, so anything missing\n // here is silently dropped on the worker. Framework-internal prep state\n // (memory keys, auth token, merged versions) is excluded by key inside\n // snapshotRequestContextEntries; the versions entry is pinned back to the\n // caller's own value (captured at step 3, before the merge) so persisted\n // input still reflects only caller intent.\n let requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext);\n // Persist the run's scope set unconditionally — [] included — so a cold resume can tell\n // \"held no scopes\" (recorded [], re-supplied scopes are rejected) from a pre-upgrade\n // snapshot (key absent, supplied scopes are adopted). The live run context deliberately\n // omits the key when the run has no non-identity scopes, so only the persisted entries\n // carry the empty marker.\n if (!Array.isArray(requestContextEntriesSnapshot?.[MASTRA_SCOPES_KEY])) {\n requestContextEntriesSnapshot = { ...requestContextEntriesSnapshot, [MASTRA_SCOPES_KEY]: [] };\n }\n if (requestVersions !== undefined) {\n const requestVersionsJson = boundedStringify(requestVersions);\n if (requestVersionsJson !== undefined) {\n requestContextEntriesSnapshot = {\n ...requestContextEntriesSnapshot,\n [MASTRA_VERSIONS_KEY]: JSON.parse(requestVersionsJson),\n };\n }\n }\n\n // Resolve background task configuration before converting tools so eligible\n // tools expose the per-call `_background` override in their input schemas.\n const backgroundTasksConfig = typedAgent.getBackgroundTasksConfig?.();\n const backgroundTaskManager =\n execOptions?.disableBackgroundTasks || execOptions?.backgroundTaskPolicy?.allowToolDispatch === false\n ? undefined\n : mastra?.backgroundTaskManager;\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 backgroundTaskEnabled: Boolean(backgroundTaskManager),\n backgroundTaskPolicy: execOptions?.backgroundTaskPolicy,\n model,\n });\n } catch (error) {\n logger?.warn?.(`[DurableAgent] Error converting tools: ${error}`);\n }\n\n // Client-executed results fire only after processors accept the request and\n // the required runtime model has resolved.\n if (!tripwireData) {\n await fireClientToolOutputHooks({\n messages,\n tools,\n abortSignal: execOptions?.abortSignal,\n logger,\n });\n // Apply server-defined toModelOutput to client-executed results by\n // enriching the ingested MessageList parts.\n await applyClientToolModelOutput({\n messageList,\n tools,\n logger,\n });\n }\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 if (scorers) {\n // Workflow input carries scorers by name only; keep the instances so a\n // scorer Mastra has never registered still runs in this process (#27579).\n setRunScorerInstances(\n runId,\n Object.fromEntries(\n Object.entries(scorers).flatMap(([key, entry]) =>\n entry?.scorer && typeof entry.scorer === 'object' ? [[key, entry.scorer]] : [],\n ),\n ),\n mastra,\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 onSaved: recordRunSavedMessages(runId),\n })\n : undefined;\n\n // 10. Serialize structured output if provided\n let serializedStructuredOutput: SerializableStructuredOutput | undefined;\n // Same strict-mode null → undefined handling as Agent.#execute, enabled when the main model or\n // any fallback model uses strict mode (the flag is persisted once per run); skipped when a separate\n // structuring model runs (its own agent call applies the transform).\n const nullToUndefined =\n Boolean(execOptions?.structuredOutput?.schema) &&\n !(execOptions?.structuredOutput as any)?.model &&\n // The model list already contains the enabled model, so the bare model is only used without a list.\n (modelList ?? [{ model, providerOptions: undefined }]).some(candidate =>\n needsNullToUndefined(\n candidate.model as any,\n mergeProviderOptions(execOptions?.providerOptions, candidate.providerOptions),\n ),\n );\n const structuredOutputSchema = execOptions?.structuredOutput?.schema\n ? toLiveStructuredOutputSchema<{}>(execOptions.structuredOutput.schema, nullToUndefined)\n : undefined;\n if (execOptions?.structuredOutput) {\n const so = execOptions.structuredOutput as any;\n if (structuredOutputSchema) {\n serializedStructuredOutput = {\n jsonPromptInjection: so.jsonPromptInjection,\n // With `model` set these are structuring-agent instructions for the finish-time\n // structuring pass; otherwise they are injected into the main model's prompt.\n instructions: so.instructions,\n useAgent: so.useAgent,\n hasStructuringModel: so.model ? true : undefined,\n nullToUndefined: nullToUndefined ? true : undefined,\n // Workers without the live config (remote/recovered runs) resolve the structuring\n // model from this. Model instances persist as `provider/modelId`, like the main model.\n structuringModelConfig:\n typeof so.model === 'string'\n ? { provider: so.model.split('/')[0] ?? '', modelId: so.model, originalConfig: so.model }\n : so.model && typeof so.model.provider === 'string' && typeof so.model.modelId === 'string'\n ? serializeModelConfig(so.model)\n : undefined,\n errorStrategy: so.errorStrategy,\n // A non-JSON-safe fallback would fail options validation; in-process runs still\n // have it through the run registry's live config.\n fallbackValue: isJsonSafe(so.fallbackValue) ? so.fallbackValue : undefined,\n // Always convert to plain JSON Schema: this crosses step boundaries as JSON, and a\n // live Zod/standard-schema instance does not survive that round trip.\n schema: asJsonSchema(structuredOutputSchema),\n };\n }\n }\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 = isObservationalMemoryEnabled(memoryConfig?.observationalMemory);\n if (execOptions.isTaskComplete) await loadDefaultOptions();\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 = resumedSpans\n ? resumedSpans.modelSpan\n : agentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n outcome: null,\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 // Pin the exact stored version this run resolved to (if any) so a resume\n // after a newer publish still re-resolves to the started version.\n agentVersionId: resolvedVersionId,\n messageList,\n tools,\n model,\n modelList: modelList ?? undefined,\n scorers,\n options: {\n clientTools: serializeClientTools(execOptions?.clientTools, tools),\n toolsetToolNames: serializeToolsetToolNames(execOptions?.toolsets),\n maxSteps: execOptions?.maxSteps,\n toolChoice: execOptions?.toolChoice as any,\n activeTools: execOptions?.activeTools,\n modelSettings: execOptions?.modelSettings as any,\n // Agent-level retry config for the llm-execution step's retry ladder.\n // Single-model agents have no modelList entry to carry maxRetries, so\n // it rides on options; the flag preserves the in-process precedence\n // rule (an explicitly configured agent value — including 0 — beats\n // call-time modelSettings.maxRetries).\n agentMaxRetries: typedAgent.maxRetries,\n agentMaxRetriesConfigured: typedAgent.__getMaxRetriesConfigured?.() ?? false,\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 ?? typedAgent.__getMaxProcessorRetries?.(),\n includeRawChunks: execOptions?.includeRawChunks,\n returnScorerData: execOptions?.returnScorerData,\n // \"Configured\" excludes framework default processors — the durable step\n // uses this to gate the implicit retry-cap warning (the cap itself is\n // driven by the resolved list from the run registry).\n hasErrorProcessors: hasConfiguredErrorProcessors,\n emptyErrorProcessorOverride: execOptions?.errorProcessors?.length === 0 ? true : undefined,\n providerOptions: execOptions?.providerOptions,\n structuredOutput: serializedStructuredOutput,\n skipBgTaskWait: (execOptions as any)?._skipBgTaskWait,\n disableBackgroundTasks: execOptions?.disableBackgroundTasks,\n backgroundTaskPolicy: execOptions?.backgroundTaskPolicy,\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 fromAgentDefaults: (() => {\n const configured = defaultOptions?.isTaskComplete;\n const active = execOptions.isTaskComplete;\n return (\n !!configured &&\n !!active.scorers &&\n !!configured.scorers &&\n active.scorers.length === configured.scorers.length &&\n active.scorers.every((scorer, index) => scorer === configured.scorers?.[index]) &&\n active.onComplete === configured.onComplete\n );\n })(),\n scorerIds: execOptions.isTaskComplete.scorers?.map(s => s.id),\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 fixedMemory: typedAgent.__hasFixedMemory(),\n },\n messageId,\n agentSpanData: agentSpan?.snapshot?.() ?? agentSpan?.exportSpan(),\n modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),\n requestContextEntries: requestContextEntriesSnapshot,\n inputTripwire: tripwireData,\n });\n\n // 14. Create registry entry for non-serializable state\n const registryEntry: RunRegistryEntry = {\n mastra,\n tools,\n requestTools: tools,\n methodType,\n saveQueueManager,\n memory,\n memoryAuthorizationChecks,\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 mcp: execOptions?.mcp,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n agent: agent as unknown as Agent<any, any, any, any>,\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 // Park the per-call delegation config so a warm resume that rebuilds tools\n // keeps the original delegation callbacks when the resume supplies none.\n delegation: execOptions?.delegation,\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 subscribePendingSignals: listener => typedAgent.__getSubscribePendingSignals()(runId, listener),\n enqueuePendingSignal: signalInput =>\n typedAgent.__getEnqueuePendingSignal()({ runId, resourceId, threadId }, signalInput),\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 ? async args => generateDurableThreadTitle({ agent, memory, ...args }) : undefined,\n // generate() returns JSON, so only stream() runs carry the title chunk (as in #executeOnFinish).\n streamThreadTitle:\n methodType === 'stream' &&\n !!memory &&\n !!agent.resolveTitleGenerationConfig(memory.getMergedThreadConfig(memoryConfig).generateTitle).emitEvent,\n onTitleGenerated: execOptions?.memory?.onTitleGenerated,\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 // Run-level execution budget (#21724). Parked on the registry so the\n // abort-controller install sites (stream/resume) can arm a session\n // timer without re-deriving it from options or the snapshot.\n timeoutTotalMs: (execOptions?.modelSettings as { timeout?: { totalMs?: number } } | undefined)?.timeout?.totalMs,\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: structuredOutputSchema\n ? {\n ...execOptions!.structuredOutput,\n schema: structuredOutputSchema,\n }\n : undefined,\n // Call-time returnScorerData flag. Also serialized into the workflow\n // input; parked here too so warm resume()/observe() can rebuild\n // scoringData without re-reading the snapshot.\n returnScorerData: execOptions?.returnScorerData,\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","type CleanupTimer = ReturnType<typeof setTimeout>;\n\n/**\n * Release of the state a durable run segment (stream, resume, recover,\n * generate, observe) holds, run at most once: either by the auto-cleanup timer\n * armed when the stream settles or by the caller's explicit cleanup().\n */\nexport interface RunCleanup {\n /** Whether the segment's state has been released. */\n readonly done: boolean;\n /** Cancel a pending timer and release now, unless already released. */\n run(): void;\n /** Arm the auto-cleanup timer, unless one is armed or already released. */\n schedule(): void;\n}\n\nexport interface CreateRunCleanupOptions {\n /** Arms the timer, e.g. the stream bus's cleanup timeout. `undefined` disables it. */\n scheduleTimer: (cleanup: () => void) => CleanupTimer | undefined;\n /** Releases the segment's state. Marked released only once it returns. */\n release: () => void;\n /** What the timer releases when it differs from {@link release}. */\n releaseOnTimer?: () => void;\n}\n\nexport function createRunCleanup({ scheduleTimer, release, releaseOnTimer }: CreateRunCleanupOptions): RunCleanup {\n let done = false;\n let timer: CleanupTimer | null = null;\n\n const run = () => {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (done) return;\n release();\n done = true;\n };\n\n const onTimer = releaseOnTimer\n ? () => {\n if (done) return;\n releaseOnTimer();\n done = true;\n }\n : run;\n\n return {\n get done() {\n return done;\n },\n run,\n schedule() {\n if (timer || done) return;\n timer = scheduleTimer(onTimer) ?? null;\n },\n };\n}\n","/**\n * Normalize `resumeGenerate` arguments for durable agents.\n *\n * Accepts the `Agent` signature `(resumeData, { runId, ...options })` and the\n * deprecated durable-only signature `(runId, resumeData, options?)`.\n */\nexport function normalizeResumeGenerateArgs<TOptions extends Record<string, any>>(\n args: unknown[],\n): { runId: string; resumeData: unknown; options: TOptions } {\n const [first, second, third] = args;\n const secondRunId =\n second && typeof second === 'object' && typeof (second as { runId?: unknown }).runId === 'string'\n ? (second as { runId: string }).runId\n : undefined;\n\n if (secondRunId !== undefined && args.length <= 2) {\n if (typeof first === 'string') {\n throw new Error(\n 'resumeGenerate received a string as the first argument and an object with runId as the second, which matches both call forms. ' +\n 'Use resumeGenerate(resumeData, { runId }) with non-string resume data, or pass the deprecated form with an explicit options argument: resumeGenerate(runId, resumeData, {}).',\n );\n }\n const { runId: _runId, ...options } = second as { runId: string } & TOptions;\n return { runId: secondRunId, resumeData: first, options: options as unknown as TOptions };\n }\n\n if (typeof first === 'string') {\n return { runId: first, resumeData: second, options: (third ?? {}) as TOptions };\n }\n\n throw new Error('resumeGenerate requires a runId: call resumeGenerate(resumeData, { runId, ...options })');\n}\n","import type { MastraServerCache } from '../../cache/base';\nimport { MastraError, ErrorDomain, ErrorCategory, getErrorFromUnknown } from '../../error';\nimport { withAck } from '../../events/acking-callback';\nimport type { PubSub } from '../../events/pubsub';\nimport { validateModelTimeoutSettings } from '../../llm/model/model-settings';\nimport type { MastraModelConfig } from '../../llm/model/shared.types';\nimport type { IMastraLogger } from '../../logger';\nimport { LOCAL_MODEL_REQUEST_KEY } from '../../loop/run-scope-keys';\nimport {\n getRunStreamSlot,\n getScopeStreamSlot,\n untilIdleHandlesBackgroundTask,\n} from '../../loop/shared/stream-until-idle-helpers';\nimport { TOOL_ABORT_GRACE_MS, TOOL_SETTLE_MARGIN_MS } from '../../loop/shared/tool-abort-grace';\nimport {\n createTimeoutAbortSignal,\n DEADLINE_SAVE_CLAIM_HOLD_MS,\n DEADLINE_SAVE_WAIT_MS,\n isMastraTimeoutError,\n settledOrElapsed,\n} from '../../loop/timeout';\nimport { withDefaultToolCallConcurrencyLimit } from '../../loop/workflows/agentic-execution/tool-call-concurrency';\nimport type { Mastra } from '../../mastra';\nimport { createRunScope } from '../../mastra/run-scope';\nimport { DEFAULT_RESTART_CONCURRENCY, runWithConcurrency } from '../../mastra/run-with-concurrency';\nimport type { MemoryConfig } from '../../memory';\nimport {\n createObservabilityContext,\n getOrCreateSpan,\n getResumeTracingContext,\n SpanType,\n EntityType,\n} from '../../observability';\nimport type { AIModelGenerationSpan, ExportedSpan, Span } from '../../observability';\nimport {\n MASTRA_RESOURCE_ID_KEY,\n MASTRA_SCOPES_KEY,\n MASTRA_THREAD_ID_KEY,\n RequestContext,\n withoutLiveRequestKeys,\n} from '../../request-context';\nimport type { DeclaredAgentSchedule } from '../../schedules/define';\nimport type { MemoryStorage, WorkflowsStorage } from '../../storage';\nimport { runOutsideRunFenceScope } from '../../storage/run-fencing';\nimport type { FullOutput, MastraModelOutput } from '../../stream/base/output';\nimport type {\n ChunkType,\n MastraOnFinishCallback,\n MastraStreamTransformOptions,\n ToolCallChunk,\n} from '../../stream/types';\nimport { ChunkFrom } from '../../stream/types';\nimport type { CoreTool } from '../../tools/types';\nimport type { DynamicArgument } from '../../types';\nimport { deepMerge, rebindProcessorTools } from '../../utils';\nimport type { ShouldPersistSnapshotFn, 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 { modelSpanAttributes } from '../model-span-attributes';\nimport { whenRunStepsSettle } from '../run-lease-fence';\nimport { SaveQueueManager } from '../save-queue';\nimport type { AgentScopesSnapshot } from '../scopes';\nimport { applyResolvedAgentScopes, incomingAgentScopes, resolveAgentScopes, restoreRunAgentScopes } from '../scopes';\nimport type { PendingSignalListener, AgentSignalInput } from '../signals';\nimport type { AgentStreamBus } from '../streams/bus';\nimport { replayResponseMessages, withRebuiltResponseMessages } from '../streams/response-messages';\nimport type { ResponseMessagesReplay } from '../streams/response-messages';\nimport { durableReplayOwnerKey, readAgentRunRecord, readDurableReplayOwner } from '../streams/run-records';\nimport type { AgentRunRecord } from '../streams/run-records';\nimport type { AgentStreamsConfig } from '../streams/types';\nimport type { AgentStreamStepFinishPayload } from '../streams/wire';\nimport { AgentThreadLeaseConflictError, agentThreadStreamRuntime } from '../thread-stream-runtime';\nimport type { AgentThreadRunRegistration } from '../thread-stream-runtime';\nimport type { AgentAbortThreadOptions, AgentDurableOption, AgentModelManagerConfig, ToolsInput } from '../types';\nimport { isDurableAgentLike } from '../types';\nimport { resolveThreadIdFromArgs } from '../utils';\n\nimport { publishAbortRequest, requestAcknowledgedAbort } from './abort-transport';\nimport {\n AGENT_STREAM_TOPIC,\n AgentStreamEventTypes,\n DURABLE_STOP_WHEN_ERROR_ID,\n DurableStepIds,\n RECOVER_ALREADY_IN_PROGRESS_ERROR_ID,\n RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID,\n RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID,\n RECOVER_RUN_SUSPENDED_ERROR_ID,\n RECOVER_RUN_NOT_ACTIVE_ERROR_ID,\n markErrorForStreamRejection,\n shouldRejectStream,\n} from './constants';\nimport { runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle } from './durable-stream-until-idle';\nimport { DurableExecutionEngine } from './execution-engine';\nimport {\n EXECUTION_ABANDONED_ERROR_ID,\n EXECUTION_UNVERIFIED_ERROR_ID,\n DurableExecutionFenceError,\n ExecutionFence,\n executionLeaseKey,\n fencePubSub,\n readRunGeneration,\n RECOVER_RUN_ACTIVE_LOCALLY_ERROR_ID,\n resolveLeaseProvider,\n RUN_ACTIVE_ERROR_ID,\n setExecutionClaim,\n supportsRunFencing,\n} from './execution-fence';\nimport type { UntrackedRunLiveness } from './execution-fence';\nimport { getExecutionStreamOwner } from './execution-stream-publisher';\nimport { detachFullStreamOnEnd } from './observe-full-stream';\nimport { persistDurableRunInput } from './persist-run-input';\nimport { prepareForDurableExecution } from './preparation';\nimport type { PreparationOptions, PreparationResult } from './preparation';\nimport { createRunAbortController } from './run-abort';\nimport { createRunCleanup } from './run-cleanup';\nimport { recordRunSavedMessages } from './run-message-refs';\nimport {\n ExtendedRunRegistry,\n deleteRunRegistryEntry,\n endRunSpansWithError,\n getRunRegistryEntry,\n globalRunRegistry,\n markResumeInFlight,\n} from './run-registry';\nimport {\n createDurableAgentStream,\n createRunGenerationFilter,\n createSupersededEventFilter,\n emitChunkEvent,\n emitErrorEvent,\n emitFinishEvent,\n emitAbortEvent,\n emitOwnershipClaimedEvent,\n} from './stream-adapter';\nimport type {\n DurableAgentStreamOptions as DurableStreamAdapterOptions,\n DurableAgentStreamResult as DurableStreamAdapterResult,\n} from './stream-adapter';\nimport { toLiveStructuredOutputSchema } from './structured-output-null-transform';\nimport type {\n AgentAbortEventData,\n AgentChunkEventData,\n AgentStreamEvent,\n AgentStepFinishEventData,\n DurableAgentStepFinishResult,\n AgentSuspendedEventData,\n DurableAgenticWorkflowInput,\n DurableToolCallInput,\n RegistryModelListEntry,\n RunRegistryEntry,\n SerializableModelListEntry,\n} from './types';\nimport { DurableProcessorRebuildError } from './utils/resolve-runtime';\nimport { restoreCompletionPolicy } from './utils/restore-completion';\nimport { normalizeResumeGenerateArgs } from './utils/resume-generate-args';\nimport type { createDurableAgenticWorkflow } from './workflows';\nimport { MAP_FINAL_OUTPUT_STEP_ID } from './workflows/durable-loop-builder';\nimport { deadlineMessageListState, runDurableDeadlineOutputPass } from './workflows/finalize-run';\nimport { readAccumulatedSteps } from './workflows/shared/accumulated-steps';\nimport { hydrateMessageListState, loadMessageListStateForResume } from './workflows/shared/message-list-state';\n\nfunction createLocalRequestReader(runId: string, entry: RunRegistryEntry, mastra: Mastra | undefined) {\n const scope = (entry.runScope ??= createRunScope());\n scope.delete(LOCAL_MODEL_REQUEST_KEY);\n const fence = entry.executionFence;\n return () => {\n const current = getRunRegistryEntry(runId, mastra);\n if (current?.runScope !== scope || current.executionFence !== fence || fence?.isLost()) return undefined;\n return scope.get(LOCAL_MODEL_REQUEST_KEY);\n };\n}\n\nconst RESOLVED_EXECUTION_OPTIONS = Symbol('mastra.durable.resolvedExecutionOptions');\nconst RESOLVED_DEFAULT_OPTIONS = Symbol('mastra.durable.resolvedDefaultOptions');\n/** Marks `prepare()` options whose scopes the caller applies itself (a resume rebuilt from storage). */\nconst SCOPES_ALREADY_APPLIED = Symbol('mastra.durable.scopesAlreadyApplied');\n/** Carries the persisted spans a resume rebuilt from storage reattaches to into `prepare()`. */\nconst RESUMED_SPAN_DATA = Symbol('mastra.durable.resumedSpanData');\n/** Recoveries in progress in this process, keyed by agent and run. */\nconst localRecoveryClaims = new Map<string, string>();\nconst RECOVER_SHUTDOWN_ERROR_ID = 'DURABLE_AGENT_RECOVER_SHUTDOWN';\nconst OBSERVED_MESSAGE_LIST_REFRESH_TIMEOUT_MS = 5_000;\n\n/**\n * Reserved request-context keys win over `memory` options, matching the base Agent: server\n * middleware sets them from the authenticated identity so a request body cannot route memory\n * to another user's thread or resource.\n */\nexport function applyReservedMemoryContextKeys<T extends { requestContext?: RequestContext; memory?: any }>(\n options: T | undefined,\n): T | undefined {\n const requestContext = options?.requestContext;\n if (!options || !requestContext) return options;\n const threadId = requestContext.get(MASTRA_THREAD_ID_KEY) as string | undefined;\n const resourceId = requestContext.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;\n if (!threadId && !resourceId) return options;\n const memory = { ...(options.memory ?? {}) };\n if (threadId) memory.thread = resolveThreadIdFromArgs({ memory, overrideId: threadId });\n if (resourceId) memory.resource = resourceId;\n return { ...options, memory };\n}\n\nconst TRANSIENT_RECOVERY_RETRY_DELAY_MS = 30_000;\nconst TRANSIENT_RECOVERY_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ESOCKETTIMEDOUT',\n 'LOADING',\n]);\n\nfunction isTransientRecoveryError(error: unknown): boolean {\n const seen = new Set<object>();\n let transient = false;\n while (typeof error === 'object' && error !== null && !seen.has(error)) {\n seen.add(error);\n if ('name' in error && error.name === 'AbortError') return false;\n if ('code' in error && typeof error.code === 'string' && TRANSIENT_RECOVERY_ERROR_CODES.has(error.code)) {\n transient = true;\n }\n if ('message' in error && typeof error.message === 'string' && /^LOADING(?:\\s|$)/.test(error.message)) {\n transient = true;\n }\n error = 'cause' in error ? error.cause : undefined;\n }\n return transient;\n}\n\n/** Why `recover()` should be deferred, or `undefined` for a permanent failure. */\nfunction recoverySkip(error: unknown): Pick<DurableAgentRecoveredRun, 'reason' | 'retryAt'> | undefined {\n const { id, details } = (error ?? {}) as { id?: unknown; details?: { retryAt?: unknown } };\n switch (id) {\n case RUN_ACTIVE_ERROR_ID:\n return typeof details?.retryAt === 'number'\n ? { reason: 'run-active', retryAt: details.retryAt }\n : { reason: 'run-active' };\n case RECOVER_RUN_ACTIVE_LOCALLY_ERROR_ID:\n return { reason: 'run-active-locally' };\n case RECOVER_ALREADY_IN_PROGRESS_ERROR_ID:\n return { reason: 'already-in-progress' };\n default:\n return isTransientRecoveryError(error)\n ? { reason: 'transient-error', retryAt: Date.now() + TRANSIENT_RECOVERY_RETRY_DELAY_MS }\n : undefined;\n }\n}\n\n/** Whether a failed owned recovery should terminate observers of the run. */\nfunction shouldReportRecoveryFailure(error: unknown): boolean {\n const errorId = (error as { id?: unknown })?.id;\n return (\n errorId !== RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID &&\n errorId !== RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID &&\n errorId !== RECOVER_RUN_SUSPENDED_ERROR_ID &&\n errorId !== RECOVER_RUN_NOT_ACTIVE_ERROR_ID &&\n errorId !== RECOVER_SHUTDOWN_ERROR_ID\n );\n}\n\ninterface RehydratedRecoveryState {\n requestContext: RequestContext;\n threadId?: string;\n resourceId?: string;\n messageList: MessageList;\n recoverAgentSpan?: Span<SpanType.AGENT_RUN>;\n recoverModelSpan?: AIModelGenerationSpan;\n registryEntry: any;\n}\n\n/**\n * Whether a crashed run's persisted AGENT_RUN/MODEL_GENERATION spans were\n * already ended: map-final-output ends them on completion, and a suspension\n * ends them as `suspended` (a recorded `resumedAt` means one happened). The\n * spans of a segment after a resume live only in the lost process.\n */\nfunction originalSpansEndedBeforeCrash(snapshot: WorkflowRunState): boolean {\n const context = snapshot.context as Record<string, { status?: string; resumedAt?: number } | undefined> | undefined;\n if (context?.[MAP_FINAL_OUTPUT_STEP_ID]?.status === 'success') return true;\n return Object.values(context ?? {}).some(result => result?.resumedAt != null);\n}\n\n/**\n * Bind live fallback model instances to the persisted ids that llm-execution\n * looks them up by (#22594).\n *\n * Identity first: explicit ids are stable across resolutions, so an exact-id\n * match is definitive regardless of resolver ordering. Position is only\n * trusted among the leftover entries on both sides — regenerated-uuid ids,\n * which can never match a persisted id — and only when those residues line up\n * 1:1. Anything still unbound degrades to config-based resolution in the\n * llm-execution step. (A renamed explicit id is indistinguishable from a\n * fresh uuid and lands in the positional residue — an inherent limit of the\n * persisted contract.)\n */\ninterface RebindModelListResult {\n modelList: RegistryModelListEntry[] | undefined;\n boundById: number;\n boundByPosition: number;\n unbound: number;\n}\n\nfunction rebindRecoveredModelList(\n persisted: SerializableModelListEntry[],\n enabledLive: AgentModelManagerConfig[],\n): RebindModelListResult {\n // Phase 1: bind by identity. Explicit ids are stable across resolutions, so\n // an exact match is definitive regardless of resolver order. Each live entry\n // binds at most once (first unused occurrence wins for duplicate ids).\n const pool = [...enabledLive];\n const bound = persisted.map(entry => {\n const i = pool.findIndex(live => live.id === entry.id);\n return i === -1 ? undefined : pool.splice(i, 1)[0];\n });\n const boundById = bound.filter(Boolean).length;\n\n // Phase 2: the leftovers on both sides carry regenerated uuids that can\n // never match, so position is the only signal left. Zip them — but only\n // when they pair 1:1; anything else risks mis-binding and stays unbound.\n if (persisted.length - boundById === pool.length) {\n for (let i = 0; i < bound.length; i++) {\n bound[i] ??= pool.shift();\n }\n }\n\n // Emit in persisted order: the persisted id wins (llm-execution looks live\n // models up by it), everything else comes from the bound live entry — same\n // field mapping as preparation.ts.\n const modelList: RegistryModelListEntry[] = [];\n persisted.forEach((entry, i) => {\n const live = bound[i];\n if (live) {\n modelList.push({\n id: entry.id,\n model: live.model,\n maxRetries: live.maxRetries ?? 0,\n enabled: true,\n headers: live.headers,\n });\n }\n });\n\n return {\n modelList: modelList.length ? modelList : undefined,\n boundById,\n boundByPosition: modelList.length - boundById,\n unbound: persisted.length - modelList.length,\n };\n}\n\n/**\n * How many candidate `running` rows `listActiveRuns()` fetches from storage\n * per batch. Bounds peak memory to one batch of hydrated snapshots instead of\n * every matching row's snapshot at once (#21501).\n */\nconst LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE = 100;\n\n/**\n * Options for DurableAgent.stream()\n */\nexport interface DurableAgentStreamOptions<OUTPUT = undefined> {\n /** Signal chunks to hide from this caller's stream. Does not affect generated results. */\n hideSignals?: AgentExecutionOptions<OUTPUT>['hideSignals'];\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 /** Scopes this run acts with. See `AgentExecutionOptions.scopes`. */\n scopes?: string[];\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 * Model to run for this call instead of the agent's model.\n *\n * A model instance can't be persisted, so `recover()` in another process falls back to the\n * agent's own model and logs a warning.\n */\n model?: DynamicArgument<MastraModelConfig>;\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 /** Provider-specific options forwarded to the model (serialized into the durable workflow input) */\n providerOptions?: AgentExecutionOptions<OUTPUT>['providerOptions'];\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, or an object with `limit`/`strategy` */\n toolCallConcurrency?: AgentExecutionOptions<OUTPUT>['toolCallConcurrency'];\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 /** Whether to return detailed scoring data in the response */\n returnScorerData?: boolean;\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: DurableAgentStepFinishResult) => 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 /** Execution-scoped background dispatch policy for delegated agents. */\n backgroundTaskPolicy?: AgentExecutionOptions<OUTPUT>['backgroundTaskPolicy'];\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 /** MCP protocol context forwarded to tools for in-process durable runs. */\n mcp?: AgentExecutionOptions<OUTPUT>['mcp'];\n /**\n * Per-call tool lifecycle hooks. Applied when tools are prepared for this execution.\n * Function hooks are not serialized; a cross-process recovery cannot restore them.\n */\n hooks?: AgentExecutionOptions<OUTPUT>['hooks'];\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 * @internal\n * Detach HTTP observers on reader cancellation instead of aborting execution.\n */\n _detachObserverOnCancel?: 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 * Whether this caller's stream closes when the run suspends (e.g. for tool\n * approval). Defaults to `false`: the stream stays open across suspension so\n * a later resume can continue streaming on this same reader.\n *\n * Set to `true` so `fullStream`, `text`, and `getFullOutput()` resolve at the\n * suspension boundary (matching non-durable `Agent.stream()`), letting callers\n * such as AG-UI or A2A react instead of hanging. Resume the run with\n * `resumeStream()`/`resume()` — those always return a fresh stream.\n */\n closeOnSuspend?: boolean;\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 * Also publishes an abort request over pubsub so the abort reaches the\n * process executing the run, which in a load-balanced deployment is usually\n * not this one. That process flips its own controller and unwinds normally;\n * the workflow run is never hard-cancelled, so the terminal `finish` event\n * still reaches stream consumers. Await the returned promise to know the\n * request has been dispatched; ignoring it keeps the previous\n * fire-and-forget behaviour.\n */\n abort: (reason?: unknown) => Promise<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> extends AgentStreamsConfig {\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 * Maximum steps for the agentic loop.\n * Defaults to the workflow default if not specified.\n */\n maxSteps?: number;\n\n /**\n * Overrides the snapshot-persistence policy for this agent's durable\n * workflows. Returning false for a status skips that snapshot write.\n *\n * The default policy always persists `pending | paused | suspended`\n * (required for human-in-the-loop `resume()`), and persists `running`\n * when the Mastra instance is configured with\n * `recovery: { durableAgents: 'auto' }`, or at each step boundary after\n * `mastra.shutdown()` starts (even with recovery off). `running`\n * checkpoints exist solely so `listActiveRuns()` / `recover()` /\n * `recoverActiveRuns()` can see in-flight runs after a crash or shutdown.\n *\n * Footguns when providing a custom predicate:\n * - Excluding `paused` / `suspended` breaks human-in-the-loop resume.\n * - Excluding `running` makes the agent invisible to crash recovery.\n * A guardrail warning is logged for both cases (detected by probing the\n * predicate with an empty `stepResults`, so predicates that read\n * `stepResults` may probe inaccurately — the warning is best-effort).\n *\n * EventedAgent and InngestAgent own their persistence policy and ignore\n * this option with a warning.\n */\n shouldPersistSnapshot?: ShouldPersistSnapshotFn;\n\n /**\n * How this agent's new runs are stored. `1` rewrites one snapshot per run\n * on every write. `2` stores a run header plus per-step entries, and each\n * write sends only what changed.\n *\n * Where the storage adapter doesn't support version 2, new runs are stored\n * as version 1 and a warning is logged. Runs keep the version they were\n * created with: a run resumed after this option changes continues in its\n * stored version.\n *\n * @default 1\n * @experimental\n */\n storageVersion?: 1 | 2;\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; `skipped` means the run was not orphaned,\n * recovery hit a transient error, its recovery wait timed out, or recovery was interrupted by shutdown.\n */\nexport interface DurableAgentRecoveredRun {\n runId: string;\n status: 'success' | 'failed' | 'skipped';\n /** Set when `status` is `failed`. */\n error?: Error;\n /**\n * Set when `status` is `skipped`:\n * - `run-active`: another execution, possibly in another process, is live.\n * Check again at `retryAt`.\n * - `run-active-locally`: this process is executing the run.\n * - `already-in-progress`: this process is already recovering the run.\n * - `transient-error`: recovery hit a transient infrastructure error. Check again at `retryAt`.\n * - `recovery-timeout`: the attempt is still pending or its 30-second wait expired. Check again at `retryAt`.\n */\n reason?: 'run-active' | 'run-active-locally' | 'already-in-progress' | 'transient-error' | 'recovery-timeout';\n /** Epoch ms to check again: claim expiry for `run-active`, or a retry delay for `transient-error` / `recovery-timeout`. */\n retryAt?: number;\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: DurableAgentStepFinishResult) => 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 is aborted */\n onAbort?: (data: AgentAbortEventData) => void | Promise<void>;\n /** Callback when the recovered run suspends again */\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n /**\n * Close the recovered stream once the run suspends (e.g. awaiting tool\n * approval) so callers can hand off to `resume()`. Defaults to `false`.\n */\n closeOnSuspend?: boolean;\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 * Take the run over even while another execution is live. The other\n * execution loses the run and stops; its writes are rejected when the\n * workflows store supports run fencing. Without `force`, `recover()` throws\n * `DURABLE_AGENT_RUN_ACTIVE` for a live run.\n */\n force?: boolean;\n}\n\n/** The most recent transcript in a snapshot: workflow state, else the last step output carrying one. */\nfunction latestMessageListState(snapshot: {\n value?: Record<string, any>;\n state?: Record<string, any>;\n context?: Record<string, any>;\n}): unknown {\n // Evented checkpoints keep the latest setState under context.__state;\n // value can still contain the transcript from the start of the iteration.\n if (snapshot.context?.__state?.messageListState) return snapshot.context.__state.messageListState;\n // The default engine persists workflow state under `value`.\n if (snapshot.value?.messageListState) return snapshot.value.messageListState;\n if (snapshot.state?.messageListState) return snapshot.state.messageListState;\n let latest: { at: number; value: unknown } | undefined;\n for (const step of Object.values(snapshot.context ?? {})) {\n const value = step?.output?.messageListState;\n const at = step?.endedAt ?? step?.startedAt ?? 0;\n if (value && (!latest || at >= latest.at)) latest = { at, value };\n }\n return latest?.value;\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 #beginSegment(runId: string): symbol {\n const segment = Symbol(runId);\n this.#segmentOwner.set(runId, segment);\n return segment;\n }\n\n #releaseSegment(runId: string, segment: symbol, entry: RunRegistryEntry): boolean {\n if (this.#segmentOwner.get(runId) !== segment) return false;\n this.#segmentOwner.delete(runId);\n if (this.#runRegistry.get(runId) === entry) this.#runRegistry.cleanup(runId);\n return true;\n }\n\n #hasRecoveryAttempt(runId: string): boolean {\n return this.#recoveryAttempts.has(runId);\n }\n\n #startRecoveryAttempt<T>(runId: string, recover: () => Promise<T>): Promise<T> {\n // Defer execution until the map is populated, including synchronous re-entrant callers.\n const attempt = Promise.resolve().then(recover);\n this.#recoveryAttempts.set(runId, attempt);\n const removeAttempt = () => {\n if (this.#recoveryAttempts.get(runId) === attempt) this.#recoveryAttempts.delete(runId);\n };\n void attempt.then(removeAttempt, removeAttempt);\n return attempt;\n }\n\n #executionEngine?: DurableExecutionEngine;\n\n /** @internal One execution owner per Agent, initialized without starting a workflow. */\n protected get executionEngine(): DurableExecutionEngine {\n return (this.#executionEngine ??= this.createExecutionEngine(this.#mastra));\n }\n\n /** @internal Subclasses supply their default engine without changing workflow fallback policy. */\n protected createExecutionEngine(mastra?: Mastra): DurableExecutionEngine {\n return new DurableExecutionEngine(this.id, mastra);\n }\n\n /** The wrapped agent */\n readonly #wrappedAgent: Agent<TAgentId, TTools, TOutput>;\n readonly #streamConfig: AgentStreamsConfig;\n #wrapperStreamBus?: AgentStreamBus;\n\n /** Registry for per-run non-serializable state */\n readonly #runRegistry: ExtendedRunRegistry;\n readonly #recoveryAttempts = new Map<string, Promise<unknown>>();\n\n /** Maximum steps for the agentic loop */\n readonly #maxSteps?: number;\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 /** The stream segment (stream() or resume()) that currently owns each run id's shared state. */\n readonly #segmentOwner = new Map<string, symbol>();\n #timedOutExecutions = new WeakSet<ExecutionFence>();\n /**\n * Accepted input of stream()/generate() executions. A total deadline that\n * settles the execution saves the turn from it as a terminal write.\n */\n #runInputs = new WeakMap<ExecutionFence, DurableAgenticWorkflowInput>();\n /**\n * Registry entries of recovered executions whose memory is fenced but which are not registered yet,\n * so a total deadline in that window still saves the turn.\n */\n #recoveredEntries = new WeakMap<ExecutionFence, RunRegistryEntry>();\n\n /**\n * User-supplied snapshot-persistence policy\n * (see DurableAgentConfig.shouldPersistSnapshot). Protected so subclasses\n * that pin their own policy (EventedAgent) can detect and warn when set.\n */\n protected readonly userShouldPersistSnapshot: ShouldPersistSnapshotFn | undefined;\n\n /** Storage version for new runs (see DurableAgentConfig.storageVersion) */\n #storageVersion: 1 | 2;\n\n /**\n * Create a new DurableAgent that wraps an existing Agent\n */\n constructor(config: DurableAgentConfig<TAgentId, TTools, TOutput>) {\n const {\n agent,\n id: idOverride,\n name: nameOverride,\n pubsub,\n cache,\n maxSteps,\n cleanupTimeoutMs,\n shouldCache,\n shouldPersistSnapshot,\n storageVersion,\n } = 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 // Preserve dynamic model resolution until a request context is available.\n model: ({ requestContext }) => agent.getModel({ requestContext }),\n notifications: agent.__getNotificationConfig(),\n });\n\n this.#wrappedAgent = agent;\n this.#runRegistry = new ExtendedRunRegistry();\n this.#maxSteps = maxSteps;\n this.#streamConfig = { pubsub, cache, cleanupTimeoutMs, shouldCache };\n this.userShouldPersistSnapshot = shouldPersistSnapshot;\n this.#storageVersion = storageVersion ?? 1;\n\n // Keep processor access on the wrapped agent, but dispatch through this wrapper.\n this.#wrappedAgent.getChannels()?.__setDispatchAgent(this);\n }\n\n /** @internal Read one request-context value captured in a suspended durable run snapshot. */\n override async __getSuspendedRunRequestContextValue({\n runId,\n key,\n }: {\n runId: string;\n key: string;\n }): Promise<unknown> {\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}\" __getSuspendedRunRequestContextValue() 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: `DurableAgent \"${this.name}\" __getSuspendedRunRequestContextValue() requires persistent storage to load the run snapshot.`,\n details: { agentName: this.name, runId },\n });\n }\n\n const persisted = await workflowsStore.getWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_LOOP,\n });\n if (!persisted) return undefined;\n const snapshot: WorkflowRunState =\n typeof persisted.snapshot === 'string' ? JSON.parse(persisted.snapshot) : persisted.snapshot;\n const workflowInput = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (workflowInput?.__workflowKind !== 'durable-agent' || workflowInput.agentId !== this.id) return undefined;\n return workflowInput.requestContextEntries?.[key];\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 return this.__getStreamBus().forRun(this.__usesSharedRunLog()).cache;\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 return this.__getStreamBus().forRun(this.__usesSharedRunLog()).pubsub;\n }\n\n /** Durable runs always publish on their stream topic. */\n override hasResumableStreams(): boolean {\n return true;\n }\n\n override __usesSharedRunLog(): boolean {\n return !!this.#mastra && this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger) === 'evented';\n }\n\n /** Durable execution uses its lifecycle publisher, not the plain Agent entry point. @internal */\n protected override __ownsPlainStreamPublisher(): boolean {\n return false;\n }\n\n /** Kept `false`, the value this getter has always reported for durable agents. */\n override get durable(): AgentDurableOption | undefined {\n return false;\n }\n\n /** @internal */\n override __getStreamBus(): AgentStreamBus {\n const bus = this.#wrappedAgent.__getStreamBus(true)!;\n if (!Object.values(this.#streamConfig).some(value => value !== undefined)) return bus;\n return (this.#wrapperStreamBus ??= bus.withConfig(this.#streamConfig));\n }\n\n /**\n * Owner of a run this process still tracks (until its auto-cleanup clears\n * the replay history), or undefined.\n * @internal\n */\n override __getRunOwner(runId: string): { resourceId?: string; threadId?: string } | undefined {\n if (!this.#runRegistry.has(runId)) return undefined;\n return { ...this.#runRegistry.getMemoryInfo(runId) };\n }\n\n override async __getRunRecord(runId: string): Promise<AgentRunRecord | undefined> {\n const bus = this.__getStreamBus();\n return readAgentRunRecord(\n bus.getRunRecordCache(this.__usesSharedRunLog()),\n this.id,\n runId,\n durableReplayOwnerKey(this.id, runId),\n );\n }\n\n /**\n * Owner of a run whose replay history is still retained: the local owner,\n * else the shared record, including legacy records without stream status.\n * Undefined once the run's topic is cleared. Only used for replay access.\n * Rejects when the shared cache cannot be read.\n * @internal\n */\n async __getReplayOwner(runId: string): Promise<{ resourceId?: string; threadId?: string } | undefined> {\n const local = this.__getRunOwner(runId);\n if (local) return local;\n const shared = await readDurableReplayOwner(\n this.__getStreamBus().getRunRecordCache(this.__usesSharedRunLog()),\n this.id,\n runId,\n );\n if (!shared) return undefined;\n return { resourceId: shared.resourceId, threadId: shared.threadId };\n }\n\n /**\n * Share the owner of a run this process registered, so other replicas can\n * authorize replay of its history. Lives until {@link #clearPubsubTopic}. A\n * failed write only leaves other replicas refusing to replay the run.\n */\n async #attachStreamPublisher(runId: string, owner: { resourceId?: string; threadId?: string }): Promise<void> {\n const claim = getRunRegistryEntry(runId, this.#mastra)?.executionFence?.claim;\n const publisher = getExecutionStreamOwner({\n runId,\n agentId: this.id,\n mastra: this.#mastra,\n agent: this,\n claim: claim && { ...claim, ...owner },\n });\n await publisher?.ready.catch(error => {\n this.logger.warn(`[DurableAgent:${this.id}] run ${runId}: failed to attach its stream publisher`, { error });\n });\n }\n\n #unverifiedReaderFences = new WeakSet<ExecutionFence>();\n\n #scheduleReaderCleanup(executionFence: ExecutionFence, cleanup: () => void) {\n if (this.#unverifiedReaderFences.has(executionFence)) return;\n return this.__getStreamBus().scheduleCleanup(() => {\n if (!this.#unverifiedReaderFences.has(executionFence)) cleanup();\n });\n }\n\n #owningReaderTerminal(runId: string, executionFence: ExecutionFence) {\n const publisher = getExecutionStreamOwner({\n runId,\n agentId: this.id,\n mastra: this.#mastra,\n agent: this,\n claim: executionFence.claim,\n });\n return async (status: 'suspended' | 'finished', generation: number | undefined) => {\n if (generation !== executionFence.generation || !executionFence.ownsRunTopics()) return;\n const currentFence = getRunRegistryEntry(runId, this.#mastra)?.executionFence;\n // A continuation can finish an earlier reader after resume replaced its execution.\n if (currentFence && currentFence !== executionFence) return;\n try {\n await publisher?.settle(status);\n } catch (error) {\n if (!(error instanceof DurableExecutionFenceError) || error.id !== EXECUTION_UNVERIFIED_ERROR_ID) throw error;\n // The local reader still finishes, but cannot mutate shared lifecycle state.\n this.#unverifiedReaderFences.add(executionFence);\n this.logger.warn(`[DurableAgent:${this.id}] run ${runId}: terminal ownership could not be verified`, { error });\n }\n };\n }\n\n /**\n * Mark `runId` as being recovered by this process, and return the release.\n * A second `recover()` of the same run in this process fails fast instead\n * of contending for the claim. Across processes the run's execution claim\n * picks the winner.\n */\n #claimLocalRecovery(runId: string): () => void {\n const key = JSON.stringify([this.id, runId]);\n if (localRecoveryClaims.has(key)) {\n throw new MastraError({\n id: RECOVER_ALREADY_IN_PROGRESS_ERROR_ID,\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" recover(${runId}): this process is already recovering this run.`,\n details: { agentName: this.name, runId },\n });\n }\n const token = crypto.randomUUID();\n localRecoveryClaims.set(key, token);\n return () => {\n if (localRecoveryClaims.get(key) === token) localRecoveryClaims.delete(key);\n };\n }\n\n /**\n * Liveness of a run without an execution claim, i.e. one started before runs\n * were claimed: a live run keeps renewing its thread's lease. A run without a\n * thread has no signal and counts as not live.\n */\n #untrackedRunLiveness(runId: string, workflowInput: DurableAgenticWorkflowInput): UntrackedRunLiveness | undefined {\n const memoryInfo = (\n workflowInput.messageListState as { memoryInfo?: { threadId?: string; resourceId?: string } } | undefined\n )?.memoryInfo;\n const threadId = workflowInput.state?.threadId ?? memoryInfo?.threadId;\n if (!threadId) return undefined;\n const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;\n return {\n isLive: () => agentThreadStreamRuntime.isRunHoldingThreadLease(this.getPubSub(), runId, threadId, resourceId),\n ttlMs: agentThreadStreamRuntime.threadLeaseTtlMs,\n };\n }\n\n /**\n * Whether the run's persisted snapshot is still `running`. Without storage,\n * or with an unreadable snapshot, answers true so `recover()` reports why.\n */\n async #isRunningSnapshot(runId: string): Promise<boolean> {\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n if (!workflowsStore) return true;\n const persisted = await workflowsStore.getWorkflowRunById({ runId, workflowName: DurableStepIds.AGENTIC_LOOP });\n if (!persisted) return false;\n if (typeof persisted.snapshot !== 'string') return persisted.snapshot?.status === 'running';\n try {\n return (JSON.parse(persisted.snapshot) as WorkflowRunState)?.status === 'running';\n } catch {\n return true;\n }\n }\n\n /**\n * The transcript as of the crash. The loop snapshot's input only has the one the run\n * started with; later steps keep it in the nested execution workflow's state.\n */\n async #loadLatestMessageListState(\n workflowsStore: WorkflowsStorage,\n runId: string,\n fallbackSnapshot: WorkflowRunState,\n ): Promise<Awaited<ReturnType<typeof hydrateMessageListState>> | undefined> {\n let latest: unknown;\n try {\n // Evented iterations have their own run id; the parent records the active one.\n const nestedRunId = fallbackSnapshot.context?.[DurableStepIds.AGENTIC_EXECUTION]?.metadata?.nestedRunId;\n const nested = await workflowsStore.getWorkflowRunById({\n runId: typeof nestedRunId === 'string' ? nestedRunId : runId,\n workflowName: DurableStepIds.AGENTIC_EXECUTION,\n });\n const snapshot = typeof nested?.snapshot === 'string' ? JSON.parse(nested.snapshot) : nested?.snapshot;\n latest = snapshot && latestMessageListState(snapshot);\n } catch {\n // Fall back to the supplied snapshot.\n }\n latest ??= latestMessageListState(fallbackSnapshot);\n if (!latest) return undefined;\n // Messages memory already stores are kept as refs; restore them so callers\n // see the full rows (e.g. ToolSearch results). #loadRecalledMessages has\n // already loaded them, so this normally needs no storage read.\n return hydrateMessageListState(\n { getInitData: () => fallbackSnapshot.context?.input, mastra: this.#mastra },\n latest as Parameters<typeof hydrateMessageListState>[1],\n );\n }\n\n async #loadRecoverableSnapshot(\n workflowsStore: WorkflowsStorage,\n runId: string,\n ): Promise<{ snapshot: WorkflowRunState; workflowInput: DurableAgenticWorkflowInput }> {\n const persisted = await workflowsStore.getWorkflowRunById({\n runId,\n workflowName: DurableStepIds.AGENTIC_LOOP,\n });\n if (!persisted) {\n throw new MastraError({\n id: RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID,\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 if (\n snapshot?.status === 'pending' &&\n snapshot.context != null &&\n typeof snapshot.context === 'object' &&\n !Array.isArray(snapshot.context) &&\n !Object.prototype.hasOwnProperty.call(snapshot.context, 'input')\n ) {\n throw new MastraError({\n id: RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID,\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" recover(${runId}): no restartable checkpoint has been persisted yet. ` +\n `Enable recovery: { durableAgents: 'auto' } or a shouldPersistSnapshot policy that includes ` +\n `\"running\" before starting the run. Even with persistence enabled, recovery is unavailable ` +\n `until the first running checkpoint is saved.`,\n details: { agentName: this.name, runId, snapshotStatus: snapshot.status },\n });\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 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 // Recovery re-drives the run with `restart()`, which the engine only accepts\n // for runs that were active when the process stopped (`running`/`waiting`, or\n // a nested `pending` run) plus the terminal snapshots `_restart` short-circuits\n // (`success`/`failed`/`tripwire`). Every other status would otherwise surface\n // as a single \"This workflow run was not active\" error chunk, asynchronously,\n // long after `recover()` resolved. Reject up front and say what to do instead:\n // a run suspended on a tool call or an approval is continued with `resume()`.\n // Checked again after the claim, since the run may suspend between discovery\n // and the claim.\n const restartable =\n snapshot.status === 'running' ||\n snapshot.status === 'waiting' ||\n snapshot.status === 'success' ||\n snapshot.status === 'failed' ||\n snapshot.status === 'tripwire' ||\n (snapshot.status === 'pending' &&\n snapshot.context != null &&\n Object.prototype.hasOwnProperty.call(snapshot.context, 'input'));\n if (!restartable) {\n throw new MastraError({\n // A suspended run is not orphaned: it waits for resume().\n id: snapshot.status === 'suspended' ? RECOVER_RUN_SUSPENDED_ERROR_ID : RECOVER_RUN_NOT_ACTIVE_ERROR_ID,\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n `DurableAgent \"${this.name}\" recover(${runId}): run status is \"${snapshot.status}\", ` +\n `so the run cannot be recovered. Runs suspended on a tool call or an approval are ` +\n `continued with resume(${runId}, ...), not recover().`,\n details: { agentName: this.name, runId, snapshotStatus: snapshot.status },\n });\n }\n\n return { snapshot, workflowInput };\n }\n\n async #loadSuspendedIteration(\n runId: string,\n ): Promise<{ toolCalls: ToolCallChunk[]; resumedText?: { priorText: string; stepText: string } }> {\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n const outerRun = await workflowsStore?.getWorkflowRunById({ runId, workflowName: DurableStepIds.AGENTIC_LOOP });\n if (!outerRun) return { toolCalls: [] };\n const outerSnapshot: WorkflowRunState =\n typeof outerRun.snapshot === 'string' ? JSON.parse(outerRun.snapshot) : outerRun.snapshot;\n const iteration = outerSnapshot.context?.[DurableStepIds.AGENTIC_EXECUTION];\n const nestedRunId = iteration?.metadata?.nestedRunId ?? runId;\n const persisted = await workflowsStore?.getWorkflowRunById({\n runId: nestedRunId,\n workflowName: DurableStepIds.AGENTIC_EXECUTION,\n });\n if (!persisted) return { toolCalls: [] };\n\n const snapshot =\n typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n const llmStep = snapshot.context?.[DurableStepIds.LLM_EXECUTION];\n if (llmStep?.status !== 'success') return { toolCalls: [] };\n // The step records hold completed iterations (in workflow state, or in the\n // nested input on runs that never seeded them); the LLM output holds the\n // current iteration, which has not reached the accumulator yet.\n const accumulatedSteps: Array<{ text?: string; toolCalls?: DurableToolCallInput[]; finishReason?: string }> =\n readAccumulatedSteps(snapshot.value, snapshot.context.input);\n const toolCalls: DurableToolCallInput[] = [\n ...accumulatedSteps.flatMap(step => step.toolCalls ?? []),\n ...(llmStep.output.toolCalls ?? []),\n ];\n // The text streamed before the suspension belongs to the resumed run's text, as on the\n // plain Agent, which restores it from its own snapshot (#27504).\n const stepText: string = llmStep.output.text ?? '';\n const priorText = accumulatedSteps\n .filter(step => step.finishReason !== 'retry')\n .map(step => step.text ?? '')\n .join('');\n\n const toolCallChunks: ToolCallChunk[] = toolCalls.map(toolCall => ({\n type: 'tool-call',\n runId,\n from: ChunkFrom.AGENT,\n payload: {\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n args: toolCall.args,\n providerMetadata: toolCall.providerMetadata as ToolCallChunk['payload']['providerMetadata'],\n providerExecuted: toolCall.providerExecuted,\n output: toolCall.output,\n },\n }));\n return { toolCalls: toolCallChunks, resumedText: { priorText, stepText } };\n }\n\n /**\n * Loads the recalled messages a persisted run keeps as refs in its transcript\n * before resume() or recover() runs anything. A memory storage failure then\n * rejects the call and leaves the run as it was. Failing in a step instead,\n * after a resumed tool already ran, would end the run.\n */\n async #loadRecalledMessages(runId: string, snapshot?: WorkflowRunState, requestContext?: RequestContext) {\n if (!snapshot) {\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n const persisted = await workflowsStore?.getWorkflowRunById({ runId, workflowName: DurableStepIds.AGENTIC_LOOP });\n snapshot =\n typeof persisted?.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted?.snapshot;\n }\n if (!snapshot) return;\n await loadMessageListStateForResume({\n state: (snapshot.context as Record<string, unknown> | undefined)?.__state ?? snapshot.value,\n getInitData: () => snapshot.context?.input,\n mastra: this.#mastra,\n requestContext,\n });\n }\n\n /**\n * Rebuild and register the stream for a claimed recovery attempt. Rolls back\n * every partial registration and releases the claim if setup fails.\n */\n async #setupRecoveredStream({\n runId,\n workflowInput,\n requestContext,\n threadId,\n resourceId,\n messageList,\n registryEntry,\n options,\n scheduleAutoCleanup,\n executionFence,\n }: {\n runId: string;\n workflowInput: DurableAgenticWorkflowInput;\n requestContext: RequestContext;\n threadId?: string;\n resourceId?: string;\n messageList: MessageList;\n registryEntry: any;\n options?: DurableAgentRecoverOptions<TOutput>;\n scheduleAutoCleanup: () => void;\n executionFence: ExecutionFence;\n }): Promise<{\n stream: DurableStreamAdapterResult<TOutput>;\n threadRegistration?: AgentThreadRunRegistration;\n }> {\n let streamCleanup: (() => void) | undefined;\n let streamOutput: MastraModelOutput<TOutput> | undefined;\n let threadRegistration: AgentThreadRunRegistration | undefined;\n try {\n this.#assertRecoveryActive();\n executionFence.throwIfLost();\n registryEntry.messageList = messageList;\n registryEntry.agentId = this.id;\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n globalRunRegistry.set(runId, registryEntry);\n await this.#attachStreamPublisher(runId, { threadId, resourceId });\n\n // Recovered runs run the agent's default lifecycle callbacks like stream() does, then the\n // caller's. Both run (rather than the caller replacing the default) because\n // recoverActiveRuns() and automatic recovery always pass their own bookkeeping callbacks.\n const defaultOptions = await this.getDefaultOptions({ requestContext });\n const onFinish = async (result: any) => {\n await defaultOptions?.onFinish?.(result);\n await options?.onFinish?.(result);\n };\n const onErrorCallback = async (error: any) => {\n await defaultOptions?.onError?.(error);\n await options?.onError?.(error);\n };\n const onAbortCallback = async (data: any) => {\n await defaultOptions?.onAbort?.(data);\n await options?.onAbort?.(data);\n };\n\n // Persistent backends may retain chunks from the pre-crash segment.\n const recoverOffset = await this.#getPubsubOffset(runId);\n this.#assertRecoveryActive();\n executionFence.throwIfLost();\n const stream = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n minGeneration: executionFence.generation,\n onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),\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,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await onErrorCallback(error);\n scheduleAutoCleanup();\n },\n onAbort: async data => {\n try {\n await onAbortCallback(data);\n } finally {\n scheduleAutoCleanup();\n }\n },\n onSuspended: options?.onSuspended,\n // Close (when requested) on the persisted workflow result in recover(),\n // not on the SUSPENDED event, which can precede a resumable snapshot.\n closeOnSuspend: false,\n messageList,\n structuredOutput: registryEntry.structuredOutput,\n requestContext: registryEntry.requestContext,\n returnScorerData: workflowInput.options?.returnScorerData,\n });\n streamCleanup = stream.cleanup;\n streamOutput = stream.output;\n await this.#raceFenceLoss(stream.ready, executionFence).catch(error => {\n if (this.#timedOutExecutions.has(executionFence)) return stream.ready;\n throw error;\n });\n if (\n (await this.#redeliverDeadlineError(registryEntry, executionFence)) ||\n this.#timedOutExecutions.has(executionFence)\n ) {\n return { stream, threadRegistration };\n }\n this.#assertRecoveryActive();\n\n const recoverStreamOptions: AgentExecutionOptions<TOutput> = {\n runId,\n requestContext,\n ...(threadId\n ? {\n memory: {\n thread: threadId,\n ...(resourceId ? { resource: resourceId } : {}),\n },\n }\n : {}),\n } as AgentExecutionOptions<TOutput>;\n executionFence.throwIfLost();\n threadRegistration = await agentThreadStreamRuntime.registerRun(\n this as unknown as Agent<any, any, any, any>,\n stream.output,\n recoverStreamOptions,\n this.getPubSub(),\n {\n strict: true,\n ...(options?.closeOnSuspend ? {} : { continuation: 'across-suspension' as const }),\n validate: () => {\n this.#assertRecoveryActive();\n executionFence.throwIfLost();\n },\n generation: executionFence.generation,\n ownershipLost: () => executionFence.isLost(),\n stepOwner: () => getRunRegistryEntry(runId, this.#mastra),\n },\n );\n this.#assertRecoveryActive();\n executionFence.throwIfLost();\n return { stream, threadRegistration };\n } catch (error) {\n const settlement = await executionFence.settle(async () => {});\n try {\n // A superseded execution leaves the thread lease to the new owner,\n // which holds it under the same runId.\n await threadRegistration?.rollback({ releaseLease: settlement !== 'superseded' });\n } catch (rollbackError) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] recover(${runId}) failed to roll back thread registration: ${rollbackError}`);\n }\n if (streamOutput) {\n agentThreadStreamRuntime.closeRunContinuation(streamOutput, this.getPubSub());\n }\n streamCleanup?.();\n if (this.#runRegistry.get(runId) === registryEntry) {\n this.#runRegistry.cleanup(runId);\n }\n if (getRunRegistryEntry(runId, this.#mastra) === registryEntry) {\n globalRunRegistry.delete(runId);\n }\n if (settlement !== 'superseded') {\n await this.#reportRecoveryFailure(runId, error, executionFence.generation);\n }\n throw error;\n }\n }\n\n #assertRecoveryActive(): void {\n if (this.#mastra?.__shuttingDown) {\n throw new MastraError({\n id: RECOVER_SHUTDOWN_ERROR_ID,\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n text: 'Durable recovery stopped because Mastra is shutting down',\n });\n }\n }\n\n async #reportRecoveryFailure(runId: string, error: unknown, generation: number | undefined): Promise<boolean> {\n // Late setup can fail after pubsub teardown; preserve the failure outcome without publishing.\n if (this.#mastra?.__shuttingDown || !shouldReportRecoveryFailure(error)) return false;\n const normalizedError = error instanceof Error ? error : new Error(String(error));\n if (normalizedError instanceof AgentThreadLeaseConflictError) {\n return false;\n }\n\n try {\n await this.emitError(runId, normalizedError, generation);\n return true;\n } catch (reportingError) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] recover(${runId}) failed to publish terminal error: ${reportingError}`);\n return false;\n }\n }\n\n /**\n * Settle `operation`, or throw the loss error as soon as the execution loses\n * its claim. A superseded recovery then unwinds even when the work it waits\n * on ignores the abort signal.\n */\n #raceFenceLoss<T>(operation: Promise<T>, executionFence: ExecutionFence): Promise<T> {\n return this.executionEngine.raceFenceLoss(operation, executionFence);\n }\n\n /** Rebuilds process-local recovery state from the persisted durable workflow input. */\n async #rehydrateRecoveryState({\n runId,\n workflowInput,\n abortController,\n executionFence,\n originalSpansEnded,\n latestMessageListState,\n }: {\n runId: string;\n workflowInput: DurableAgenticWorkflowInput;\n abortController: AbortController;\n executionFence: ExecutionFence;\n originalSpansEnded: boolean;\n /** The transcript as of the crash; `workflowInput` only has the one the run started with. */\n latestMessageListState?: unknown;\n }): Promise<RehydratedRecoveryState> {\n const requestContext: RequestContext = workflowInput.requestContextEntries\n ? new RequestContext(Object.entries(workflowInput.requestContextEntries) as Iterable<readonly [string, unknown]>)\n : new RequestContext();\n restoreRunAgentScopes(requestContext);\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\n // `requestContextEntries` contains caller state captured before preparation\n // installed the run's framework-managed memory context. Rebuild that entry\n // from persisted run state so recovery never inherits a caller/parent thread.\n if (threadId && resourceId) {\n requestContext.set('MastraMemory', {\n thread: { id: threadId },\n resourceId,\n memoryConfig: workflowInput.state?.memoryConfig,\n });\n } else {\n requestContext.delete('MastraMemory');\n }\n\n const messageList = new MessageList({ threadId, resourceId });\n try {\n // The persisted input keeps messages memory already stores as refs.\n messageList.deserialize(\n await hydrateMessageListState(\n { getInitData: () => workflowInput, mastra: this.#mastra },\n workflowInput.messageListState,\n ),\n );\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) messageList deserialize skipped: ${error}`);\n }\n\n const wrapped = this.#wrappedAgent as Agent<string, any, TOutput>;\n let model;\n try {\n model = await wrapped.getModel({ requestContext });\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to resolve model during recover(${runId}): ${error}`);\n }\n // A per-call `model` is a live instance and cannot be persisted, so recovery\n // resolves the agent's own model instead. Say so rather than switching silently.\n const persistedModelId = workflowInput.modelConfig?.modelId;\n if (model && persistedModelId && model.modelId !== persistedModelId) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(\n `[DurableAgent] recover(${runId}) continues with the agent's model '${model.modelId}'; the run started with '${persistedModelId}', which cannot be restored.`,\n );\n }\n executionFence.throwIfLost();\n\n // Restore the live fallback model list the run was prepared with (#22594).\n // The persisted (enabled-only, ordered) list is the source of truth for\n // the run's shape; the live resolution is the only source of real model\n // instances. Ids regenerate on every resolution (`toFallbackEntry` assigns\n // `mdl.id ?? randomUUID()`), so live entries must be rebound to the\n // persisted ids that llm-execution looks models up by — identity first,\n // position only for the unidentifiable residue (see\n // rebindRecoveredModelList).\n let modelList: RegistryModelListEntry[] | undefined;\n const persistedModelList = workflowInput.modelList;\n if (persistedModelList?.length) {\n try {\n const liveModelList = await wrapped.getModelList(requestContext);\n const enabledLive = (liveModelList ?? []).filter(entry => entry.enabled !== false);\n const rebound = rebindRecoveredModelList(persistedModelList, enabledLive);\n modelList = rebound.modelList;\n if (rebound.unbound > 0) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(\n `[DurableAgent] recover(${runId}) model list drifted (persisted ${persistedModelList.length} enabled entries, resolved ${enabledLive.length}); ` +\n `bound ${rebound.boundById} by id, ${rebound.boundByPosition} by position; ${rebound.unbound} will resolve from serialized config`,\n );\n }\n } catch (error) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] Failed to resolve model list during recover(${runId}): ${error}`);\n }\n }\n executionFence.throwIfLost();\n\n // Like step-level rehydration, fail recovery rather than run the recovered\n // turn without memory (nothing it produces would be persisted).\n let memory;\n try {\n memory = await wrapped.getMemory({ requestContext });\n } catch (error) {\n this.#mastra\n ?.getLogger?.()\n ?.error?.(`[DurableAgent] Failed to resolve memory during recover(${runId}): ${error}`);\n throw new DurableProcessorRebuildError(this.id, error);\n }\n executionFence.throwIfLost();\n\n // The entry below carries a live model, so resolveRuntimeDependencies trusts\n // it as fully hydrated and never rebuilds tools — they must be restored here.\n let tools: Record<string, CoreTool> = {};\n let workspace;\n try {\n tools = await wrapped.getToolsForExecution({\n runId,\n threadId,\n resourceId,\n requestContext,\n memoryConfig: workflowInput.state?.memoryConfig,\n autoResumeSuspendedTools: workflowInput.options?.autoResumeSuspendedTools,\n clientTools: workflowInput.options?.clientTools as ToolsInput | undefined,\n // Tools a processor (ToolSearch) loaded mid-run are only recorded in the run's transcript (#26437).\n runMessages: latestMessageListState\n ? new MessageList({ threadId, resourceId })\n .deserialize(latestMessageListState as Parameters<MessageList['deserialize']>[0])\n .get.all.db()\n : undefined,\n });\n workspace = await wrapped.getWorkspace({ requestContext });\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) tool resolution failed: ${error}`);\n }\n executionFence.throwIfLost();\n\n const saveQueueManager = memory\n ? new SaveQueueManager({\n logger: this.#mastra?.getLogger?.() as any,\n memory,\n onSaved: recordRunSavedMessages(runId),\n })\n : undefined;\n const backgroundTasksConfig = this.getBackgroundTasksConfig?.();\n const backgroundTaskManager = this.#mastra?.backgroundTaskManager;\n\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 (error) {\n // Running the recovered turn without its processors would silently skip guardrails.\n this.#mastra?.getLogger?.()?.error?.(`[DurableAgent] recover(${runId}) processor resolution failed: ${error}`);\n throw new DurableProcessorRebuildError(this.id, error);\n }\n executionFence.throwIfLost();\n\n const processorStates = new Map<string, any>();\n const origAgentSpanData = workflowInput.agentSpanData as ExportedSpan<SpanType.AGENT_RUN> | undefined;\n const origModelSpanData = workflowInput.modelSpanData as ExportedSpan<SpanType.MODEL_GENERATION> | undefined;\n let recoverAgentSpan: Span<SpanType.AGENT_RUN> | undefined;\n let recoverModelSpan: AIModelGenerationSpan | undefined;\n if (this.#mastra?.observability) {\n // The crashed process never ended the original spans, and stores persist\n // only span-end events, so end them here — otherwise the recovered span\n // below is parented under a root that never lands (or stays RUNNING).\n // Skip when they were already ended: as `suspended` before a resume, or\n // by map-final-output before the crash.\n if (!originalSpansEnded) {\n try {\n const observability = this.#mastra.observability.getSelectedInstance({ requestContext });\n const output = { status: 'interrupted' as const, reason: 'run recovered after its process stopped' };\n if (origModelSpanData)\n observability\n ?.rebuildSpan(origModelSpanData)\n ?.end({ output, outcome: 'interrupted', stopReason: null, stopReasonContext: null });\n if (origAgentSpanData)\n observability\n ?.rebuildSpan(origAgentSpanData)\n ?.end({ output, outcome: 'interrupted', stopReason: null, stopReasonContext: null });\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to end interrupted spans: ${error}`);\n }\n }\n try {\n const persistedHead = persistedModelList?.find(entry => entry.enabled);\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 outcome: null,\n name: `agent run: '${wrapped.id}' (recovered)`,\n entityType: EntityType.AGENT,\n entityId: wrapped.id,\n entityName: wrapped.name,\n // The persisted list is the run's shape: the recovered step tries its\n // first enabled entry first, as the live model rebound to that id, or\n // rebuilt from the serialized config when the resolver no longer returns it.\n attributes: modelSpanAttributes(\n modelList?.find(entry => entry.id === persistedHead?.id)?.model ?? persistedHead?.config ?? model,\n ),\n metadata: {\n runId,\n recovered: true,\n ...(origAgentSpanData?.id ? { recoveredFromSpanId: origAgentSpanData.id } : {}),\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n tracingPolicy: agentTracingPolicy,\n resumeFrom: getResumeTracingContext(origAgentSpanData),\n requestContext,\n mastra: this.#mastra,\n });\n recoverModelSpan = recoverAgentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n outcome: null,\n name: `llm: '${model?.modelId ?? ''}'`,\n attributes: { model: model?.modelId, provider: model?.provider, streaming: true },\n metadata: { runId, recovered: true },\n requestContext,\n });\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open recover span: ${error}`);\n }\n }\n executionFence.throwIfLost();\n\n const restoredCompletion = await restoreCompletionPolicy({\n agent: wrapped,\n persisted: workflowInput.options?.isTaskComplete,\n requestContext,\n runId,\n logger: this.#mastra?.getLogger?.(),\n });\n\n const registryEntry = {\n isTaskComplete: restoredCompletion,\n // Call-time toolset tools died with the original process. Mark the entry\n // as a placeholder so the first step rebuilds tools and fails loudly\n // (DURABLE_AGENT_TOOLSETS_UNAVAILABLE) instead of running without them.\n isPlaceholder: (workflowInput.options?.toolsetToolNames?.length ?? 0) > 0,\n // Restore the original run's flag from the persisted snapshot so a\n // warm resume after recovery keeps returning scoringData without the\n // caller re-passing the option.\n returnScorerData: workflowInput.options?.returnScorerData,\n mastra: this.#mastra,\n // The live model below makes resolveRuntimeDependencies skip its rebuild,\n // so processor hooks only get the agent if it is stored here.\n agent: wrapped,\n model,\n modelList,\n tools,\n workspace,\n memory,\n saveQueueManager,\n requestContext,\n agentSpan: recoverAgentSpan,\n // Same override resume() installs: steps nest under, and terminal\n // end()/error() target, the recovered spans instead of the persisted\n // originals ended above.\n resumeAgentSpan: recoverAgentSpan,\n resumeModelSpan: recoverModelSpan,\n resumeAgentSpanData: recoverAgentSpan?.snapshot?.() ?? recoverAgentSpan?.exportSpan(),\n resumeModelSpanData: recoverModelSpan?.snapshot?.() ?? recoverModelSpan?.exportSpan(),\n // abortController/abortSignal are installed by\n // #installAbortWithTotalTimeout below, with the run-level budget\n // composed in.\n // Restore the run-level execution budget from the persisted snapshot so\n // a recovered session is bounded like the original one (#21724).\n timeoutTotalMs: workflowInput.options?.modelSettings?.timeout?.totalMs,\n // Rebuild the live structured output config from the persisted JSON Schema\n // so the recovered stream still emits `object-result` chunks.\n structuredOutput: workflowInput.options?.structuredOutput?.schema\n ? {\n ...workflowInput.options.structuredOutput,\n schema: toLiveStructuredOutputSchema(\n workflowInput.options.structuredOutput.schema,\n workflowInput.options.structuredOutput.nullToUndefined,\n ),\n }\n : undefined,\n backgroundTaskManager,\n backgroundTasksConfig,\n inputProcessors,\n llmRequestInputProcessors,\n outputProcessors,\n errorProcessors,\n processorStates,\n drainPendingSignals: (scope?: 'pending' | 'pre-run') => wrapped.__getDrainPendingSignals()(runId, scope),\n subscribePendingSignals: (listener: PendingSignalListener) =>\n wrapped.__getSubscribePendingSignals()(runId, listener),\n enqueuePendingSignal: (signalInput: AgentSignalInput) =>\n wrapped.__getEnqueuePendingSignal()({ runId, resourceId, threadId }, signalInput),\n cleanup: () => {},\n };\n this.#installAbortWithTotalTimeout(registryEntry as unknown as RunRegistryEntry, abortController, executionFence);\n // The recovered run's deadline saves the turn as of the crash, until its first step snapshots it.\n this.#runInputs.set(executionFence, {\n ...workflowInput,\n messageListState:\n (latestMessageListState as DurableAgenticWorkflowInput['messageListState'] | undefined) ??\n workflowInput.messageListState,\n });\n\n return {\n requestContext,\n threadId,\n resourceId,\n messageList,\n recoverAgentSpan,\n recoverModelSpan,\n registryEntry,\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 * File-based schedules live on the wrapped agent: `assembleAgentFromFsEntry`\n * attaches them to the inner `Agent` before it is wrapped for durable\n * execution, and `#declaredSchedules` is private to each instance. Without\n * this delegate the wrapper would report none of its own and Mastra would\n * never sync a durable agent's `schedules/` directory.\n */\n public override getDeclaredSchedules(): DeclaredAgentSchedule[] {\n return this.#wrappedAgent.getDeclaredSchedules();\n }\n\n /**\n * Mirrors {@link getDeclaredSchedules} so attaching schedules to an\n * already-wrapped agent lands on the instance the getter reads from.\n */\n public override __setDeclaredSchedules(schedules: DeclaredAgentSchedule[]): void {\n this.#wrappedAgent.__setDeclaredSchedules(schedules);\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.__getStreamBus().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 override __setLogger(logger: IMastraLogger) {\n super.__setLogger(logger);\n this.#wrappedAgent.__setLogger(logger);\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 snapshot?: AgentScopesSnapshot,\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 withDefaultToolCallConcurrencyLimit(defaultOptions ?? {}, options) 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 const scopedOptions = await this.#applyScopes(resolvedOptions, {\n callScopes: options?.scopes,\n defaultScopes: defaultOptions?.scopes,\n snapshot,\n });\n // Preserve the marker when the until-idle wrapper spreads these options.\n Object.defineProperty(scopedOptions, RESOLVED_EXECUTION_OPTIONS, { value: true, enumerable: true });\n Object.defineProperty(scopedOptions, RESOLVED_DEFAULT_OPTIONS, { value: defaultOptions, enumerable: true });\n return scopedOptions;\n }\n\n /**\n * Applies agent scopes to durable execution options. Durable runs resolve their thread and\n * resource from `memory` only, so options are returned unchanged unless the run has scopes.\n */\n async #applyScopes<T extends DurableAgentStreamOptions<TOutput>>(\n options: T,\n {\n callScopes,\n defaultScopes,\n snapshot,\n }: { callScopes?: string[]; defaultScopes?: string[]; snapshot?: AgentScopesSnapshot },\n ): Promise<T> {\n const requestContext = options.requestContext ?? new RequestContext();\n // A resumed run keeps its suspended scopes, so the Agent's configuration is not consulted.\n const incomingScopes = snapshot?.scopes\n ? undefined\n : incomingAgentScopes({ requestContext, callScopes, defaultScopes, mastra: this.#mastra });\n const agentScopes = incomingScopes ? await this.getScopes({ requestContext, scopes: incomingScopes }) : undefined;\n if (!agentScopes?.length && !callScopes?.length && !requestContext.has(MASTRA_SCOPES_KEY) && !snapshot?.scopes) {\n return options;\n }\n const resolved = resolveAgentScopes({\n requestContext,\n agentScopes,\n incomingScopes,\n callScopes,\n memory: options.memory,\n snapshot,\n mastra: this.#mastra,\n });\n return applyResolvedAgentScopes(options, resolved, requestContext);\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 getScopes(options?: any) {\n return this.#wrappedAgent.getScopes(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 override async getConfiguredErrorProcessorIds(requestContext?: any) {\n return this.#wrappedAgent.getConfiguredErrorProcessorIds(requestContext);\n }\n\n override async __resolveRunErrorProcessors(requestContext: any, overrides?: any) {\n return this.#wrappedAgent.__resolveRunErrorProcessors(requestContext, overrides);\n }\n\n override async __listLLMRequestProcessors(requestContext?: any, errorProcessorOverrides?: any) {\n return this.#wrappedAgent.__listLLMRequestProcessors(requestContext, errorProcessorOverrides);\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 agentChannels.__setDispatchAgent(this);\n }\n\n // --- PubSub (base Agent fields — DurableAgent has its own pubsub) ---\n override hasOwnPubSub() {\n return this.#wrappedAgent.hasOwnPubSub();\n }\n\n override getPubSub() {\n return this.#wrappedAgent.getPubSub();\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 getMemory()/getWorkspace() also work.\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 * Raw stored config lives on the wrapped agent for the same reason as the\n * mutators above: durable preparation and tracing read\n * `resolvedVersionId` from the wrapped agent's rawConfig, and the editor\n * stamps it on the outer fork via `__setRawConfig` after\n * `applyStoredOverrides`. Without this delegation the stamp lands on the\n * (unread) DurableAgent-level field and version metadata silently\n * disappears from spans and suspend snapshots.\n */\n override toRawConfig(): Record<string, unknown> | undefined {\n return this.#wrappedAgent.toRawConfig();\n }\n\n override __setRawConfig(rawConfig: Record<string, unknown>): void {\n this.#wrappedAgent.__setRawConfig(rawConfig);\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 sharedChannels = this.#wrappedAgent.getChannels();\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 ...this.#streamConfig,\n id: this.id,\n name: this.name,\n maxSteps: this.#maxSteps,\n shouldPersistSnapshot: this.userShouldPersistSnapshot,\n storageVersion: this.#storageVersion,\n });\n\n // A transient version fork must not take over the singleton's channel ingress.\n if (sharedChannels && sharedChannels === innerFork.getChannels()) {\n sharedChannels.__setAgent(this.#wrappedAgent);\n sharedChannels.__setDispatchAgent(this);\n }\n\n // Preserve Mastra registration without re-triggering its side effects.\n // The inner fork inherits registration and resolves its shared bus lazily.\n if (this.#mastra) {\n fork.__inheritMastraForFork(this.#mastra);\n fork.#mastra = this.#mastra;\n }\n fork.source = this.source;\n // Share the untilIdle wrappers, so a task finishing under the fork's stream isn't\n // also reported by the registered agent (mirrors `Agent.__fork()`).\n fork.#activeStreamUntilIdle = this.#activeStreamUntilIdle;\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 run registry for use by subclasses.\n * @internal\n */\n protected get runRegistryInternal(): ExtendedRunRegistry {\n return this.#runRegistry;\n }\n\n /**\n * Which workflow execution engine the durable agentic loop runs on.\n * Subclasses override this (EventedAgent → 'evented').\n * @internal\n */\n protected get workflowEngine(): 'default' | 'evented' {\n return 'default';\n }\n\n /** Whether new runs opt into journal storage. @internal */\n protected get storesRunsInJournal(): boolean {\n return this.#storageVersion === 2;\n }\n\n /**\n * Warns once when `storageVersion: 2` is set but the registered store can't\n * store version 2 runs. The loop workflow's `autoStorageVersion` then stores\n * new runs as version 1. An agent with no registered store isn't warned.\n */\n #warnIfStorageVersionUnsupported(): void {\n if (this.#storageVersion !== 2) return;\n // Read `stores` directly, as resolveWorkflowEngine() does: getWorkflow() is synchronous.\n const storage = this.#mastra?.getStorage();\n const workflowsStore = storage?.stores?.workflows;\n if (workflowsStore && !workflowsStore.supportsRunJournal()) {\n this.guardrailLogger?.warn(\n `DurableAgent '${this.id}' sets storageVersion: 2, which ${storage?.name ?? 'the configured'} storage ` +\n `doesn't support yet; storing new runs as version 1.`,\n );\n }\n }\n\n /**\n * Resolve the engine this agent's workflow instance actually runs on.\n *\n * An evented agent without a Mastra host cannot execute evented runs — the\n * evented engine's `createRun` requires the host's registries, storage, and\n * event workers. Before the evented engine was re-enabled, a hostless\n * EventedAgent silently streamed on the default in-process engine; that is\n * released behavior, so we preserve it here as a fallback (with a warning)\n * instead of throwing.\n *\n * The same applies to a host whose storage cannot apply concurrent workflow\n * updates atomically. The evented engine advances a run from concurrent\n * workers, so `createRun()` refuses to start on such a store. Letting that\n * throw would turn a working durable agent into a hard failure on upgrade\n * for stores like Redis, so durable agents degrade to the in-process engine\n * the same way a hostless one does. A workflow that opts into the evented\n * engine directly (by declaring a `schedule`) still gets the error, because\n * there is no other engine it could have meant.\n *\n * The result is memoized: `getWorkflow()` caches the created workflow, so\n * an agent that first streamed hostless keeps its default-engine workflow\n * even if it is registered on a Mastra instance afterwards — identical to\n * the previously shipped behavior. The cache is deliberately not\n * invalidated.\n *\n * @internal\n */\n protected resolveWorkflowEngine(): 'default' | 'evented' {\n return this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger);\n }\n\n /**\n * Evented-engine runs execute via pubsub events consumed by in-process\n * workers — without them `run.start()`/`resume()`/`restart()` never\n * resolve (they wait on the `workflows-finish` topic). No-op on the\n * default engine; idempotent on Mastra's side.\n * @internal\n */\n protected async ensureEngineWorkersStarted(): Promise<void> {\n return this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);\n }\n\n private async persistInitialInput(runId: string, workflowInput: DurableAgenticWorkflowInput): Promise<void> {\n await persistDurableRunInput(runId, workflowInput, this.#mastra);\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: Runs steps through event workers and tracks completion\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(\n runId: string,\n workflowInput: DurableAgenticWorkflowInput,\n ): Promise<{ status?: string } | void> {\n const workflow = this.getWorkflow();\n const entry = getRunRegistryEntry(runId, this.#mastra);\n const requestContext = entry?.requestContext;\n // Captured now: a later resume() replaces the registry's fence.\n const executionFence = entry?.executionFence;\n\n // Populate the run row's resourceId column so storage-level resource\n // filters (listSuspendedRuns / listActiveRuns) can narrow the query,\n // mirroring the non-durable agentic loop (loop/workflows/stream.ts).\n const memoryInfo = (\n workflowInput.messageListState as { memoryInfo?: { threadId?: string; resourceId?: string } } | undefined\n )?.memoryInfo;\n const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;\n\n const run = await this.executionEngine.createRun(workflow, {\n runId,\n resourceId,\n pubsub: this.fenceRunPubSub(executionFence, entry?.abortController),\n });\n // Parent the workflow run under the AGENT_RUN span so the trace exports under it.\n let result;\n try {\n result = await this.withSuspensionAfterPersist(runId, () =>\n this.executionEngine.startRun(\n run,\n workflowInput,\n requestContext,\n createObservabilityContext({ currentSpan: entry?.agentSpan }),\n ),\n );\n const outcome = this.executionEngine.finishExecution(runId, executionFence, false, { result });\n if (outcome.owner === 'agent') await this.settleExecution(runId, executionFence, outcome);\n return result;\n } finally {\n this.executionEngine.releaseRun(workflow, runId, run, result?.status);\n }\n }\n\n /**\n * Run a workflow leg with suspension chunks/events held back until the leg\n * returns, i.e. until the engine has saved the suspended snapshot. Without\n * this a crash between publishing the question and saving the snapshot\n * leaves a run that `resume()` rejects (#26435).\n */\n private async withSuspensionAfterPersist<T>(runId: string, execute: () => Promise<T>): Promise<T> {\n const entry = this.suspendPersistedOnReturn ? getRunRegistryEntry(runId, this.#mastra) : undefined;\n if (!entry) return execute();\n const pending: Array<() => Promise<void>> = [];\n entry.pendingSuspensionEvents = pending;\n let result: T;\n try {\n result = await execute();\n } finally {\n if (entry.pendingSuspensionEvents === pending) delete entry.pendingSuspensionEvents;\n }\n // Only announce a suspension the engine actually persisted; if persisting failed,\n // the run isn't resumable and the queued events would advertise a dead question.\n if ((result as { status?: string } | undefined)?.status === 'suspended') {\n for (const publish of pending) {\n try {\n await publish();\n } catch (error) {\n this.logger.warn('Failed to publish deferred suspension event', { runId, error });\n }\n }\n }\n return result;\n }\n\n /**\n * Whether `executeWorkflow()` resolves only after a suspended snapshot has\n * been persisted, reporting `{ status: 'suspended' }`. When true,\n * `closeOnSuspend` streams close on that result instead of on the SUSPENDED\n * pubsub event (which the tool-call step publishes before persistence), so\n * an immediate cold resume finds the `suspended` snapshot.\n * @internal\n */\n protected get suspendPersistedOnReturn(): boolean {\n return true;\n }\n\n /**\n * Create the durable workflow for this agent.\n *\n * Retained for direct calls and subclass super calls. Run execution creates\n * workflows through the execution engine, not through overrides of this method.\n *\n * @internal\n */\n protected createWorkflow(): ReturnType<typeof createDurableAgenticWorkflow> {\n return this.executionEngine.createWorkflow({\n maxSteps: this.#maxSteps,\n workflowEngine: this.workflowEngine,\n storesRunsInJournal: this.storesRunsInJournal,\n shouldPersistSnapshot: this.userShouldPersistSnapshot,\n logger: this.logger,\n guardrailLogger: this.guardrailLogger,\n });\n }\n\n /**\n * Resolve the effective snapshot-persistence policy for this agent's\n * workflows: the user-supplied predicate when set, otherwise the\n * recovery-aware default. Engine variants own this policy during execution;\n * overriding this compatibility method does not change running workflows.\n *\n * @internal\n */\n protected resolveShouldPersistSnapshot(): ShouldPersistSnapshotFn {\n return this.executionEngine.resolveShouldPersistSnapshot(this.userShouldPersistSnapshot);\n }\n\n protected workflowFailureError(workflowError: unknown, fallbackMessage: string): Error {\n return this.executionEngine.workflowFailureError(workflowError, fallbackMessage);\n }\n\n protected workflowExecutionError(workflowError: unknown, fallbackMessage: string): Error {\n return this.executionEngine.workflowExecutionError(workflowError, fallbackMessage);\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 * @param generation - Claim generation of the execution reporting the error\n * @internal\n */\n protected async emitError(runId: string, error: Error, generation?: number): 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 runOutsideRunFenceScope(() =>\n emitErrorEvent(this.pubsub, runId, error, generation, shouldRejectStream(error) ? 'reject' : undefined),\n );\n }\n\n /**\n * Claim the run's execution fence (#23734): `acquire` for a new execution\n * segment, `takeover` when recovering an orphaned run. With a\n * `requestContext`, the claim also covers the run's memory store (see\n * {@link DurableAgent.#coverMemory}).\n */\n async #claimExecution(\n runId: string,\n mode: 'acquire' | 'recover' | 'takeover',\n requestContext?: RequestContext,\n untrackedRun?: UntrackedRunLiveness,\n ): Promise<ExecutionFence> {\n const fence = await this.executionEngine.claimExecution(runId, mode, this.pubsub, this.logger, untrackedRun);\n if (requestContext) await this.#coverMemory(fence, requestContext);\n return fence;\n }\n\n /**\n * Raise the memory store the run writes to to the fence's claim before the\n * run touches memory. Settles the fence if a newer claim already covers\n * memory. Memory that cannot be resolved stays unfenced: the run's own\n * memory writes fail the same way. Warns about a memory store that can't\n * fence when the run is being recovered, or when recovery is automatic.\n */\n async #coverMemory(fence: ExecutionFence, requestContext: RequestContext, recovering = false): Promise<void> {\n if (fence.generation === undefined) return;\n let store: MemoryStorage | undefined;\n try {\n const memory = await this.getMemory({ requestContext });\n store = memory ? await memory.storage.getStore('memory') : undefined;\n } catch (error) {\n this.logger.warn(`[DurableAgent] run ${fence.runId}: memory is not fenced, failed to resolve its store`, {\n runId: fence.runId,\n error,\n });\n }\n if (recovering || this.#mastra?.recoveryConfig?.durableAgents === 'auto') {\n await this.#warnIfUnfenced(store, 'memory');\n }\n try {\n await fence.coverMemory(store);\n } catch (error) {\n await fence.settle(async () => {});\n throw error;\n }\n }\n\n /**\n * Warn, once per store, that a store recovery relies on can't fence run\n * writes (#23734). Returns whether it can't. A store that can't tell yet\n * isn't warned about: claims on it fail until it can.\n */\n async #warnIfUnfenced(\n store: WorkflowsStorage | MemoryStorage | undefined,\n domain: 'workflows' | 'memory',\n ): Promise<boolean> {\n return this.executionEngine.warnIfUnfenced(store, domain, this.guardrailLogger);\n }\n\n /**\n * The pubsub a run's workflow publishes on, bound to its execution.\n *\n * Once the execution loses the run, `abortController` is aborted so the LLM\n * stream and tool calls stop, and the execution's publishes are dropped:\n * the run's topics are shared with the new owner's consumers, which must not\n * see this execution's chunks or the `finish` its abort produces.\n *\n * The evented engine publishes on `mastra.pubsub` instead of this pubsub.\n * Its shared workflow controller must not be aborted on ownership loss:\n * that would publish a cancellation to the recovering execution. Durable\n * step guards instead cancel invocation-local work and suppress its stream\n * publications, leaving engine failure and settlement events untouched.\n *\n * @internal\n */\n protected fenceRunPubSub(\n executionFence: ExecutionFence | undefined,\n abortController: AbortController | undefined,\n pubsub: PubSub = this.pubsub,\n ): PubSub {\n return this.executionEngine.fenceRunPubSub(\n executionFence,\n abortController,\n pubsub,\n this.workflowEngine,\n this.logger,\n );\n }\n\n /**\n * End an execution segment: publish the error of a failed segment and delete\n * the snapshots of a run that reached a non-suspended terminal status.\n *\n * With an execution fence these writes happen only while the segment still\n * owns the run, and the fence is released afterwards. A superseded segment\n * writes nothing — the run belongs to the execution that took it over. A\n * segment that lost its lease without being replaced still reports its error\n * but keeps the snapshots so the run stays recoverable.\n *\n * Never rejects: a pubsub that is already closing (for example during\n * shutdown) must not turn a run's own failure into an unhandledRejection.\n *\n * @internal\n */\n protected async settleExecution(\n runId: string,\n fence: ExecutionFence | undefined,\n outcome: { status?: string; error?: Error },\n ): Promise<void> {\n const { status, error } = outcome;\n if (fence && this.#timedOutExecutions.has(fence)) return;\n const totalTimeout = isMastraTimeoutError(error) && error.timeoutType === 'total';\n if (fence && totalTimeout) this.#timedOutExecutions.add(fence);\n const reportError = async (reported: Error) => {\n try {\n await this.emitError(runId, reported, fence?.generation);\n } catch (publishError) {\n this.logger.warn(`Failed to publish error event for run ${runId}`, { runId, error: publishError });\n }\n };\n // Reaching any non-suspended terminal status means the run is done and its\n // persisted snapshot rows will never be resumed. Suspended runs keep their\n // snapshots (and owner records) so `resume()` / `recoverActiveRuns()` can\n // find them.\n const finished = totalTimeout || (status !== undefined && status !== 'suspended');\n const runInput = totalTimeout && fence ? this.#runInputs.get(fence) : undefined;\n // Captured before the error below lets the caller clean the run up.\n const runInputEntry =\n runInput && (getRunRegistryEntry(runId, this.#mastra) ?? (fence && this.#recoveredEntries.get(fence)));\n let wrote = false;\n let deadlineSave: Promise<void> | undefined;\n const writeTerminalState = async () => {\n wrote = true;\n if (totalTimeout && fence) fence.deadlineError = error;\n if (runInput && runInputEntry && !runInputEntry.tripwire) {\n // The run never reaches its finish step, so the output processors get their pass here, over the\n // steps that completed in time (or just the accepted request). Saves made under the claim the\n // deadline replaced are rejected; this one writes under the replacement. Saves upsert by ID.\n // Like the finish step, memory is saved before the caller sees the run end.\n this.#runInputs.delete(fence!);\n deadlineSave = (async () => {\n // A tool the deadline aborted still gets its grace window to return; wait (bounded) so its step can be saved.\n await settledOrElapsed(\n new Promise<void>(resolve => whenRunStepsSettle(runInputEntry, resolve)),\n TOOL_ABORT_GRACE_MS + TOOL_SETTLE_MARGIN_MS,\n );\n const deadlineSpan = runInputEntry.resumeAgentSpan ?? runInputEntry.agentSpan;\n await runDurableDeadlineOutputPass({\n runId,\n initData: runInput,\n ...deadlineMessageListState(runInputEntry, runInput.messageListState),\n entry: runInputEntry,\n mastra: this.#mastra,\n tracingContext: deadlineSpan ? { currentSpan: deadlineSpan } : undefined,\n logger: this.logger,\n });\n })().catch(saveError => {\n this.logger.warn(`Failed to save run ${runId} at its total deadline`, { runId, error: saveError });\n });\n // Saved before the caller sees the run end, unless the store hangs: the deadline must still surface.\n await settledOrElapsed(deadlineSave, DEADLINE_SAVE_WAIT_MS);\n }\n // The observable deadline must not wait for snapshot I/O.\n if (error) await reportError(error);\n if (finished) await this.deleteRunSnapshots(runId);\n // The claim is held until the save lands (bounded), so it is not rejected as a stale write.\n if (deadlineSave) await settledOrElapsed(deadlineSave, DEADLINE_SAVE_CLAIM_HOLD_MS);\n };\n\n if (!fence) return writeTerminalState();\n let settlement;\n try {\n settlement = await fence.settle(writeTerminalState, totalTimeout);\n } catch (settlementError) {\n if (totalTimeout && !wrote && error) await reportError(error);\n throw settlementError;\n }\n // A deadline losing to normal completion or suspension must not publish a\n // second terminal event. Non-timeout bookkeeping failures still surface.\n if (!wrote && error && (settlement === 'orphaned' || (!totalTimeout && settlement === 'owned'))) {\n await reportError(error);\n }\n }\n\n /**\n * Abort the thread's active run.\n *\n * The base implementation flips the run's prepared `AbortController`, which a\n * durable run never has: its controller lives on this agent's run registry,\n * and the steps reading it may execute in another process. Without the abort\n * request below, aborting a thread whose active run is durable records an\n * intent nothing reads and lets the run stream on.\n */\n /** @internal Durable `untilIdle` streams are tracked on this agent, not the wrapped one. */\n override __untilIdleHandlesBackgroundTask(threadId: string, resourceId: string, taskId: string): boolean {\n return untilIdleHandlesBackgroundTask(this.#activeStreamUntilIdle, threadId, resourceId, taskId);\n }\n\n abortThreadStream(options: AgentAbortThreadOptions): boolean {\n const aborted = this.#abortThreadStreamLocally(options);\n // The lookup is async, so this synchronous call can't report its outcome.\n // Server routes use `__abortThreadStreamAcrossProcesses` for that.\n if (!aborted && !options.localOnly) {\n void this.#abortThreadLeaseOwner(options).catch(error => {\n this.#mastra?.getLogger?.()?.warn?.('Failed to abort durable agent thread run on another process', {\n agentId: this.id,\n threadId: options.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }\n return aborted;\n }\n\n /** @internal Like {@link abortThreadStream}, but reports whether a run on another process was asked to stop. */\n async __abortThreadStreamAcrossProcesses(options: AgentAbortThreadOptions): Promise<boolean> {\n const aborted = this.#abortThreadStreamLocally(options);\n if (aborted || options.localOnly) return aborted;\n return this.#abortThreadLeaseOwner(options);\n }\n\n #abortThreadStreamLocally(options: AgentAbortThreadOptions): boolean {\n const scopeKey = `${options.threadId ?? ''}|${options.resourceId ?? ''}`;\n const wrapperClose = getScopeStreamSlot(this.#activeStreamUntilIdle, scopeKey, options.expectedRunId);\n if (wrapperClose) {\n wrapperClose();\n return true;\n }\n\n // Resolve the run before the base call: aborting releases the thread lease,\n // after which the thread no longer has an active run to look up.\n const runId = agentThreadStreamRuntime.getActiveThreadRunId(options, this.getPubSub());\n const aborted = super.abortThreadStream(options);\n if (!aborted || !runId) return aborted;\n\n if (!options.localOnly) {\n this.#abortLocalController(runId);\n void this.requestRemoteAbort(runId);\n }\n return true;\n }\n\n /**\n * A process only knows another process's run while it subscribes to the\n * thread, so a server answering a bare abort request usually knows none.\n * The thread lease names the run holding the thread wherever it executes;\n * stop that run the way {@link abortRunStream} does (#28310).\n */\n async #abortThreadLeaseOwner(options: AgentAbortThreadOptions): Promise<boolean> {\n const runId = await agentThreadStreamRuntime.getThreadLeaseOwnerRunId(this.getPubSub(), options);\n if (!runId) return false;\n // Never stop a successor run the caller didn't mean (#24422).\n if (options.expectedRunId !== undefined && options.expectedRunId !== runId) return false;\n // The run executes elsewhere, so success means the request was published: a\n // failed lease lookup or publish throws rather than reading as an idle thread.\n // The thread-topic request reaches the owner's thread runtime, which stops an\n // executing run and also releases one parked on a suspension; a run-topic request\n // only reaches an executing step. With clearPendingSignals the owner must clear the\n // queued input before the run ends and drains it, so only the thread request goes.\n await Promise.all([\n agentThreadStreamRuntime.requestThreadRunAbort(this.getPubSub(), options, runId),\n options.clearPendingSignals ? undefined : publishAbortRequest(this.pubsub, runId),\n ]);\n return true;\n }\n\n override abortRunStream(runId: string): boolean {\n return (\n super.abortRunStream(runId) ||\n this.#runRegistry.get(runId) !== undefined ||\n getRunRegistryEntry(runId, this.#mastra) !== undefined ||\n agentThreadStreamRuntime.hasThreadRun(runId, this.getPubSub())\n );\n }\n\n protected override __abortLocalRun(runId: string): boolean {\n const wrapperClose = getRunStreamSlot(this.#activeStreamUntilIdle, runId);\n if (wrapperClose) {\n wrapperClose();\n return true;\n }\n const aborted = super.__abortLocalRun(runId);\n const controller = (this.#runRegistry.get(runId) ?? getRunRegistryEntry(runId, this.#mastra))?.abortController;\n this.#abortLocalController(runId);\n // An evented run's registry entry can belong to a caller, not its executor.\n // Let the base path send the request to the workers in that case.\n return (\n aborted ||\n (this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger) === 'default' &&\n controller !== undefined)\n );\n }\n\n /**\n * Abort `runId` and resolve whether the abort was confirmed.\n *\n * Only a close this process performs itself counts as local confirmation. A\n * run-registry entry does not: an evented run keeps one here while another\n * process executes its steps, possibly a dead one. Every other run gets a\n * single correlated request, and only the executor's answer confirms it.\n * The local controller is flipped after that answer, so an executor in this\n * process cannot unwind and drop its listener before the request reaches it.\n *\n * @internal Used by the server's run abort route.\n */\n override async __abortRunAcknowledged(runId: string): Promise<boolean> {\n const wrapperClose = getRunStreamSlot(this.#activeStreamUntilIdle, runId);\n if (wrapperClose) {\n wrapperClose();\n return true;\n }\n if (agentThreadStreamRuntime.abortRun(runId, this.getPubSub())) {\n this.#abortLocalController(runId);\n void this.requestRemoteAbort(runId);\n if (await this.#cancelParkedRun(runId)) await this.#announceCanceledRun(runId);\n return true;\n }\n try {\n const canceled = await this.#cancelParkedRun(runId);\n if (canceled) await this.#announceCanceledRun(runId);\n return (await requestAcknowledgedAbort(this.pubsub, runId)) || canceled;\n } finally {\n this.#abortLocalController(runId);\n }\n }\n\n /**\n * Record the abort of a parked run in shared storage, so a resume on any server\n * refuses it. The in-process resume fence only covers this process. The status\n * moves from `suspended` to `canceled` with a guarded write: a resume that claimed\n * the run first has already moved it to `running`, and that run is stopped by the\n * abort request instead. Stores that cannot enforce the guard atomically get the\n * same check on a best-effort basis, so a finished or running run is never marked\n * canceled. Stores without concurrent updates (some don't implement\n * `updateWorkflowState`) get the canceled status by rewriting the run's snapshot,\n * which every store supports. Resolves whether this call canceled the parked run.\n * Storage errors propagate: an abort acknowledged without this write would not stop\n * another server from resuming the run.\n */\n async #cancelParkedRun(runId: string): Promise<boolean> {\n return this.executionEngine.cancelParkedRun(runId);\n }\n\n /**\n * Publish the abort terminal for a parked run this call just canceled. The bus is\n * shared, so observers on every server close now, whichever server later refuses\n * the approval. Only the call that won the cancel publishes. A failed publish does\n * not undo the abort: the cancel is already stored, and a refused resume on this\n * server retries the publish.\n */\n async #announceCanceledRun(runId: string): Promise<void> {\n return this.executionEngine.announceCanceledRun(runId, this.pubsub);\n }\n\n async #isRunCanceledInStorage(runId: string): Promise<boolean> {\n return this.executionEngine.isRunCanceledInStorage(runId);\n }\n\n /**\n * A durable run parked on a suspension has no prepared run in this process, so the\n * base abort cannot tell it was parked and never deletes its snapshot. Once a resume\n * is rejected by the abort fence the run can never continue; delete its snapshot rows\n * if they are still suspended so it drops out of `listSuspendedRuns()` (#27619), and\n * publish the abort terminal so observers still attached to the parked run close.\n * Done here rather than at abort time: a run still executing in this process unwinds\n * through its own abort path, which reads the snapshot.\n * A run the abort already marked `canceled` keeps its row, since that row is what\n * stops other servers from resuming it; its abort terminal was published by the\n * abort, and is published here only if that publish failed.\n */\n async #deleteFencedSuspendedRun(runId: string): Promise<void> {\n try {\n const snapshot = await this.executionEngine.loadRunSnapshot(runId);\n if (snapshot?.status === 'canceled') {\n await this.executionEngine.publishCanceledRunTerminal(runId, this.pubsub);\n return;\n }\n if (snapshot?.status !== 'suspended') return;\n await this.deleteRunSnapshots(runId);\n await emitAbortEvent(this.pubsub, runId, { steps: [], text: '' });\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`Failed to delete snapshot of aborted suspended run ${runId}`, {\n runId,\n error,\n });\n }\n }\n\n /** Flip the controller this process holds for `runId`, if it holds one. */\n #abortLocalController(runId: string): void {\n const controller = (this.#runRegistry.get(runId) ?? getRunRegistryEntry(runId, this.#mastra))?.abortController;\n if (controller && !controller.signal.aborted) {\n controller.abort(new Error('Aborted'));\n }\n }\n\n async #redeliverDeadlineError(entry: RunRegistryEntry, fence: ExecutionFence): Promise<boolean> {\n if (!fence.deadlineError) return false;\n if (!entry.deadlineErrorRedelivered) {\n entry.deadlineErrorRedelivered = true;\n await this.emitError(fence.runId, fence.deadlineError, fence.generation);\n }\n return true;\n }\n\n /**\n * Install `abortController` on a registry entry with the run-level execution\n * budget (`modelSettings.timeout.totalMs`, #21724 parity port) composed in.\n *\n * Every durable step reads `abortSignal` off the registry, so composing here\n * bounds the whole session — every loop iteration, tool call and retry.\n * Pass-through when no budget is configured. The budget is armed per\n * execution session (stream/generate/resume), matching the main loop where\n * each session gets a fresh timer. The timer is torn down via the entry's\n * `cleanup` slot, which every settle path invokes through the run registry.\n */\n #installAbortWithTotalTimeout(\n entry: RunRegistryEntry,\n abortController: AbortController,\n executionFence: ExecutionFence,\n ): void {\n entry.abortController = abortController;\n entry.deadlineErrorRedelivered = false;\n const totalTimeout = createTimeoutAbortSignal({\n parentSignal: abortController.signal,\n timeoutMs: entry.timeoutTotalMs,\n timeoutType: 'total',\n // The controller is per-session, but entry cleanup can also run on registry\n // eviction while calls holding `entry.abortSignal` are still in flight (#26126).\n // Only tear down the timer so `abort()` keeps reaching them.\n detachParentOnCleanup: false,\n });\n entry.abortSignal = totalTimeout.signal;\n if (totalTimeout.timeoutPromise) {\n void totalTimeout.timeoutPromise\n .catch(async error => {\n if (!isMastraTimeoutError(error) || error.timeoutType !== 'total' || totalTimeout.signal?.reason !== error)\n return;\n await this.settleExecution(executionFence.runId, executionFence, { status: 'failed', error });\n })\n .catch(error => {\n this.logger.warn('Failed to settle durable agent at its total deadline', { error });\n });\n }\n void executionFence.whenSettled.then(() => totalTimeout.cleanup());\n const previousCleanup = entry.cleanup;\n entry.cleanup = () => {\n totalTimeout.cleanup();\n previousCleanup?.();\n };\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 await this.executionEngine.deleteRunSnapshots(runId, this.getWorkflow());\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(applyReservedMemoryContextKeys(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 validateModelTimeoutSettings(options?.modelSettings?.timeout);\n\n // 1. Claim the run before preparing it, so a run that is already executing\n // fails before any span or memory write is made for this call.\n const runId = options?.runId ?? crypto.randomUUID();\n const requestContext = options?.requestContext ?? new RequestContext();\n const executionFence = await this.#claimExecution(runId, 'acquire', requestContext);\n\n // 1a. Prepare for durable execution (non-durable phase)\n let preparation: PreparationResult<TOutput>;\n try {\n preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options: options as AgentExecutionOptions<TOutput>,\n runId,\n requestContext,\n optionsAreResolved: true,\n resolvedDefaultOptions: (options as any)?.[RESOLVED_DEFAULT_OPTIONS],\n scopesResolved: true,\n mastra: this.#mastra,\n durableAgentId: this.id,\n durableAgentName: this.name,\n });\n } catch (error) {\n // The run never started: drop its owner record rather than leave it behind.\n await executionFence.settle(async () => {});\n throw error;\n }\n\n const { messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;\n // Set after preparation so request-context schema validation never sees it.\n setExecutionClaim(requestContext, runId, executionFence.claim);\n registryEntry.executionFence = executionFence;\n this.#runInputs.set(executionFence, workflowInput);\n\n // 1b. 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 { controller: abortController } = createRunAbortController(options?.abortSignal);\n if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) {\n abortController.abort();\n }\n this.#installAbortWithTotalTimeout(registryEntry, abortController, executionFence);\n\n // Share the scope before either registry copies the entry.\n const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);\n\n // 2. Register non-serializable state (both local and global registries)\n registryEntry.agentId = this.id;\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n const globalRegistryEntry = { ...registryEntry, messageList };\n globalRunRegistry.set(runId, globalRegistryEntry);\n await this.#attachStreamPublisher(runId, { threadId, resourceId });\n const segment = this.#beginSegment(runId);\n\n // Assigned once the stream is created below. Declared here so the shared\n // performCleanup() closure can unsubscribe the pubsub reader (via\n // streamCleanup) from both the auto-cleanup timer and the explicit\n // cleanup() path — mirroring observe().\n let streamCleanup: (() => void) | undefined;\n\n // Single cleanup path for both the auto-cleanup timer and the explicit\n // cleanup(). Revokes continuation before unsubscribing the pubsub reader,\n // then tears down the registry entries and pubsub topic this execution\n // still owns — an execution that recovered the run in this process holds\n // its own. The topic stays when the run's latest execution here (this one\n // or a later resume()) lost the run: whoever took it over, in any process,\n // writes to it. Runs at most once.\n const runCleanup = createRunCleanup({\n scheduleTimer: cleanup => this.#scheduleReaderCleanup(executionFence, cleanup),\n release: () => {\n agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());\n streamCleanup?.();\n // A deferred cleanup must not tear down a newer segment (e.g. resume())\n // registered under the same run id.\n if (this.#releaseSegment(runId, segment, registryEntry)) {\n if (getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {\n globalRunRegistry.delete(runId);\n if (\n !this.#unverifiedReaderFences.has(executionFence) &&\n (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)\n )\n this.#clearPubsubTopic(runId, globalRegistryEntry);\n }\n }\n },\n });\n const performCleanup = runCleanup.run;\n // Schedule automatic registry cleanup after stream ends\n const scheduleAutoCleanup = runCleanup.schedule;\n\n // Whether this caller's stream closes at the suspension boundary. Defaults\n // to false (stream stays open for a same-reader resume). The same value\n // gates the `across-suspension` continuation so the two cannot drift.\n const closeOnSuspend = options?.closeOnSuspend ?? false;\n const closeOnPersistedSuspend = closeOnSuspend && this.suspendPersistedOnReturn;\n\n // 3. Create the durable agent stream (subscribes to pubsub)\n const {\n output,\n cleanup: createdStreamCleanup,\n detach: detachStream,\n waitForEventDelivery,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n minGeneration: executionFence.generation,\n onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),\n readLocalRequest,\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 // When the engine reports the persisted suspension, the stream is closed\n // after executeWorkflow() returns (below) rather than on the SUSPENDED\n // event, which is published before the snapshot is saved.\n closeOnSuspend: closeOnSuspend && !closeOnPersistedSuspend,\n hideSignals: options?.hideSignals,\n structuredOutput: registryEntry.structuredOutput as any,\n outputProcessors: registryEntry.outputProcessors,\n processorStates: registryEntry.processorStates,\n agent: registryEntry.agent,\n requestContext: registryEntry.requestContext,\n returnScorerData: workflowInput.options.returnScorerData,\n tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : undefined,\n messageList,\n });\n streamCleanup = createdStreamCleanup;\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 = executionFence.run(() =>\n ready\n .then(async () => {\n if (await this.#redeliverDeadlineError(registryEntry, executionFence)) return;\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(fencePubSub(this.pubsub, executionFence), 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: getRunRegistryEntry(runId, this.#mastra)?.requestContext,\n });\n }\n let result: { status?: string } | void;\n try {\n await this.persistInitialInput(runId, workflowInput);\n result = await this.executeWorkflow(runId, workflowInput);\n } finally {\n await stopGoalActivity({ agentId: workflowInput.agentId, runId });\n }\n if (closeOnPersistedSuspend && result?.status === 'suspended') {\n // The workflow result is the persisted suspension boundary. Deliver\n // buffered events (including onSuspended) before closing the stream.\n await this.pubsub.flush();\n await waitForEventDelivery();\n detachStream();\n }\n })\n .catch(error =>\n this.settleExecution(runId, executionFence, {\n error: this.executionEngine.workflowExecutionError(error, 'Workflow execution failed'),\n }),\n ),\n );\n const trackedEntry = getRunRegistryEntry(runId, this.#mastra);\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 continuation: closeOnSuspend ? undefined : 'across-suspension',\n generation: executionFence.generation,\n ownershipLost: () => executionFence.isLost(),\n stepOwner: () => getRunRegistryEntry(runId, this.#mastra),\n },\n );\n\n // 5. Cleanup function — routes through the shared performCleanup() so the\n // explicit call and the auto-cleanup timer release the same resources.\n // A cleanup() that arrives before the output settles waits for the run's\n // terminal event, including an error event still being published in the\n // background. Tearing down the reader first would drop it, leaving the\n // output unsettled and the thread busy forever (#25974).\n const cleanup = () => {\n if (runCleanup.done || output.status !== 'running') return performCleanup();\n void Promise.race([workflowExecution, executionFence.whenSettled])\n .then(() => this.pubsub.flush())\n .then(() => waitForEventDelivery())\n .catch(() => {})\n .finally(performCleanup);\n };\n\n const abort = async (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n // Also stop the run wherever it is actually executing — see\n // `requestRemoteAbort`. The local controller above only reaches steps\n // running in this process.\n await this.requestRemoteAbort(runId);\n // A run parked on a suspension has no steps left to stop; release it so\n // it is no longer listed as suspended.\n if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);\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 const abortedRunError = () =>\n new MastraError({\n id: 'AGENT_RESUME_ABORTED_RUN',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" cannot resume aborted run \"${runId}\".`,\n details: { agentName: this.name, runId },\n });\n if (agentThreadStreamRuntime.isResumeFenced(runId, this.getPubSub())) {\n // The fenced run can never continue, so the rejected caller must not find it in\n // listSuspendedRuns() afterwards (#27619).\n await this.#deleteFencedSuspendedRun(runId);\n throw abortedRunError();\n }\n // Marked before the first await, so a second resume of the same tool call\n // fails fast even when both start in the same tick (#27365).\n const toolCallId = options?.toolCallId;\n let releaseResumeMarker = () => {};\n if (toolCallId !== undefined) {\n const release = markResumeInFlight(runId, toolCallId);\n if (!release) {\n throw new MastraError({\n id: 'AGENT_RESUME_ALREADY_CLAIMED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}) cannot resume the run because another resume of it is already running.`,\n details: { agentName: this.name, runId, toolCallId },\n });\n }\n releaseResumeMarker = release;\n }\n try {\n // An abort on another server leaves the run canceled in storage.\n if (await this.#isRunCanceledInStorage(runId)) throw abortedRunError();\n return await this.#resumeRun(runId, resumeData, options, releaseResumeMarker);\n } catch (error) {\n releaseResumeMarker();\n throw error;\n }\n }\n\n /**\n * A resume claims the run by marking it `running` (#27619). When the process holding\n * that claim dies, nothing else moves the run on, so the run would stay unresumable.\n * Recover the run once the claim's lease has lapsed: when no running progress was\n * checkpointed (the default snapshot policy) recovery parks it at its suspension\n * again and this resume goes on; otherwise recovery finishes it.\n */\n async #takeOverResumeClaim(runId: string, workflowsStore: WorkflowsStorage): Promise<WorkflowRunState> {\n const outcome = (await this.recoverActiveRuns({ runId })).recovered[0];\n if (outcome?.status === 'skipped') {\n throw new MastraError({\n id: 'AGENT_RESUME_ALREADY_CLAIMED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}) cannot resume the run because another resume of it is still running.`,\n details: { agentName: this.name, runId, reason: outcome.reason ?? '', retryAt: outcome.retryAt ?? '' },\n });\n }\n if (outcome?.status === 'failed' && outcome.error) throw outcome.error;\n const persisted = await workflowsStore.getWorkflowRunById({ runId, workflowName: DurableStepIds.AGENTIC_LOOP });\n if (!persisted) {\n throw new MastraError({\n id: 'AGENT_RESUME_RUN_FINISHED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}) cannot resume the run because it already finished: recovery completed it after the process running its previous resume stopped.`,\n details: { agentName: this.name, runId },\n });\n }\n return typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n }\n\n async #resumeRun(\n runId: string,\n resumeData: unknown,\n options: DurableAgentResumeOptions<TOutput> | undefined,\n releaseResumeMarker: () => void,\n ): Promise<DurableAgentStreamResult<TOutput>> {\n let entry = this.#runRegistry.get(runId);\n // Scopes persisted with a run rebuilt from storage. They are the suspended run's set even when\n // the caller passes its own request context.\n let rehydratedScopes: unknown;\n let coldSnapshot: WorkflowRunState | undefined;\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 MastraError({\n id: 'AGENT_RESUME_NO_SNAPSHOT_FOUND',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `No registry entry found for run ${runId}. Cannot resume.`,\n details: { agentName: this.name, runId },\n });\n }\n\n let snapshot =\n typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n const readWorkflowInput = (snapshot: WorkflowRunState, allowRunning = false) => {\n if (snapshot?.status !== 'suspended' && !(allowRunning && snapshot?.status === 'running')) {\n throw new MastraError({\n id: 'AGENT_RESUME_RUN_NOT_SUSPENDED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}) cannot resume the run because it is not waiting to be resumed (status: ${snapshot?.status}).`,\n details: { agentName: this.name, runId, status: snapshot?.status },\n });\n }\n const input = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (!input || input.__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 (input.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 \"${input.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: input.agentId },\n });\n }\n return input;\n };\n let workflowInput = readWorkflowInput(snapshot, true);\n\n // A run that suspended while executing a stored version must resume on\n // *that* version. Cold rehydration rebuilds tools/model/instructions\n // from whatever `this` currently resolves to — which, for status\n // selectors, hot-switches to the latest publish mid-flight. Re-resolve\n // to the pinned id and delegate. An explicit exact version at the call\n // site is an operator escape hatch and wins over the pin, and forks\n // already produced by `resolveVersionedAgent` are left alone (they are\n // either this very delegation or an explicit server-side resolution).\n const pinnedVersionId = workflowInput.agentVersionId;\n if (pinnedVersionId && this.#mastra && !this.__isStoredVersionApplied()) {\n const callSiteSelector = options?.versions?.agents?.[this.id];\n const hasExplicitVersion = !!callSiteSelector && 'versionId' in callSiteSelector;\n const currentVersionId = this.toRawConfig()?.resolvedVersionId as string | undefined;\n if (!hasExplicitVersion && pinnedVersionId !== currentVersionId) {\n let resolved: Agent | undefined;\n try {\n resolved = await this.#mastra.resolveVersionedAgent(this as unknown as Agent, {\n versionId: pinnedVersionId,\n });\n } catch (versionError) {\n // The pinned version may have been deleted while the run sat\n // suspended — resume on the current definition rather than\n // failing at the approver (mirrors Agent#execute's fallback).\n this.logger.warn('Failed to resolve pinned agent version for durable resume, using current definition', {\n agentId: this.id,\n runId,\n pinnedVersionId,\n error: versionError,\n });\n }\n if (resolved && resolved !== (this as unknown as Agent)) {\n // Hand the tool-call marker to the pinned agent's resume(), which\n // re-takes it synchronously before its first await.\n releaseResumeMarker();\n return (resolved as unknown as DurableAgent<TAgentId, TTools, TOutput>).resume(runId, resumeData, options);\n }\n }\n }\n\n if (snapshot?.status === 'running' && workflowsStore) {\n // Recovery can execute the run. Dynamic defaults still require the rehydrated context below.\n this.#wrappedAgent.__validateStaticModelTimeoutSettings(options?.modelSettings);\n validateModelTimeoutSettings((options?.modelSettings ?? workflowInput.options?.modelSettings)?.timeout);\n snapshot = await this.#takeOverResumeClaim(runId, workflowsStore);\n workflowInput = readWorkflowInput(snapshot);\n }\n coldSnapshot = snapshot;\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 // The starting request's user and token are left out, so they come only from this resume.\n const snapshotRequestContext = workflowInput.requestContextEntries\n ? new RequestContext<unknown>(Object.entries(withoutLiveRequestKeys(workflowInput.requestContextEntries)))\n : undefined;\n if (snapshotRequestContext) restoreRunAgentScopes(snapshotRequestContext);\n const persistedScopes = workflowInput.requestContextEntries?.[MASTRA_SCOPES_KEY];\n if (\n persistedScopes !== undefined &&\n (!Array.isArray(persistedScopes) || persistedScopes.some(scope => typeof scope !== 'string'))\n ) {\n // A malformed persisted set must not be coerced to \"no scopes\": that would both\n // drop the run's scopes and falsely reject re-supplied ones as additions.\n throw new MastraError({\n id: 'AGENT_SCOPES_INVALID',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.SYSTEM,\n // Corrupted persisted state is a system fault, not a caller error: no\n // `details.status`, so server handlers surface it as HTTP 500.\n text: `DurableAgent \"${this.name}\" resume(${runId}): persisted run scopes are malformed; expected an array of strings.`,\n details: { agentName: this.name, runId },\n });\n }\n // Absent (vs recorded []) marks a run suspended before the scopes upgrade; the resume\n // adopts the supplied scopes with the same trust posture as a fresh run.\n rehydratedScopes = persistedScopes;\n const memory = threadId\n ? {\n ...options?.memory,\n thread: threadId,\n resource: resourceId ?? options?.memory?.resource,\n }\n : options?.memory;\n\n // The resume below applies the suspended run's scopes, so preparation does not resolve them again.\n await this.prepare([], {\n [SCOPES_ALREADY_APPLIED]: true,\n [RESUMED_SPAN_DATA]: { agentSpanData: workflowInput.agentSpanData, modelSpanData: workflowInput.modelSpanData },\n ...(options as AgentExecutionOptions<TOutput>),\n runId,\n requestContext: options?.requestContext ?? snapshotRequestContext,\n memory,\n // Restore the original run's flag from the persisted snapshot so a\n // cross-process resume still returns scoringData; caller override wins.\n returnScorerData: options?.returnScorerData ?? workflowInput.options?.returnScorerData,\n // Restore the original run's modelSettings so the rebuilt registry\n // entry re-arms the run-level timeout budget (#21724); caller\n // override wins.\n modelSettings: options?.modelSettings ?? (workflowInput.options?.modelSettings as any),\n } as AgentExecutionOptions<TOutput>);\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 // The suspended run's non-identity scopes live on its persisted request context;\n // its identity is the registered memory. A resume keeps that set (rule: re-supplied\n // scopes may only be a subset of it).\n // A recorded set — [] included — is authoritative: a resume may not add scopes.\n // Cold resumes read the persisted entries, which preparation stamps unconditionally,\n // so an absent value there marks a pre-upgrade snapshot whose resume adopts the\n // supplied scopes. Warm registry entries only exist for runs this (post-upgrade)\n // process started, so an absent live value simply means the run held no scopes.\n const snapshotScopes = coldSnapshot ? rehydratedScopes : (entry.requestContext?.get(MASTRA_SCOPES_KEY) ?? []);\n const resumeScopesSnapshot: AgentScopesSnapshot = {\n resourceId: memoryInfo?.resourceId,\n threadId: memoryInfo?.threadId,\n scopes: Array.isArray(snapshotScopes) ? snapshotScopes : undefined,\n };\n\n // The suspended run's values carry over, except the starting request's user and\n // token: those come only from this resume, so a resume without a signed-in user\n // can't act as the user who started the run.\n const carriedEntries = entry.requestContext\n ? Object.entries(withoutLiveRequestKeys(Object.fromEntries(entry.requestContext.entries())))\n : undefined;\n // Tools built for the starting request are bound to its context, so they are rebuilt below.\n const droppedStartingUser = carriedEntries !== undefined && carriedEntries.length < entry.requestContext!.size();\n // Copy only when user keys were removed; otherwise keep the run's own instance.\n let resumeRequestContext = droppedStartingUser ? new RequestContext<unknown>(carriedEntries) : entry.requestContext;\n if (options?.requestContext) {\n // Keep the caller's instance so schema-transformed contexts retain their\n // input source. Caller values win except for framework-managed memory.\n resumeRequestContext = options.requestContext;\n for (const [key, value] of carriedEntries ?? []) {\n // The suspended run's scopes are applied on the run's own context below, never the caller's.\n if (key === MASTRA_SCOPES_KEY) continue;\n if (!resumeRequestContext.has(key)) resumeRequestContext.set(key, value);\n }\n if (entry.requestContext?.has('MastraMemory')) {\n resumeRequestContext.set('MastraMemory', entry.requestContext.get('MastraMemory'));\n } else {\n resumeRequestContext.delete('MastraMemory');\n }\n }\n\n // The resumed segment always carries its own claim: without a context the\n // engine would restore the previous segment's claim from the snapshot.\n resumeRequestContext ??= new RequestContext();\n const resolvedOptions = (await this.#resolveExecutionOptions(\n {\n ...(options as DurableAgentStreamOptions<TOutput>),\n requestContext: resumeRequestContext as DurableAgentStreamOptions<TOutput>['requestContext'],\n memory: registeredMemory ?? options?.memory,\n },\n resumeScopesSnapshot,\n )) as DurableAgentResumeOptions<TOutput>;\n validateModelTimeoutSettings(resolvedOptions.modelSettings?.timeout);\n // Scoped runs execute on a run-scoped copy of the request context.\n resumeRequestContext = (resolvedOptions.requestContext as typeof resumeRequestContext) ?? resumeRequestContext;\n\n entry.requestContext = resumeRequestContext;\n const globalEntryForContext = getRunRegistryEntry(runId, this.#mastra);\n if (globalEntryForContext) {\n globalEntryForContext.requestContext = resumeRequestContext;\n }\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 // The idle-loop wrapper re-enters resume() for this same tool call.\n releaseResumeMarker();\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 // Settle the prior segment before claiming the run and reading its snapshot\n // and event offset. The suspension chunk can arrive before the suspended\n // snapshot is persisted, and a late suspension event replayed into the new\n // segment would close it early.\n const priorExecution = getRunRegistryEntry(runId, this.#mastra)?.workflowExecution;\n await priorExecution?.catch(() => {\n /* errors already handled by the prior segment */\n });\n // A warm resume reuses the tools built for the first request, which close\n // over its request context, delegation hooks, and tool hooks (#25960). Rebuild them for\n // this call and swap in only entries still holding a request-built tool, so\n // tools a processor added or replaced are kept. Processor-added tools are\n // rebuilt for this call's request context instead (#27544). Cold resumes already\n // rebuilt everything in prepare() above.\n if (!coldSnapshot && (options?.requestContext || options?.delegation || options?.hooks || droppedStartingUser)) {\n try {\n const requestTools = await this.#wrappedAgent.getToolsForExecution({\n toolsets: resolvedOptions.toolsets,\n clientTools: resolvedOptions.clientTools,\n threadId: memoryInfo?.threadId,\n resourceId: memoryInfo?.resourceId,\n runId,\n requestContext: resumeRequestContext,\n memoryConfig: resolvedOptions.memory?.options,\n autoResumeSuspendedTools: resolvedOptions.autoResumeSuspendedTools,\n // resolvedOptions always carries defaultOptions.delegation, so only a delegation passed\n // to this resume may replace the one the first call parked on the entry.\n delegation: options?.delegation\n ? resolvedOptions.delegation\n : (entry.delegation ?? resolvedOptions.delegation),\n hooks: resolvedOptions.hooks,\n // Build for the method that started the run. `closeOnSuspend` is also a\n // stream() option and resumeStream() always sets it, so it cannot tell (#29436).\n methodType: entry.methodType ?? 'stream',\n backgroundTaskEnabled: Boolean(entry.backgroundTaskManager),\n backgroundTaskPolicy: resolvedOptions.backgroundTaskPolicy,\n model: entry.model,\n });\n const refresh = (current: Record<string, CoreTool>, previous: Record<string, CoreTool> | undefined) => {\n const next = { ...current };\n for (const [name, tool] of Object.entries(requestTools)) {\n // A name missing from current but present in previous was withheld by a processor.\n const configured = name in current ? current[name] === previous?.[name] : !previous || !(name in previous);\n if (configured) next[name] = tool;\n }\n return next;\n };\n for (const reg of new Set([entry, getRunRegistryEntry(runId, this.#mastra)])) {\n if (!reg) continue;\n reg.tools = rebindProcessorTools(refresh(reg.tools ?? {}, reg.requestTools), resumeRequestContext);\n if (reg.baseTools)\n reg.baseTools = rebindProcessorTools(refresh(reg.baseTools, reg.requestTools), resumeRequestContext);\n // Tools this rebuild did not produce still hold their earlier build, so\n // keep that as their baseline; otherwise a later resume can never refresh them.\n reg.requestTools = { ...reg.requestTools, ...requestTools };\n if (options?.delegation) reg.delegation = resolvedOptions.delegation;\n }\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] resume(${runId}) tool resolution failed: ${error}`);\n }\n }\n // Claimed before the abort controller and timeout are replaced, so a\n // conflicting resume leaves the executing segment's state untouched.\n // Memory is covered only once the run is known to be resumable below, so a\n // resume that lost the race never raises the memory fence past the winner.\n const executionFence = await this.#claimExecution(runId, 'acquire');\n let initialToolCalls: ToolCallChunk[];\n let resumedText: { priorText: string; stepText: string } | undefined;\n let resumeOffset: number | 'latest';\n let persistedInput: DurableAgenticWorkflowInput | undefined;\n try {\n // A concurrent resume of the same suspension may have claimed and run it while this one\n // waited for the execution claim. Report that as a lost race, not a generic failure.\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n const current = await workflowsStore?.loadWorkflowSnapshot({\n workflowName: DurableStepIds.AGENTIC_LOOP,\n runId,\n });\n // The row is gone once a run finishes (possibly in another process). When\n // this process already ran a segment of the run (settled above), a missing\n // row means there is nothing left to resume; resuming anyway would write a\n // fresh `pending` row. A run that was only prepared has no row yet.\n if (workflowsStore && !current && priorExecution) {\n throw new MastraError({\n id: 'AGENT_RESUME_NO_SNAPSHOT_FOUND',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}) could not find a suspended run for this runId. The run has already finished (for example, an earlier approval or resume already handled it), never suspended, or the runId is invalid.`,\n details: { agentName: this.name, runId },\n });\n }\n // Only a settled run counts: a just-suspended run's row can still read `running`\n // briefly, because the suspension chunk is emitted before the row is durable.\n if (current && !['suspended', 'running', 'pending', 'waiting'].includes(current.status)) {\n throw new MastraError({\n id: 'AGENT_RESUME_ALREADY_CLAIMED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}) cannot resume the run because another resume of it already ran.`,\n details: { agentName: this.name, runId },\n });\n }\n if (resumeRequestContext) await this.#coverMemory(executionFence, resumeRequestContext);\n await this.#loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);\n ({ toolCalls: initialToolCalls, resumedText } = await this.#loadSuspendedIteration(runId));\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 resumeOffset = await this.#getPubsubOffset(runId);\n persistedInput = current?.context?.input as DurableAgenticWorkflowInput | undefined;\n // A parked run that lost its thread lease must hold it again before the segment runs. Later\n // registration fails open, so take it here: a successor that now holds the thread refuses this\n // resume instead of running beside it, and the run stays parked.\n await agentThreadStreamRuntime.reacquireParkedRunLease(runId, this.getPubSub());\n } catch (error) {\n // The segment never started: release the run so it can be resumed again.\n await executionFence.settle(async () => {});\n throw error;\n }\n setExecutionClaim(resumeRequestContext, runId, executionFence.claim);\n for (const reg of [entry, getRunRegistryEntry(runId, this.#mastra)]) {\n if (!reg) continue;\n reg.executionFence = executionFence;\n reg.resumeToolCallId = resolvedOptions.toolCallId;\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 { controller: abortController, detach: detachExternalAbort } = createRunAbortController(\n resolvedOptions.abortSignal,\n );\n if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) {\n abortController.abort();\n }\n // Re-arm the run-level execution budget for the resumed session (#21724).\n // Warm resumes read the original budget parked on the registry entry;\n // cold resumes restored it from the persisted workflow input during\n // prepare(). A caller-supplied modelSettings on the resume call wins.\n const resumeTotalMs = (resolvedOptions.modelSettings as { timeout?: { totalMs?: number } } | undefined)?.timeout\n ?.totalMs;\n if (resumeTotalMs !== undefined) {\n entry.timeoutTotalMs = resumeTotalMs;\n }\n // The resumed segment's deadline saves the turn from the run's persisted input, as a first segment does.\n if (persistedInput) this.#runInputs.set(executionFence, persistedInput);\n this.#installAbortWithTotalTimeout(entry, abortController, executionFence);\n const globalEntryForAbort = getRunRegistryEntry(runId, this.#mastra);\n if (globalEntryForAbort) {\n globalEntryForAbort.abortController = abortController;\n globalEntryForAbort.abortSignal = entry.abortSignal;\n }\n\n const segment = this.#beginSegment(runId);\n\n // Assigned once the stream is created below so the shared performCleanup()\n // closure can unsubscribe the pubsub reader (via streamCleanup) from both\n // the auto-cleanup timer and the explicit cleanup() path — mirroring observe().\n let streamCleanup: (() => void) | undefined;\n // Set when a concurrent resume ran the run first: the topic is that resume's.\n let lostResumeRace = false;\n\n // Single cleanup path for both the auto-cleanup timer and the explicit\n // cleanup(). Revokes continuation before unsubscribing the pubsub reader,\n // then tears down the registry entries and pubsub topic this execution\n // still owns — an execution that recovered the run in this process holds\n // its own. The topic stays when the run's latest execution here (this one\n // or a later resume()) lost the run: whoever took it over, in any process,\n // writes to it. Runs at most once.\n const runCleanup = createRunCleanup({\n scheduleTimer: cleanup => this.#scheduleReaderCleanup(executionFence, cleanup),\n release: () => {\n agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());\n streamCleanup?.();\n if (this.#releaseSegment(runId, segment, entry)) {\n if (getRunRegistryEntry(runId, this.#mastra) === globalEntryForAbort) {\n globalRunRegistry.delete(runId);\n if (\n !this.#unverifiedReaderFences.has(executionFence) &&\n !lostResumeRace &&\n (globalEntryForAbort?.executionFence ?? executionFence).ownsRunTopics()\n ) {\n this.#clearPubsubTopic(runId, globalEntryForAbort);\n }\n }\n }\n },\n });\n const performCleanup = runCleanup.run;\n const scheduleAutoCleanup = runCleanup.schedule;\n\n const globalEntry = getRunRegistryEntry(runId, this.#mastra);\n const resumeModel = globalEntry?.model as any;\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.\n // Opened before the stream adapter so per-chunk processor spans parent under it.\n const origTraceId = entry.agentSpan?.traceId;\n const origSpanId = entry.agentSpan?.id;\n // Spans this resume opened, ended by it alone if it turns out to have lost the run.\n const ownResumeSpans: Array<{ error: (options: { error: Error; endSpan: boolean }) => void } | undefined> = [];\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.\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 outcome: null,\n name: `agent run: '${ag.id}' (resumed)`,\n entityType: EntityType.AGENT,\n entityId: ag.id,\n entityName: ag.name,\n attributes: modelSpanAttributes(resumeModel),\n metadata: {\n runId,\n resumed: true,\n ...(origSpanId ? { resumedFromSpanId: origSpanId } : {}),\n ...(resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}),\n },\n resumeFrom: getResumeTracingContext(entry.agentSpan),\n tracingPolicy: agentTracingPolicy,\n tracingOptions: { traceId: origTraceId, ...entry.agentSpan?.traceState },\n traceState: entry.agentSpan?.traceState,\n samplingDecision: entry.agentSpan?.isValid,\n requestContext: resolvedOptions.requestContext,\n mastra: this.#mastra,\n });\n const resumeModelSpan = resumeAgentSpan?.createChildSpan({\n type: SpanType.MODEL_GENERATION,\n outcome: null,\n name: `llm: '${resumeModel?.modelId ?? ''}'`,\n attributes: { model: resumeModel?.modelId, provider: resumeModel?.provider, streaming: true },\n metadata: { runId, resumed: true },\n requestContext: resolvedOptions.requestContext,\n });\n ownResumeSpans.push(resumeModelSpan, resumeAgentSpan);\n for (const reg of [entry, getRunRegistryEntry(runId, this.#mastra)]) {\n if (!reg) continue;\n reg.resumeAgentSpan = resumeAgentSpan;\n reg.resumeModelSpan = resumeModelSpan;\n reg.resumeAgentSpanData = resumeAgentSpan?.snapshot?.() ?? resumeAgentSpan?.exportSpan();\n reg.resumeModelSpanData = resumeModelSpan?.snapshot?.() ?? resumeModelSpan?.exportSpan();\n // Fresh spans capture their own first-chunk clock, never a prior segment's.\n reg.resumeCompletionStartTime = undefined;\n reg.resumeTimeToFirstTokenMs = undefined;\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 const resumeSegmentSpan = entry.resumeAgentSpan ?? entry.agentSpan;\n\n // Same default-false semantics as the initial stream() path.\n const closeOnSuspend = (resolvedOptions as DurableAgentStreamOptions<TOutput>).closeOnSuspend ?? false;\n\n const {\n output,\n cleanup: createdStreamCleanup,\n detach: detachResumeStream,\n fail: failResumeStream,\n waitForEventDelivery,\n ready,\n } = createDurableAgentStream<TOutput>({\n pubsub: this.pubsub,\n runId,\n minGeneration: executionFence.generation,\n onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),\n messageId: crypto.randomUUID(),\n initialToolCalls,\n resumedText,\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 hideSignals: resolvedOptions.hideSignals,\n onStepFinish: resolvedOptions.onStepFinish,\n onFinish: resolvedOptions.onFinish,\n onStreamFinished: scheduleAutoCleanup,\n onError: async error => {\n await resolvedOptions.onError?.(error);\n scheduleAutoCleanup();\n },\n onAbort: async data => {\n try {\n await resolvedOptions.onAbort?.(data);\n } finally {\n scheduleAutoCleanup();\n }\n },\n onSuspended: resolvedOptions.onSuspended,\n // Resume segments settle at the persisted workflow result below. A sibling\n // that was already suspended may not emit another SUSPENDED event, while\n // evented execution may emit one before its snapshot is safe to resume.\n closeOnSuspend: false,\n structuredOutput: entry.structuredOutput as any,\n outputProcessors: entry.outputProcessors,\n processorStates: entry.processorStates,\n agent: entry.agent,\n requestContext: resolvedOptions.requestContext,\n // Caller option wins, then the flag persisted at prepare time. Only fall\n // back to resolvedOptions (which merges agent defaultOptions) last, so a\n // configured default can't override the original run-level request.\n returnScorerData: options?.returnScorerData ?? entry.returnScorerData ?? resolvedOptions.returnScorerData,\n tracingContext: resumeSegmentSpan ? { currentSpan: resumeSegmentSpan } : undefined,\n messageList: globalEntry?.messageList ?? this.#runRegistry.getMessageList(runId),\n });\n streamCleanup = createdStreamCleanup;\n\n // Wait for subscription to be ready, then resume workflow\n const requestContext = resolvedOptions.requestContext;\n\n const workflowExecution = executionFence.run(() =>\n ready\n .then(async () => {\n if (await this.#redeliverDeadlineError(entry, executionFence)) return;\n // Looked up inside the chain so a throw settles (releases) the claim.\n const workflow = this.getWorkflow();\n // The prior segment was settled above (before the event-offset\n // capture), so the snapshot is already persisted as 'suspended'.\n // Evented engine: make sure the workflow event workers are running\n // before resume — a resume in a fresh process (or after shutdown())\n // would otherwise publish events nobody consumes and hang.\n await this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);\n const run = await workflow.createRun({\n runId,\n resourceId: memoryInfo?.resourceId,\n pubsub: this.fenceRunPubSub(executionFence, abortController),\n });\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 this.withSuspensionAfterPersist(runId, () =>\n run.resume({\n resumeData,\n label: resolvedOptions.toolCallId,\n requestContext,\n actor: resolvedOptions.actor,\n ...createObservabilityContext({ currentSpan: entry.resumeAgentSpan ?? entry.agentSpan }),\n }),\n );\n } catch (error) {\n // This resume saw the run suspended when it claimed it, so the workflow no longer\n // being suspended means a concurrent resume ran it first. The run, its topic and\n // its spans belong to that resume: release the claim without writing run state\n // and report the lost race to this caller only.\n // When the resume claim is persisted (`persistResumeClaim`), the losing CAS reports the\n // race as WORKFLOW_RESUME_ALREADY_CLAIMED instead.\n if (\n error instanceof MastraError &&\n (error.id === 'WORKFLOW_RUN_NOT_SUSPENDED' || error.id === 'WORKFLOW_RESUME_ALREADY_CLAIMED')\n ) {\n const lost = new MastraError({\n id: 'AGENT_RESUME_ALREADY_CLAIMED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" resume(${runId}) cannot resume the run because another resume of it already ran.`,\n details: { agentName: this.name, runId },\n });\n lostResumeRace = true;\n await executionFence.settle(async () => {});\n for (const span of ownResumeSpans) span?.error({ error: lost, endSpan: true });\n await failResumeStream(lost);\n return;\n }\n throw error;\n } finally {\n await stopGoalActivity({ agentId: this.id, runId });\n if (result?.status !== 'suspended' && workflow.runs.get(runId) === run) {\n workflow.runs.delete(runId);\n }\n }\n await this.settleExecution(runId, executionFence, {\n status: result?.status,\n error:\n result?.status === 'failed'\n ? this.executionEngine.workflowFailureError((result as any).error, 'Workflow resume failed')\n : undefined,\n });\n if (result?.status === 'suspended' && closeOnSuspend) {\n // The workflow result is the authoritative persisted suspension boundary.\n // Flush transport buffers, then wait for callbacks already delivered to\n // this observer before closing only the resume segment. This preserves\n // onSuspended delivery without advancing queued resumes against a stale\n // sibling snapshot. Settling first releases the run, so a queued\n // resume can claim it without waiting.\n await this.pubsub.flush();\n await waitForEventDelivery();\n detachResumeStream();\n }\n })\n .catch(error =>\n this.settleExecution(runId, executionFence, {\n error: this.executionEngine.workflowExecutionError(error, 'Workflow resume failed'),\n }),\n )\n .finally(detachExternalAbort),\n );\n const trackedResumeEntry = getRunRegistryEntry(runId, this.#mastra);\n if (trackedResumeEntry) {\n trackedResumeEntry.workflowExecution = workflowExecution;\n }\n void workflowExecution.then(releaseResumeMarker, releaseResumeMarker);\n\n const resumeStreamOptions: AgentExecutionOptions<TOutput> = {\n ...resolvedOptions,\n runId,\n } as AgentExecutionOptions<TOutput>;\n const continued = agentThreadStreamRuntime.continueRun(\n this as unknown as Agent<any, any, any, any>,\n output,\n resumeStreamOptions,\n this.getPubSub(),\n { generation: executionFence.generation, ownershipLost: () => executionFence.isLost() },\n );\n if (!continued) {\n await agentThreadStreamRuntime.registerRun(\n this as unknown as Agent<any, any, any, any>,\n output,\n resumeStreamOptions,\n this.getPubSub(),\n {\n continuation: closeOnSuspend ? undefined : 'across-suspension',\n generation: executionFence.generation,\n ownershipLost: () => executionFence.isLost(),\n stepOwner: () => getRunRegistryEntry(runId, this.#mastra),\n },\n );\n }\n\n // Route the explicit cleanup through the shared performCleanup() so it and\n // the auto-cleanup timer release the same resources.\n const cleanup = performCleanup;\n\n const abort = async (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n // Also stop the run wherever it is actually executing — see\n // `requestRemoteAbort`. The local controller above only reaches steps\n // running in this process.\n await this.requestRemoteAbort(runId);\n // A run parked on a suspension has no steps left to stop; release it so\n // it is no longer listed as suspended.\n if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);\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 * Only orphaned runs are recovered. If another execution still owns the run\n * (its lease is live), this throws `DURABLE_AGENT_RUN_ACTIVE` with the\n * holder and a `retryAt` hint; pass `{ force: true }` to take the run over,\n * which aborts the other execution and rejects its later writes. A run this\n * process is already driving or recovering, or one that is suspended, is\n * refused with its own error id (use `resume()` for suspended runs).\n *\n * When the store doesn't fence runs, an execution whose lease lapsed with\n * nobody taking the run over keeps the thread's lease until that expires,\n * up to 15 seconds later. Until then this throws `DURABLE_AGENT_RUN_ACTIVE`\n * with `retryAt` no earlier than the expiry. The lease can't be released\n * sooner: an execution that recovers the run in the same process holds it\n * under the same run id.\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 this.#assertRecoveryActive();\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 await this.#warnIfUnfenced(workflowsStore, 'workflows');\n\n // 1. Validate the persisted durable-agent input before claiming ownership\n // so obvious caller errors fail fast.\n let { workflowInput } = await this.#loadRecoverableSnapshot(workflowsStore, runId);\n this.#assertRecoveryActive();\n\n // A crashed run that was executing a stored version must recover on\n // *that* version — rehydration rebuilds tools/model/instructions from\n // whatever `this` currently resolves to, which for status selectors\n // hot-switches to the latest publish (mirrors the resume() pin above).\n // Resolution happens BEFORE lease acquisition so we never delegate to a\n // fork while holding the lease; reading the pin from the pre-claim\n // snapshot is safe because `agentVersionId` is stamped once at\n // preparation and never mutated. Unlike resume(), recover options carry\n // no call-site version selector, so the pin always wins here — recovery\n // is unattended and has no operator escape hatch.\n const pinnedVersionId = workflowInput.agentVersionId;\n if (pinnedVersionId && this.#mastra && !this.__isStoredVersionApplied()) {\n const currentVersionId = this.toRawConfig()?.resolvedVersionId as string | undefined;\n if (pinnedVersionId !== currentVersionId) {\n try {\n const resolved = await this.#mastra.resolveVersionedAgent(this as unknown as Agent, {\n versionId: pinnedVersionId,\n });\n if (resolved !== (this as unknown as Agent)) {\n return (resolved as unknown as DurableAgent<TAgentId, TTools, TOutput>).recover(runId, options);\n }\n } catch (versionError) {\n // The pinned version may have been deleted while the run sat\n // crashed — recover on the current definition rather than failing\n // an unattended path (mirrors resume()'s deleted-pin fallback).\n this.logger.warn('Failed to resolve pinned agent version for durable recovery, using current definition', {\n agentId: this.id,\n runId,\n pinnedVersionId,\n error: versionError,\n });\n }\n }\n }\n\n // 2. Claim the run before resolving any live dependencies so a concurrent\n // caller cannot finish first and leave this attempt using a stale\n // snapshot.\n this.#assertRecoveryActive();\n const releaseLocalRecovery = this.#claimLocalRecovery(runId);\n const { controller: abortController } = createRunAbortController(options?.abortSignal);\n\n let executionFence: ExecutionFence | undefined;\n let recoveryState: RehydratedRecoveryState;\n let finishPublishedBeforeCrash: boolean;\n let claimedSnapshot: WorkflowRunState;\n try {\n // A run this process is still executing is not orphaned. Recovering it\n // here would replace the live execution's registry entry mid-flight\n // (#23734), so not even `force` takes it over. Checked after the local\n // recovery claim so a concurrent recover() still reports\n // DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS.\n const localExecution = ExecutionFence.getLocalActive(runId);\n if (localExecution && !localExecution.isLost()) {\n throw new MastraError({\n id: RECOVER_RUN_ACTIVE_LOCALLY_ERROR_ID,\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" recover(${runId}): this process is still executing the run. Wait for it to finish instead of recovering it.`,\n details: { agentName: this.name, runId },\n });\n }\n // Claim the run only while no execution is live, or take it over from\n // the live one under `force`, before reading its state: from here on any\n // other execution can no longer write (#23734).\n executionFence = await this.#claimExecution(\n runId,\n options?.force ? 'takeover' : 'recover',\n undefined,\n this.#untrackedRunLiveness(runId, workflowInput),\n );\n this.#assertRecoveryActive();\n // An earlier owner may have completed while this one claimed. Re-read\n // after the claim and recover from that authoritative snapshot, never\n // from the pre-claim copy.\n const loaded = await this.#loadRecoverableSnapshot(workflowsStore, runId);\n workflowInput = loaded.workflowInput;\n claimedSnapshot = loaded.snapshot;\n // map-final-output publishes FINISH before saving its result. Restart skips\n // that saved success, so recovery must publish FINISH for the new subscriber.\n finishPublishedBeforeCrash = loaded.snapshot.context?.[MAP_FINAL_OUTPUT_STEP_ID]?.status === 'success';\n // Before anything is registered, so a failed load leaves only the claim to release.\n await this.#loadRecalledMessages(runId, loaded.snapshot);\n executionFence.throwIfLost();\n recoveryState = await this.#rehydrateRecoveryState({\n runId,\n workflowInput,\n abortController,\n executionFence,\n originalSpansEnded: originalSpansEndedBeforeCrash(loaded.snapshot),\n latestMessageListState: await this.#loadLatestMessageListState(workflowsStore, runId, loaded.snapshot),\n });\n // Memory is resolved from the rehydrated context; rehydration does not write to it.\n await this.#coverMemory(executionFence, recoveryState.requestContext, true);\n this.#recoveredEntries.set(executionFence, recoveryState.registryEntry as unknown as RunRegistryEntry);\n this.#assertRecoveryActive();\n } catch (error) {\n const settlement = await executionFence?.settle(async () => {});\n if (executionFence && settlement !== 'superseded' && shouldReportRecoveryFailure(error)) {\n await this.#reportRecoveryFailure(runId, error, executionFence.generation);\n }\n releaseLocalRecovery();\n throw error;\n }\n const { requestContext, threadId, resourceId, messageList, recoverAgentSpan, recoverModelSpan, registryEntry } =\n recoveryState;\n if (executionFence.generation !== undefined) {\n // Record the earliest event from the step the persisted snapshot will re-execute.\n // A replay can then omit the abandoned tail without losing completed iterations.\n const supersededFrom = await this.#supersededFrom(workflowsStore, runId, claimedSnapshot);\n await emitOwnershipClaimedEvent(this.pubsub, runId, executionFence.generation, supersededFrom).catch(error => {\n this.logger.warn(`[DurableAgent] recover(${runId}) failed to announce its claim on the run stream`, {\n runId,\n error,\n });\n });\n }\n setExecutionClaim(requestContext, runId, executionFence.claim);\n registryEntry.executionFence = executionFence;\n\n // 3. Cleanup plumbing (mirrors stream()/resume()).\n // Assigned once the recovered stream is created below so the shared\n // performCleanup() closure can unsubscribe the pubsub reader (via\n // streamCleanup) from both the auto-cleanup timer and the explicit\n // cleanup() path — mirroring observe().\n let streamCleanup: (() => void) | undefined;\n const cleanupOwnedRegistryState = () => {\n // A warm resume reuses the registry entry but replaces its execution fence.\n if (registryEntry.executionFence !== executionFence) return;\n if (this.#runRegistry.get(runId) === registryEntry) {\n this.#runRegistry.cleanup(runId);\n }\n if (getRunRegistryEntry(runId, this.#mastra) === registryEntry) {\n globalRunRegistry.delete(runId);\n // The topic stays when the run's latest execution here (this one or a\n // later resume()) lost the run: whoever took it over writes to it.\n if (\n !this.#unverifiedReaderFences.has(executionFence) &&\n (registryEntry.executionFence?.ownsRunTopics() ?? true)\n )\n this.#clearPubsubTopic(runId, registryEntry);\n }\n };\n // Single cleanup path for the auto-cleanup timer, the explicit cleanup(),\n // and the recovery error paths. Revokes continuation before unsubscribing\n // the pubsub reader, then tears down the owned registry entries. Runs at\n // most once.\n const runCleanup = createRunCleanup({\n scheduleTimer: cleanup => this.#scheduleReaderCleanup(executionFence, cleanup),\n release: () => {\n agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());\n streamCleanup?.();\n cleanupOwnedRegistryState();\n },\n });\n const performCleanup = runCleanup.run;\n const scheduleAutoCleanup = runCleanup.schedule;\n\n let workflow: ReturnType<DurableAgent<TAgentId, TTools, TOutput>['getWorkflow']>;\n try {\n this.#assertRecoveryActive();\n workflow = this.getWorkflow();\n } catch (error) {\n const settlement = await executionFence.settle(async () => {});\n if (settlement !== 'superseded' && shouldReportRecoveryFailure(error)) {\n await this.#reportRecoveryFailure(runId, error, executionFence.generation);\n }\n releaseLocalRecovery();\n throw error;\n }\n\n // 4. Register the reconstructed state and recovered stream only after\n // claiming the run.\n const { stream, threadRegistration } = await this.#setupRecoveredStream({\n runId,\n workflowInput,\n requestContext,\n threadId,\n resourceId,\n messageList,\n registryEntry,\n options,\n scheduleAutoCleanup,\n executionFence,\n }).catch(error => {\n releaseLocalRecovery();\n throw error;\n });\n const { output, cleanup: createdStreamCleanup, ready } = stream;\n streamCleanup = createdStreamCleanup;\n const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);\n\n // 5. 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 // Races the claim's loss so a recovery that lost the run settles promptly\n // even if the workflow ignores the abort.\n const workflowExecution = executionFence.run(() =>\n this.#raceFenceLoss(ready, executionFence)\n .then(async () => {\n executionFence.throwIfLost();\n this.#assertRecoveryActive();\n await this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);\n executionFence.throwIfLost();\n this.#assertRecoveryActive();\n const run = await this.#raceFenceLoss(\n workflow.createRun({ runId, resourceId, pubsub: recoveryPubsub }),\n executionFence,\n );\n executionFence.throwIfLost();\n this.#assertRecoveryActive();\n const result = await this.#raceFenceLoss(\n run.restart({\n requestContext,\n ...createObservabilityContext({ currentSpan: recoverAgentSpan }),\n } as any),\n executionFence,\n );\n executionFence.throwIfLost();\n if (finishPublishedBeforeCrash && result?.status === 'success') {\n // The run's result is map-final-output's saved output, passed through\n // execute-scorers unchanged: the same payload the lost FINISH carried.\n const { output: finalOutput, stepResult } = result.result;\n // map-final-output, which ends the recovered spans, did not re-run.\n // Workflow success alone cannot distinguish an agent success from a limit/block.\n // Keep unknown until the authoritative termination is recovered (OBS-754).\n recoverModelSpan?.end();\n recoverAgentSpan?.end({ output: { text: finalOutput?.text } });\n await emitFinishEvent(recoveryPubsub, runId, { output: finalOutput, stepResult });\n }\n if (result?.status === 'suspended' && options?.closeOnSuspend) {\n // Same contract as resume(): close on the persisted suspension,\n // after flushing and delivering already-published events.\n await this.pubsub.flush();\n await stream.waitForEventDelivery();\n executionFence.throwIfLost();\n stream.detach();\n }\n // Snapshot cleanup runs for every non-suspended terminal (success or\n // failed) so storage stays bounded — mirrors the start()/resume()\n // contract — but only while this recovery still owns the run.\n const finished = !!result?.status && result.status !== 'suspended';\n await executionFence.settle(async () => {\n if (finished) await this.deleteRunSnapshots(runId);\n });\n if (result?.status === 'failed') {\n throw this.executionEngine.workflowFailureError((result as any).error, 'Workflow recover failed');\n }\n })\n .catch(async error => {\n if (error?.id === RECOVER_SHUTDOWN_ERROR_ID) {\n await executionFence.abandon();\n }\n const executionError = this.executionEngine.workflowExecutionError(error, 'Workflow recover failed');\n // Settles a recovery that failed before the run finished; otherwise\n // returns the settlement reached above.\n const settlement = await executionFence.settle(async () => {});\n if (settlement === 'superseded') {\n // Nothing is reported for a superseded recovery, so nothing else\n // ends the recovered spans; stores only persist span ends.\n const output = { status: 'interrupted' as const, reason: 'recovery superseded' };\n recoverModelSpan?.end({ output, outcome: 'interrupted', stopReason: null, stopReasonContext: null });\n recoverAgentSpan?.end({ output, outcome: 'interrupted', stopReason: null, stopReasonContext: null });\n // The execution that took the run over holds the thread lease under\n // the same runId and owns the run's topic: leave both to it.\n await threadRegistration?.rollback({ releaseLease: false });\n performCleanup();\n } else if (\n !this.#timedOutExecutions.has(executionFence) &&\n !(await this.#reportRecoveryFailure(runId, executionError, executionFence.generation))\n ) {\n await threadRegistration?.rollback();\n performCleanup();\n }\n throw executionError;\n })\n .finally(releaseLocalRecovery),\n );\n const trackedRecoverEntry = getRunRegistryEntry(runId, this.#mastra);\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 // Route the explicit cleanup through the shared performCleanup() so it, the\n // auto-cleanup timer, and the recovery error paths release the same resources.\n const cleanup = performCleanup;\n\n const abort = async (reason?: unknown) => {\n if (!abortController.signal.aborted) {\n abortController.abort(reason);\n }\n // Also stop the run wherever it is actually executing — see\n // `requestRemoteAbort`. The local controller above only reaches steps\n // running in this process.\n await this.requestRemoteAbort(runId);\n // A run parked on a suspension has no steps left to stop; release it so\n // it is no longer listed as suspended.\n if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);\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 closeOnSuspend: resumeOptions.closeOnSuspend ?? true,\n } as Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2]);\n return result.output;\n }\n\n /** @deprecated Use `resumeStream(resumeData, { untilIdle: true })` instead. */\n override async resumeStreamUntilIdle(resumeData: any, streamOptions?: any): Promise<MastraModelOutput<TOutput>> {\n const { maxIdleMs, ...options } = streamOptions ?? {};\n return this.resumeStream(resumeData, {\n ...options,\n untilIdle: maxIdleMs === undefined ? true : { maxIdleMs },\n });\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; reason?: string } & Record<string, any>,\n ): Promise<MastraModelOutput<any>> {\n const { reason, ...resumeOptions } = options;\n return this.resumeStream({ approved: false, ...(reason !== undefined ? { reason } : {}) }, resumeOptions);\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({ approved: true }, { ...resumeOptions, runId } as any) as any;\n }\n\n override async declineToolCallGenerate<OUTPUT = undefined>(\n options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string; reason?: string },\n ): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['getFullOutput']>>> {\n const { runId, reason, ...resumeOptions } = options;\n return this.resumeGenerate({ approved: false, ...(reason !== undefined ? { reason } : {}) }, {\n ...resumeOptions,\n runId,\n } 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: both `DurableAgent` and `EventedAgent` track\n * the workflow engine's `run.start()` through snapshot persistence, so\n * awaiting `workflowExecution` on suspend is sufficient for a subsequent\n * `resumeGenerate()` to find the snapshot.\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(applyReservedMemoryContextKeys(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 validateModelTimeoutSettings(options?.modelSettings?.timeout);\n\n // 1. Claim the run before preparing it — see stream().\n const runId = options?.runId ?? crypto.randomUUID();\n const requestContext = options?.requestContext ?? new RequestContext();\n const executionFence = await this.#claimExecution(runId, 'acquire', requestContext);\n\n // 1a. Prepare for durable execution (non-durable phase)\n let preparation: PreparationResult<TOutput>;\n try {\n preparation = await prepareForDurableExecution<TOutput>({\n agent: this.#wrappedAgent as Agent<string, any, TOutput>,\n messages,\n options: options as AgentExecutionOptions<TOutput>,\n runId,\n requestContext,\n optionsAreResolved: true,\n resolvedDefaultOptions: (options as any)?.[RESOLVED_DEFAULT_OPTIONS],\n scopesResolved: true,\n mastra: this.#mastra,\n methodType: 'generate',\n durableAgentId: this.id,\n durableAgentName: this.name,\n });\n } catch (error) {\n // The run never started: drop its owner record rather than leave it behind.\n await executionFence.settle(async () => {});\n throw error;\n }\n\n const { messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;\n // Set after preparation so request-context schema validation never sees it.\n setExecutionClaim(requestContext, runId, executionFence.claim);\n registryEntry.executionFence = executionFence;\n this.#runInputs.set(executionFence, workflowInput);\n\n // 1b. 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 { controller: abortController } = createRunAbortController(options?.abortSignal);\n if (agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) {\n abortController.abort();\n }\n this.#installAbortWithTotalTimeout(registryEntry, abortController, executionFence);\n\n // Share the scope before either registry copies the entry.\n const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);\n\n // 2. Register non-serializable state (both local and global registries)\n registryEntry.agentId = this.id;\n this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, { threadId, resourceId });\n const globalRegistryEntry = { ...registryEntry, messageList };\n globalRunRegistry.set(runId, globalRegistryEntry);\n await this.#attachStreamPublisher(runId, { threadId, resourceId });\n\n // Tears down the registry entries and pubsub topic this execution still\n // owns, as stream() does: an execution that recovered the run in this\n // process registers its own under the same runId, and one that took the\n // run over, in any process, writes to the topic.\n const releaseRunState = () => {\n if (this.#runRegistry.get(runId) === registryEntry) {\n this.#runRegistry.cleanup(runId);\n }\n if (getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {\n globalRunRegistry.delete(runId);\n if (\n !this.#unverifiedReaderFences.has(executionFence) &&\n (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)\n )\n this.#clearPubsubTopic(runId, globalRegistryEntry);\n }\n };\n\n // The explicit cleanup() also revokes continuation and unsubscribes the\n // pubsub reader; the auto-cleanup timer only releases the run state.\n const runCleanup = createRunCleanup({\n scheduleTimer: cleanup => this.#scheduleReaderCleanup(executionFence, cleanup),\n release: () => {\n agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());\n streamCleanup();\n releaseRunState();\n },\n releaseOnTimer: releaseRunState,\n });\n // Schedule automatic registry cleanup after stream ends\n const scheduleAutoCleanup = runCleanup.schedule;\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 minGeneration: executionFence.generation,\n onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),\n readLocalRequest,\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 processorStates: registryEntry.processorStates,\n agent: registryEntry.agent,\n requestContext: registryEntry.requestContext,\n returnScorerData: workflowInput.options.returnScorerData,\n tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : undefined,\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 = executionFence.run(() =>\n ready\n .then(async () => {\n if (await this.#redeliverDeadlineError(registryEntry, executionFence)) return;\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(fencePubSub(this.pubsub, executionFence), 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: getRunRegistryEntry(runId, this.#mastra)?.requestContext,\n });\n }\n try {\n await this.persistInitialInput(runId, workflowInput);\n return await this.executeWorkflow(runId, workflowInput);\n } finally {\n await stopGoalActivity({ agentId: workflowInput.agentId, runId });\n }\n })\n .catch(error =>\n this.settleExecution(runId, executionFence, {\n error: this.executionEngine.workflowExecutionError(error, 'Workflow execution failed'),\n }),\n ),\n );\n const trackedEntry = getRunRegistryEntry(runId, this.#mastra);\n if (trackedEntry) {\n trackedEntry.workflowExecution = workflowExecution;\n }\n\n // 5. Create cleanup function (cancels auto-cleanup timer if called)\n const cleanup = runCleanup.run;\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 getRunRegistryEntry(runId, this.#mastra)?.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 resumeData: unknown,\n options: Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2] & { runId: string },\n ): Promise<FullOutput<TOutput>>;\n /** @deprecated Use `resumeGenerate(resumeData, { runId, ...options })`, matching `Agent.resumeGenerate`. */\n async resumeGenerate(\n runId: string,\n resumeData: unknown,\n options?: Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2],\n ): Promise<FullOutput<TOutput>>;\n async resumeGenerate(...args: unknown[]): Promise<FullOutput<TOutput>> {\n const { runId, resumeData, options } = normalizeResumeGenerateArgs(args);\n const result = await this.resume(runId, resumeData, {\n ...(options ?? {}),\n closeOnSuspend: 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 getRunRegistryEntry(result.runId, this.#mastra)?.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). See https://mastra.ai/docs/storage`,\n details: { agentName: this.name },\n });\n }\n\n // resourceId is a storage column, so it is pushed down to narrow the query\n // (the in-process check below remains as backstop for adapters that skip\n // the filter and for rows persisted before the column was populated).\n // Filtering by agentId/threadId happens in application code because those\n // fields only exist inside each row's `snapshot` JSON — storage adapters\n // have no predicate for them. Fetch candidates in bounded batches so peak\n // memory is O(batch size) hydrated snapshots instead of every `running`\n // row's full snapshot at once (#21501). Only the small per-run summary is\n // retained across batches; each batch's snapshots are discarded before the\n // next fetch.\n const matchedRuns: DurableAgentActiveRun[] = [];\n for (let storagePage = 0; ; storagePage++) {\n const { runs, total: storageTotal } = await workflowsStore.listWorkflowRuns({\n workflowName: DurableStepIds.AGENTIC_LOOP,\n status: 'running',\n resourceId,\n fromDate,\n toDate,\n perPage: LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE,\n page: storagePage,\n });\n\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 // A short batch means the last page. A batch larger than requested means\n // the adapter ignored pagination and returned everything in one call —\n // continuing would refetch the same rows forever.\n if (runs.length !== LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE) break;\n if ((storagePage + 1) * LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE >= storageTotal) break;\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 * Only orphaned runs are recovered. A run another execution still drives,\n * in this process or another, is reported as `skipped`; for one live in\n * another process, `retryAt` says when to check again. A run that finished\n * or suspended before its turn is left out.\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 if (this.#mastra?.__shuttingDown) return { recovered: [], succeeded: 0, failed: 0 };\n const { runId, ...discoveryOptions } = options;\n\n // Without fencing in the workflows store nothing is fenced, memory included.\n const storage = this.#mastra?.getStorage();\n if (!(await this.#warnIfUnfenced(await storage?.getStore('workflows'), 'workflows'))) {\n await this.#warnIfUnfenced(await storage?.getStore('memory'), 'memory');\n }\n\n let targetRunIds: string[];\n if (runId) {\n // Like discovery, an explicit run is only recovered while its snapshot is\n // `running`: a finished run has nothing to recover, and a suspended one\n // waits for resume().\n targetRunIds = (await this.#isRunningSnapshot(runId)) ? [runId] : [];\n } else {\n const { runs } = await this.listActiveRuns(discoveryOptions);\n targetRunIds = runs.map(r => r.runId);\n }\n\n const outcomes: (DurableAgentRecoveredRun | undefined)[] = new Array(targetRunIds.length);\n const timeoutOutcome = (targetRunId: string): DurableAgentRecoveredRun => ({\n runId: targetRunId,\n status: 'skipped',\n reason: 'recovery-timeout',\n retryAt: Date.now() + TRANSIENT_RECOVERY_RETRY_DELAY_MS,\n });\n\n await runWithConcurrency(\n targetRunIds.map((targetRunId, index) => ({ targetRunId, index })),\n DEFAULT_RESTART_CONCURRENCY,\n async ({ targetRunId, index }) => {\n if (this.#mastra?.__shuttingDown) return;\n if (this.#hasRecoveryAttempt(targetRunId)) {\n outcomes[index] = timeoutOutcome(targetRunId);\n return;\n }\n const attempt = this.#startRecoveryAttempt(\n targetRunId,\n async (): Promise<DurableAgentRecoveredRun | undefined> => {\n if (this.#mastra?.__shuttingDown) return;\n let runError: Error | undefined;\n let started = false;\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. `recover()` cleans up on its own after FINISH/ERROR and keeps\n // suspended runs registered, so thread subscribers still see the\n // terminal event and a later approval can resume the run (#25891).\n // With auto-cleanup disabled nothing else releases a finished run, and\n // bulk callers never get the cleanup handle. Release it once the\n // terminal event has been delivered; suspended runs never get here.\n let releaseAfterTerminal: (() => void) | undefined;\n const onTerminal = () => {\n if (this.__getStreamBus().cleanupTimeoutMs === 0) setTimeout(() => releaseAfterTerminal?.(), 0);\n };\n const { cleanup } = await this.recover(targetRunId, {\n onError: ({ error }) => {\n runError = error instanceof Error ? error : new Error(String(error));\n onTerminal();\n },\n onFinish: onTerminal,\n onAbort: onTerminal,\n });\n started = true;\n releaseAfterTerminal = cleanup;\n try {\n const workflowExecution = getRunRegistryEntry(targetRunId, this.#mastra)?.workflowExecution;\n if (workflowExecution) {\n await workflowExecution;\n }\n } catch (error) {\n cleanup();\n throw error;\n }\n if (runError) throw runError;\n return { runId: targetRunId, status: 'success' };\n } catch (error) {\n const errorId = (error as { id?: unknown })?.id;\n if (!runError && (errorId === RECOVER_SHUTDOWN_ERROR_ID || errorId === EXECUTION_ABANDONED_ERROR_ID)) {\n return { runId: targetRunId, status: 'skipped' };\n }\n if (!started) {\n // The checkpoint disappeared or the run suspended between discovery and recovery.\n if (\n errorId === RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID ||\n errorId === RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID ||\n errorId === RECOVER_RUN_SUSPENDED_ERROR_ID\n )\n return;\n const skipped = recoverySkip(error);\n if (skipped) {\n if (skipped.reason === 'transient-error') {\n this.#mastra\n ?.getLogger()\n ?.warn(`[DurableAgent] Deferring recovery of run ${targetRunId} after a transient error`, {\n error,\n retryAt: skipped.retryAt,\n });\n }\n return { runId: targetRunId, status: 'skipped', ...skipped };\n }\n }\n const err = runError ?? (error instanceof Error ? error : new Error(String(error)));\n this.#mastra\n ?.getLogger?.()\n ?.error?.(`[DurableAgent] Failed to recover run ${targetRunId}: ${err.message}`, { error: err });\n return { runId: targetRunId, status: 'failed', error: err };\n }\n },\n );\n const bounded = this.#mastra\n ? await this.#mastra.__awaitDurableRecoveryAttempt(attempt, `durable agent ${this.id} run ${targetRunId}`)\n : { value: await attempt };\n outcomes[index] = bounded ? bounded.value : timeoutOutcome(targetRunId);\n },\n );\n\n const recovered = outcomes.filter((outcome): outcome is DurableAgentRecoveredRun => outcome !== undefined);\n const succeeded = recovered.filter(outcome => outcome.status === 'success').length;\n const failed = recovered.filter(outcome => outcome.status === 'failed').length;\n return { recovered, succeeded, failed };\n }\n\n /** Locate the start of the model step that recovery will re-execute, if it was published. */\n async #supersededFrom(\n workflowsStore: WorkflowsStorage,\n runId: string,\n parentSnapshot: WorkflowRunState,\n ): Promise<number | undefined> {\n try {\n const nestedRunId = parentSnapshot.context?.[DurableStepIds.AGENTIC_EXECUTION]?.metadata?.nestedRunId;\n const nested = await workflowsStore.getWorkflowRunById({\n runId: typeof nestedRunId === 'string' ? nestedRunId : runId,\n workflowName: DurableStepIds.AGENTIC_EXECUTION,\n });\n const snapshot = typeof nested?.snapshot === 'string' ? JSON.parse(nested.snapshot) : nested?.snapshot;\n if (!snapshot || snapshot.context?.[DurableStepIds.LLM_EXECUTION]?.status === 'success') return;\n const stepIndex = snapshot.context?.input?.iterationCount;\n if (typeof stepIndex !== 'number') return;\n const history = (await this.pubsub.getHistory(AGENT_STREAM_TOPIC(runId), 0)) as AgentStreamEvent[];\n const starts = history.filter(\n event =>\n (event.type === AgentStreamEventTypes.ITERATION_START || event.type === AgentStreamEventTypes.STEP_START) &&\n event.stepIndex === stepIndex,\n );\n const latestGeneration = starts.reduce<number | undefined>(\n (latest, event) =>\n typeof event.generation === 'number' ? Math.max(latest ?? event.generation, event.generation) : latest,\n undefined,\n );\n return (\n starts.find(\n event => event.type === AgentStreamEventTypes.ITERATION_START && event.generation === latestGeneration,\n ) ?? starts.find(event => event.generation === latestGeneration)\n )?.index;\n } catch (error) {\n this.logger.warn(`[DurableAgent] recover(${runId}) couldn't locate the uncheckpointed stream tail`, { error });\n }\n }\n\n /**\n * A replay from an offset can start past the marker of the execution that\n * took the run over, and would then accept what the lost execution still\n * publishes, its finish included. Start the reader with the floor it would\n * have reached by reading the skipped events: the highest generation among\n * them. Ordinary suspend/resume segments then still replay, since each\n * segment's events precede the next claim. When the transport keeps no\n * history to read, follow the run's current claim instead.\n * Runs fenced by a pubsub lease have no generation and are unaffected.\n * The floor only adds protection, so a failed read must not fail the reconnect;\n * the reader reads the claim again before an event can end its stream.\n */\n async #readReplayFloor(\n runId: string,\n offset: number | undefined,\n ): Promise<\n Pick<DurableStreamAdapterOptions, 'minGeneration' | 'rereadMinGeneration' | 'keepReplayEvent'> & {\n refreshReplayFilter?: () => Promise<unknown>;\n }\n > {\n try {\n const history = (await this.pubsub.getHistory(AGENT_STREAM_TOPIC(runId), 0)) as AgentStreamEvent[];\n const initialFilter = createSupersededEventFilter(history);\n let refreshedFilter: Promise<typeof initialFilter> | undefined;\n let currentFilter: typeof initialFilter | undefined;\n // Subscription can replay a newer claim than the snapshot above. Refresh\n // before the first replayed event; live events and later deliveries stay synchronous.\n const refreshReplayFilter = () => {\n refreshedFilter ??= this.pubsub\n .getHistory(AGENT_STREAM_TOPIC(runId), 0)\n .then(entries => (currentFilter = createSupersededEventFilter(entries as AgentStreamEvent[])))\n .catch(() => (currentFilter = initialFilter));\n return refreshedFilter;\n };\n const keepReplayEvent = (event: AgentStreamEvent): boolean | Promise<boolean> => {\n if (event.index === undefined) return (currentFilter ?? initialFilter)(event);\n if (currentFilter) return currentFilter(event);\n return refreshReplayFilter().then(filter => filter(event));\n };\n if (!offset) return { keepReplayEvent, refreshReplayFilter };\n const skipped = history.slice(0, offset);\n if (skipped.length === offset) {\n let floor: number | undefined;\n for (const event of skipped) {\n const generation = event.generation;\n if (typeof generation === 'number' && (floor === undefined || generation > floor)) floor = generation;\n }\n return { minGeneration: floor, keepReplayEvent, refreshReplayFilter };\n }\n return { minGeneration: await readRunGeneration(this.#mastra, runId), keepReplayEvent, refreshReplayFilter };\n } catch (error) {\n this.logger.warn(`[DurableAgent] Couldn't read the claim of run ${runId}; observing it without a floor`, {\n error,\n });\n return { rereadMinGeneration: () => readRunGeneration(this.#mastra, runId) };\n }\n }\n\n /** Reconcile only after subscribing, so a completion racing attachment is not lost. */\n async #isObservationComplete(runId: string): Promise<boolean> {\n try {\n const workflowsStore = await this.#mastra?.getStorage()?.getStore('workflows');\n // Read twice before concluding absence/completion. In particular a newer\n // claim must win over terminal replay from the execution it superseded.\n for (let attempt = 0; attempt < 2; attempt++) {\n const history = await this.pubsub.getHistory(AGENT_STREAM_TOPIC(runId), 0);\n // A newer segment's nonterminal history keeps the observer attached even\n // when ownership reads fail or an older segment ended with suspension.\n const historyGeneration = history.reduce<number | undefined>(\n (floor, event) =>\n event.generation === undefined ? floor : Math.max(floor ?? event.generation, event.generation),\n undefined,\n );\n const latest = history.findLast(\n event =>\n event.generation === undefined || historyGeneration === undefined || event.generation >= historyGeneration,\n );\n if (latest) {\n const type = latest.type === AgentStreamEventTypes.CHUNK ? latest.data?.type : latest.type;\n if (type !== 'finish' && type !== 'error' && type !== 'abort') return false;\n }\n const ownership =\n workflowsStore && (await supportsRunFencing(workflowsStore))\n ? await workflowsStore.getRunOwnership({ runId })\n : undefined;\n const minGeneration = history.reduce<number | undefined>(\n (floor, event) =>\n event.generation === undefined ? floor : Math.max(floor ?? event.generation, event.generation),\n ownership?.generation,\n );\n const keepGeneration = createRunGenerationFilter({ minGeneration });\n let hasHistory = false;\n let terminal = false;\n for (const event of history) {\n if (!(await keepGeneration(event as unknown as AgentStreamEvent))) continue;\n hasHistory = true;\n const type = event.type === AgentStreamEventTypes.CHUNK ? event.data?.type : event.type;\n if (type === 'finish' || type === 'error' || type === 'abort') terminal = true;\n }\n if (!terminal) {\n if (hasHistory || ownership?.live) return false;\n if (getRunRegistryEntry(runId, this.#mastra) || this.#runRegistry.get(runId)) return false;\n if (await resolveLeaseProvider(this.pubsub).getLeaseOwner(executionLeaseKey(this.id, runId))) {\n return false;\n }\n if (workflowsStore) {\n for (const workflowName of [DurableStepIds.AGENTIC_LOOP, DurableStepIds.AGENTIC_EXECUTION]) {\n const record = await workflowsStore.getWorkflowRunById({ runId, workflowName });\n if (!record) continue;\n const snapshot =\n typeof record.snapshot === 'string'\n ? (JSON.parse(record.snapshot) as WorkflowRunState)\n : record.snapshot;\n const input = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (input?.__workflowKind === 'durable-agent' && input.agentId !== this.id) {\n throw new MastraError({\n id: 'DURABLE_AGENT_OBSERVE_AGENT_MISMATCH',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" observe(${runId}): persisted run belongs to agent \"${input.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: input.agentId },\n });\n }\n // A failed cleanup can leave terminal snapshots behind. Unknown\n // statuses stay observable, including suspension without a lease.\n if (\n !snapshot ||\n !['success', 'failed', 'tripwire', 'canceled', 'bailed', 'skipped'].includes(snapshot.status)\n ) {\n return false;\n }\n }\n }\n }\n }\n return true;\n } catch (error) {\n if (error instanceof MastraError && error.id === 'DURABLE_AGENT_OBSERVE_AGENT_MISMATCH') throw error;\n // Unavailable lifecycle evidence cannot prove that the producer is gone.\n return false;\n }\n }\n\n /**\n * Subscribe to a run's raw AgentStreamEvents, filtering out events from\n * executions that lost ownership and takeover markers. Callers must map\n * these events to the public frame contract produced by stream-adapter.ts's\n * createDurableAgentStream before sending them to clients; raw event\n * envelopes are not public stream frames. Resolves once subscribed, with\n * a function that unsubscribes.\n *\n * @internal\n */\n async __subscribeToRunStream(\n runId: string,\n options: { offset?: number; onComplete?: () => void },\n onEvent: (event: AgentStreamEvent) => void,\n ): Promise<() => Promise<void>> {\n const replayFloor = await this.#readReplayFloor(runId, options.offset);\n const keepGeneration = createRunGenerationFilter(replayFloor);\n const topic = AGENT_STREAM_TOPIC(runId);\n let subscribed = true;\n let activityVersion = 0;\n let bufferingReplay = true;\n const bufferedEvents: Array<() => Promise<void>> = [];\n\n // Step-finish events carry only the response messages that changed; rebuild the full list so\n // the frames match what the run's own stream reports. A reader starting at an offset first\n // rebuilds it from the events it skips.\n let responseMessages: ResponseMessagesReplay = { messages: [] };\n const offset = options.offset;\n if (offset !== undefined && offset > 0 && this.pubsub.supportsOffsets) {\n try {\n const skipped = (await this.pubsub.getHistory(topic, 0)).filter(\n event => typeof event.index === 'number' && event.index < offset,\n );\n responseMessages = replayResponseMessages(skipped);\n } catch (error) {\n this.logger.warn(`[DurableAgent] Couldn't read run ${runId}'s history before offset ${offset}`, { error });\n }\n }\n\n const deliver = (event: AgentStreamEvent) => {\n activityVersion++;\n if (\n !subscribed ||\n event.type === AgentStreamEventTypes.OWNERSHIP_CLAIMED ||\n event.type === AgentStreamEventTypes.ITERATION_START\n )\n return;\n const chunk = event.type === AgentStreamEventTypes.CHUNK ? (event.data as AgentChunkEventData) : undefined;\n if (chunk?.type === 'step-finish' && chunk.payload) {\n event = {\n ...event,\n data: {\n ...chunk,\n payload: withRebuiltResponseMessages(\n responseMessages,\n chunk.payload as unknown as AgentStreamStepFinishPayload,\n ),\n },\n };\n }\n // Keep `index`: the observe route forwards it on each frame so clients can resume at index + 1.\n onEvent(event);\n };\n const filterEvent = (streamEvent: AgentStreamEvent) => {\n const filterGeneration = () => {\n const keep = keepGeneration(streamEvent);\n if (typeof keep === 'boolean') {\n if (keep) deliver(streamEvent);\n return;\n }\n return keep.then(kept => {\n if (kept) deliver(streamEvent);\n });\n };\n const keepReplay = replayFloor.keepReplayEvent?.(streamEvent);\n if (keepReplay === undefined || keepReplay === true) return filterGeneration();\n if (keepReplay === false) return;\n return keepReplay.then(keep => {\n if (keep) return filterGeneration();\n });\n };\n // Replayed frames are held until attachment finishes and the claim history\n // is refreshed; a claim can arrive partway through replay. Acknowledge only\n // after filtering and delivery, including frames that are dropped.\n const acknowledge = withAck(event => filterEvent(event as AgentStreamEvent));\n const callback: ReturnType<typeof withAck> = (event, ...args) => {\n if (!subscribed) return args[0]?.() ?? Promise.resolve();\n activityVersion++;\n if (bufferingReplay) {\n bufferedEvents.push(async () => {\n await acknowledge(event, ...args);\n });\n return Promise.resolve();\n }\n return acknowledge(event, ...args);\n };\n const unsubscribe = async () => {\n if (!subscribed) return;\n subscribed = false;\n await this.pubsub.unsubscribe(topic, callback);\n };\n\n try {\n await (options.offset !== undefined\n ? this.pubsub.subscribeFromOffset(topic, options.offset, callback)\n : this.pubsub.subscribeWithReplay(topic, callback));\n await replayFloor.refreshReplayFilter?.();\n // Index cursor keeps the drain linear; live frames can still append while draining.\n for (let i = 0; i < bufferedEvents.length; i++) {\n await bufferedEvents[i]!();\n }\n bufferedEvents.length = 0;\n bufferingReplay = false;\n\n const reconciledVersion = activityVersion;\n if (options.onComplete && (await this.#isObservationComplete(runId)) && activityVersion === reconciledVersion) {\n options.onComplete();\n }\n return unsubscribe;\n } catch (error) {\n await unsubscribe();\n throw error;\n }\n }\n\n /**\n * Observe an existing stream.\n * Use this to reconnect to a stream after a network disconnection.\n *\n * To stop observing without affecting the run, call the returned `detach()`\n * or leave the `for await` loop over `fullStream` (break, return, or throw).\n * Both unsubscribe this observer only; the run keeps going and other\n * observers can still replay it. To stop observing when a request is\n * cancelled, wire its signal to `detach`:\n *\n * ```ts\n * const { fullStream, detach } = await agent.observe(runId, { offset });\n * req.signal.addEventListener('abort', detach, { once: true });\n * if (req.signal.aborted) detach();\n * for await (const chunk of fullStream) send(chunk);\n * ```\n *\n * **Warning:** The returned `cleanup()` function destroys the run's registry\n * entries and cached PubSub events (replay history), including for other\n * observers. Only call it when you are done with the run entirely. If the\n * workflow is suspended and you intend to resume later, do not call cleanup —\n * let the auto-cleanup timer handle it after FINISH/ERROR. Auto-cleanup does\n * not fire on SUSPENDED events.\n *\n * Pass `idleTimeoutMs` to bound how long the stream waits on a silent topic:\n * a durable run whose driving process crashed stops emitting chunks but never\n * publishes a terminal event, so without this `observe()` hangs forever on a\n * producerless topic. When the idle timeout fires, the optional `isAlive`\n * probe is consulted first — returning true (e.g. a live run-liveness\n * heartbeat, or a suspended HITL gate) re-arms the timer and keeps waiting,\n * while false/absent terminates the stream with an error chunk. Only an\n * `isAlive` that returns false schedules the run's full cleanup; a bare\n * `idleTimeoutMs` (no `isAlive`) only detaches this observer, so pass\n * `isAlive` if you rely on the timeout to reclaim a crashed run's state. Both\n * options are opt-in; omit them for the current unbounded behavior.\n */\n async observe(\n runId: string,\n options?: {\n /**\n * Inclusive, zero-based PubSub event index. It counts all cached run-topic events, including\n * lifecycle events, not chunks. Each chunk carries its event's index as `chunk.index`: to resume\n * after a dropped connection, pass the `index + 1` of the last chunk that has an index. Omit it to replay all available cached events. Transports\n * without numeric offsets live-tail instead. Skipping earlier text deltas produces partial text\n * and may make structured output fail to parse; beyond retained history, an offset also skips\n * lower-index live events on numeric-offset transports. See\n * https://mastra.ai/reference/agents/durable-agent#observerunid-options.\n */\n offset?: number;\n idleTimeoutMs?: number;\n isAlive?: () => boolean | Promise<boolean>;\n onChunk?: (chunk: ChunkType<TOutput>) => void | Promise<void>;\n experimentalTransform?: MastraStreamTransformOptions<TOutput>;\n onStepFinish?: (result: DurableAgentStepFinishResult) => void | Promise<void>;\n onFinish?: MastraOnFinishCallback<TOutput>;\n onError?: ({ error }: { error: Error | string }) => void | Promise<void>;\n onAbort?: (data: AgentAbortEventData) => void | Promise<void>;\n onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;\n },\n ): Promise<Omit<DurableAgentStreamResult<TOutput>, 'runId'> & { runId: string; detach: () => void }> {\n let memoryInfo = this.#runRegistry.getMemoryInfo(runId);\n\n let terminalCompleted = false;\n let abortPending = false;\n let cleanupRequested = false;\n let streamCleanup: (() => void) | undefined;\n\n const localEntry = this.#runRegistry.get(runId);\n const observedEntry = localEntry ?? getRunRegistryEntry(runId, this.#mastra);\n const observedFence = observedEntry?.executionFence;\n const runCleanup = createRunCleanup({\n scheduleTimer: cleanup =>\n observedFence\n ? this.#scheduleReaderCleanup(observedFence, cleanup)\n : this.__getStreamBus().scheduleCleanup(cleanup),\n release: () => {\n streamCleanup?.();\n if (\n observedFence &&\n (this.#unverifiedReaderFences.has(observedFence) ||\n !observedFence.ownsRunTopics() ||\n getRunRegistryEntry(runId, this.#mastra)?.executionFence !== observedFence ||\n (localEntry &&\n (this.#runRegistry.get(runId) !== localEntry || localEntry.executionFence !== observedFence)))\n ) {\n return;\n }\n this.#runRegistry.cleanup(runId);\n deleteRunRegistryEntry(runId, this.#mastra);\n this.#clearPubsubTopic(runId, observedEntry);\n },\n });\n const performCleanup = runCleanup.run;\n const scheduleAutoCleanup = runCleanup.schedule;\n\n const completeTerminalLifecycle = () => {\n terminalCompleted = true;\n abortPending = false;\n if (cleanupRequested) {\n performCleanup();\n } else {\n scheduleAutoCleanup();\n }\n };\n\n const observedAgentSpan = observedEntry?.resumeAgentSpan ?? observedEntry?.agentSpan;\n let structuredOutput = observedEntry?.structuredOutput;\n let outputProcessors = observedEntry?.outputProcessors;\n const processorStates = observedEntry?.processorStates;\n let streamAgent: Agent<any, any, any, any> = observedEntry?.agent ?? this.#wrappedAgent;\n let returnScorerData = observedEntry?.returnScorerData;\n let requestContext = observedEntry?.requestContext;\n let messageList = observedEntry?.messageList ?? this.#runRegistry.getMessageList(runId);\n // Worker entries can carry runtime dependencies without the caller's live transcript.\n const liveEntry = messageList ? observedEntry : undefined;\n if (liveEntry?.agentId !== undefined && liveEntry.agentId !== this.id) {\n throw new MastraError({\n id: 'DURABLE_AGENT_OBSERVE_AGENT_MISMATCH',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" observe(${runId}): live run belongs to agent \"${liveEntry.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: liveEntry.agentId },\n });\n }\n let workflowInput: DurableAgenticWorkflowInput | undefined;\n let loopSnapshot: WorkflowRunState | undefined;\n let workflowInputSnapshot: WorkflowRunState | undefined;\n const workflowsStore = !liveEntry ? await this.#mastra?.getStorage()?.getStore('workflows') : undefined;\n\n if (!structuredOutput || !liveEntry) {\n const snapshotStore = workflowsStore ?? (await this.#mastra?.getStorage()?.getStore('workflows'));\n\n for (const workflowName of [DurableStepIds.AGENTIC_LOOP, DurableStepIds.AGENTIC_EXECUTION]) {\n const persisted = await snapshotStore?.getWorkflowRunById({ runId, workflowName });\n if (!persisted) continue;\n\n const snapshot =\n typeof persisted.snapshot === 'string'\n ? (JSON.parse(persisted.snapshot) as WorkflowRunState)\n : persisted.snapshot;\n if (workflowName === DurableStepIds.AGENTIC_LOOP) loopSnapshot = snapshot;\n const persistedInput = snapshot?.context?.input as DurableAgenticWorkflowInput | undefined;\n if (persistedInput?.__workflowKind !== 'durable-agent') continue;\n\n workflowInput = persistedInput;\n workflowInputSnapshot = snapshot;\n break;\n }\n }\n\n if (!liveEntry && workflowInput && workflowInput.agentId !== this.id) {\n throw new MastraError({\n id: 'DURABLE_AGENT_OBSERVE_AGENT_MISMATCH',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `DurableAgent \"${this.name}\" observe(${runId}): persisted run belongs to agent \"${workflowInput.agentId}\", not \"${this.id}\".`,\n details: { agentName: this.name, runId, ownerAgentId: workflowInput.agentId },\n });\n }\n\n if (!structuredOutput && workflowInput) {\n const persistedStructuredOutput = workflowInput.options?.structuredOutput;\n if (persistedStructuredOutput?.schema) {\n const { errorStrategy, fallbackValue, ...rest } = persistedStructuredOutput;\n const schema = toLiveStructuredOutputSchema<{}>(\n persistedStructuredOutput.schema,\n persistedStructuredOutput.nullToUndefined,\n );\n // A non-JSON-safe fallbackValue is not persisted; keep the default strategy then.\n structuredOutput =\n errorStrategy === 'fallback'\n ? fallbackValue === undefined\n ? { ...rest, schema }\n : { ...rest, schema, errorStrategy, fallbackValue: fallbackValue as {} }\n : { ...rest, schema, errorStrategy };\n }\n }\n\n if (!liveEntry && workflowInput) {\n requestContext = workflowInput.requestContextEntries\n ? new RequestContext(\n Object.entries(workflowInput.requestContextEntries) as Iterable<readonly [string, unknown]>,\n )\n : new RequestContext();\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 memoryInfo = threadId && resourceId ? { threadId, resourceId } : undefined;\n\n if (threadId && resourceId) {\n requestContext.set('MastraMemory', {\n thread: { id: threadId },\n resourceId,\n memoryConfig: workflowInput.state?.memoryConfig,\n });\n } else {\n requestContext.delete('MastraMemory');\n }\n\n messageList = new MessageList({ threadId, resourceId });\n try {\n const snapshot = workflowInputSnapshot ?? loopSnapshot;\n const storedState = workflowInput.messageListState ?? (snapshot ? latestMessageListState(snapshot) : undefined);\n if (storedState) {\n const initialState = await hydrateMessageListState(\n { getInitData: () => workflowInput!, mastra: this.#mastra },\n storedState,\n );\n messageList.deserialize(initialState);\n }\n\n if (workflowsStore && snapshot) {\n const inputMessages = messageList.get.input.db();\n const latestState = await this.#loadLatestMessageListState(workflowsStore, runId, snapshot);\n if (latestState) {\n messageList.deserialize(latestState);\n if (messageList.get.input.db().length === 0 && inputMessages.length > 0) {\n messageList.add(inputMessages, 'input');\n }\n }\n }\n } catch (error) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] observe(${runId}) messageList deserialize skipped: ${error}`);\n }\n\n let processorAgent: Agent<any, any, TOutput> = this.#wrappedAgent as Agent<any, any, TOutput>;\n const pinnedVersionId = workflowInput.agentVersionId;\n if (pinnedVersionId && this.#mastra && !this.__isStoredVersionApplied()) {\n const currentVersionId = this.toRawConfig()?.resolvedVersionId;\n if (pinnedVersionId !== currentVersionId) {\n try {\n processorAgent = (await this.#mastra.resolveVersionedAgent(this as unknown as Agent, {\n versionId: pinnedVersionId,\n })) as unknown as Agent<any, any, TOutput>;\n } catch (error) {\n this.#mastra\n .getLogger?.()\n ?.warn?.(\n `[DurableAgent] Failed to resolve pinned agent version for durable observe, using current definition: ${error}`,\n );\n }\n }\n }\n\n // Hooks get the agent the output processors come from, not an entry's agent\n // (which is the current version). A pinned version is a DurableAgent fork; unwrap it.\n streamAgent =\n isDurableAgentLike(processorAgent) && processorAgent.agent !== processorAgent\n ? processorAgent.agent\n : processorAgent;\n try {\n outputProcessors = (await processorAgent.listOutputProcessors(requestContext)) ?? [];\n } catch (error) {\n outputProcessors = [];\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] observe(${runId}) processor resolution failed: ${error}`);\n }\n returnScorerData = workflowInput.options?.returnScorerData;\n }\n\n const refreshObservedMessageList = async (isExpired: () => boolean) => {\n const targetMessageList = messageList;\n const snapshot = workflowInputSnapshot ?? loopSnapshot;\n if (!workflowsStore || !snapshot || !targetMessageList) return;\n\n try {\n const inputMessages = targetMessageList.get.input.db();\n const latestState = await this.#loadLatestMessageListState(workflowsStore, runId, snapshot);\n if (latestState && !isExpired()) {\n targetMessageList.deserialize(latestState);\n if (targetMessageList.get.input.db().length === 0 && inputMessages.length > 0) {\n targetMessageList.add(inputMessages, 'input');\n }\n }\n } catch (error) {\n this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] observe(${runId}) messageList refresh failed: ${error}`);\n }\n };\n\n const refreshObservedMessageListWithTimeout = async () => {\n const refreshTimeoutMs = Math.min(\n options?.idleTimeoutMs && options.idleTimeoutMs > 0\n ? options.idleTimeoutMs\n : OBSERVED_MESSAGE_LIST_REFRESH_TIMEOUT_MS,\n OBSERVED_MESSAGE_LIST_REFRESH_TIMEOUT_MS,\n );\n let expired = false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<boolean>(resolve => {\n timeout = setTimeout(() => {\n expired = true;\n resolve(true);\n }, refreshTimeoutMs);\n });\n\n try {\n const didTimeOut = await Promise.race([refreshObservedMessageList(() => expired).then(() => false), timedOut]);\n if (didTimeOut) {\n this.#mastra\n ?.getLogger?.()\n ?.warn?.(`[DurableAgent] observe(${runId}) messageList refresh timed out after ${refreshTimeoutMs}ms`);\n }\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n };\n\n let observedResponseText = '';\n const handleObservedChunk = async (chunk: ChunkType<TOutput>) => {\n if (chunk.type === 'text-delta' && typeof chunk.payload.text === 'string') {\n observedResponseText += chunk.payload.text;\n }\n if (chunk.type === 'step-finish') {\n await refreshObservedMessageListWithTimeout();\n if (messageList && messageList.get.response.db().length === 0 && observedResponseText) {\n messageList.add({ role: 'assistant', content: observedResponseText }, 'response');\n }\n }\n await options?.onChunk?.(chunk);\n };\n\n const replayFloor = await this.#readReplayFloor(runId, options?.offset);\n\n const stream = 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 replayResponseMessagesBeforeOffset: true,\n ...replayFloor,\n idleTimeoutMs: options?.idleTimeoutMs,\n isAlive: options?.isAlive,\n onChunk: handleObservedChunk,\n experimentalTransform: options?.experimentalTransform,\n onStepFinish: options?.onStepFinish,\n onFinish: options?.onFinish,\n onStreamFinished: completeTerminalLifecycle,\n onError: async ({ error, runDead }) => {\n try {\n await options?.onError?.({ error });\n } finally {\n // A bare idle timeout (runDead === false) only means this observer\n // stopped hearing from the run — it may still be alive elsewhere, so\n // don't tear down its registry entry or replay history.\n if (runDead !== false) completeTerminalLifecycle();\n }\n },\n onAbort: async data => {\n try {\n await options?.onAbort?.(data);\n } finally {\n completeTerminalLifecycle();\n }\n },\n onSuspended: options?.onSuspended,\n structuredOutput: structuredOutput as any,\n agent: streamAgent,\n outputProcessors,\n processorStates,\n returnScorerData,\n requestContext,\n tracingContext: observedAgentSpan ? { currentSpan: observedAgentSpan } : undefined,\n messageList,\n });\n const { output, ready, detach } = stream;\n streamCleanup = stream.cleanup;\n\n // This output belongs to this observer alone, so a consumer that stops\n // reading fullStream (break/return/throw out of `for await`) should detach\n // the observer. MastraModelOutput fans out to several readers and only drops\n // the cancelled reader's listeners, so the cancel never reaches the pubsub\n // subscription — pass it through here.\n detachFullStreamOnEnd(output, detach);\n\n // Wait for subscription to be ready\n try {\n await ready;\n await replayFloor.refreshReplayFilter?.();\n await stream.waitForEventDelivery();\n const reconciledVersion = stream.activityVersion;\n if ((await this.#isObservationComplete(runId)) && stream.activityVersion === reconciledVersion) detach();\n } catch (error) {\n detach();\n throw error;\n }\n\n const cleanup = () => {\n if (abortPending) {\n cleanupRequested = true;\n scheduleAutoCleanup();\n return;\n }\n performCleanup();\n };\n\n // observe() doesn't own the run's lifecycle, but the returned `abort` can\n // still stop it. Flip the in-process controller if one happens to be\n // installed here, then cancel the workflow run so the abort also reaches\n // the process actually executing it — the common case for observe(), which\n // exists precisely to watch runs this process did not start.\n const abort = async (reason?: unknown) => {\n abortPending = !terminalCompleted;\n const controller = (getRunRegistryEntry(runId, this.#mastra) ?? this.#runRegistry.get(runId))?.abortController;\n if (controller && !controller.signal.aborted) {\n controller.abort(reason);\n }\n await this.requestRemoteAbort(runId);\n // A run parked on a suspension has no steps left to stop; release it so\n // it is no longer listed as suspended, as the stream abort does.\n if (agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);\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 detach,\n abort,\n };\n }\n\n /**\n * Clear retained pubsub state for a run's topics (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 * Clears both the agent stream topic and `workflow.events.v2.<runId>`.\n * The agent stream topic is cleared only here, on both engines. For the\n * workflow events topic the engines differ:\n * - Default engine (`DurableAgent`): no other cleanup exists — without\n * this, CachingPubSub permanently orphans a no-TTL counter key per\n * completed run.\n * - Evented engine (`EventedAgent`): the WorkflowEventProcessor also\n * clears `workflow.events.v2.<runId>` via its own delayed,\n * restart-guarded terminal cleanup. The two clears overlap safely:\n * `clearTopic` is idempotent and clearing an empty topic is a no-op.\n *\n * This needs no restart guard of its own — the lifecycle facts are\n * engine-agnostic: cleanup timers arm only on terminal outcomes\n * (FINISH/ERROR/ABORT — never SUSPENDED), `resume()` rejects runs whose\n * snapshot isn't `suspended`, and `untilIdle` continuations mint a fresh\n * runId per segment. An execution that lost its run never calls this:\n * the execution that took the run over, in this or another process, may\n * still be writing to both topics, so it clears them when it ends. The one\n * evented-only edge — at-least-once redelivery writing to the workflow\n * events topic after this clear — is covered by the WEP's own cleanup,\n * which reschedules deletion on that run's terminal end.\n */\n #clearPubsubTopic(runId: string, entry = getRunRegistryEntry(runId, this.#mastra)): void {\n const publisher = getExecutionStreamOwner({\n runId,\n agentId: this.id,\n mastra: this.#mastra,\n agent: this,\n entry,\n });\n if (publisher) void publisher.cleanup();\n else void this.pubsub.clearTopic(AGENT_STREAM_TOPIC(runId));\n void this.pubsub.clearTopic(`workflow.events.v2.${runId}`);\n }\n\n /**\n * Resolve the replay position for this run's stream topic.\n * Returns the cached event count when history is available, or `latest` when it is unavailable.\n * Resume and recovery use this position so they don't re-deliver events emitted by the prior segment\n * (notably the SUSPENDED chunk that paused it) from a persistent transport.\n */\n async #getPubsubOffset(runId: string): Promise<number | 'latest'> {\n const pubsub = this.pubsub as PubSub & {\n getHistory?: (topic: string) => Promise<unknown[]>;\n };\n if (typeof pubsub.getHistory !== 'function') return 'latest';\n try {\n const history = await pubsub.getHistory(AGENT_STREAM_TOPIC(runId));\n return Array.isArray(history) && history.length > 0 ? history.length : 'latest';\n } catch {\n return 'latest';\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(): ReturnType<typeof createDurableAgenticWorkflow> {\n if (!this.executionEngine.workflow) this.#warnIfStorageVersionUnsupported();\n return (\n this.executionEngine.workflow ??\n this.executionEngine.getWorkflow({\n maxSteps: this.#maxSteps,\n workflowEngine: this.workflowEngine,\n storesRunsInJournal: this.storesRunsInJournal,\n shouldPersistSnapshot: this.userShouldPersistSnapshot,\n logger: this.logger,\n guardrailLogger: this.guardrailLogger,\n })\n );\n }\n\n /**\n * One-time guardrail warnings for user-supplied `shouldPersistSnapshot`\n * policies. Probes the predicate with an empty `stepResults`, so predicates\n * that read `stepResults` may probe inaccurately — the warnings are\n * best-effort and never block execution.\n *\n * Engine variants own their warnings during workflow creation. This method\n * remains available for direct calls and subclass super calls.\n *\n * @internal\n */\n protected warnOnRiskyPersistencePolicy(): void {\n this.executionEngine.warnOnRiskyPersistencePolicy(this.userShouldPersistSnapshot, this.guardrailLogger);\n }\n\n /**\n * Logger for the persistence-policy guardrail warnings. The durable\n * registration path rewires the *underlying* agent's logger but not the\n * wrapper's, so prefer the Mastra-configured logger (which also respects\n * `logger: false`) and fall back to the base logger for unregistered\n * agents.\n *\n * @internal\n */\n protected get guardrailLogger() {\n return this.#mastra?.getLogger() ?? this.logger;\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 scopesResolved: !!(options as { [SCOPES_ALREADY_APPLIED]?: boolean } | undefined)?.[SCOPES_ALREADY_APPLIED],\n resumedSpanData: (options as { [RESUMED_SPAN_DATA]?: PreparationOptions['resumedSpanData'] } | undefined)?.[\n RESUMED_SPAN_DATA\n ],\n mastra: this.#mastra,\n durableAgentId: this.id,\n durableAgentName: this.name,\n });\n\n preparation.registryEntry.agentId = this.id;\n this.#runRegistry.registerWithMessageList(preparation.runId, preparation.registryEntry, preparation.messageList, {\n threadId: preparation.threadId,\n resourceId: preparation.resourceId,\n });\n await this.#attachStreamPublisher(preparation.runId, {\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 this.#executionEngine?.registerMastra(mastra);\n // Also set on wrapped agent\n this.#wrappedAgent.__registerMastra(mastra);\n this.#wrapperStreamBus?.registerMastra(mastra.pubsub);\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 { ShouldPersistSnapshotFn } from '../../workflows/types';\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 * Overrides the snapshot-persistence policy for the agent's durable\n * workflows. By default `pending | paused | suspended` snapshots are always\n * persisted (required for human-in-the-loop `resume()`), and `running`\n * checkpoints are persisted only when the Mastra instance sets\n * `recovery: { durableAgents: 'auto' }`. See\n * {@link DurableAgentConfig.shouldPersistSnapshot} for caveats.\n */\n shouldPersistSnapshot?: ShouldPersistSnapshotFn;\n\n /**\n * How the agent's new runs are stored (`1` or `2`). Defaults to `1`. See\n * {@link DurableAgentConfig.storageVersion}.\n *\n * @experimental\n */\n storageVersion?: 1 | 2;\n\n /**\n * Per-topic opt-out of the replay cache.\n *\n * Return `false` to publish a topic straight through to the underlying\n * PubSub without recording it in the cache. Subscribers of that topic then\n * receive live events only and cannot resume from an offset. Use this to\n * trade replay for minimum publish latency on hot topics when the cache is\n * remote (e.g. cross-region Redis). Run-local topics are always excluded,\n * regardless of this option.\n */\n shouldCache?: (topic: string) => boolean;\n}\n\n/**\n * Create a DurableAgent that wraps an existing Agent.\n *\n * This factory function is the recommended way to add checkpoint-backed durable\n * execution to an agent. The `durable` option on `AgentConfig` only configures\n * resumable streams and never wraps the agent.\n *\n * Wrapping does not change the wrapped Agent's direct runs, including runs already\n * in flight. Without explicit stream settings, the wrapper shares the Agent's\n * stream bus; pubsub, cache, cleanupTimeoutMs, and shouldCache overrides apply\n * only to the wrapper's runs. Evented wrapper runs use Mastra's shared run log\n * without changing the wrapped Agent's native stream routing.\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 {\n agent,\n id,\n name,\n cache,\n pubsub,\n maxSteps,\n cleanupTimeoutMs,\n shouldCache,\n shouldPersistSnapshot,\n storageVersion,\n } = options;\n\n return new DurableAgent({\n agent,\n id,\n name,\n cache,\n pubsub,\n maxSteps,\n cleanupTimeoutMs,\n shouldCache,\n shouldPersistSnapshot,\n storageVersion,\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","import { EventEmitterPubSub } from '../../events/event-emitter';\nimport type { PubSub } from '../../events/pubsub';\nimport type { IMastraLogger } from '../../logger';\nimport type { ShouldPersistSnapshotFn } from '../../workflows/types';\nimport { DurableExecutionEngine } from './execution-engine';\nimport type { ExecutionCompletion, ExecutionOutcome } from './execution-engine';\nimport { DurableExecutionFenceError, EXECUTION_UNVERIFIED_ERROR_ID } from './execution-fence';\nimport type { ExecutionFence } from './execution-fence';\nimport { defaultShouldPersistSnapshot } from './workflows/create-durable-agentic-workflow';\n\nexport class EventedExecutionEngine extends DurableExecutionEngine {\n #warnedUnfencedSharedExecution = false;\n override prepareExecution(\n pubsub: PubSub | undefined,\n fence: ExecutionFence | undefined,\n workflowEngine: 'default' | 'evented',\n logger: IMastraLogger,\n guardrailLogger: IMastraLogger | undefined,\n ): { sharedExecution: boolean; usesRunPubSub: boolean } {\n const engine = this.resolveWorkflowEngine(workflowEngine, logger);\n const sharedTransport =\n engine === 'evented' && pubsub !== undefined && !(pubsub.__rawBus() instanceof EventEmitterPubSub);\n const sharedExecution = sharedTransport && fence?.generation !== undefined;\n if (sharedTransport && !sharedExecution && !this.#warnedUnfencedSharedExecution) {\n this.#warnedUnfencedSharedExecution = true;\n guardrailLogger?.warn(\n `EventedAgent '${this.id}': shared execution without storage-backed run fencing keeps its existing ` +\n 'behavior: API shutdown or loss can interrupt remote workers. Use a shared fencing-capable storage adapter ' +\n 'to keep workers running independently of the API process.',\n );\n }\n return { sharedExecution, usesRunPubSub: engine === 'default' };\n }\n\n override finishExecution(\n runId: string,\n executionFence: ExecutionFence | undefined,\n sharedExecution: boolean,\n completion: ExecutionCompletion,\n ): ExecutionOutcome {\n if (!sharedExecution) return super.finishExecution(runId, executionFence, sharedExecution, completion);\n executionFence?.detach();\n if ('error' in completion) {\n // With no successor, only the disconnected observer can close its stream.\n if (\n completion.error instanceof DurableExecutionFenceError &&\n completion.error.id === EXECUTION_UNVERIFIED_ERROR_ID\n ) {\n return { owner: 'workers', error: completion.error };\n }\n this.mastra?.getLogger()?.warn('Evented durable observer disconnected; workers retain settlement authority', {\n runId,\n error: completion.error,\n });\n }\n return { owner: 'workers' };\n }\n\n override resolveShouldPersistSnapshot(_predicate?: ShouldPersistSnapshotFn): ShouldPersistSnapshotFn {\n return defaultShouldPersistSnapshot;\n }\n override warnOnRiskyPersistencePolicy(\n predicate: ShouldPersistSnapshotFn | undefined,\n guardrailLogger: IMastraLogger | undefined,\n ): void {\n if (predicate)\n guardrailLogger?.warn(\n `EventedAgent '${this.id}': ignoring the shouldPersistSnapshot option. ` +\n 'The evented engine requires the full snapshot set (pending|paused|suspended|running) — ' +\n `the initial 'running' write creates the base row that suspend-merges and multi-worker coordination build on.`,\n );\n }\n}\n","/**\n * EventedAgent - A durable agent that executes steps through event workers.\n *\n * EventedAgent extends DurableAgent and overrides the execution strategy to use\n * the evented workflow engine. stream() returns without awaiting execution,\n * while the run's completion promise is tracked for safe suspension/resume.\n * Events are streamed via pubsub as the workflow executes.\n */\n\nimport type { Mastra } from '../../mastra';\nimport { createObservabilityContext } from '../../observability';\nimport { agentThreadStreamRuntime } from '../thread-stream-runtime';\nimport type { ToolsInput } from '../types';\n\nimport { DurableAgent } from './durable-agent';\nimport type { DurableAgentConfig } from './durable-agent';\n\nimport { EventedExecutionEngine } from './evented-execution-engine';\nimport { setExecutionClaim } from './execution-fence';\nimport { getRunRegistryEntry } from './run-registry';\nimport type { DurableAgenticWorkflowInput } from './types';\n\n/**\n * Configuration for EventedAgent - wraps an existing Agent with fire-and-forget execution\n */\nexport interface EventedAgentConfig<\n TAgentId extends string = string,\n TTools extends ToolsInput = ToolsInput,\n TOutput = undefined,\n> extends DurableAgentConfig<TAgentId, TTools, TOutput> {}\n\n/**\n * EventedAgent extends DurableAgent to use fire-and-forget execution.\n *\n * This agent type uses the built-in evented workflow engine, which is useful when:\n * - You don't need an external execution engine (like Inngest)\n * - You want fire-and-forget execution with pubsub streaming\n * - You need resumable streams with event caching\n * - You need runs to survive process death: an active run can be picked up by\n * a fresh process over the same storage via `recover(runId)` /\n * `recoverActiveRuns()` (running step state is persisted before execution)\n *\n * The key difference from DurableAgent is the execution strategy:\n * - DurableAgent: Runs workflow steps in-process via createRun + start.\n * - EventedAgent: Steps execute via events on `mastra.pubsub`, so any worker\n * sharing that bus can process them. The agent's stream follows\n * `mastra.pubsub`, so streaming, suspend/resume, and finish events work even\n * when the agent was constructed with its own pubsub. Execution is tracked\n * in the background so resume waits for suspension persistence.\n *\n * Register the EventedAgent on a `Mastra` instance (with storage) to get\n * evented execution — the evented engine needs the host's pubsub, storage,\n * and event workers. Without a host, the agent falls back to the default\n * in-process engine (with a warning), preserving the released behavior of a\n * standalone evented agent. Recovery entry points (`recover`,\n * `listActiveRuns`, `recoverActiveRuns`) still require a host and throw\n * directly without one.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core';\n * import { Agent } from '@mastra/core/agent';\n * import { EventedAgent } 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 eventedAgent = new EventedAgent({ agent });\n *\n * // Register on a Mastra host to get evented execution (a hostless agent\n * // falls back to the default in-process engine).\n * const mastra = new Mastra({\n * agents: { myAgent: eventedAgent },\n * storage: new LibSQLStore({ url: 'file:mastra.db' }),\n * });\n *\n * const { output, runId, cleanup } = await eventedAgent.stream('Hello!');\n * const text = await output.text;\n * cleanup();\n *\n * // After a crash/restart, a fresh process over the same storage can resume:\n * // await eventedAgent.recoverActiveRuns();\n * ```\n */\nexport class EventedAgent<\n TAgentId extends string = string,\n TTools extends ToolsInput = ToolsInput,\n TOutput = undefined,\n> extends DurableAgent<TAgentId, TTools, TOutput> {\n /**\n * Create a new EventedAgent that wraps an existing Agent\n */\n constructor(config: EventedAgentConfig<TAgentId, TTools, TOutput>) {\n super(config);\n }\n\n /**\n * EventedAgent runs the durable agentic loop on the evented execution\n * engine (pubsub + WorkflowEventProcessor) instead of the default\n * in-process engine.\n * @internal\n */\n protected override get workflowEngine(): 'default' | 'evented' {\n return 'evented';\n }\n\n protected override createExecutionEngine(mastra?: Mastra): EventedExecutionEngine {\n return new EventedExecutionEngine(this.id, mastra);\n }\n\n // The evented engine may resolve before the suspended snapshot lands, so\n // closeOnSuspend keeps closing on the SUSPENDED event.\n protected override get suspendPersistedOnReturn(): boolean {\n return false;\n }\n\n /**\n * Execute the durable workflow using the evented engine.\n *\n * The caller tracks this promise in the background without blocking stream(),\n * then cleans up snapshots on a non-suspended terminal status.\n *\n * @param runId - The unique run ID\n * @param workflowInput - The serialized workflow input\n * @internal\n */\n protected override async executeWorkflow(runId: string, workflowInput: DurableAgenticWorkflowInput): Promise<void> {\n // Captured now: a later resume() replaces the registry's fence before this\n // segment's background promise settles.\n const entry = getRunRegistryEntry(runId, this.getMastraInstance());\n const executionFence = entry?.executionFence;\n const pubsub = this.getMastraInstance()?.pubsub ?? this.getPubSub();\n const { sharedExecution, usesRunPubSub } = this.executionEngine.prepareExecution(\n pubsub,\n executionFence,\n this.workflowEngine,\n this.logger,\n this.guardrailLogger,\n );\n if (entry) entry.eventedExecution = sharedExecution;\n try {\n const workflow = this.getWorkflow();\n // The evented engine executes via pubsub events consumed by in-process\n // workers — without them `run.start()` never resolves (it waits on the\n // `workflows-finish` topic). Idempotent; a no-op when the server has\n // already booted the workers.\n await this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);\n // Populate the run row's resourceId column so storage-level resource\n // filters (listSuspendedRuns / listActiveRuns) can narrow the query.\n const memoryInfo = (\n workflowInput.messageListState as { memoryInfo?: { threadId?: string; resourceId?: string } } | undefined\n )?.memoryInfo;\n const threadId = workflowInput.state?.threadId ?? memoryInfo?.threadId;\n if (sharedExecution && pubsub && entry?.requestContext && executionFence && threadId) {\n await agentThreadStreamRuntime.claimDurableThreadLease(\n pubsub,\n runId,\n threadId,\n workflowInput.state?.resourceId ?? memoryInfo?.resourceId,\n executionFence.generation,\n executionFence.executionId,\n );\n setExecutionClaim(entry.requestContext, runId, {\n ...executionFence.claim,\n threadId,\n resourceId: workflowInput.state?.resourceId ?? memoryInfo?.resourceId,\n });\n }\n // Note: unlike the default engine, evented `createRun` accepts no\n // `pubsub` — the engine always publishes on `mastra.pubsub` so any\n // worker in a fleet can execute a step. The agent's stream still sees\n // those events because its CachingPubSub follows `mastra.pubsub` as its\n // source (wired at registration; see #ensurePubsubInitialized).\n //\n // On the hostless fallback (default engine, see resolveWorkflowEngine)\n // there is no `mastra.pubsub`: the default engine publishes on the\n // pubsub handed to `createRun`, so pass the agent's own transport —\n // otherwise the caller's stream never sees a single event and hangs.\n // This mirrors the previously shipped standalone behavior.\n const run = await this.executionEngine.createRun(workflow, {\n runId,\n resourceId: workflowInput.state?.resourceId ?? memoryInfo?.resourceId,\n ...(usesRunPubSub ? { pubsub: this.fenceRunPubSub(executionFence, entry?.abortController) } : {}),\n });\n // stream() runs executeWorkflow in the background. Track the full run here\n // so an immediate resume waits for the suspension snapshot to be persisted.\n // Pass the caller's requestContext (so config selectors pick the same observability\n // instance the root spans were created with) and parent the run under the AGENT_RUN span.\n await this.executionEngine\n .startRun(\n run,\n workflowInput,\n entry?.requestContext,\n createObservabilityContext({ currentSpan: entry?.agentSpan }),\n )\n .then(\n result => this.executionEngine.finishExecution(runId, executionFence, sharedExecution, { result }),\n error => this.executionEngine.finishExecution(runId, executionFence, sharedExecution, { error }),\n )\n .then(outcome => {\n if (outcome.owner === 'agent') return this.settleExecution(runId, executionFence, outcome);\n if (outcome.error) {\n return this.emitError(runId, outcome.error, executionFence?.generation).catch(publishError =>\n this.logger.warn(`Failed to publish error event for run ${runId}`, { runId, error: publishError }),\n );\n }\n });\n } catch (error) {\n await this.settleExecution(runId, executionFence, {\n error: this.executionEngine.workflowExecutionError(error, 'Workflow execution failed'),\n });\n }\n }\n}\n\n/**\n * Check if an object is an EventedAgent class instance\n */\nexport function isEventedAgentClass(obj: any): obj is EventedAgent {\n return obj instanceof EventedAgent;\n}\n","/**\n * Factory function to create an EventedAgent that wraps an existing Agent.\n *\n * This creates a durable agent that runs its agentic loop on the built-in\n * evented workflow engine: execution is fire-and-forget (the run is started\n * without being awaited) and driven by events on the Mastra host's pubsub.\n *\n * The returned agent must be registered on a `Mastra` instance (with storage)\n * before use; calling it unregistered fails with a clear `MastraError`.\n *\n * @example\n * ```typescript\n * import { Agent } from '@mastra/core/agent';\n * import { createEventedAgent } 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 eventedAgent = createEventedAgent({ agent });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: eventedAgent },\n * });\n * ```\n */\n\nimport type { MastraServerCache } from '../../cache/base';\nimport type { PubSub } from '../../events/pubsub';\nimport type { ShouldPersistSnapshotFn } from '../../workflows/types';\nimport type { Agent } from '../agent';\n\nimport { EventedAgent } from './evented-agent';\nimport type { EventedAgentConfig } from './evented-agent';\n\n/**\n * Options for createEventedAgent factory function.\n */\nexport interface CreateEventedAgentOptions<\n TAgentId extends string = string,\n TTools extends Record<string, any> = Record<string, any>,\n TOutput = undefined,\n> {\n /** The Agent to wrap with evented durable execution capabilities */\n agent: Agent<TAgentId, TTools, TOutput>;\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 /** Maximum steps for agentic loop */\n maxSteps?: number;\n\n /**\n * Per-topic opt-out of the replay cache.\n *\n * Return `false` to publish a topic straight through to the underlying\n * PubSub without recording it in the cache. Subscribers of that topic then\n * receive live events only and cannot resume from an offset. Use this to\n * trade replay for minimum publish latency on hot topics when the cache is\n * remote (e.g. cross-region Redis). Run-local topics are always excluded,\n * regardless of this option.\n */\n shouldCache?: (topic: string) => boolean;\n\n /**\n * Accepted for API symmetry with `createDurableAgent`, but **ignored** by\n * EventedAgent (a warning is logged if set). The evented engine requires\n * the full snapshot set (`pending | paused | suspended | running`): the\n * initial `running` write creates the base row that suspend-merges and\n * multi-worker coordination build on.\n */\n shouldPersistSnapshot?: ShouldPersistSnapshotFn;\n\n /**\n * How the agent's new runs are stored (`1` or `2`). Defaults to `1`. See\n * {@link DurableAgentConfig.storageVersion}.\n *\n * @experimental\n */\n storageVersion?: 1 | 2;\n}\n\n/**\n * Create an EventedAgent that wraps an existing Agent.\n *\n * This factory function creates an EventedAgent instance with fire-and-forget\n * execution via the built-in evented workflow engine. Runs survive process\n * death: over the same storage, a fresh process can resume in-flight runs via\n * `recover(runId)` / `recoverActiveRuns()`.\n *\n * @param options - Configuration options\n * @returns An EventedAgent instance (register it on a `Mastra` host before use)\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 eventedAgent = createEventedAgent({ agent });\n *\n * const mastra = new Mastra({\n * agents: { myAgent: eventedAgent },\n * });\n * ```\n */\nexport function createEventedAgent<\n TAgentId extends string = string,\n TTools extends Record<string, any> = Record<string, any>,\n TOutput = undefined,\n>(options: CreateEventedAgentOptions<TAgentId, TTools, TOutput>): EventedAgent<TAgentId, TTools, TOutput> {\n const { agent, pubsub, cache, maxSteps, shouldCache, shouldPersistSnapshot, storageVersion } = options;\n\n return new EventedAgent({\n agent,\n pubsub,\n cache,\n maxSteps,\n shouldCache,\n shouldPersistSnapshot,\n storageVersion,\n } as EventedAgentConfig<TAgentId, TTools, TOutput>);\n}\n\n/**\n * Check if an object is an EventedAgent\n */\nexport function isEventedAgent(obj: any): obj is EventedAgent {\n return obj instanceof EventedAgent;\n}\n\n// Re-export types for convenience\nexport type { EventedAgentConfig } from './evented-agent';\n","/**\n * Deprecated durable tool-execution helpers.\n *\n * This is the frozen pre-unification implementation of the shared durable\n * tool-call executor, preserved verbatim so the public\n * `@mastra/core/agent/durable` entry point keeps its released surface at\n * patch level. The durable engines no longer call it — tool execution now\n * flows through the shared loop cores (`loop/shared/steps`), which handle\n * background dispatch, processors, approval, and abort. New code should not\n * import from this module.\n *\n * @deprecated Superseded by the shared loop cores; will be removed in v2.\n */\n\nimport type { RequestContext } from '../../../request-context';\nimport type { Workspace } from '../../../workspace';\nimport type { DurableToolCallInput, DurableToolCallOutput } from '../types';\n\n/**\n * Context for tool execution\n *\n * @deprecated Superseded by the shared loop cores; will be removed in v2.\n */\nexport interface ToolExecutionContext {\n /** Tool calls from the LLM output */\n toolCalls: DurableToolCallInput[];\n /** Resolved tools with execute functions */\n tools: Record<string, any>;\n /** Run identifier */\n runId: string;\n /** Agent identifier */\n agentId: string;\n /** Message identifier */\n messageId: string;\n /** Serializable state */\n state: any;\n /** Workspace for file/sandbox operations */\n workspace?: Workspace;\n /** Request context for auth data, feature flags, etc. */\n requestContext?: RequestContext;\n\n /**\n * Optional hooks for observability/streaming.\n * All hooks can be sync or async.\n */\n\n /** Called before starting tool execution (for span creation) */\n onToolStart?: (toolCall: DurableToolCallInput) => void | Promise<void>;\n /** Called after successful tool execution (for span close, pubsub emit) */\n onToolResult?: (toolCall: DurableToolCallInput, result: unknown) => void | Promise<void>;\n /** Called on tool execution error (for span error, pubsub emit) */\n onToolError?: (toolCall: DurableToolCallInput, error: ToolExecutionError) => void | Promise<void>;\n}\n\n/**\n * Error structure for tool execution failures\n *\n * @deprecated Superseded by the shared loop cores; will be removed in v2.\n */\nexport interface ToolExecutionError {\n name: string;\n message: string;\n stack?: string;\n}\n\n/**\n * Execute tool calls durably with optional hooks for observability and streaming.\n *\n * @deprecated Superseded by the shared loop cores; will be removed in v2.\n * The durable agent workflows no longer call this helper.\n *\n * @param ctx - Tool execution context with tool calls, resolved tools, and optional hooks\n * @returns Array of tool call outputs with results or errors\n */\nexport async function executeDurableToolCalls(ctx: ToolExecutionContext): Promise<DurableToolCallOutput[]> {\n const toolResults: DurableToolCallOutput[] = [];\n\n for (const toolCall of ctx.toolCalls) {\n // Handle provider-executed tools (e.g., OpenAI function calling with parallel_tool_calls)\n if (toolCall.providerExecuted && toolCall.output !== undefined) {\n toolResults.push({\n ...toolCall,\n result: toolCall.output,\n });\n continue;\n }\n\n // Resolve the tool from the tools record\n const tool = ctx.tools[toolCall.toolName];\n\n if (!tool) {\n const error: ToolExecutionError = {\n name: 'ToolNotFoundError',\n message: `Tool ${toolCall.toolName} not found`,\n };\n await ctx.onToolError?.(toolCall, error);\n toolResults.push({\n ...toolCall,\n error,\n });\n continue;\n }\n\n // Notify start of tool execution (for observability)\n await ctx.onToolStart?.(toolCall);\n\n // Execute the tool\n try {\n if (tool.execute) {\n const result = await tool.execute(toolCall.args, {\n toolCallId: toolCall.toolCallId,\n messages: [],\n workspace: ctx.workspace,\n requestContext: ctx.requestContext,\n });\n await ctx.onToolResult?.(toolCall, result);\n toolResults.push({\n ...toolCall,\n result,\n });\n } else {\n // Tool has no execute function - return undefined result\n await ctx.onToolResult?.(toolCall, undefined);\n toolResults.push({\n ...toolCall,\n result: undefined,\n });\n }\n } catch (error) {\n const toolError: ToolExecutionError = {\n name: 'ToolExecutionError',\n message: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n };\n await ctx.onToolError?.(toolCall, toolError);\n toolResults.push({\n ...toolCall,\n error: toolError,\n });\n }\n }\n\n return toolResults;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,eAAsB,0BACpB,QACA,OACA,QACA,UACe;CACf,IAAI,QAAQA,qBAAAA,oBAAoB,OAAO,MAAM;CAE7C,IAAI,CAAC,OAAO;EAMV,QAAQ,EAAE,eAAe,KAAK;EAE9B,IAAI,CAACC,qBAAAA,oBAAoB,OAAO,OAAO,MAAM,GAAG;CAClD;CAKA,IAAI,CAAC,MAAM,iBAAiB,qBAAqB,KAAK;CAMtD,gBAAgB,OAAO,QAAQ;CAE/B,IAAI,MAAM,8BAA8B;CAIxC,MAAM,+BAA+B;CAGrC,MAAM,WADYC,qBAAAA,sBAAsB,OAAO,OAAO,MAC7B,CAAC,CAAC,eAAe,cAAc;EACtD,MAAM,aAAaF,qBAAAA,oBAAoB,OAAO,MAAM,CAAC,EAAE,mBAAmB,MAAM;EAChF,IAAI,cAAc,CAAC,WAAW,OAAO,SAAS,WAAW,sBAAM,IAAI,MAAM,SAAS,CAAC;CACrF,C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