@mastra/core
Version:
13,067 lines • 553 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_error = require("../../error-D90lJ6M7.cjs");
const require_output_helpers = require("../../output-helpers-JL-HeCbT.cjs");
const require_run_registry = require("../../run-registry-BrKoxzT0.cjs");
const require_utils = require("../../utils-DdUtwAiS.cjs");
const require_stream = require("../../stream-hnlwNJ12.cjs");
const require_observability = require("../../observability-fxVZWiFW.cjs");
const require_utils$1 = require("../../utils-D-eNsgDM.cjs");
const require_storage = require("../../storage-CfG0I2aF.cjs");
const require_request_context = require("../../request-context-D9RXYCy8.cjs");
const require_llm = require("../../llm-BoBmCoSK.cjs");
const require_message_list = require("../../message-list-Bc69E1sT.cjs");
const require_workflows_constants = require("../../workflows/constants.cjs");
const require_ee_iTj2bRDt = require("../../ee-iTj2bRDt-D3-QLGDF.cjs");
const require_logger = require("../../logger-CvzZYuJd.cjs");
const require_toolchecks = require("../../toolchecks-BSANSUXW.cjs");
const require_error$1 = require("../../error-CBEbujW6.cjs");
const require_payload_transform = require("../../payload-transform-CWgnsO9w.cjs");
const require_signals = require("../../signals-CWxAMEmE.cjs");
const require_stream$1 = require("../../stream-BGbj9jAU.cjs");
const require_tool = require("../../tool-BMl4Lb5_.cjs");
const require_error_count = require("../../error-count-DeDpeWU2.cjs");
const require_utils_safe_stringify = require("../../utils/safe-stringify.cjs");
let _isaacs_ttlcache = require("@isaacs/ttlcache");
let zod = require("zod");
let _mastra_schema_compat = require("@mastra/schema-compat");
let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
// src/agent/durable/abort-transport.ts
/**
* Make the current process responsive to abort requests for `runId`.
*
* Called by durable steps as they start work. The step may be running on a
* worker that never saw the caller's `abort()`, so this is where that process
* grows an `AbortController` of its own — the same one every downstream call
* already reads off the run registry (`registryEntry.abortSignal`), so nothing
* downstream needs to know abort arrived from elsewhere.
*
* Idempotent: a run executes many steps in the same process, and each of them
* calls this. The subscription is torn down with the registry entry, whether
* that happens on explicit cleanup or TTL eviction.
*/
async function ensureRemoteAbortListener(pubsub, runId, mastra, deadline) {
let entry = require_run_registry.getRunRegistryEntry(runId, mastra);
if (!entry) {
entry = { isPlaceholder: true };
if (!require_run_registry.setRunRegistryEntry(runId, entry, mastra)) return;
}
if (!entry.abortController) giveWorkerController(entry);
syncRunDeadline(entry, deadline);
if (entry.remoteAbortListenerInstalled) return;
entry.remoteAbortListenerInstalled = true;
const listener = require_run_registry.getRunStreamPublisher(runId, entry, mastra).listenForAbort(pubsub, () => {
const controller = require_run_registry.getRunRegistryEntry(runId, mastra)?.abortController ?? entry.abortController;
if (controller && !controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("Aborted"));
});
try {
await listener.ready;
} catch (error) {
await listener.detach();
entry.remoteAbortListenerInstalled = false;
throw error;
}
}
/** Controllers this module created for a worker that had none, as opposed to an owner's controller wired to its `abort()`. */
const workerControllers = /* @__PURE__ */ new WeakSet();
function giveWorkerController(entry) {
const controller = new AbortController();
workerControllers.add(controller);
entry.abortController = controller;
entry.abortSignal = controller.signal;
}
/**
* A new segment is starting on a warm worker. If the previous segment's total deadline already
* stopped the worker's own controller (e.g. it passed while the run was suspended), the resumed
* segment gets a fresh one instead of inheriting that abort. Any other abort is kept.
*/
function replaceTimedOutWorkerController(entry) {
const controller = entry.abortController;
if (!controller || !workerControllers.has(controller) || !controller.signal.aborted) return;
const reason = controller.signal.reason;
if (!require_stream.isMastraTimeoutError(reason) || reason.timeoutType !== "total") return;
giveWorkerController(entry);
}
/** The deadline each entry currently has armed, and the controller it stops, so a later segment can replace it. */
const armedDeadlines = /* @__PURE__ */ new WeakMap();
/** Arm the entry's deadline, replacing a timer armed for a different deadline. */
function syncRunDeadline(entry, deadline) {
const armed = armedDeadlines.get(entry);
if (armed && armed.at !== deadline?.at) replaceTimedOutWorkerController(entry);
if (!deadline) {
if (armed) {
clearTimeout(armed.timer);
armedDeadlines.delete(entry);
}
return;
}
if (armed?.at === deadline.at && armed.controller === entry.abortController) return;
if (armed) clearTimeout(armed.timer);
else {
const previousCleanup = entry.cleanup;
entry.cleanup = () => {
try {
previousCleanup?.();
} finally {
clearTimeout(armedDeadlines.get(entry)?.timer);
armedDeadlines.delete(entry);
}
};
}
const controller = entry.abortController;
armedDeadlines.set(entry, {
at: deadline.at,
controller,
timer: armRunDeadline(controller, deadline)
});
}
/**
* Request-context key the caller sets to the run's absolute total deadline for one execution
* segment (stream or resume), so every worker can stop at it on its own clock.
*/
const RUN_DEADLINE_KEY = "__mastra_runDeadline";
/** The run deadline a step's request context carries, if any. */
function readRunDeadline(requestContext) {
const value = requestContext?.get(RUN_DEADLINE_KEY);
if (typeof value?.at !== "number" || typeof value.timeoutMs !== "number") return void 0;
return {
at: value.at,
timeoutMs: value.timeoutMs
};
}
/**
* Abort the controller with the deadline's timeout error now, or when the deadline arrives.
* The timer is bound to the controller it was armed for: a warm resume swaps a fresh controller
* onto the entry, and the previous segment's timer must not stop the resumed segment.
*/
function armRunDeadline(controller, deadline) {
const expire = () => {
if (controller && !controller.signal.aborted) controller.abort(new require_stream.MastraTimeoutError({
timeoutType: "total",
timeoutMs: deadline.timeoutMs
}));
};
const remaining = deadline.at - Date.now();
if (remaining <= 0) {
expire();
return;
}
const timer = setTimeout(expire, remaining);
timer.unref?.();
return timer;
}
// src/agent/durable/durable-stream-until-idle.ts
/**
* Run `DurableAgent.streamUntilIdle` (or `DurableAgent.stream({ untilIdle })`).
* Initial turn invokes `agent.stream(messages, ...)`; continuations triggered
* by background-task completions run as fresh `agent.stream([], ...)` calls
* against the same memory thread.
*/
async function runDurableStreamUntilIdle(agent, messages, streamOptions, deps) {
const innerCleanups = [];
const innerAborts = [];
return require_run_registry.runIdleLoop(agent, streamOptions, deps, (opts) => agent.stream(messages, opts), (opts) => agent.stream([], opts), (first, ctx) => {
if (!ctx) return first;
return {
output: new Proxy(first.output, { get(target, prop) {
if (prop === "fullStream") return ctx.combinedStream;
const value = Reflect.get(target, prop, target);
return typeof value === "function" ? value.bind(target) : value;
} }),
get fullStream() {
return ctx.combinedStream;
},
runId: first.runId,
threadId: ctx.threadId,
resourceId: ctx.resourceId,
cleanup: ctx.forceClose,
abort: async (reason) => {
await Promise.all(innerAborts.map(async (innerAbort) => {
try {
await innerAbort(reason);
} catch {}
}));
ctx.abort();
}
};
}, {
detachOnCancel: streamOptions?._detachObserverOnCancel === true,
onInnerResult: (inner) => {
if (typeof inner.cleanup === "function") innerCleanups.push(inner.cleanup);
if (typeof inner.abort === "function") innerAborts.push(inner.abort);
},
onAbortActive: () => {
const abort = innerAborts.at(-1);
if (!abort) return;
try {
Promise.resolve(abort(/* @__PURE__ */ new Error("Aborted"))).catch(() => {});
} catch {}
},
onForceClose: () => {
for (const fn of innerCleanups) try {
fn();
} catch {}
}
});
}
/**
* Run `DurableAgent.resume(..., { untilIdle })`. Same idle-loop semantics as
* `runDurableStreamUntilIdle` — initial turn calls `agent.resume(runId,
* resumeData, ...)` against the existing run snapshot, and subsequent
* continuations triggered by background-task completions use
* `agent.stream([], continuationOpts)` (a normal multi-turn agent stream)
* since the resume completes and we're back in regular conversation flow.
*/
async function runResumeDurableStreamUntilIdle(agent, runId, resumeData, streamOptions, deps) {
const innerCleanups = [];
const innerAborts = [];
return require_run_registry.runIdleLoop(agent, {
...streamOptions,
runId
}, deps, (opts) => agent.resume(runId, resumeData, opts), (opts) => agent.stream([], opts), (first, ctx) => {
if (!ctx) return first;
return {
output: new Proxy(first.output, { get(target, prop) {
if (prop === "fullStream") return ctx.combinedStream;
const value = Reflect.get(target, prop, target);
return typeof value === "function" ? value.bind(target) : value;
} }),
get fullStream() {
return ctx.combinedStream;
},
runId: first.runId,
threadId: ctx.threadId,
resourceId: ctx.resourceId,
cleanup: ctx.forceClose,
abort: async (reason) => {
await Promise.all(innerAborts.map(async (innerAbort) => {
try {
await innerAbort(reason);
} catch {}
}));
ctx.abort();
}
};
}, {
detachOnCancel: streamOptions?._detachObserverOnCancel === true,
onInnerResult: (inner) => {
if (typeof inner.cleanup === "function") innerCleanups.push(inner.cleanup);
if (typeof inner.abort === "function") innerAborts.push(inner.abort);
},
onAbortActive: () => {
const abort = innerAborts.at(-1);
if (!abort) return;
try {
Promise.resolve(abort(/* @__PURE__ */ new Error("Aborted"))).catch(() => {});
} catch {}
},
onForceClose: () => {
for (const fn of innerCleanups) try {
fn();
} catch {}
}
});
}
// src/agent/durable/utils/run-message-list.ts
/** The id generator does not survive the serialize/deserialize round-trip a durable run makes on every step. */
function createRunMessageList({ mastra, threadId, resourceId }) {
return new require_message_list.MessageList({
threadId,
resourceId,
generateMessageId: mastra?.generateId?.bind(mastra)
});
}
// src/agent/durable/memory-fga.ts
function getDurableMemoryAuthorizationChecks(entry) {
if (!entry) return /* @__PURE__ */ new Map();
return entry.memoryAuthorizationChecks ??= /* @__PURE__ */ new Map();
}
function authorizeDurableMemory(checks, options) {
const existingCheck = checks.get(options.permission);
if (existingCheck) return existingCheck;
const check = require_run_registry.checkThreadFGA(options).catch((error) => {
checks.delete(options.permission);
throw error;
});
checks.set(options.permission, check);
return check;
}
// src/agent/durable/structured-output-null-transform.ts
/**
* Mirrors the check in `Agent.#execute`: OpenAI-style strict JSON schema models answer
* omitted optional fields with `null`, so the live schema must map `null` back to `undefined`.
*/
function needsNullToUndefined(model, providerOptions) {
return model.provider.includes("openai") || Boolean(model.modelId?.includes("openai")) || require_run_registry.usesOpenAIStrictJsonSchema(model, providerOptions);
}
/** Builds a live standard schema from a persisted JSON Schema, applying the null transform when flagged. */
function toLiveStructuredOutputSchema(schema, nullToUndefined) {
const standard = (0, _mastra_schema_compat_schema.toStandardSchema)(schema);
return nullToUndefined ? (0, _mastra_schema_compat.wrapSchemaWithNullTransform)(standard) : standard;
}
// src/agent/durable/run-message-refs.ts
/**
* Messages each run knows memory storage holds — recalled ones it verified and
* ones it saved itself — shared by every step this process runs for it. Losing
* an entry only costs a storage read (or keeps saved messages inline until the
* next save).
*/
const runMessageRefs = new _isaacs_ttlcache.TTLCache({
max: 1e3,
ttl: 6e5,
updateAgeOnGet: true
});
function getRunMessageRefs(runId) {
let refs = runId ? runMessageRefs.get(runId) : void 0;
if (!refs) {
refs = new require_run_registry.MemoryMessageRefs();
if (runId) runMessageRefs.set(runId, refs);
}
return refs;
}
/** The run's refs if this process holds them, without creating an entry. */
function peekRunMessageRefs(runId) {
return runId ? runMessageRefs.get(runId) : void 0;
}
function releaseRunMessageRefs(runId) {
if (runId) runMessageRefs.delete(runId);
}
/**
* A `SaveQueueManager` `onSaved` callback that records the rows a run saved,
* so its persisted transcript references them instead of repeating them. Only
* runs that store refs hold an entry (the transcript store creates it), so saves
* for other runs, or landing after the run released its entry, are not kept.
*/
function recordRunSavedMessages(runId) {
return (rows) => {
const refs = peekRunMessageRefs(runId);
if (!refs) return;
const byThread = /* @__PURE__ */ new Map();
for (const row of rows) {
if (!row.threadId) continue;
const key = `${row.threadId}\u0000${row.resourceId ?? ""}`;
byThread.set(key, [...byThread.get(key) ?? [], row]);
}
for (const threadRows of byThread.values()) {
const { threadId, resourceId } = threadRows[0];
refs.recordSaved(threadRows, {
threadId,
resourceId
});
}
};
}
// src/agent/durable/utils/resolve-runtime.ts
/**
* Build a SaveQueueManager for a run's memory, or `undefined` when no memory
* is configured. Shared by `resolveRuntimeDependencies` and
* `rebuildRunToolsFromMastra` so the construction lives in one place.
*/
function makeSaveQueueManager(memory, runId, mastra) {
if (!memory) return void 0;
return new require_run_registry.SaveQueueManager({
logger: mastra?.getLogger?.(),
memory,
onSaved: recordRunSavedMessages(runId)
});
}
/**
* The run's `requestContextEntries` as handed to scorers (`customContext`), with
* the signed-in user taken from the live run-level context rather than the
* snapshot. The bearer token is never included.
*/
function restoreCustomContext(entries, runLevel) {
if (!entries) return void 0;
return Object.fromEntries([...Object.entries(require_request_context.withoutLiveRequestKeys(entries)), ...require_run_registry.liveRequestEntries(runLevel).filter(([key]) => key !== require_request_context.MASTRA_AUTH_TOKEN_KEY)]);
}
/**
* Thrown when the per-request processor pipeline cannot be rebuilt during
* cross-process rehydration. Propagated (not swallowed) because continuing
* without the rebuilt processors would silently drop skills / workspace
* instructions — the exact failure mode this rebuild exists to fix.
*/
var DurableProcessorRebuildError = class extends Error {
constructor(agentId, cause) {
super(`[DurableAgent:${agentId}] Failed to rebuild processor pipeline during cross-process rehydration: ${cause instanceof Error ? cause.message : String(cause)}`);
this.name = "DurableProcessorRebuildError";
this.cause = cause;
}
};
async function rebuildProcessorPipeline(options) {
const { agent, agentId, requestContext, emptyErrorProcessorOverride, processorStates, logger } = options;
try {
const inputProcessors = await agent.listInputProcessors?.(requestContext);
const outputProcessors = await agent.listOutputProcessors?.(requestContext);
const errorProcessorOverride = emptyErrorProcessorOverride ? [] : void 0;
const errorProcessors = (await agent.__resolveRunErrorProcessors?.(requestContext, errorProcessorOverride))?.errorProcessors;
return {
inputProcessors,
llmRequestInputProcessors: await agent.__listLLMRequestProcessors?.(requestContext, errorProcessors),
outputProcessors,
errorProcessors,
processorStates: processorStates ?? /* @__PURE__ */ new Map()
};
} catch (processorError) {
logger?.error?.(`[DurableAgent:${agentId}] Failed to rebuild processors from Mastra: ${processorError}`);
throw new DurableProcessorRebuildError(agentId, processorError);
}
}
/** True when the registry entry was seeded in this process (not a cross-process placeholder). */
function isHydratedRegistryEntry(entry) {
const model = entry?.model;
return !!entry && entry.isPlaceholder !== true && !!model && model.__metadataOnly !== true;
}
/**
* Throws when call-time `toolsets` tools named in the durable options are missing
* after a cross-process rebuild, instead of silently running without them.
*/
function assertToolsetToolsAvailable(tools, toolsetToolNames, agentId, runId) {
const missingToolsetTools = (toolsetToolNames ?? []).filter((name) => !(name in tools));
if (missingToolsetTools.length > 0) throw new require_error.MastraError({
id: "DURABLE_AGENT_TOOLSETS_UNAVAILABLE",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `Call-time toolsets tool(s) ${missingToolsetTools.map((n) => `"${n}"`).join(", ")} are not available to durable agent "${agentId}" in this worker process. Toolset tools contain server-side code that cannot be serialized across processes; register them on the agent (statically or via requestContext) instead.`,
details: {
agentId,
runId,
missingTools: missingToolsetTools.join(",")
}
});
}
/**
* Resolve all runtime dependencies needed for durable step execution.
*
* This function reconstructs the non-serializable state needed to execute
* agent steps from:
* 1. The Mastra instance (for agent lookup, tools, model)
* 2. The serialized workflow input (for MessageList, state)
*
* Unlike the registry-based approach, this reconstructs tools and model
* from the agent registered with Mastra, making it truly durable across
* process restarts.
*/
async function resolveRuntimeDependencies(options) {
const { mastra, runId, agentId, input, logger } = options;
const existingEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
const messageList = existingEntry?.messageList ? existingEntry.messageList.deserialize(input.messageListState) : createRunMessageList({
mastra,
threadId: input.state.threadId,
resourceId: input.state.resourceId
}).deserialize(input.messageListState);
const globalEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
const hasHydratedEntry = isHydratedRegistryEntry(globalEntry);
let tools = globalEntry?.baseTools ?? globalEntry?.tools ?? {};
let model = globalEntry?.model;
let modelList = globalEntry?.modelList;
let workspace = globalEntry?.workspace;
let memory = globalEntry?.memory;
let inputProcessors = globalEntry?.inputProcessors;
let llmRequestInputProcessors = globalEntry?.llmRequestInputProcessors;
let outputProcessors = globalEntry?.outputProcessors;
let errorProcessors = globalEntry?.errorProcessors;
let processorStates = globalEntry?.processorStates;
let rehydratedFromMastra = false;
let rebuiltAgent;
if (hasHydratedEntry) logger?.debug?.(`[DurableAgent:${agentId}] Using model and tools from global registry for run ${runId}`);
else if (mastra) try {
const agent = mastra.getAgentById(agentId);
rebuiltAgent = require_run_registry.isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
const resolveRequestContext = require_run_registry.restoreRequestContext(input.requestContextEntries, options.requestContext);
tools = await agent.getToolsForExecution({
runId,
threadId: input.state.threadId,
resourceId: input.state.resourceId,
requestContext: resolveRequestContext,
memoryConfig: input.state.memoryConfig,
autoResumeSuspendedTools: input.options?.autoResumeSuspendedTools,
clientTools: input.options?.clientTools
});
assertToolsetToolsAvailable(tools, input.options?.toolsetToolNames, agentId, runId);
model = await agent.getModel?.({ requestContext: resolveRequestContext }) ?? resolveModel(input.modelConfig, mastra);
const rawModelList = await agent.getModelList?.(resolveRequestContext);
if (rawModelList && Array.isArray(rawModelList)) modelList = rawModelList.map((entry) => ({
id: entry.id,
model: entry.model,
maxRetries: entry.maxRetries ?? 0,
enabled: entry.enabled ?? true,
headers: entry.headers
}));
memory = await agent.getMemory?.({ requestContext: resolveRequestContext });
workspace = await agent.getWorkspace?.({ requestContext: resolveRequestContext });
const rebuiltProcessors = await rebuildProcessorPipeline({
agent,
agentId,
requestContext: resolveRequestContext,
emptyErrorProcessorOverride: input.options?.emptyErrorProcessorOverride,
processorStates: globalEntry?.processorStates,
logger
});
inputProcessors = rebuiltProcessors.inputProcessors;
llmRequestInputProcessors = rebuiltProcessors.llmRequestInputProcessors;
outputProcessors = rebuiltProcessors.outputProcessors;
errorProcessors = rebuiltProcessors.errorProcessors;
processorStates = rebuiltProcessors.processorStates;
rehydratedFromMastra = true;
} catch (error) {
if (error instanceof DurableProcessorRebuildError) throw error;
if ((input.options?.toolsetToolNames?.length ?? 0) > 0) throw error;
logger?.debug?.(`[DurableAgent:${agentId}] Failed to get agent from Mastra: ${error}`);
model = resolveModel(input.modelConfig, mastra);
}
else {
logger?.debug?.(`[DurableAgent:${agentId}] No Mastra instance available, using fallback model`);
model = resolveModel(input.modelConfig);
}
if (Object.keys(tools).length === 0) logger?.debug?.(`[DurableAgent:${agentId}] No tools resolved for run ${runId}`);
const saveQueueManager = makeSaveQueueManager(memory, runId, mastra);
if (rehydratedFromMastra) {
const rebuilt = {
isPlaceholder: false,
tools,
model,
modelList,
workspace,
memory,
saveQueueManager,
inputProcessors,
llmRequestInputProcessors,
outputProcessors,
errorProcessors,
processorStates,
agent: rebuiltAgent
};
if (globalEntry) Object.assign(globalEntry, rebuilt);
else require_run_registry.setRunRegistryEntry(runId, rebuilt, mastra);
}
return {
_internal: resolveInternalState({
state: input.state,
memory,
saveQueueManager,
tools
}),
tools,
model,
modelList,
messageList,
memory,
saveQueueManager,
workspace,
inputProcessors,
llmRequestInputProcessors,
outputProcessors,
errorProcessors,
processorStates
};
}
/**
* Rebuild the run's tools (and workspace/memory) from the agent registered on
* the Mastra instance, then write them back into the per-process run registry.
*
* The durable tool-call step runs as a SEPARATE step from the LLM-execution
* step and, on a cross-process engine (e.g. the @mastra/inngest connect()
* worker), can execute in a different process than the one that prepared the
* run. In that process `getRunRegistryEntry(runId, mastra as Mastra | undefined)` is empty (or a minimal
* placeholder), so per-request closure tools (workspace/skill tools:
* `skill`, `skill_read`, `skill_search`, `mastra_workspace_*`) are absent and
* the model's tool call rejects with `ToolNotFoundError`.
*
* The LLM step already rebuilds the full toolset via
* `resolveRuntimeDependencies` → `getToolsForExecution`; this helper gives the
* tool-call step the same rebuild so tool resolution is symmetric cross-process.
* The writeback means the first unresolved tool call rebuilds once and later
* calls in the same process hit the registry.
*
* Returns `undefined` when no Mastra instance is available or the agent can't
* be resolved — callers fall back to their existing `ToolNotFoundError`.
*/
async function rebuildRunToolsFromMastra(options) {
const { mastra, runId, agentId, state, options: execOptions, requestContextEntries, requestContext, logger } = options;
if (!mastra) return void 0;
let agentResolved = false;
try {
const agent = mastra.getAgentById(agentId);
agentResolved = true;
const processorAgent = require_run_registry.isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
const resolveRequestContext = require_run_registry.restoreRequestContext(requestContextEntries, requestContext);
const tools = await agent.getToolsForExecution({
runId,
threadId: state.threadId,
resourceId: state.resourceId,
requestContext: resolveRequestContext,
memoryConfig: state.memoryConfig,
autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,
clientTools: execOptions?.clientTools
});
if (!isHydratedRegistryEntry(require_run_registry.getRunRegistryEntry(runId, mastra))) assertToolsetToolsAvailable(tools, execOptions?.toolsetToolNames, agentId, runId);
const memory = await agent.getMemory?.({ requestContext: resolveRequestContext });
const workspace = await agent.getWorkspace?.({ requestContext: resolveRequestContext });
const saveQueueManager = makeSaveQueueManager(memory, runId, mastra);
let existing = require_run_registry.getRunRegistryEntry(runId, mastra);
const rebuiltProcessors = !options.rehydrateProcessors ? {} : existing?.outputProcessors && existing.processorStates ? {
inputProcessors: existing.inputProcessors,
llmRequestInputProcessors: existing.llmRequestInputProcessors,
outputProcessors: existing.outputProcessors,
errorProcessors: existing.errorProcessors,
processorStates: existing.processorStates
} : await rebuildProcessorPipeline({
agent,
agentId,
requestContext: resolveRequestContext,
emptyErrorProcessorOverride: execOptions?.emptyErrorProcessorOverride,
processorStates: existing?.processorStates,
logger
});
const patch = {
tools,
workspace,
memory,
saveQueueManager,
agent: processorAgent,
...rebuiltProcessors,
...options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}
};
existing = require_run_registry.getRunRegistryEntry(runId, mastra);
if (existing) {
const needsProcessorPipeline = !existing.outputProcessors || !existing.processorStates;
if (options.rehydrateProcessors && (existing.isPlaceholder && needsProcessorPipeline || !existing.requestContext)) existing.requestContext = resolveRequestContext;
const registryModel = existing.model;
if (!(existing.isPlaceholder !== true && !!registryModel && registryModel.__metadataOnly !== true && (existing.baseTools !== void 0 || existing.tools !== void 0)) && Object.keys(existing.tools ?? {}).length === 0) existing.tools = tools;
existing.workspace ??= workspace;
existing.memory ??= memory;
existing.saveQueueManager ??= saveQueueManager;
existing.inputProcessors ??= rebuiltProcessors.inputProcessors;
existing.llmRequestInputProcessors ??= rebuiltProcessors.llmRequestInputProcessors;
existing.outputProcessors ??= rebuiltProcessors.outputProcessors;
existing.errorProcessors ??= rebuiltProcessors.errorProcessors;
existing.processorStates ??= rebuiltProcessors.processorStates;
existing.agent ??= processorAgent;
} else {
existing = patch;
require_run_registry.setRunRegistryEntry(runId, existing, mastra);
}
return {
tools,
workspace,
memory,
saveQueueManager,
inputProcessors: existing.inputProcessors,
llmRequestInputProcessors: existing.llmRequestInputProcessors,
outputProcessors: existing.outputProcessors,
errorProcessors: existing.errorProcessors,
processorStates: existing.processorStates,
requestContext: resolveRequestContext
};
} catch (error) {
if (error instanceof DurableProcessorRebuildError) throw error;
const entry = require_run_registry.getRunRegistryEntry(runId, mastra);
if ((execOptions?.toolsetToolNames?.length ?? 0) > 0 && !isHydratedRegistryEntry(entry)) throw error;
if (agentResolved && options.rehydrateProcessors && (!entry?.outputProcessors || !entry.processorStates)) throw new DurableProcessorRebuildError(agentId, error);
logger?.debug?.(`[DurableAgent:${agentId}] Failed to rebuild tools from Mastra for run ${runId}: ${error}`);
return;
}
}
/**
* Resolve the language model from serialized config.
*
* Note: This is a fallback when the model is not in the run registry.
* The preferred approach is to store the actual model instance in the
* run registry during preparation and retrieve it via runRegistry.getModel().
*
* This fallback returns a metadata-only stub that will fail the
* isSupportedLanguageModel check with a descriptive error message.
*/
function resolveModel(config, _mastra) {
const metadataError = () => {
throw new Error(`Model ${config.provider}/${config.modelId} is a metadata-only stub. The actual model instance should be resolved from the run registry.`);
};
return {
provider: config.provider,
modelId: config.modelId,
specificationVersion: config.specificationVersion ?? "v2",
supportedUrls: {},
doGenerate: metadataError,
doStream: metadataError,
__metadataOnly: true
};
}
/**
* Reconstruct the _internal (StreamInternal) object from available state
*/
function resolveInternalState(options) {
const { state, memory, saveQueueManager, tools } = options;
return {
now: () => Date.now(),
generateId: () => crypto.randomUUID(),
currentDate: () => /* @__PURE__ */ new Date(),
saveQueueManager,
memory,
memoryConfig: state.memoryConfig,
threadId: state.threadId,
resourceId: state.resourceId,
threadExists: state.threadExists,
stepTools: tools
};
}
/**
* Resolve a single tool by name from Mastra's global tool registry
*/
function resolveTool(toolName, mastra) {
try {
return mastra?.getTool?.(toolName);
} catch {
return;
}
}
/**
* Check if a tool requires human approval.
*
* Mirrors the non-durable precedence:
* - Function-form global `requireToolApproval` is evaluated per call with
* `(toolName, args, ...)`. Throwing defaults to "require approval" (safe).
* - Boolean global / tool-level `requireApproval` seed the decision.
* - Approval-exempt tools (skill tools) never require approval.
* - A per-tool `needsApprovalFn` is authoritative when
* present and overrides the seed. It receives `{ requestContext, workspace }`
* as its second argument, exactly like the non-durable loop.
*
* In durable execution the function form lives on the run registry, not on
* the serialized workflow input — pass the resolved value from the caller.
*/
async function toolRequiresApproval(tool, globalRequireApproval, args, approvalContext) {
if (require_toolchecks.isApprovalExempt(tool)) return false;
let globalRequires;
if (typeof globalRequireApproval === "function") try {
globalRequires = !!await globalRequireApproval({
toolName: approvalContext?.toolName ?? "",
args: args ?? {},
requestContext: approvalContext?.requestContext,
workspace: approvalContext?.workspace
});
} catch {
globalRequires = true;
}
else globalRequires = !!globalRequireApproval;
let requires = globalRequires || !!tool.requireApproval;
const needsApprovalFn = require_toolchecks.getNeedsApprovalFn(tool);
if (needsApprovalFn) try {
requires = !!await needsApprovalFn(args ?? {}, {
requestContext: approvalContext?.requestContext,
workspace: approvalContext?.workspace
});
} catch {
requires = true;
}
return requires;
}
/**
* Resolve a language model from a serialized model config.
*
* This is used during durable execution to reconstruct models from
* serialized configuration. It uses the originalConfig string (e.g., 'openai/gpt-4o')
* to resolve the model through the standard model resolution pipeline.
*
* @param config The serialized model configuration
* @param mastra Optional Mastra instance for custom gateways
* @returns Resolved language model
*/
async function resolveModelFromConfig(config, mastra) {
const requestContext = new require_request_context.RequestContext();
const modelConfigString = config.originalConfig ?? `${config.provider}/${config.modelId}`;
if (typeof modelConfigString === "string") return await require_llm.resolveModelConfig(modelConfigString, requestContext, mastra);
return await require_llm.resolveModelConfig(modelConfigString, requestContext, mastra);
}
/**
* Resolve a model from a model list entry.
*
* @param entry The model list entry with config, maxRetries, enabled
* @param mastra Optional Mastra instance
* @returns Resolved language model
*/
async function resolveModelFromListEntry(entry, mastra) {
return resolveModelFromConfig(entry.config, mastra);
}
// src/agent/durable/workflows/shared/background-results.ts
const BACKGROUND_RESULTS = require_stream.createRunScopeKey("durable-background-results");
/** Returns the record for `taskId`, replacing one left by an earlier attempt of the tool-call step. */
function recordBackgroundResult(entry, taskId, toolCallId, settled) {
const scope = entry.runScope ??= require_stream.createRunScope();
let records = scope.get(BACKGROUND_RESULTS);
if (!records) scope.set(BACKGROUND_RESULTS, records = /* @__PURE__ */ new Map());
let record = records.get(taskId);
if (record?.settled !== settled) {
const created = {
toolCallId,
settled
};
settled.then(() => created.done = true);
records.set(taskId, record = created);
}
return record;
}
/** Whether `onResult` has applied any result that a transcript may still need. */
function hasAppliedBackgroundResults(entry) {
for (const record of entry?.runScope?.get(BACKGROUND_RESULTS)?.values() ?? []) if (record.apply) return true;
return false;
}
function holdsPlaceholder(messageList, taskId, toolCallId) {
return messageList.get.all.db().some((message) => message.role === "assistant" && message.content?.parts?.some((part) => {
if (part.type !== "tool-invocation" || part.toolInvocation?.toolCallId !== toolCallId) return false;
const backgroundTask = part.providerMetadata?.mastra?.backgroundTask;
return backgroundTask?.taskId === taskId && backgroundTask.status === "running";
}));
}
/**
* Writes every result `onResult` has applied into `messageList` where it still shows that task's
* placeholder. Returns whether anything changed.
*/
async function foldBackgroundResults(entry, messageList) {
let changed = false;
for (const [taskId, record] of entry?.runScope?.get(BACKGROUND_RESULTS) ?? []) {
if (!record.apply || !holdsPlaceholder(messageList, taskId, record.toolCallId)) continue;
await record.apply(messageList);
changed = true;
}
return changed;
}
/**
* A task's status turns terminal before its `onResult` hook runs. Waits for the hooks of recorded tasks
* that `isFinished` reports done, giving up after `timeoutMs` so a lost completion event cannot hang the step.
*/
async function settleFinishedBackgroundResults(entry, isFinished, timeoutMs) {
const finished = [];
for (const [taskId, record] of entry?.runScope?.get(BACKGROUND_RESULTS) ?? []) if (!record.done && await isFinished(taskId)) finished.push(record.settled);
if (finished.length === 0) return;
let timer;
try {
await Promise.race([Promise.all(finished), new Promise((resolve) => timer = setTimeout(resolve, timeoutMs))]);
} finally {
clearTimeout(timer);
}
}
// src/agent/durable/workflows/shared/message-list-state.ts
/**
* Where the serialized transcript (`messageListState`) lives between steps.
*
* The durable loop seeds it into workflow state once (`init-iteration-state`),
* so every persisted snapshot carries a single copy in `value` instead of one
* per step payload. Runs that never seeded it — those persisted before the
* move, or workflows composing these steps without seeding — keep threading
* it through step input/output unchanged.
*
* In workflow state, messages memory already stores (recalled, or saved by
* this run) are kept as refs to their memory rows (see {@link MemoryMessageRefs}): reads restore them, writes
* re-create them. Step payloads carry the full transcript while a step runs;
* {@link dehydrateSnapshotTranscripts} swaps in refs when a snapshot is persisted.
*/
async function readMessageListState(params, stepPayload) {
const stored = (await params.getState(["messageListState"]))?.messageListState ?? stepPayload?.messageListState;
if (!stored?.messages?.some(require_run_registry.isMemoryMessageRef)) return stored;
return hydrateMidRun(runTranscriptRefs(params), stored, params.abortSignal);
}
/**
* Stores an updated transcript where this run keeps it. Returns the fields to
* spread into the step output: nothing when it went to workflow state,
* `{ messageListState }` when the run threads it through step payloads.
*/
async function storeMessageListState(params, messageListState) {
if ((await params.getState(["messageListState"]))?.messageListState === void 0) return { messageListState };
await params.setState({ messageListState: await dehydrateMessageListState(params, messageListState) });
return {};
}
/**
* The transcript for code that reads and rewrites it in place across several
* phases (the continuation predicate): restored once up front, then `write`
* keeps the live copy and stores it back where it came from.
*/
async function openMessageListState(params, stepPayload) {
const workflowState = await params.getState();
if (workflowState?.messageListState === void 0) {
stepPayload.messageListState = await readMessageListState(params, stepPayload);
return {
read: () => stepPayload.messageListState,
write: (next) => {
stepPayload.messageListState = next;
}
};
}
const run = runTranscriptRefs(params);
const { state } = params.getInitData() ?? {};
let current = await hydrateMidRun(run, workflowState.messageListState, params.abortSignal);
return {
read: () => current,
write: (next) => {
current = next;
workflowState.messageListState = state?.fixedMemory ? run.refs.dehydrate(next) : next;
}
};
}
let midRunLoadRetryDelaysMs = [
500,
2e3,
8e3
];
/**
* Restores refs inside a running step or the loop predicate. A step without
* this process's loaded rows (another worker, an evicted cache entry) reads
* them from memory storage after the iteration's tools already ran, so a
* failure here would end the run with no way to retry it. Transient storage
* errors are retried for about ten seconds first. Every caller reads before
* doing any work, so a retry repeats nothing.
*/
async function hydrateMidRun(run, stored, abortSignal) {
for (let attempt = 0;; attempt++) try {
return await run.refs.hydrate(stored, run.load, run);
} catch (error) {
const wait = midRunLoadRetryDelaysMs[attempt];
const permanent = error instanceof require_error.MastraError && error.id === "AGENT_MEMORY_MESSAGE_REF_UNRESOLVABLE";
if (wait === void 0 || permanent || abortSignal?.aborted) throw error;
run.logger?.warn("Could not load recalled messages from memory storage; retrying", {
runId: run.runId,
attempt: attempt + 1,
error
});
await require_utils.delay(wait, abortSignal);
}
}
/** The transcript as workflow state stores it. */
async function dehydrateMessageListState(params, messageListState) {
const { state } = params.getInitData() ?? {};
if (!state?.fixedMemory) return messageListState;
const run = runTranscriptRefs(params);
await run.refs.verify(messageListState, run.load, run.logger);
return run.refs.dehydrate(messageListState);
}
/**
* Loads the recalled messages a persisted run stores as refs before it resumes
* or recovers, dropping any this process verified earlier so the run picks up
* edits or deletions made in memory meanwhile. Called before anything runs, so
* a memory storage failure leaves the run as it was; the steps then restore the
* transcript from the rows loaded here.
*/
async function loadMessageListStateForResume(params) {
releaseMessageListState(params);
const stored = params.state?.messageListState;
if (stored === void 0) return;
const run = runTranscriptRefs(params);
await run.refs.hydrate(stored, run.load, run);
}
/** Restores the refs in a transcript read straight from a persisted snapshot. */
async function hydrateMessageListState(params, stored) {
const run = runTranscriptRefs(params);
return run.refs.hydrate(stored, run.load, run);
}
/**
* Replaces messages memory already stores with refs in the transcript copies a
* persisted snapshot carries outside workflow state: the run input, step
* payloads and outputs, and the evented engine's `__state` mirror. Without
* this every checkpoint rewrites the conversation once per copy (#26600).
* Never reads storage; anything not yet saved stays inline. Copy-on-write.
*/
function dehydrateSnapshotTranscripts(snapshot) {
const context = snapshot.context;
const refs = (context?.input)?.state?.fixedMemory ? peekRunMessageRefs(snapshot.runId) : void 0;
if (!context || !refs) return snapshot;
const withRefs = (carrier) => {
const state = carrier?.messageListState;
if (!state?.messages) return carrier;
const next = refs.dehydrate(state);
return next === state ? carrier : {
...carrier,
messageListState: next
};
};
let changed = false;
const nextContext = {};
for (const [key, value] of Object.entries(context)) {
let next = value;
if (key === "input" || key === "__state") next = withRefs(value);
else if (value && typeof value === "object") {
const step = value;
const payload = withRefs(step.payload);
const output = withRefs(step.output);
if (payload !== step.payload || output !== step.output) next = {
...step,
payload,
output
};
}
changed ||= next !== value;
nextContext[key] = next;
}
const value = withRefs(snapshot.value);
if (!changed && value === snapshot.value) return snapshot;
return {
...snapshot,
value,
context: changed ? nextContext : context
};
}
/** Loads stored messages of the run by id from the run's memory. */
function loadRunStoredMessages(params) {
return runTranscriptRefs(params).load;
}
/** Frees this process's verified rows once the run has read its transcript for the last time. */
function releaseMessageListState(params) {
const { runId } = params.getInitData() ?? {};
releaseRunMessageRefs(runId);
}
function runTranscriptRefs(params) {
const run = params.getInitData() ?? {};
const refs = getRunMessageRefs(run.runId);
let memory;
const load = async (ids) => require_run_registry.createStoredMessageLoader(await (memory ??= runMemory(params, run)))(ids);
return {
refs,
load,
runId: run.runId,
logger: params.mastra?.getLogger?.()
};
}
/** The run's memory: the live instance in this process, else re-resolved from the agent. */
async function runMemory(params, run) {
const memory = run.runId ? require_run_registry.getRunRegistryEntry(run.runId, params.mastra)?.memory : void 0;
if (memory || !params.mastra || !run.agentId) return memory;
return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: require_run_registry.restoreRequestContext(run.requestContextEntries, params.requestContext) });
}
// src/agent/durable/workflows/finalize-run.ts
function restoreRequestContext(entries, fallback) {
if (!entries) return fallback ?? new require_request_context.RequestContext();
const restored = new require_request_context.RequestContext(fallback?.entries());
for (const [key, value] of Object.entries(require_request_context.withoutLiveRequestKeys(entries))) restored.set(key, value);
require_run_registry.restoreRunAgentScopes(restored);
return restored;
}
function resolveOutputText(messageList) {
const responseMessages = messageList.get.response.db();
if (responseMessages.some((message) => message.content?.metadata?.completionResult)) {
const lastRealMessage = responseMessages.findLast((message) => !message.content?.metadata?.completionResult);
const lastConverted = (lastRealMessage ? require_message_list.convertMessages([lastRealMessage]).to("AIV4.Core") : []).at(-1);
return lastConverted ? require_message_list.coreContentToString(lastConverted.content) : "";
}
const lastResponseMessage = messageList.get.response.aiV4.core().at(-1);
return lastResponseMessage ? require_message_list.coreContentToString(lastResponseMessage.content) : "";
}
/**
* Run the side effects that happen after the durable agentic loop reaches its
* terminal state. Every durable engine calls this before emitting its finish
* event so remote workers provide the same behavior as the built-in engine.
*
* The returned state is the SAME MessageList that output processors mutated
* and memory persistence flushed. Callers must use it in their final output;
* rebuilding from the pre-processor state would discard redactions and other
* processOutputResult changes.
*/
async function runDurableFinishSideEffects({ runId, initData, messageListState, mastra, requestContext, tracingContext, logger, outputResult, messageId = initData.messageId }) {
const effectiveLogger = logger ?? mastra?.getLogger?.() ?? require_logger.noopLogger;
const durableState = initData.state;
let registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
let rebuiltSaveQueueManager;
let rebuiltMemory;
const needsProcessorRebuild = registryEntry?.outputProcessors === void 0;
const needsMemoryRebuild = !!durableState?.threadId && !registryEntry?.saveQueueManager;
if ((needsProcessorRebuild || needsMemoryRebuild) && mastra) try {
const resolved = await resolveRuntimeDependencies({
mastra,
runId,
agentId: initData.agentId,
input: {
...initData,
messageListState
},
logger: effectiveLogger
});
rebuiltSaveQueueManager = resolved.saveQueueManager;
rebuiltMemory = resolved.memory;
registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
} catch (error) {
effectiveLogger.error("[DurableAgent] Failed to rebuild finish-time dependencies", {
agentId: initData.agentId,
runId,
error
});
}
const effectiveRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext);
if (!effectiveRequestContext.has("MastraMemory") && durableState?.threadId) effectiveRequestContext.set("MastraMemory", {
thread: { id: durableState.threadId },
resourceId: durableState.resourceId,
memoryConfig: durableState.memoryConfig
});
const messageList = (registryEntry?.messageList ?? new require_message_list.MessageList({
threadId: durableState?.threadId,
resourceId: durableState?.resourceId
})).deserialize(messageListState);
if (registryEntry) registryEntry.messageList = messageList;
await foldBackgroundResults(registryEntry, messageList);
const structuredOutput = initData.options?.structuredOutput;
const structuredOutputText = resolveOutputText(messageList);
const liveStructuredOutput = registryEntry?.structuredOutput;
const structuredOutputSchema = liveStructuredOutput?.schema ?? (structuredOutput?.schema ? toLiveStructuredOutputSchema(structuredOutput.schema, structuredOutput.nullToUndefined) : void 0);
let structuredOutputChunks;
const structuringParts = structuredOutput?.hasStructuringModel ? responseStreamParts(messageList) : void 0;
if (structuredOutputSchema && (structuredOutputText.trim() || structuringParts?.length)) {
const finishReason = outputResult?.finishReason;
const truncated = finishReason === "length" || finishReason === "content-filter";
const errorStrategy = liveStructuredOutput ? liveStructuredOutput.errorStrategy : structuredOutput?.errorStrategy;
const fallbackValue = liveStructuredOutput ? liveStructuredOutput.fallbackValue : structuredOutput?.fallbackValue;
let value;
if (structuredOutput?.hasStructuringModel) {
const structuringModel = liveStructuredOutput?.model ?? structuredOutput.structuringModelConfig?.originalConfig;
if (structuringModel && !truncated && !(finishReason === "abort" || finishReason === "error")) {
structuredOutputChunks = await runStructuringPass({
options: {
...liveStructuredOutput ?? {},
schema: liveStructuredOutput?.schema ?? (0, _mastra_schema_compat_schema.toStandardSchema)(structuredOutput.schema),
model: structuringModel,
instructions: liveStructuredOutput?.instructions ?? structuredOutput.instructions,
jsonPromptInjection: liveStructuredOutput?.jsonPromptInjection ?? structuredOutput.jsonPromptInjection,
errorStrategy,
fallbackValue
},
mastra,
agentId: initData.agentId,
messageList,
streamParts: structuringParts,
requestContext: effectiveRequestContext,
logger: effectiveLogger
});
const objectChunk = structuredOutputChunks.findLast((chunk) => chunk.type === "object-result");
value = objectChunk?.type === "object-result" ? objectChunk.object : void 0;
} else if (!structuringModel) effectiveLogger.warn("[DurableAgent] structuredOutput.model is not available on this worker", { runId });
} else {
const result = truncated ? void 0 : await require_stream.createOutputHandler({ schema: structuredOutputSchema }).validateAndTransformFinal(structuredOutputText);
value = result?.success ? result.value : errorStrategy === "fallback" ? fallbackValue : void 0;
}
const lastAssistantMessage = messageList.get.response.db().findLast((message) => message.role === "assistant" && !message.content?.metadata?.completionResult);
if (value !== void 0 && lastAssistantMessage) lastAssistantMessage.content.metadata = {
...lastAssistantMessage.content.metadata,
structuredOutput: value
};
}
const assertOwned = () => require_run_registry.assertExecutionOwned({
runId,
agentId: initData.agentId,
requestContext,
mastra
});
await assertOwned();
const replyMessageId = messageList.get.response.db().some((message) => message.id === messageId) ? messageId : require_stream.resolveOutputMessageSkippingCompletionChecks(messageList)?.id ?? messageId;
const outputResultChunks = [];
const outputResultWriter = { custom: async (data, writerOptions) => {
require_stream.persistProcessorDataChunk(messageList, writerOptions?.messageId ?? replyMessageId, data);
outputResultChunks.push(data);
} };
const outputTextBeforeProcessing = resolveOutputText(messageList);
if (registryEntry?.outputProcessors?.length) try {
let agent = registryEntry.agent;
if (!agent && mastra) try {
const registered = mastra.getAgentById(initData.agentId);
agent = require_run_registry.isDurableAgentLike(registered) && registered.agent !== registered ? registered.agent : registered;
} catch {
agent = void 0;
}
await new require_stream.ProcessorRunner({
inputProcessors: registryEntry.inputProcessors ?? [],
outputProcessors: registryEntry.outputProcessors,
errorProcessors: registryEntry.errorProcessors ?? [],
logger: effectiveLogger,
agentName: initData.agentName ?? initData.agentId,
agent,
processorStates: registryEntry.processorStates
}).runOutputProcessors(messageList, require_observability.createObservabilityContext(tracingContext), effectiveRequestContext, 0, outputResultWriter, outputResult);
} catch (error) {
if (error instanceof require_stream.TripWire) {
await require_run_registry.undoSavedResponseMessages({
memory: registryEntry?.memory ?? rebuiltMemory,
threadId: durableState?.threadId,
memoryConfig: durableState?.memoryConfig,
messageList,
saveQueueManager: registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager,
logger: effectiveLogger,
runId
});
const outputText = resolveOutputText(messageList);
return {
messageListState: messageList.serialize(),
outputText,
outputTextChanged: outputText !== outputTextBeforeProcessing,
outputResultChunks,
tripwire: {
reason: error.message,
processorId: error.processorId,
retry: error.options?.retry,
metadata: error.options?.metadata
}
};
}
effectiveLogger.warn("[DurableAgent] Error running output processors", {
runId,
error
});
if (durableState?.observationalMemory) throw error;
}
const outputText = resolveOutputText(messageList);
const outputTextChanged = outputText !== outputTextBeforeProcessing;
const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
const memory = registryEntry?.memory ?? rebuiltMemory;
const authorizeMemory = durableState?.threadId && durableState.resourceId ? (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
mastra,
user: effectiveRequestContext.get("user"),
threadId: durableState.threadId,
resourceId: durableState.resourceId,
agentId: initData.agentId,
requestContext: effectiveRequestContext,
permission,
actor: initData.options?.actor
}) : void 0;
if (saveQueueManager && memory && durableState?.threadId && durableState?.resourceId && !durableState.observationalMemory && !durableState.memoryConfig?.readOnly) {
await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_WRITE);
if (!durableState.threadExists) await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_READ);
try {
if (!durableState.threadExists) await memory.createThread?.({
threadId: durableState.threadId,
resourceId: durableState.resourceId,
memoryConfig: durableState.memoryConfig
});
await saveQueueManager.flushMessages(messageList, durableState.threadId, durableState.memoryConfig, {
beforePersist: assertOwned,
throwOnError: true
});
} catch (error) {
if (require_run_registry.isExecutionFenceError(error)) throw error;
effectiveLogger.error("[DurableAgent] Error persisting messages", {
runId,
threadId: durableState.threadId,
error
});
throw error;
}
}
let titleGeneration;
let titleForStream;
if (durableState?.threadId && durableState?.resourceId && !durableState.observationalMemory && !durableState.memoryConfig?.readOnly) {
const titleArgs = {
threadId: durableState.threadId,
resourceId: durableState.resourceId,
memoryConfig: durableState.memoryConfig,
messageListState: messageList.serialize(),
requestContext: effectiveRequestContext,
tracingContext
};
const generateThreadTitle = registryEntry?.generateThreadTitle;
await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_READ);
await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_WRITE);
const savedTitle = (async () => {
if (generateThreadTitle) return generateThreadTitle(titleArgs);
else if (mastra) {
const agent = mastra.getAgentById(initData.agentId);
const titleMemory = memory ?? await agent.getMemory({ requestContext: effectiveRequestContext });
if (titleMemory) return generateDurableThreadTitle({
agent,
memory: titleMemory,
...titleArgs
});
}
})().catch((error) => {
effectiveLogger.warn("[DurableAgent] Error generating thread title", {
runId,
error
});
});
if (registryEntry?.streamThreadTitle) titleForStream = savedTitle;
const onTitleGenerated = registryEntry?.onTitleGenerated;
titleGeneration = savedTitle.then(async (title) => {
if (title && onTitleGenerated) await onTitleGenerated(title);
}).catch((error) => {
effectiveLogger.error("[DurableAgent] Error in onTitleGenerated callback", {
runId,
error
});
});
}
return {
messageListState: messageList.serialize(),
outputText,
outputTextChanged,
titleGeneration,
titleForStream,
structuredOutputChunks,
outputResultChunks
};
}
/**
* What a total deadline saves: the steps that completed in time, plus the step in flight. A step cut off
* mid-stream contributes the text it already streamed, which never reached the step processors. A step cut off
* while its tools ran is kept whole, with the tool results that came back in time or during the deadline's grace
* window and any call still running saved as aborted.
*/
function deadlineMessageListState(entry, fallback) {
if (entry.streamedStepText) return {
messageListState: entry.completedStepsState ?? fallback,
cutOffText: entry.streamedStepText.join("")
};
const settled = entry.settledToolResults;
if (settled?.length && entry.messageList) {
const inFlight = new require_message_list.MessageList().deserialize(JSON.parse(JSON.stringify(entry.messageList.serialize())));
for (const result of settled) require_stream.commitToolResult({
messageList: inFlight,
outcome: result.outcome,
toolCallId: result.toolCallId,
toolName: result.toolName,
toolArgs: result.args,
approval: result.approval,
providerMetadata: result.providerMetadata
});
const unsettled = inFlight.get.response.db().flatMap((message) => message.content.parts ?? []).filter((part) => part.type === "tool-invocation" && !require_message_list.isTerminalToolInvocationState(part.toolInvocation.state));
for (const part of unsettled) {
if (part.type !== "tool-invocation") continue;
require_stream.commitToolResult({
messageList: inFlight,
outcome: {
kind: "result",
result: require_utils.TOOL_ABORT_NOTICE
},
toolCallId: part.toolInvocation.toolCallId,
toolName: part.toolInvocation.toolName,
toolArgs: part.toolInvocation.args
});
}
return { messageListState: inFlight.serialize() };
}
return { messageListState: entry.completedStepsState ?? fallback };
}
/**
* Give the output processors (and with them memory) their one pass when a total deadline ends a
* durable run. The run never reaches its finish step, so this runs over what the deadline saves
* (see `deadlineMessageListState`), as the default loop's deadline pass does.
*/
async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, mastra, tracingContext, logger }) {
const durableState = initData.state;
const requestContext = restoreRequestContext(initData.requestContextEntries, entry.requestContext);
if (!requestContext.has("MastraMemory") && durableState?.threadId) requestContext.set("MastraMemory", {
thread: { id: durableState.threadId },
resourceId: durableState.resourceId,
memoryConfig: durableState.memoryConfig
});
const memoryContext = requestContext.get("MastraMemory");
if (durableState?.memoryConfig?.readOnly || memoryContext?.memoryConfig?.readOnly) return;
const resourceId = durableState?.resourceId ?? memoryContext?.resourceId;
if (entry.memory && resourceId) {
const threadIds = new Set([durableState?.threadId, memoryContext?.thread?.id].filter(Boolean));
try {
for (const threadId of threadIds) await authorizeDurableMemory(threadId === durableState?.threadId ? getDurableMemoryAuthorizationChecks(entry) : /* @__PURE__ */ new Map(), {
mastra,
user: requestContext.get("user"),
threadId,
resourceId,
agentId: initData.agentId,
requestContext,
permission: require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_WRITE,
actor: initData.options?.actor
});
} catch (authError) {
logger.warn("[DurableAgent] Memory write denied at the total deadline, the turn is not saved", {
runId,
error: authError
});
return;
}
}
const messageList = new require_message_list.MessageList({
threadId: durableState?.threadId,
resourceId: durableState?.resourceId
}).deserialize(await hydrateMessageListState({
getInitData: () => initData,
mastra,
requestContext
}, messageListState));
const replyMessageId = require_stream.resolveOutputMessageSkippingCompletionChecks(messageList)?.id ?? initData.messageId;
let inFlightMessageId;
if (cutOffText?.trim()) {
messageList.add({
role: "assistant",
content: [{
type: "text",
text: cutOffText
}]
}, "response", { merge: false });
inFlightMessageId = messageList.get.response.db().at(-1).id;
}
if (entry.outputProcessors?.length) {
const runner = new require_stream.ProcessorRunner({
inputProcessors: entry.inputProcessors ?? [],
outputProcessors: entry.outputProcessors,
errorProcessors: entry.errorProcessors ?? [],
logger,
agentName: initData.agentName ?? initData.agentId,
agent: entry.agent,
processorStates: entry.processorStates
});
let heldDataChunks;
const writer = { custom: async (data, writerOptions) => {
if (heldDataChunks && (!writerOptions?.messageId || writerOptions.messageId === inFlightMessageId)) heldDataChunks.push({
data,
messageId: writerOptions?.messageId
});
else require_stream.persistProcessorDataChunk(messageList, require_stream.resolveProcessorWriterMessageId(messageList, replyMessageId, writerOptions?.messageId), data);
} };
if (inFlightMessageId) {
heldDataChunks = [];
try {
const stepList = messageList.clone();
stepList.removeByIds(stepList.get.all.db().map((message) => message.id).filter((id) => id !== inFlightMessageId));
await runner.runProcessOutputStep({
steps: [],
messages: stepList.get.all.db(),
messageList: stepList,
stepNumber: 0,
finishReason: "error",
text: cutOffText,
...require_observability.createObservabilityContext(tracingContext),
requestContext,
writer
});
messageList.removeByIds([inFlightMessageId]);
for (const message of stepList.get.all.db()) messageList.add(message, "response", { merge: false });
} catch (stepError) {
messageList.removeByIds([inFlightMessageId]);
logger.warn("[DurableAgent] Output step processors failed on the text cut off at the total deadline", {
runId,
error: stepError
});
}
for (const { data, messageId } of heldDataChunks) {
const target = messageId && messageList.get.all.db().some((message) => message.id === messageId) ? messageId : require_stream.resolveProcessorWriterMessageId(messageList, replyMessageId);
require_stream.persistProcessorDataChunk(messageList, target, data);
}
heldDataChunks = void 0;
}
try {
await runner.runOutputProcessors(messageList, require_observability.createObservabilityContext(tracingContext), requestContext, 0, writer, {
text: resolveOutputText(messageList),
usage: {
inputTokens: void 0,
outputTokens: void 0,
totalTokens: void 0
},
finishReason: "error",
steps: []
});
} catch (processorError) {
if (processorError instanceof require_stream.TripWire) {
await require_run_registry.undoSavedResponseMessages({
memory: entry.memory,
threadId: durableState?.threadId,
memoryConfig: durableState?.memoryConfig,
messageList,
saveQueueManager: entry.saveQueueManager,
logger,
runId
});
return;
}
logger.warn("[DurableAgent] Error running output processors at the total deadline", {
runId,
error: processorError
});
if (durableState?.observationalMemory) return;
}
}
if (!entry.saveQueueManager || !entry.memory || !durableState?.threadId || !durableState.resourceId || durableState.observationalMemory) return;
await entry.saveQueueManager.flushMessages(messageList, durableState.threadId, durableState.memoryConfig, { throwOnError: true });
}
var StructuringPassError = class extends Error {
constructor(message, cause) {
super(message, { cause });
this.name = "StructuringPassError";
}
};
/**
* Rebuild the chunks the structuring prompt reads (text, tool calls and results) from the
* run's response messages; the durable finish step has no in-memory chunk history.
*/
function responseStreamParts(messageList) {
const parts = [];
for (const message of messageList.get.response.db()) {
if (message.role !== "assistant" || message.content?.metadata?.completionResult) continue;
for (const part of message.content?.parts ?? []) if (part.type === "text") parts.push({
type: "text-delta",
payload: {
id: "",
text: part.text
}
});
else if (part.type === "tool-invocation") {
const { toolCallId, toolName, args } = part.toolInvocation;
parts.push({
type: "tool-call",
payload: {
toolCallId,
toolName,
args
}
});
if (part.toolInvocation.state === "result") parts.push({
type: "tool-result",
payload: {
toolCallId,
toolName,
result: part.toolInvocation.result
}
});
}
}
return parts;
}
/**
* Run Agent's StructuredOutputProcessor once against the finished turn and collect the
* chunks it would have streamed (object deltas and the final `object-result`).
*/
async function runStructuringPass({ options, mastra, agentId, messageList, streamParts, requestContext, logger }) {
const chunks = [];
try {
const processor = new require_run_registry.StructuredOutputProcessor({
...options,
logger
});
if (mastra) {
processor.__registerMastra(mastra);
if (options.useAgent) try {
processor.setAgent(mastra.getAgentById(agentId));
} catch {}
}
const state = { controller: { enqueue: (chunk) => chunks.push(chunk) } };
await processor.processOutputStream({
part: { type: "finish" },
state,
streamParts,
messageList,
requestContext,
abort: (() => {
throw new Error("abort is not supported in the durable structuring pass");
}),
retryCount: 0
});
processor.processOutputStep({
state,
messages: [],
abort: ((reason, opts) => {
throw new StructuringPassError(reason, opts?.metadata?.error);
})
});
} catch (error) {
if (error instanceof StructuringPassError || (options.errorStrategy ?? "strict") === "strict") throw error;
logger.error("[DurableAgent] Structured output structuring pass failed", { error });
}
return chunks;
}
/**
* Generate a durable thread title from messages belonging to that thread.
* This is standalone so a remote worker can call it with the agent and memory
* it rebuilt from its own Mastra instance.
*/
async function generateDurableThreadTitle({ agent, memory, threadId, resourceId, memoryConfig, messageListState, requestContext, tracingContext }) {
const thread = await memory.getThreadById({ threadId });
const mergedConfig = memory.getMergedThreadConfig(memoryConfig);
const { shouldGenerate, model, instructions, minMessages } = agent.resolveTitleGenerationConfig(mergedConfig.generateTitle);
if (!shouldGenerate || thread?.title) return void 0;
const titleMessageList = new require_message_list.MessageList().deserialize(messageListState);
const uiMessages = agent.filterUiMessagesByThread(titleMessageList, threadId, titleMessageList.get.all.ui());
if (uiMessages.length < (minMessages ?? 1)) return void 0;
const userMessage = agent.getMostRecentUserMessage(uiMessages);
if (!userMessage) return void 0;
const title = await agent.genTitle(userMessage, requestContext ?? new require_request_context.RequestContext(), require_observability.createObservabilityContext(tracingContext), model, instructions, uiMessages);
if (!title) return void 0;
const currentThread = thread ?? await memory.getThreadById({ threadId });
if (currentThread) await memory.updateThread({
id: threadId,
title,
metadata: currentThread.metadata ?? {},
memoryConfig
});
else await memory.createThread({
threadId,
resourceId,
memoryConfig,
title
});
return title;
}
// src/agent/durable/workflows/shared/execute-scorers.ts
/**
* Run an agent's configured scorers after a durable run completes.
*
* Every durable engine needs this, so it lives here rather than inside one
* engine's workflow builder: the Inngest engine shipped without scorers purely
* because its builder was a copy that missed a step core later added. Sharing
* the implementation means a scorer change lands on every engine at once.
*
* Scoring is fire-and-forget and must never affect the run: scorers come from
* the in-process run when available, otherwise they are resolved by
* name from the Mastra instance (so this is safe on a worker in another
* process), and anything that goes wrong is logged and skipped.
*/
async function executeDurableAgentScorers({ initData, finalOutput, mastra, requestContext, tracingContext, loadStoredMessages, scorerInstances }) {
const scorers = initData.scorers;
if (!scorers || Object.keys(scorers).length === 0) return;
const logger = mastra?.getLogger?.();
const inputMessageList = new require_message_list.MessageList();
inputMessageList.deserialize(initData.messageListState);
const scorerInput = {
inputMessages: inputMessageList.getPersisted.input.db(),
rememberedMessages: inputMessageList.getPersisted.remembered.db(),
systemMessages: inputMessageList.getSystemMessages(),
taggedSystemMessages: inputMessageList.getPersisted.taggedSystemMessages
};
const outputMessageList = new require_message_list.MessageList();
outputMessageList.deserialize(finalOutput.messageListState);
let scorerOutput;
try {
scorerOutput = await outputMessageList.getRunResponseMessages(loadStoredMessages);
} catch (error) {
logger?.warn?.("Skipped scorers: could not load pruned response messages", {
error,
runId: initData.runId
});
return;
}
const resolveContext = requestContext ?? new require_request_context.RequestContext();
for (const [scorerKey, scorerEntry] of Object.entries(scorers)) {
const { scorerName, sampling, filter } = scorerEntry;
try {
let scorer = scorerInstances?.[scorerKey];
if (!scorer) try {
scorer = mastra?.getScorerById?.(scorerName);
} catch {
scorer = void 0;
}
if (!scorer) try {
scorer = mastra?.getScorer?.(scorerName);
} catch {
scorer = void 0;
}
if (!scorer) {
logger?.warn?.(`Scorer ${scorerName} not found in Mastra, skipping`, {
runId: initData.runId,
scorerKey
});
continue;
}
const scorerObject = {
scorer,
sampling,
filter
};
require_run_registry.runScorer({
mastra,
runId: initData.runId,
scorerId: scorerKey,
scorerObject,
input: scorerInput,
output: scorerOutput,
requestContext: resolveContext,
entity: {
id: initData.agentId,
name: initData.agentName ?? initData.agentId
},
structuredOutput: false,
source: "LIVE",
entityType: "AGENT",
threadId: initData.state?.threadId,
resourceId: initData.state?.resourceId,
...require_observability.createObservabilityContext(tracingContext)
});
} catch (error) {
logger?.warn?.(`Error executing scorer ${scorerName}`, {
error,
runId: initData.runId,
scorerKey
});
}
}
}
// src/agent/durable/workflows/shared/schemas.ts
/**
* Shared Zod schemas for durable agentic workflows.
*
* These schemas are used by:
* - Core DurableAgent workflow
* - Inngest durable agent workflow
* - Evented durable agent workflow (future)
*/
/**
* Returns the path of the first value that would not survive a JSON round trip
* (functions, symbols, bigints, non-finite numbers, class instances, cycles, and
* `undefined` array items), or undefined if the value is JSON-safe. Undefined
* object properties are allowed (JSON drops them), and so are Dates: the workflow
* snapshot codec round-trips them.
*/
function findNonJsonSafePath(value, path, ancestors) {
if (value === null || value === void 0) return void 0;
const type = typeof value;
if (type === "string" || type === "boolean") return void 0;
if (type === "number") return Number.isFinite(value) ? void 0 : path || "<root>";
if (type !== "object") return path || "<root>";
if (value instanceof Date) return void 0;
if (ancestors.has(value)) return path || "<root>";
ancestors.add(value);
try {
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
const itemPath = `${path}[${i}]`;
if (value[i] === void 0) return itemPath;
const bad = findNonJsonSafePath(value[i], itemPath, ancestors);
if (bad) return bad;
}
return;
}
const proto = Object.getPrototypeOf(value);
if (proto !== Object.prototype && proto !== null) return path || "<root>";
for (const [key, child] of Object.entries(value)) {
const bad = findNonJsonSafePath(child, path ? `${path}.${key}` : key, ancestors);
if (bad) return bad;
}
return;
} finally {
ancestors.delete(value);
}
}
function isJsonSafe(value) {
return findNonJsonSafePath(value, "", /* @__PURE__ */ new Set()) === void 0;
}
/**
* Schema for the serialized durable options carried in workflow input. These
* options cross step boundaries (and processes) as JSON, so live objects such
* as Zod schemas must be converted before they get here — otherwise they are
* silently mangled by the round trip.
*/
const durableOptionsSchema = zod.z.any().superRefine((value, ctx) => {
const badPath = findNonJsonSafePath(value, "", /* @__PURE__ */ new Set());
if (badPath) ctx.addIssue({
code: zod.z.ZodIssueCode.custom,
message: `Durable agent options must be JSON-safe; found a non-serializable value at options.${badPath}`
});
});
/**
* Schema for model configuration
*/
const modelConfigSchema = zod.z.object({
provider: zod.z.string(),
modelId: zod.z.string(),
specificationVersion: zod.z.string().optional(),
settings: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerOptions: zod.z.record(zod.z.string(), zod.z.any()).optional()
});
/**
* Schema for model list entry (fallback support)
*/
const modelListEntrySchema = zod.z.object({
id: zod.z.string(),
config: zod.z.object({
provider: zod.z.string(),
modelId: zod.z.string(),
specificationVersion: zod.z.string().optional(),
originalConfig: zod.z.union([zod.z.string(), zod.z.record(zod.z.string(), zod.z.any())]).optional(),
settings: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerOptions: zod.z.record(zod.z.string(), zod.z.any()).optional()
}),
maxRetries: zod.z.number(),
enabled: zod.z.boolean()
});
/**
* Schema for accumulated usage across iterations
*/
const accumulatedUsageSchema = zod.z.object({
inputTokens: zod.z.number().optional(),
outputTokens: zod.z.number().optional(),
totalTokens: zod.z.number().optional(),
cachedInputTokens: zod.z.number().optional(),
cacheCreationInputTokens: zod.z.number().optional(),
reasoningTokens: zod.z.number().optional()
});
/**
* Provider id and serving model of one response.
*/
const responseRecordSchema = zod.z.object({
id: zod.z.string().optional(),
modelId: zod.z.string().optional()
});
/**
* Schema for output from the durable agentic workflow
*/
const durableAgenticOutputSchema = zod.z.object({
messageListState: zod.z.any(),
messageId: zod.z.string(),
stepResult: zod.z.any(),
output: zod.z.object({
text: zod.z.string().optional(),
usage: zod.z.any(),
steps: zod.z.array(zod.z.any())
}),
state: zod.z.any()
});
/**
* Base schema for durable agentic workflow input.
* Implementations can extend this with additional fields.
*/
const baseDurableAgenticInputSchema = zod.z.object({
runId: zod.z.string(),
agentId: zod.z.string(),
agentName: zod.z.string().optional(),
messageListState: zod.z.any(),
toolsMetadata: zod.z.array(zod.z.any()),
modelConfig: modelConfigSchema,
options: durableOptionsSchema,
state: zod.z.any(),
messageId: zod.z.string(),
inputTripwire: zod.z.object({
reason: zod.z.string(),
retry: zod.z.boolean().optional(),
processorId: zod.z.string().optional(),
metadata: zod.z.unknown().optional()
}).optional()
});
/**
* Base schema for iteration state.
* Implementations can extend this with additional fields.
*/
const baseIterationStateSchema = zod.z.object({
runId: zod.z.string(),
agentId: zod.z.string(),
agentName: zod.z.string().optional(),
messageListState: zod.z.any().optional(),
initialUntaggedSystemMessages: zod.z.array(zod.z.any()).optional(),
toolsMetadata: zod.z.array(zod.z.any()),
modelConfig: zod.z.any(),
options: durableOptionsSchema,
state: zod.z.any(),
messageId: zod.z.string(),
requestContextEntries: zod.z.record(zod.z.string(), zod.z.any()).optional(),
inputTripwire: baseDurableAgenticInputSchema.shape.inputTripwire,
iterationCount: zod.z.number(),
accumulatedSteps: zod.z.array(zod.z.any()).optional(),
accumulatedUsage: accumulatedUsageSchema,
usageAggregationVersion: zod.z.literal(1).optional(),
lastStepResult: zod.z.any().optional(),
deferredStepFinishChunk: zod.z.any().optional(),
backgroundTaskPending: zod.z.boolean().optional(),
delegationBailed: zod.z.boolean().optional(),
deadlineTimeout: zod.z.object({
timeoutType: zod.z.literal("total"),
timeoutMs: zod.z.number()
}).optional(),
runAborted: zod.z.boolean().optional(),
pendingFeedbackStop: zod.z.boolean().optional(),
responseMessagesCursor: zod.z.object({
producer: zod.z.string(),
seq: zod.z.number(),
fingerprints: zod.z.array(zod.z.string()),
wholeListSize: zod.z.number().optional(),
sentSinceWholeList: zod.z.number().optional()
}).optional(),
agentSpanData: zod.z.any().optional(),
modelSpanData: zod.z.any().optional(),
completionStartTime: zod.z.coerce.date().optional(),
timeToFirstTokenMs: zod.z.number().optional(),
lastResponse: responseRecordSchema.optional(),
tracingStopCause: zod.z.enum(require_run_registry.CONTINUATION_STOP_CAUSES).optional(),
tracingTermination: zod.z.custom().optional(),
tracingDelegationFailure: zod.z.custom().optional()
});
// src/agent/durable/workflows/shared/iteration-state.ts
/**
* The first-chunk clocks for spans rebuilt from a run-start snapshot. A
* resumed segment keeps them on the run registry beside its fresh spans; the
* originals keep them in the loop state. Undefined when none was captured yet.
*/
function carriedSpanClocks(registry, state) {
const clocks = registry?.resumeModelSpanData ? {
completionStartTime: registry.resumeCompletionStartTime,
timeToFirstTokenMs: registry.resumeTimeToFirstTokenMs
} : state;
const attributes = {
...clocks.completionStartTime ? { completionStartTime: new Date(clocks.completionStartTime) } : {},
...clocks.timeToFirstTokenMs !== void 0 ? { timeToFirstTokenMs: clocks.timeToFirstTokenMs } : {}
};
return Object.keys(attributes).length ? attributes : void 0;
}
/**
* Calculate accumulated usage from current state and new execution output.
*/
function calculateAccumulatedUsage(currentUsage, executionUsage) {
const accumulate = (current, next) => current !== void 0 && next !== void 0 ? current + next : void 0;
const usage = {
inputTokens: accumulate(currentUsage.inputTokens, executionUsage?.inputTokens),
outputTokens: accumulate(currentUsage.outputTokens, executionUsage?.outputTokens),
totalTokens: accumulate(currentUsage.totalTokens, executionUsage?.totalTokens)
};
for (const key of [
"cachedInputTokens",
"cacheCreationInputTokens",
"reasoningTokens"
]) {
const current = currentUsage[key];
const step = executionUsage?.[key];
if (current !== void 0 || step !== void 0) usage[key] = (current ?? 0) + (step ?? 0);
}
return usage;
}
/**
* Build a step record from execution output.
*/
function buildStepRecord(executionOutput) {
return {
text: executionOutput.output.text,
content: executionOutput.output.content,
toolCalls: executionOutput.output.toolCalls,
toolResults: executionOutput.toolResults?.map(({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, ...result }) => result),
usage: executionOutput.output.usage,
finishReason: executionOutput.stepResult.reason,
tripwire: executionOutput.stepResult.tripwire
};
}
/**
* An output processor can hold a tool result past its tool-call step and emit
* it when a later stream ends. The tool-call step recorded it as hidden; now
* that it was emitted, callbacks report it again.
*/
function withReleasedToolResults(steps, released) {
if (!released?.length) return steps;
const ids = new Set(released);
return steps.map((step) => {
if (!step.toolResults?.some((result) => isHeldResult(result, ids))) return step;
return {
...step,
toolResults: step.toolResults.map((result) => {
if (!isHeldResult(result, ids)) return result;
const { resultHidden: _resultHidden, ...rest } = result;
return rest;
})
};
});
}
function isHeldResult(result, ids) {
const record = result;
return !!record?.resultHidden && !!record.toolCallId && ids.has(record.toolCallId);
}
/**
* Create the base iteration state update.
*
* This returns the common fields for iteration state updates.
* Implementations can extend this with their specific fields.
*
* @example
* ```typescript
* const baseUpdate = createBaseIterationStateUpdate({
* currentState: initData,
* executionOutput,
* });
*
* // Core extends with modelList
* const coreState = { ...baseUpdate, modelList: initData.modelList };
*
* // Inngest extends with observability
* const inngestState = {
* ...baseUpdate,
* agentSpanData: initData.agentSpanData,
* modelSpanData: initData.modelSpanData,
* stepIndex: initData.stepIndex + 1,
* };
* ```
*/
function createBaseIterationStateUpdate(input) {
const { currentState, executionOutput } = input;
const previousSteps = currentState.accumulatedSteps ?? [];
const currentUsage = currentState.usageAggregationVersion === 1 || previousSteps.length === 0 ? currentState.accumulatedUsage : {
...currentState.accumulatedUsage,
inputTokens: void 0,
outputTokens: void 0,
totalTokens: void 0
};
const signalPreempted = executionOutput.stepResult.signalPreempted === true;
const newUsage = signalPreempted ? currentState.accumulatedUsage : calculateAccumulatedUsage(currentUsage, executionOutput.output.usage);
const lastStepResult = { ...executionOutput.stepResult };
delete lastStepResult.request;
return {
runId: currentState.runId,
agentId: currentState.agentId,
agentName: currentState.agentName,
messageListState: executionOutput.messageListState,
initialUntaggedSystemMessages: currentState.initialUntaggedSystemMessages,
toolsMetadata: currentState.toolsMetadata,
modelConfig: currentState.modelConfig,
options: currentState.options,
state: executionOutput.state,
messageId: executionOutput.messageId,
requestContextEntries: currentState.requestContextEntries,
inputTripwire: signalPreempted ? currentState.inputTripwire : void 0,
iterationCount: currentState.iterationCount + (signalPreempted ? 0 : 1),
accumulatedSteps: signalPreempted ? previousSteps : [...withReleasedToolResults(previousSteps, executionOutput.releasedToolResultIds), buildStepRecord(executionOutput)],
accumulatedUsage: newUsage,
usageAggregationVersion: signalPreempted ? currentState.usageAggregationVersion : 1,
lastStepResult,
deferredStepFinishChunk: executionOutput.deferredStepFinishChunk,
backgroundTaskPending: executionOutput.backgroundTaskPending,
delegationBailed: executionOutput.delegationBailed,
deadlineTimeout: executionOutput.deadlineTimeout ?? currentState.deadlineTimeout,
runAborted: executionOutput.runAborted ?? currentState.runAborted,
pendingFeedbackStop: currentState.pendingFeedbackStop,
responseMessagesCursor: currentState.responseMessagesCursor,
agentSpanData: currentState.agentSpanData,
modelSpanData: currentState.modelSpanData,
...currentState.completionStartTime ? {
completionStartTime: currentState.completionStartTime,
timeToFirstTokenMs: currentState.timeToFirstTokenMs
} : {
completionStartTime: executionOutput.completionStartTime,
timeToFirstTokenMs: executionOutput.timeToFirstTokenMs
},
lastResponse: signalPreempted ? currentState.lastResponse : executionOutput.response,
tracingTermination: executionOutput.tracingTermination,
tracingDelegationFailure: executionOutput.tracingDelegationFailure
};
}
// src/agent/durable/workflows/shared/accumulated-steps.ts
/**
* Where the run's step records (`accumulatedSteps`) live between steps. Same
* rule as the transcript (see `readMessageListState`): the durable loop seeds
* them into workflow state once (`init-iteration-state`), so a persisted
* snapshot carries one copy (in `value`) instead of one per step payload. Runs
* that never seeded them — those persisted before the move, or workflows
* composing these steps without seeding — keep threading them through step
* input/output unchanged.
*/
function readAccumulatedSteps(workflowState, stepPayload) {
return workflowState?.accumulatedSteps ?? stepPayload?.accumulatedSteps ?? [];
}
/** Loads the run's step records, and nothing else from workflow state. */
async function loadAccumulatedSteps(params, stepPayload) {
return readAccumulatedSteps(await params.getState(["accumulatedSteps"]), stepPayload);
}
/**
* Stores updated step records where this run keeps them. Returns the fields to
* spread into the step output: nothing when they went to workflow state,
* `{ accumulatedSteps }` when the run threads them through step payloads.
*/
async function storeAccumulatedSteps(params, accumulatedSteps) {
if ((await params.getState(["accumulatedSteps"]))?.accumulatedSteps === void 0) return { accumulatedSteps };
await params.setState({ accumulatedSteps });
return {};
}
// src/agent/durable/workflows/shared/tool-call-concurrency.ts
/**
* Resolves the effective tool-call foreach concurrency for a durable agentic
* workflow from the serialized workflow input (iteration state) and the
* step's tool calls.
*
* Mirrors @mastra/core's non-durable loop semantics
* (loop/workflows/agentic-execution/tool-call-concurrency.ts):
* - Global `requireToolApproval` forces sequential execution. The serialized
* boolean shadow is `true` for function-form policies, so those degrade
* safely to sequential as well.
* - Any tool in the step's *effective active tool set* with `requireApproval`
* or `hasSuspendSchema` forces sequential execution so approval/suspension
* flows never race with concurrent tool calls. The check is against the
* active tool set, NOT the tools the model actually called: a registered
* suspending/approval tool the model skipped this step must still force
* sequential execution, since a concurrently-running sibling tool would
* race the suspension.
* - Otherwise the configured `toolCallConcurrency` applies
* (default {@link DurableAgentDefaults.TOOL_CALL_CONCURRENCY}).
*
* The active tool set is the `activeTools` allowlist the LLM step stamps on
* each tool call (processors may narrow or clear it; all calls in one step
* share the value, `null` = restriction cleared → unrestricted). When the
* calls carry no stamp, the run-level `activeTools` option applies.
*
* Designed to be called from a foreach concurrency resolver at execution
* time, reading only serialized state — safe across durable-engine replays
* and shared workflow instances.
*/
function resolveDurableToolCallConcurrency({ options, toolsMetadata, toolCalls }) {
if (options?.requireToolApproval) return 1;
if (toolCalls?.some((tc) => tc.requireApproval || tc.hasSuspendSchema)) return 1;
const { limit, strategy } = require_run_registry.normalizeToolCallConcurrency(options?.toolCallConcurrency);
let consideredTools;
if (strategy === "called") {
const calledNames = new Set((toolCalls ?? []).map((tc) => tc.toolName).filter((name) => !!name));
consideredTools = (toolsMetadata ?? []).filter((tool) => calledNames.has(tool.name));
} else {
const stamped = toolCalls?.find((tc) => tc.activeTools !== void 0);
const activeTools = stamped ? stamped.activeTools : options?.activeTools;
consideredTools = activeTools === void 0 || activeTools === null ? toolsMetadata ?? [] : (toolsMetadata ?? []).filter((tool) => activeTools.includes(tool.name));
}
if (consideredTools.some((tool) => tool.hasSuspendSchema || tool.requireApproval)) return 1;
return limit > 0 ? limit : require_run_registry.DurableAgentDefaults.TOOL_CALL_CONCURRENCY;
}
// src/agent/durable/workflows/steps/background-task-check.ts
const BG_CHECK_STEP_ID = `${require_run_registry.DurableStepIds.AGENTIC_EXECUTION}-bg-task-check`;
/**
* The background task check step accepts the output of llmMappingStep
* and passes it through, adding backgroundTaskPending if tasks are running.
*/
const bgCheckInputSchema = zod.z.any();
const bgCheckOutputSchema = zod.z.any();
/**
* Create a durable background task check step. Behavior lives in the shared
* `checkBackgroundTasks` core; this glue owns registry/init-data access, the
* durable wait gate, and pubsub emission.
*
* The durable wait gate differs from the main loop's on purpose: the regular
* agent can skip waiting because background tool-result chunks are pushed
* directly into the live ReadableStream controller — that works even after
* this step returns. The durable agent emits tool-result chunks via pubsub,
* and the subscription is torn down when the stream closes. If this step
* returned without waiting, the workflow would finish, FINISH would fire,
* cleanup would run, and the subscriber would be gone before the background
* task could deliver its result. Therefore the durable agent must always
* wait when tasks are running — using the configured waitTimeoutMs, or a 1 s
* default to keep the workflow (and pubsub) alive. It only signals pending
* without blocking on retryCount 0 when an explicit timeout is configured
* (meaning the caller drives continuation externally).
*/
function createDurableBackgroundTaskCheckStep() {
return require_run_registry.createStep$1({
id: BG_CHECK_STEP_ID,
inputSchema: bgCheckInputSchema,
outputSchema: bgCheckOutputSchema,
execute: async (params) => {
const { inputData, getInitData, retryCount } = params;
const pubsub = params[require_workflows_constants.PUBSUB_SYMBOL];
const typedInput = inputData;
if (typedInput.stepResult?.signalPreempted && !typedInput.stepResult.isContinued) return typedInput;
const initData = getInitData();
const { runId, agentId } = initData;
const registryEntry = require_run_registry.getRunRegistryEntry(runId, params.mastra);
const bgManager = registryEntry?.backgroundTaskManager;
const waitTimeoutMs = registryEntry?.backgroundTasksConfig?.waitTimeoutMs ?? bgManager?.config?.waitTimeoutMs;
const outcome = await require_run_registry.checkBackgroundTasks({
bgManager,
runId,
agentId,
threadId: initData.state?.threadId,
resourceId: initData.state?.resourceId,
skipWait: initData.options?.skipBgTaskWait,
retryCount,
resolveWaitMs: (rc) => rc === 0 && waitTimeoutMs ? void 0 : waitTimeoutMs ?? 1e3,
emitChunk: (chunk) => {
if (!pubsub) return;
return require_run_registry.emitChunkEvent(pubsub, runId, chunk);
}
});
if (bgManager) await settleFinishedBackgroundResults(registryEntry, async (taskId) => {
const status = (await bgManager.getTask(taskId).catch(() => void 0))?.status;
return status === "completed" || status === "failed" || status === "timed_out";
}, waitTimeoutMs ?? 1e3);
let output = typedInput;
if (hasAppliedBackgroundResults(registryEntry)) {
const transcript = await readMessageListState(params, typedInput);
const list = createRunMessageList({ mastra: params.mastra }).deserialize(transcript);
if (await foldBackgroundResults(registryEntry, list)) output = {
...typedInput,
...await storeMessageListState(params, list.serialize())
};
}
switch (outcome.status) {
case "pass-through":
case "timeout": return output;
case "pending": return {
...output,
backgroundTaskPending: true
};
case "completed":
if (output.stepResult) return {
...output,
backgroundTaskPending: true,
stepResult: {
...output.stepResult,
isContinued: true
}
};
return {
...output,
backgroundTaskPending: true
};
}
}
});
}
// src/agent/durable/workflows/steps/llm-execution.ts
/**
* Detect a run-level budget expiry (`modelSettings.timeout.totalMs`, #21724
* parity port). Total timeouts must surface as run *failures* — not clean
* aborts and never retries/fallbacks — matching the main loop, where the
* total-timeout race rejects the stream with the `MastraTimeoutError`.
*
* Step budgets (`timeoutType: 'step'`) are deliberately excluded: they are
* handled inside the shared `execute()` (no same-model retry, fall back to
* the next model) and must not kill the whole run.
*/
function resolveTotalTimeoutAbort(signal, error) {
const reason = require_stream.getAbortReason(signal);
if (require_stream.isMastraTimeoutError(reason) && reason.timeoutType === "total") return reason;
if (require_stream.isMastraTimeoutError(error) && error.timeoutType === "total") return error;
}
var DurableOutputProcessorError$1 = class extends Error {
constructor(error) {
super(error instanceof Error ? error.message : String(error), { cause: error });
this.name = "DurableOutputProcessorError";
}
};
var DurableChunkPublishError$1 = class extends Error {
constructor(error) {
super(error instanceof Error ? error.message : String(error), { cause: error });
this.name = "DurableChunkPublishError";
}
};
/**
* Input schema for the durable LLM execution step
*/
const durableLLMInputSchema = zod.z.object({
runId: zod.z.string(),
agentId: zod.z.string(),
agentName: zod.z.string().optional(),
messageListState: zod.z.any(),
initialUntaggedSystemMessages: zod.z.array(zod.z.any()).optional(),
toolsMetadata: zod.z.array(zod.z.any()),
modelConfig: zod.z.object({
provider: zod.z.string(),
modelId: zod.z.string(),
specificationVersion: zod.z.string().optional(),
originalConfig: zod.z.union([zod.z.string(), zod.z.record(zod.z.string(), zod.z.any())]).optional(),
settings: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerOptions: zod.z.record(zod.z.string(), zod.z.any()).optional()
}),
modelList: zod.z.array(zod.z.object({
id: zod.z.string(),
config: zod.z.object({
provider: zod.z.string(),
modelId: zod.z.string(),
specificationVersion: zod.z.string().optional(),
originalConfig: zod.z.union([zod.z.string(), zod.z.record(zod.z.string(), zod.z.any())]).optional(),
settings: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerOptions: zod.z.record(zod.z.string(), zod.z.any()).optional()
}),
maxRetries: zod.z.number(),
enabled: zod.z.boolean()
})).optional(),
options: durableOptionsSchema,
state: zod.z.any(),
messageId: zod.z.string(),
requestContextEntries: zod.z.record(zod.z.string(), zod.z.any()).optional(),
inputTripwire: baseIterationStateSchema.shape.inputTripwire,
agentSpanData: zod.z.any().optional(),
modelSpanData: zod.z.any().optional(),
completionStartTime: zod.z.coerce.date().optional(),
timeToFirstTokenMs: zod.z.number().optional(),
stepIndex: zod.z.number().optional(),
signalPreempted: zod.z.boolean().optional(),
accumulatedSteps: zod.z.array(zod.z.any()).optional()
});
/**
* Output schema for the durable LLM execution step.
*
* Declared for type/schema honesty: no engine validates step outputs today
* (`validateInputs: false` in both loop builders, no output-side validation
* in the workflows engine), but Zod would strip undeclared fields if
* validation is ever (re-)enabled — declare new output fields here.
*/
const durableLLMOutputSchema = zod.z.object({
messageListState: zod.z.any().optional(),
text: zod.z.string().optional(),
toolCalls: zod.z.array(zod.z.object({
toolCallId: zod.z.string(),
toolName: zod.z.string(),
args: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerMetadata: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerExecuted: zod.z.boolean().optional(),
output: zod.z.any().optional(),
activeTools: zod.z.array(zod.z.string()).nullable().optional(),
requireApproval: zod.z.boolean().optional(),
hasSuspendSchema: zod.z.boolean().optional(),
stepSpanData: zod.z.any().optional()
})),
stepResult: zod.z.object({
reason: zod.z.string(),
warnings: zod.z.array(zod.z.any()),
isContinued: zod.z.boolean(),
signalPreempted: zod.z.boolean().optional(),
totalUsage: zod.z.any().optional(),
tripwire: zod.z.any().optional(),
messageId: zod.z.string().optional()
}),
metadata: zod.z.any(),
processorRetryCount: zod.z.number().optional(),
processorRetryFeedback: zod.z.string().optional(),
releasedToolResultIds: zod.z.array(zod.z.string()).optional(),
state: zod.z.any(),
stepIndex: zod.z.number().optional(),
modelSpanData: zod.z.any().optional(),
stepSpanData: zod.z.any().optional(),
stepFinishPayload: zod.z.any().optional(),
deferredStepFinishChunk: zod.z.any().optional(),
completionStartTime: zod.z.coerce.date().optional(),
timeToFirstTokenMs: zod.z.number().optional(),
response: responseRecordSchema.optional(),
tracingTermination: zod.z.custom().optional()
});
/** Close on failure too, so retained callbacks never write to an abandoned step. */
function withStepLifetime(execute) {
return async (params) => {
const lifetime = { closed: false };
try {
return await execute(params, lifetime);
} finally {
lifetime.closed = true;
}
};
}
/**
* Create a durable LLM execution step.
*
* This step:
* 1. Deserializes the MessageList from workflow input
* 2. Resolves tools and model from the runtime context
* 3. Executes the LLM call
* 4. Emits streaming chunks via pubsub
* 5. Returns serialized state for the next step
*
* The key difference from the non-durable version is that all state
* flows through the workflow input/output, and non-serializable
* dependencies are resolved at execution time.
*/
function createDurableLLMExecutionStep(_options) {
return require_run_registry.createStep$1({
id: require_run_registry.DurableStepIds.LLM_EXECUTION,
inputSchema: durableLLMInputSchema,
outputSchema: durableLLMOutputSchema,
execute: withStepLifetime(async (params, stepLifetime) => {
const { inputData, mastra, tracingContext, requestContext, abortSignal } = params;
const ownership = require_run_registry.getExecutionOwnershipGuard(params);
const pubsub = params[require_workflows_constants.PUBSUB_SYMBOL];
const typedInput = inputData;
const { agentId, messageId, options: execOptions } = typedInput;
const runId = typedInput.runId;
const logger = mastra?.getLogger?.();
if (pubsub) await require_run_registry.emitIterationStartEvent(pubsub, runId, inputData.stepIndex ?? 0);
const { messageList, tools, model: resolvedModel, modelList: resolvedModelList, inputProcessors: resolvedInputProcessors, llmRequestInputProcessors: resolvedLlmRequestInputProcessors, outputProcessors: resolvedOutputProcessors } = await resolveRuntimeDependencies({
mastra,
runId,
agentId,
input: {
...typedInput,
messageListState: await readMessageListState(params, typedInput)
},
requestContext,
logger
});
const storeStepTranscript = () => {
stepLifetime.closed = true;
return storeMessageListState(params, messageList.serialize());
};
const signalOwner = require_run_registry.getRunRegistryEntry(runId, mastra);
const enqueuePendingSignal = signalOwner?.enqueuePendingSignal;
const lateSignalSink = enqueuePendingSignal ? {
isClosed: () => stepLifetime.closed,
send: async (signalInput) => {
if (!signalOwner || require_run_registry.getRunRegistryEntry(runId, mastra) !== signalOwner || signalOwner.executionFence && (require_run_registry.ExecutionFence.getLocalActive(runId) !== signalOwner.executionFence || signalOwner.executionFence.isLost()) || signalOwner.abortSignal?.aborted) throw new Error(`Cannot send processor signal: run ${runId} is no longer active`);
if (typedInput.state?.threadId && typedInput.state?.resourceId) return enqueuePendingSignal(signalInput);
const signal = require_signals.createSignal(signalInput);
(signalOwner.pendingProcessorSignals ??= []).push(signal);
return signal;
}
} : void 0;
if (pubsub) try {
await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(requestContext));
} catch (error) {
ownership?.throwIfLost();
logger?.warn?.("Failed to subscribe to cross-process abort requests", {
runId,
error: error instanceof Error ? error.message : String(error)
});
}
let request = {};
let terminateAttemptSpans;
let tracingTermination;
const recordTermination = (termination) => {
tracingTermination = termination;
const registry = require_run_registry.getRunRegistryEntry(runId, mastra);
if (registry) registry.tracingTermination = termination;
};
const emitFatalErrorBail = async (fatalError, modelId, signalPreempted = false) => {
ownership?.throwIfLost();
require_run_registry.getRunRegistryEntry(runId, mastra)?.runScope?.set(require_run_registry.LOCAL_MODEL_REQUEST_KEY, request);
const usage = {
inputTokens: void 0,
outputTokens: void 0,
totalTokens: void 0
};
const termination = require_observability.executionFailureTermination(fatalError);
recordTermination(termination);
terminateAttemptSpans?.(termination);
require_run_registry.endRunSpansWithError(runId, fatalError, { endSpan: require_stream.isMastraTimeoutError(fatalError) && fatalError.timeoutType === "total" });
if (pubsub) {
await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "error",
runId,
from: "AGENT",
payload: { error: require_output_helpers.serializeError(fatalError) }
});
if (!signalPreempted) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "step-finish",
runId,
from: "AGENT",
payload: {
stepResult: {
reason: "error",
isContinued: false
},
output: { usage },
metadata: {}
}
});
}
return {
...await storeStepTranscript(),
text: "",
toolCalls: [],
stepResult: {
reason: "error",
warnings: [],
isContinued: false,
...signalPreempted ? { signalPreempted: true } : {}
},
metadata: { modelId },
state: typedInput.state,
tracingTermination
};
};
const selectedAbortSignal = require_run_registry.getRunRegistryEntry(runId, mastra)?.abortSignal ?? abortSignal;
const executionAbortSignalEarly = ownership?.composeSignal(selectedAbortSignal) ?? selectedAbortSignal;
ownership?.throwIfLost();
if (executionAbortSignalEarly?.aborted) {
const earlyTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly);
if (earlyTimeout) return emitFatalErrorBail(earlyTimeout, typedInput.modelConfig?.modelId ?? "unknown", inputData.signalPreempted === true);
return {
...await storeStepTranscript(),
text: "",
toolCalls: [],
stepResult: {
reason: "abort",
warnings: [],
isContinued: false,
...inputData.signalPreempted ? { signalPreempted: true } : {}
},
metadata: {},
state: typedInput.state
};
}
const registryTripwire = require_run_registry.getRunRegistryEntry(runId, mastra)?.tripwire ?? typedInput.inputTripwire;
if (registryTripwire) {
const entry = require_run_registry.getRunRegistryEntry(runId, mastra);
if (entry) entry.tripwire = void 0;
recordTermination(require_observability.agentLoopTermination({ tripwire: registryTripwire }));
logger?.warn?.("Input processor tripwire triggered (from preparation)", {
agent: agentId,
reason: registryTripwire.reason,
processorId: registryTripwire.processorId,
retry: registryTripwire.retry
});
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tripwire",
runId,
from: "AGENT",
payload: {
reason: registryTripwire.reason || "",
retry: registryTripwire.retry,
metadata: registryTripwire.metadata,
processorId: registryTripwire.processorId
}
});
return {
...await storeStepTranscript(),
text: "",
toolCalls: [],
stepResult: {
reason: "tripwire",
warnings: [],
isContinued: false
},
metadata: {},
state: typedInput.state,
tracingTermination
};
}
const hasModelList = typedInput.modelList && typedInput.modelList.length > 0;
const modelList = hasModelList ? typedInput.modelList.filter((m) => m.enabled) : [{
id: `${typedInput.modelConfig.provider}/${typedInput.modelConfig.modelId}`,
config: typedInput.modelConfig,
maxRetries: typedInput.options?.agentMaxRetries ?? 0,
enabled: true
}];
if (modelList.length === 0) throw new Error("No enabled models available for execution");
let lastError;
let skipUnavailableAttachments = false;
const maxProcessorRetries = require_run_registry.resolveMaxProcessorRetries({
maxProcessorRetries: typedInput.options?.maxProcessorRetries,
hasErrorProcessors: Boolean(require_run_registry.getRunRegistryEntry(runId, mastra)?.errorProcessors?.length),
hasConfiguredErrorProcessors: Boolean(typedInput.options?.hasErrorProcessors),
agentId,
logger
});
let currentMessageId = messageId;
const rotateResponseMessageId = () => {
currentMessageId = messageList.rotateResponseMessageId(currentMessageId);
return currentMessageId;
};
const signalRegistry = require_run_registry.getRunRegistryEntry(runId, mastra);
const interruption = new AbortController();
let interruptionOutcome = {
outcome: "interrupted",
stopReason: "signal_received"
};
let interruptible = false;
signalRegistry?.stopStepSignalListener?.();
const stopListening = signalRegistry?.subscribePendingSignals?.((signals) => {
if (interruptible && !executionAbortSignalEarly?.aborted && !interruption.signal.aborted) {
interruptionOutcome = {
outcome: "interrupted",
stopReason: "signal_received",
stopReasonContext: require_run_registry.snapshotSignalOutcome(signals)
};
interruption.abort(/* @__PURE__ */ new Error("Interrupted by a queued signal"));
}
});
if (signalRegistry) signalRegistry.stopStepSignalListener = stopListening;
const throwIfInterrupted = () => {
ownership?.throwIfLost();
if (interruption.signal.aborted) throw interruption.signal.reason;
};
const openReasoningIds = /* @__PURE__ */ new Set();
let endAttemptSpans;
let recordClocks;
let failInference;
const finishInterruptedRequest = async (error, modelId) => {
ownership?.throwIfLost();
stopListening?.();
endAttemptSpans?.();
for (const state of signalRegistry?.processorStates?.values() ?? []) state.streamParts.splice(processorPartCounts.get(state) ?? 0);
if (pubsub) for (const id of openReasoningIds) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "reasoning-end",
runId,
from: "AGENT",
payload: { id }
}, true);
const totalTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly, error instanceof Error ? error : void 0);
if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, true);
return {
...await storeStepTranscript(),
text: "",
toolCalls: [],
stepResult: {
reason: "other",
warnings: [],
isContinued: executionAbortSignalEarly?.aborted !== true,
signalPreempted: true
},
metadata: { modelId },
state: typedInput.state,
...recordClocks?.()
};
};
const previousSteps = await loadAccumulatedSteps(params, inputData);
let processorRetryCount = 0;
for (let i = previousSteps.length - 1; i >= 0 && previousSteps[i]?.finishReason === "retry"; i--) processorRetryCount++;
const lastStep = previousSteps.at(-1);
const processorRetryFeedback = lastStep?.finishReason === "retry" ? lastStep.tripwire?.reason : void 0;
if (processorRetryFeedback) {
rotateResponseMessageId();
const feedbackSignal = messageList.addSignal(require_signals.createSignal({
type: "reactive",
tagName: "system-reminder",
contents: processorRetryFeedback
}));
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, feedbackSignal.toDataPart());
}
const initialEchoes = signalRegistry?.initialSignalEchoes?.splice(0) ?? [];
const isFirstRequest = (inputData.stepIndex ?? 0) === 0 && !inputData.signalPreempted;
const queuedSignals = [
...(inputData.stepIndex ?? 0) === 0 ? signalRegistry?.drainPendingSignals?.("pre-run") ?? [] : [],
...isFirstRequest ? [] : signalRegistry?.drainPendingSignals?.("pending") ?? [],
...signalRegistry?.pendingProcessorSignals?.splice(0) ?? []
];
if (queuedSignals.length) rotateResponseMessageId();
const admittedSignals = queuedSignals.map((signal) => messageList.addSignal(signal));
interruptible = true;
const processorPartCounts = new Map([...signalRegistry?.processorStates?.values() ?? []].map((state) => [state, state.streamParts.length]));
if (pubsub) for (const signal of [...initialEchoes, ...admittedSignals]) await require_run_registry.emitChunkEvent(pubsub, runId, signal.toDataPart());
const deadlineEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
if (deadlineEntry?.timeoutTotalMs) deadlineEntry.completedStepsState = JSON.parse(JSON.stringify(messageList.serialize()));
const iterationBoundary = previousSteps.length > 0 ? messageList.openStepBoundary().boundary : void 0;
let terminalAttemptContext;
for (let modelIndex = 0; modelIndex < modelList.length; modelIndex++) {
const modelEntry = modelList[modelIndex];
const maxRetries = hasModelList || (typedInput.options?.agentMaxRetriesConfigured ?? false) ? modelEntry.maxRetries || 0 : typedInput.options?.modelSettings?.maxRetries ?? modelEntry.maxRetries ?? 0;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
ownership?.throwIfLost();
request = {};
const attemptMessageId = currentMessageId;
terminalAttemptContext = { recordTerminalError: (error) => {
require_error$1.recordTerminalErrorMessage({
messageList,
attemptId: attemptMessageId,
activeId: currentMessageId,
error
});
} };
const textDeltas = [];
let materializeStreamedMessages;
let removeAttemptAbortListener;
let deferredStepFinishChunk = null;
const prepareDeferredStepFinishChunk = ({ reason, isContinued, tripwire }) => {
if (!deferredStepFinishChunk) return void 0;
deferredStepFinishChunk = {
...deferredStepFinishChunk,
payload: {
...deferredStepFinishChunk.payload,
...reason === "retry" && tripwire ? { processorRetryFeedback: tripwire.reason } : {},
stepResult: {
...deferredStepFinishChunk.payload?.stepResult,
...reason ? { reason } : {},
isContinued,
...reason === "retry" && tripwire ? {
retryReason: tripwire.reason,
retryMetadata: tripwire.metadata,
retryProcessorId: tripwire.processorId
} : {}
},
...tripwire ? { output: {
...deferredStepFinishChunk.payload?.output,
steps: [{ tripwire }]
} } : {}
}
};
return deferredStepFinishChunk;
};
try {
const model = !hasModelList ? resolvedModel : resolvedModelList?.find((m) => m.id === modelEntry.id)?.model ?? await resolveModelFromListEntry(modelEntry, mastra);
if (!require_stream.isSupportedLanguageModel(model)) {
const hint = model.__metadataOnly ? " The model could not be resolved from the run registry or Mastra instance." : "";
throw new Error(`Unsupported model version: ${model.specificationVersion}. Model must implement doStream.${hint}`);
}
let currentModel = model;
let currentTools = tools;
let currentToolChoice = execOptions.toolChoice;
let currentActiveTools = execOptions.activeTools;
const entrySettings = modelEntry.config.settings;
let currentModelSettings = {
...execOptions.modelSettings,
...entrySettings,
...execOptions.modelSettings?.timeout || entrySettings?.timeout ? { timeout: {
...execOptions.modelSettings?.timeout,
...entrySettings?.timeout
} } : {}
};
let currentProviderOptions = require_run_registry.mergeProviderOptions(execOptions.providerOptions, modelEntry.config.providerOptions);
const observability = mastra?.observability?.getSelectedInstance({ requestContext });
const inputModelSpanData = require_run_registry.getRunRegistryEntry(runId, mastra)?.resumeModelSpanData ?? inputData.modelSpanData;
const resumeRegistry = require_run_registry.getRunRegistryEntry(runId, mastra);
const carriedClocks = carriedSpanClocks(resumeRegistry, inputData);
const withCarriedClocks = (data) => {
if (!carriedClocks?.completionStartTime || data.attributes?.completionStartTime) return data;
return {
...data,
attributes: {
...data.attributes,
...carriedClocks
}
};
};
recordClocks = () => {
const completionStartTime = modelSpanTracker?.getCompletionStartTime?.();
const timeToFirstTokenMs = modelSpanTracker?.getTimeToFirstTokenMs?.();
if (resumeRegistry?.resumeModelSpanData && completionStartTime && !resumeRegistry.resumeCompletionStartTime) {
resumeRegistry.resumeCompletionStartTime = completionStartTime;
resumeRegistry.resumeTimeToFirstTokenMs = timeToFirstTokenMs;
}
return {
completionStartTime,
timeToFirstTokenMs
};
};
const modelSpan = inputModelSpanData ? observability?.rebuildSpan(withCarriedClocks(inputModelSpanData)) : void 0;
const inputAgentSpanData = require_run_registry.getRunRegistryEntry(runId, mastra)?.resumeAgentSpanData ?? inputData.agentSpanData;
const agentRunSpan = inputAgentSpanData ? observability?.rebuildSpan(withCarriedClocks(inputAgentSpanData)) : void 0;
const modelSpanTracker = modelSpan?.createTracker({ agentRunSpan });
const recordProcessedChunk = (chunk) => {
try {
modelSpanTracker?.recordChunk?.(chunk);
} catch {}
};
failInference = (error) => modelSpanTracker?.failInference?.(error);
const endAttempt = (termination) => {
if (modelSpanTracker?.endAttempt) modelSpanTracker.endAttempt(termination);
else {
const stepData = modelSpanTracker?.exportCurrentStep();
if (stepData) observability?.rebuildSpan(stepData)?.end(termination);
}
};
endAttemptSpans = () => {
modelSpanTracker?.interruptInference?.(interruptionOutcome);
endAttempt(interruptionOutcome);
};
const stepIndex = inputData.stepIndex ?? 0;
modelSpanTracker?.setStepIndex(stepIndex);
modelSpanTracker?.startStep();
terminateAttemptSpans = (termination) => {
endAttempt(termination);
};
const endTripwireSpans = (cause) => {
const termination = require_observability.agentLoopTermination({ tripwire: cause instanceof require_stream.TripWire ? {
reason: cause.message,
processorId: cause.processorId,
retry: cause.options?.retry,
metadata: cause.options?.metadata
} : cause });
recordTermination(termination);
endAttempt(termination);
};
const structuredOutputConfig = execOptions.structuredOutput;
let structuredOutput = structuredOutputConfig?.schema && !structuredOutputConfig?.structuringModelConfig && !structuredOutputConfig?.hasStructuringModel ? {
schema: structuredOutputConfig.schema,
jsonPromptInjection: structuredOutputConfig.jsonPromptInjection,
instructions: structuredOutputConfig.instructions
} : void 0;
const registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
const selectedRunAbortSignal = registryEntry?.abortSignal ?? abortSignal;
if (selectedRunAbortSignal) {
const endAbortedAttempt = () => {
const reason = require_stream.getAbortReason(selectedRunAbortSignal);
terminateAttemptSpans?.(require_stream.isMastraTimeoutError(reason) ? require_observability.executionFailureTermination(reason) : {
outcome: "abort",
stopReason: "caller_cancelled"
});
};
selectedRunAbortSignal.addEventListener("abort", endAbortedAttempt, { once: true });
removeAttemptAbortListener = () => selectedRunAbortSignal.removeEventListener("abort", endAbortedAttempt);
if (selectedRunAbortSignal.aborted) endAbortedAttempt();
}
const runAbortSignal = ownership?.composeSignal(selectedRunAbortSignal) ?? selectedRunAbortSignal;
const executionAbortSignal = stopListening ? runAbortSignal ? AbortSignal.any([runAbortSignal, interruption.signal]) : interruption.signal : runAbortSignal;
const baseInputProcessors = registryEntry?.inputProcessors ?? resolvedInputProcessors ?? [];
const llmRequestInputProcessors = registryEntry?.llmRequestInputProcessors ?? registryEntry?.inputProcessors ?? resolvedLlmRequestInputProcessors ?? resolvedInputProcessors ?? [];
const effectiveOutputProcessors = registryEntry?.outputProcessors ?? resolvedOutputProcessors ?? [];
const stepInputProcessors = registryEntry?.prepareStep ? [...baseInputProcessors, new require_run_registry.PrepareStepProcessor({ prepareStep: registryEntry.prepareStep })] : baseInputProcessors;
messageList.replaceAllSystemMessages(typedInput.initialUntaggedSystemMessages ?? messageList.getSystemMessages());
if (require_stream.needsTrailingAssistantGuard(currentModel, stepInputProcessors)) {
const inputStepWriter = pubsub ? { custom: async (data) => {
await require_run_registry.emitChunkEvent(pubsub, runId, data);
} } : void 0;
const runner = new require_stream.ProcessorRunner({
lateSignalSink,
inputProcessors: stepInputProcessors,
outputProcessors: effectiveOutputProcessors,
errorProcessors: registryEntry?.errorProcessors ?? [],
logger,
agentName: typedInput.agentName ?? typedInput.agentId,
agent: registryEntry?.agent,
processorStates: registryEntry?.processorStates
});
try {
const processInputStepResult = await runner.runProcessInputStep({
llmRequestProcessorIds: require_stream.ProcessorRunner.getLLMRequestProcessorIds(llmRequestInputProcessors),
messageList,
stepNumber: stepIndex,
steps: require_run_registry.expandDurableSteps(previousSteps),
tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
requestContext,
memory: registryEntry?.memory,
resourceId: typedInput.state?.resourceId,
threadId: typedInput.state?.threadId,
model: currentModel,
messageId: currentMessageId,
rotateResponseMessageId,
tools: currentTools,
toolChoice: currentToolChoice,
providerOptions: currentProviderOptions,
activeTools: currentActiveTools,
modelSettings: currentModelSettings,
structuredOutput,
retryCount: processorRetryCount,
abortSignal: runAbortSignal,
writer: inputStepWriter
});
ownership?.throwIfLost();
const merged = require_run_registry.composeStepInput({
messageId: currentMessageId,
model: currentModel,
tools: currentTools,
toolChoice: currentToolChoice,
activeTools: currentActiveTools,
providerOptions: currentProviderOptions,
modelSettings: currentModelSettings,
structuredOutput
}, processInputStepResult);
currentMessageId = merged.messageId;
currentModel = merged.model;
currentTools = merged.tools;
currentToolChoice = merged.toolChoice;
currentActiveTools = merged.activeTools;
currentProviderOptions = merged.providerOptions;
currentModelSettings = merged.modelSettings ?? {};
structuredOutput = merged.structuredOutput;
if (processInputStepResult.tools) {
const boundLogger = logger || new require_logger.ConsoleLogger({ level: "error" });
const convertedTools = {};
for (const [name, tool] of Object.entries(currentTools)) if (require_toolchecks.isMastraTool(tool)) convertedTools[name] = require_utils.makeProcessorCoreTool(tool, {
name,
runId,
threadId: typedInput.state?.threadId,
resourceId: typedInput.state?.resourceId,
logger: boundLogger,
mastra: mastra ? require_utils.createMastraProxy({
mastra,
logger: boundLogger
}) : void 0,
memory: registryEntry?.memory,
agentName: typedInput.agentName ?? agentId,
agentId,
requestContext,
workspace: registryEntry?.workspace,
requireApproval: tool.requireApproval,
backgroundConfig: tool.background,
agentBackgroundConfig: registryEntry?.backgroundTasksConfig,
outputWriter: pubsub ? async (chunk) => {
await require_run_registry.emitChunkEvent(pubsub, runId, chunk);
} : void 0
}, void 0, execOptions.autoResumeSuspendedTools, Boolean(registryEntry?.backgroundTaskManager));
else convertedTools[name] = tool;
currentTools = convertedTools;
if (registryEntry) {
registryEntry.baseTools = tools;
registryEntry.tools = convertedTools;
}
} else if (registryEntry?.baseTools) registryEntry.tools = registryEntry.baseTools;
} catch (error) {
ownership?.throwIfLost();
if (error instanceof require_stream.TripWire) {
const tripwire = {
reason: error.message,
retry: error.options?.retry,
metadata: error.options?.metadata,
processorId: error.processorId
};
endTripwireSpans(error);
logger?.warn?.("Streaming input processor tripwire triggered", {
reason: error.message,
processorId: error.processorId,
retry: error.options?.retry
});
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tripwire",
runId,
from: "AGENT",
payload: {
processorId: error.processorId,
reason: error.message,
retry: error.options?.retry,
metadata: error.options?.metadata
}
});
return {
...await storeStepTranscript(),
text: "",
toolCalls: [],
stepResult: {
reason: "tripwire",
tripwire,
warnings: [],
isContinued: false
},
metadata: { modelId: currentModel.modelId },
state: typedInput.state,
tracingTermination
};
}
logger?.error?.("Error in processInputStep processors:", error);
throw error;
}
}
const messageListPromptArgs = await require_run_registry.buildLlmPromptArgs({
model: currentModel,
skipUnavailableAttachments
});
const llmPromptForModel = currentModel.specificationVersion === "v4" ? messageList.get.all.aiV7.llmPrompt : currentModel.specificationVersion === "v3" ? messageList.get.all.aiV6.llmPrompt : messageList.get.all.aiV5.llmPrompt;
const backgroundOutcomes = typedInput.options?.skipBgTaskWait ? require_run_registry.snapshotBackgroundOutcomes(messageList) : void 0;
let inputMessages = await llmPromptForModel(messageListPromptArgs);
const builtPrompt = inputMessages;
const dbMessages = messageList.get.all.db();
const continuationIndex = dbMessages.findIndex((message) => message.id === "om-continuation");
let omContinuationPrompt;
if (continuationIndex !== -1) {
const precedingMessages = createRunMessageList({ mastra });
precedingMessages.add(dbMessages.slice(0, continuationIndex), "input");
const precedingUserCount = precedingMessages.get.all.aiV5.model().filter((message) => message.role === "user" && message.content.length > 0).length;
omContinuationPrompt = inputMessages.filter((message) => message.role === "user")[precedingUserCount];
if (omContinuationPrompt) omContinuationPrompt.providerOptions = {
...omContinuationPrompt.providerOptions,
mastra: {
...omContinuationPrompt.providerOptions?.mastra,
messageId: "om-continuation"
}
};
}
require_stream.removeTrailingAssistantGuardContinuations(messageList);
await require_run_registry.persistUnavailableAttachments({
messageList,
memory: require_run_registry.getRunRegistryEntry(runId, mastra)?.memory,
readOnly: typedInput.state?.memoryConfig?.readOnly,
logger
});
inputMessages = require_run_registry.applyAutoResumeSystemMessage({
autoResume: execOptions.autoResumeSuspendedTools,
inputMessages,
messages: messageList.get.all.db()
});
inputMessages = require_run_registry.injectBackgroundTaskPrompt({
inputMessages,
backgroundTaskManager: registryEntry?.backgroundTaskManager,
tools: currentTools,
agentBackgroundConfig: registryEntry?.backgroundTasksConfig
});
let cachedResponse;
const requestStepRunner = llmRequestInputProcessors.length > 0 ? new require_stream.ProcessorRunner({
lateSignalSink,
inputProcessors: llmRequestInputProcessors,
outputProcessors: [],
logger,
agentName: typedInput.agentName ?? typedInput.agentId,
agent: registryEntry?.agent,
processorStates: registryEntry?.processorStates
}) : void 0;
const requestStepWriter = pubsub ? { custom: async (data) => {
await require_run_registry.emitChunkEvent(pubsub, runId, data);
} } : void 0;
if (requestStepRunner) try {
const requestStepResult = await requestStepRunner.runProcessLLMRequest({
prompt: inputMessages,
model: currentModel,
apiProviderId: await require_llm.resolveApiProviderId(currentModel),
messageList,
workspace: registryEntry?.workspace,
stepNumber: inputData.stepIndex ?? 0,
steps: require_run_registry.expandDurableSteps(previousSteps),
retryCount: processorRetryCount,
requestContext,
tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
writer: requestStepWriter,
abortSignal: runAbortSignal
});
ownership?.throwIfLost();
inputMessages = requestStepResult.prompt;
cachedResponse = requestStepResult.response;
} catch (error) {
ownership?.throwIfLost();
if (error instanceof require_stream.TripWire) {
endTripwireSpans(error);
logger?.warn?.("Streaming request processor tripwire triggered", {
reason: error.message,
processorId: error.processorId,
retry: error.options?.retry
});
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tripwire",
runId,
from: "AGENT",
payload: {
processorId: error.processorId,
reason: error.message,
retry: error.options?.retry,
metadata: error.options?.metadata
}
});
return {
...await storeStepTranscript(),
text: "",
toolCalls: [],
stepResult: {
reason: "tripwire",
warnings: [],
isContinued: false
},
metadata: { modelId: currentModel.modelId },
state: typedInput.state,
tracingTermination
};
}
logger?.error?.("Error in processLLMRequest processors:", error);
throw error;
}
const delegationMessages = omContinuationPrompt ? inputMessages.filter((message) => message !== omContinuationPrompt && message.providerOptions?.mastra?.messageId !== "om-continuation") : inputMessages;
if (registryEntry) {
registryEntry.runScope ??= require_stream.createRunScope();
registryEntry.runScope.set(require_run_registry.STEP_MODEL_MESSAGES_KEY, delegationMessages);
}
const backgroundResultTaskIds = backgroundOutcomes && !cachedResponse ? require_run_registry.backgroundOutcomesInPrompt(backgroundOutcomes, builtPrompt, inputMessages) : [];
modelSpanTracker?.setDeferStepClose(true);
let warnings = [];
let rawResponse = {};
const toolCalls = [];
let finishReason = "stop";
let usage = {
inputTokens: void 0,
outputTokens: void 0,
totalTokens: void 0
};
let responseMetadata = {};
let hasStepContent = false;
const clientToolArgsTextByToolCallId = /* @__PURE__ */ new Map();
const clientToolObservabilityByToolCallId = /* @__PURE__ */ new Map();
const resolvedToolByCallId = /* @__PURE__ */ new Map();
const pendingProviderToolCallsByToolCallId = /* @__PURE__ */ new Map();
const materializedProviderToolCallIds = /* @__PURE__ */ new Set();
const resolveToolDef = (toolName) => {
const directTool = currentTools?.[toolName];
if (directTool) return directTool;
const registryTool = registryEntry?.tools?.[toolName];
if (registryTool) return registryTool;
const providerTool = require_run_registry.findProviderToolByName(currentTools, toolName);
if (providerTool) return providerTool;
return require_run_registry.findProviderToolByName(registryEntry?.tools, toolName);
};
const endClientToolObservabilitySpan = (toolCallId, args) => {
const entry = clientToolObservabilityByToolCallId.get(toolCallId);
if (!entry || entry.ended) {
clientToolArgsTextByToolCallId.delete(toolCallId);
return;
}
entry.span.end(args !== void 0 ? { metadata: { args } } : void 0);
entry.ended = true;
clientToolArgsTextByToolCallId.delete(toolCallId);
};
const parseClientToolArgsFromDeltas = (toolCallId) => {
const deltas = clientToolArgsTextByToolCallId.get(toolCallId);
if (!deltas?.length) return void 0;
const input = deltas.join("");
if (!input) return void 0;
try {
return JSON.parse(input);
} catch {
return;
}
};
const injectClientToolObservability = ({ toolCallId, toolName, args, providerExecuted, payload }) => {
const toolDef = resolveToolDef(toolName);
if (!(!require_run_registry.inferProviderExecuted(providerExecuted, toolDef) && !toolDef?.execute) || !mastra || !tracingContext?.currentSpan) return { toolDef };
const existingCarrier = clientToolObservabilityByToolCallId.get(toolCallId);
if (existingCarrier) {
payload.observability = existingCarrier.carrier;
if (args !== void 0) endClientToolObservabilitySpan(toolCallId, args);
return { toolDef };
}
const proxy = mastra.observability?.getClientObservabilityProxy?.();
if (!proxy) return { toolDef };
try {
const clientToolSpan = resolveAgentRunFallback(tracingContext.currentSpan).createChildSpan?.({
type: "client_tool_call",
name: `client_tool: '${toolName}'`,
entityType: require_storage.EntityType.TOOL,
entityId: toolName,
entityName: toolName,
attributes: {
toolDescription: toolDef?.description,
toolType: "client-tool"
},
...args !== void 0 ? { input: args } : {}
});
if (clientToolSpan) {
const carrier = proxy.inject(clientToolSpan);
const entry = {
carrier,
span: clientToolSpan,
ended: false
};
clientToolObservabilityByToolCallId.set(toolCallId, entry);
payload.observability = carrier;
if (args !== void 0) endClientToolObservabilitySpan(toolCallId, args);
}
} catch (err) {
logger?.warn?.("[ClientObservabilityProxy] failed to create CLIENT_TOOL_CALL span", {
error: err instanceof Error ? err.message : String(err),
toolName
});
}
return { toolDef };
};
const resolveAgentRunFallback = (span) => span.type === "agent_run" ? span : agentRunSpan ?? span.findParent?.("agent_run") ?? span;
const recordProviderToolCall = ({ toolCallId, toolName, args, providerExecuted }) => {
if (!tracingContext?.currentSpan) return;
const toolDef = resolveToolDef(toolName);
if (!require_run_registry.inferProviderExecuted(providerExecuted, toolDef)) return;
const existingEntry = pendingProviderToolCallsByToolCallId.get(toolCallId);
if (existingEntry) {
if (args !== void 0 && existingEntry.args === void 0) existingEntry.args = args;
return;
}
pendingProviderToolCallsByToolCallId.set(toolCallId, {
toolName,
args,
startTime: /* @__PURE__ */ new Date(),
toolDescription: toolDef?.description,
fallbackParentSpan: resolveAgentRunFallback(tracingContext.currentSpan)
});
};
const cleanupToolObservabilitySpans = (flushPendingProviderToolCalls) => {
for (const [toolCallId, entry] of clientToolObservabilityByToolCallId.entries()) if (!entry.ended) {
const parsedArgs = parseClientToolArgsFromDeltas(toolCallId);
entry.span.end(parsedArgs !== void 0 ? { metadata: { args: parsedArgs } } : void 0);
entry.ended = true;
}
clientToolArgsTextByToolCallId.clear();
if (flushPendingProviderToolCalls) for (const [toolCallId, pending] of pendingProviderToolCallsByToolCallId.entries()) require_run_registry.endPendingProviderToolSpan({
toolCallId,
pending,
parentSpan: pending.fallbackParentSpan,
logger
});
pendingProviderToolCallsByToolCallId.clear();
};
const inferenceTools = modelSpanTracker?.getTracingContext()?.currentSpan?.isValid ? require_run_registry.getToolDefinitionsForTracing({
tools: currentTools,
toolChoice: currentToolChoice,
activeTools: currentActiveTools,
specificationVersion: currentModel.specificationVersion,
stripToolsWhenNone: require_run_registry.sendsNativeResponseFormat(structuredOutput, currentModel)
}) : void 0;
modelSpanTracker?.setInferenceContext?.({
parameters: currentModelSettings,
providerOptions: currentProviderOptions,
availableTools: inferenceTools?.map((tool) => tool.name) ?? [],
tools: inferenceTools,
toolChoice: currentToolChoice,
responseFormat: structuredOutput ? "json_schema" : void 0
});
throwIfInterrupted();
require_run_registry.validateModelTimeoutSettings(currentModelSettings?.timeout);
modelSpanTracker?.startInference?.({
request: {},
inputMessages,
messageId: currentMessageId,
...cachedResponse ? {} : {
modelId: currentModel.modelId,
provider: currentModel.provider
}
});
let inferenceStartedAt;
const collectedChunks = [];
if (registryEntry?.timeoutTotalMs) registryEntry.streamedStepText = [];
const materializationMessageId = currentMessageId;
materializeStreamedMessages = () => {
ownership?.throwIfLost();
if (interruption.signal.aborted) return;
const responseModelId = currentModel.modelId ?? responseMetadata?.modelId;
const responseTraceId = require_utils$1.getRootExportSpan(modelSpanTracker?.getTracingContext()?.currentSpan ?? tracingContext?.currentSpan)?.externalTraceId;
const responseModelMetadata = responseModelId || currentModel.provider || responseTraceId ? { metadata: {
...responseModelId ? { modelId: responseModelId } : {},
...currentModel.provider ? { provider: currentModel.provider } : {},
...responseTraceId ? { traceId: responseTraceId } : {}
} } : void 0;
const builtMessages = require_run_registry.buildMessagesFromChunks({
chunks: collectedChunks,
messageId: materializationMessageId,
tools: currentTools,
responseModelMetadata
});
if (builtMessages.length > 0) {
for (const msg of builtMessages) messageList.add(msg, "response");
if (registryEntry) registryEntry.messageList = messageList;
}
};
terminalAttemptContext = { recordTerminalError: (error) => {
materializeStreamedMessages?.();
require_error$1.recordTerminalErrorMessage({
messageList,
attemptId: materializationMessageId,
activeId: currentMessageId,
error
});
} };
let modelResult;
if (cachedResponse) {
interruptible = false;
warnings = cachedResponse.warnings ?? [];
request = cachedResponse.request ?? {};
rawResponse = cachedResponse.rawResponse;
modelSpanTracker?.updateStep?.({
request: request || {},
inputMessages,
warnings: warnings || [],
messageId: currentMessageId
});
const replayChunks = cachedResponse.chunks;
modelResult = new ReadableStream({ start(ctrl) {
for (const chunk of replayChunks) ctrl.enqueue({
...chunk,
runId,
from: "AGENT"
});
ctrl.close();
} });
} else {
const releaseModelCallActivity = require_run_registry.markRunActive(runId);
try {
inferenceStartedAt = Date.now();
modelResult = require_utils$1.executeWithContextSync({
span: modelSpanTracker?.getTracingContext()?.currentSpan,
fn: () => require_run_registry.execute({
runId,
model: currentModel,
providerOptions: currentProviderOptions,
inputMessages,
tools: currentTools,
toolChoice: currentToolChoice,
activeTools: currentActiveTools,
options: { abortSignal: executionAbortSignal },
headers: require_run_registry.mergeLlmCallHeaders({
memoryHeaders: require_run_registry.buildMemoryHeaders({
threadId: typedInput.state?.threadId,
resourceId: typedInput.state?.resourceId
}),
modelConfigHeaders: resolvedModelList?.find((m) => m.id === modelEntry.id)?.headers,
callTimeHeaders: registryEntry?.callTimeHeaders || currentModelSettings?.headers ? {
...registryEntry?.callTimeHeaders,
...currentModelSettings?.headers
} : void 0
}),
modelSettings: {
...currentModelSettings,
maxRetries: 0
},
includeRawChunks: execOptions.includeRawChunks,
methodType: "stream",
structuredOutput,
onResult: ({ warnings: w, request: r, rawResponse: rr }) => {
warnings = w || [];
request = r || {};
rawResponse = rr || {};
modelSpanTracker?.updateStep?.({
request,
inputMessages,
warnings,
messageId: currentMessageId
});
}
})
});
} finally {
releaseModelCallActivity();
}
}
const providerStream = stopListening && !cachedResponse ? require_run_registry.watchInterruptibleStream(modelResult, interruption.signal, () => interruptible = false) : modelResult;
const outputStream = new require_stream.MastraModelOutput({
model: {
modelId: currentModel.modelId,
provider: currentModel.provider,
version: currentModel.specificationVersion
},
stream: providerStream,
messageList,
messageId: currentMessageId,
options: {
runId,
tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
requestContext
}
});
const rawBaseStream = outputStream._getBaseStream();
const stepBoundaryStream = (modelSpanTracker?.recordChunk ? modelSpanTracker.wrapInferenceStream?.(rawBaseStream) ?? rawBaseStream : rawBaseStream).pipeThrough(new TransformStream({ transform(chunk, controller) {
if (chunk?.type === "finish") controller.enqueue({
...chunk,
type: "step-finish"
});
else controller.enqueue(chunk);
} }));
const trackedStream = modelSpanTracker?.recordChunk ? stepBoundaryStream : modelSpanTracker?.wrapStream(stepBoundaryStream) ?? stepBoundaryStream;
let toolResultTripwire = null;
let outputStreamBlocked = false;
const releasedToolResultIds = [];
let toolResultRunner;
const getToolResultRunner = () => {
toolResultRunner ??= new require_stream.ProcessorRunner({
lateSignalSink,
inputProcessors: [],
outputProcessors: effectiveOutputProcessors,
logger,
agentName: typedInput.agentName ?? typedInput.agentId,
agent: registryEntry?.agent,
processorStates: registryEntry?.processorStates
});
return toolResultRunner;
};
const toolResultChunkWriter = pubsub ? { custom: async (data, writerOptions) => {
ownership?.throwIfLost();
require_stream.persistProcessorDataChunk(messageList, writerOptions?.messageId ?? currentMessageId, data);
await require_run_registry.emitChunkEvent(pubsub, runId, data);
} } : void 0;
const outputStreamWriter = pubsub ? { custom: async (data, writerOptions) => {
ownership?.throwIfLost();
require_stream.persistProcessorDataChunk(messageList, writerOptions?.messageId ?? currentMessageId, data);
try {
await require_run_registry.emitChunkEvent(pubsub, runId, data, true);
} catch (error) {
ownership?.throwIfLost();
throw new DurableChunkPublishError$1(error);
}
} } : void 0;
const releaseStreamActivity = require_run_registry.markRunActive(runId);
const settleRequest = require_utils.startRunStep(registryEntry);
try {
let stepStartEmitted = false;
for await (const rawChunk of trackedStream) {
ownership?.throwIfLost();
if (!rawChunk) continue;
if (executionAbortSignal?.aborted) break;
if (!stepStartEmitted && pubsub) {
stepStartEmitted = true;
const stepStartChunk = require_run_registry.createStepStartChunk(runId, {
stepId: require_run_registry.DurableStepIds.LLM_EXECUTION,
messageId: currentMessageId,
startedAt: inferenceStartedAt,
modelId: currentModel.modelId,
provider: currentModel.provider,
warnings,
...backgroundResultTaskIds.length > 0 ? { backgroundResultTaskIds } : {}
});
if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) {
try {
await require_run_registry.processAndEmitChunk(stepStartChunk, {
runner: getToolResultRunner(),
processorStates: registryEntry.processorStates,
observabilityContext: require_observability.createObservabilityContext(),
requestContext,
messageList,
streamWriter: outputStreamWriter,
emitChunk: async (chunk) => {
if (chunk.type === "tripwire") {
endTripwireSpans(chunk.payload);
outputStreamBlocked = true;
}
try {
if (chunk.type === "step-start") await require_run_registry.publishStepStartChunk(pubsub, runId, chunk, true, inputData.stepIndex ?? 0);
else await require_run_registry.emitChunkEvent(pubsub, runId, chunk, true);
} catch (error) {
ownership?.throwIfLost();
throw new DurableChunkPublishError$1(error);
}
},
onProcessorError: (error) => {
throwIfInterrupted();
if (error instanceof DurableChunkPublishError$1) throw error.cause;
throw new DurableOutputProcessorError$1(error);
}
});
} catch (error) {
ownership?.throwIfLost();
throwIfInterrupted();
if (error instanceof DurableOutputProcessorError$1) {
const processorError = error.cause instanceof Error ? error.cause : error;
terminalAttemptContext?.recordTerminalError(processorError);
return emitFatalErrorBail(processorError, currentModel.modelId);
}
throw error;
}
if (outputStreamBlocked) break;
} else await require_run_registry.publishStepStartChunk(pubsub, runId, stepStartChunk, void 0, inputData.stepIndex ?? 0);
}
const transformTools = currentTools;
let deferredEnrichedChunk;
if (rawChunk.type === "tool-result" && rawChunk.payload && !rawChunk.payload.preliminary && "result" in rawChunk.payload) {
const resultPayload = rawChunk.payload;
const resultToolDef = resolveToolDef(resultPayload.toolName);
const resultProviderExecuted = require_run_registry.inferProviderExecuted(resultPayload.providerExecuted, resultToolDef);
if (effectiveOutputProcessors.length > 0) try {
await getToolResultRunner().runProcessToolResult({
steps: require_run_registry.expandDurableSteps(previousSteps),
messages: messageList.get.all.db(),
messageList,
stepNumber: previousSteps.length,
toolName: resultPayload.toolName,
toolCallId: resultPayload.toolCallId,
toolArgs: resultPayload.args,
result: resultPayload.result,
providerExecuted: resultProviderExecuted,
requestContext,
retryCount: processorRetryCount,
tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
writer: toolResultChunkWriter,
abortSignal: runAbortSignal
});
ownership?.throwIfLost();
const postProcessorResult = require_run_registry.readToolResultFromMessageList(messageList, resultPayload.toolCallId);
if (postProcessorResult !== void 0 && postProcessorResult !== resultPayload.result) resultPayload.result = postProcessorResult;
} catch (error) {
ownership?.throwIfLost();
if (error instanceof require_stream.TripWire) {
logger?.warn?.("Tool result processor tripwire triggered", {
reason: error.message,
processorId: error.processorId,
retry: error.options?.retry
});
toolResultTripwire = error;
break;
}
logger?.error?.("Error in processToolResult processors:", error);
throw error;
}
if (registryEntry?.toolPayloadTransform || transformTools) deferredEnrichedChunk = await require_run_registry.applyToolPayloadTransformToChunk(rawChunk, {
policy: registryEntry?.toolPayloadTransform,
tools: transformTools,
logger
});
messageList.updateToolInvocation({
type: "tool-invocation",
toolInvocation: {
toolCallId: resultPayload.toolCallId,
toolName: resultPayload.toolName,
args: resultPayload.args,
...require_run_registry.getToolResultInvocationState(resultPayload)
},
providerMetadata: require_payload_transform.withToolPayloadTransformProviderMetadata(resultPayload.providerMetadata, deferredEnrichedChunk?.metadata),
providerExecuted: resultProviderExecuted
});
}
const clientChunk = deferredEnrichedChunk ?? (registryEntry?.toolPayloadTransform || transformTools ? await require_run_registry.applyToolPayloadTransformToChunk(rawChunk, {
policy: registryEntry?.toolPayloadTransform,
tools: transformTools,
logger
}) : rawChunk);
let toolInputStartToolDef;
if (rawChunk.type === "tool-call-input-streaming-start") {
({toolDef: toolInputStartToolDef} = injectClientToolObservability({
toolCallId: rawChunk.payload.toolCallId,
toolName: rawChunk.payload.toolName,
providerExecuted: rawChunk.payload.providerExecuted,
payload: clientChunk.payload
}));
if (toolInputStartToolDef) resolvedToolByCallId.set(rawChunk.payload.toolCallId, toolInputStartToolDef);
recordProviderToolCall({
toolCallId: rawChunk.payload.toolCallId,
toolName: rawChunk.payload.toolName,
providerExecuted: rawChunk.payload.providerExecuted
});
} else if (rawChunk.type === "tool-call-delta") {
const toolCallId = rawChunk.payload.toolCallId;
if (toolCallId && rawChunk.payload.argsTextDelta) {
const deltas = clientToolArgsTextByToolCallId.get(toolCallId) ?? [];
deltas.push(rawChunk.payload.argsTextDelta);
clientToolArgsTextByToolCallId.set(toolCallId, deltas);
}
} else if (rawChunk.type === "tool-call-input-streaming-end") {
const parsedArgs = parseClientToolArgsFromDeltas(rawChunk.payload.toolCallId);
if (parsedArgs !== void 0) endClientToolObservabilitySpan(rawChunk.payload.toolCallId, parsedArgs);
} else if (rawChunk.type === "tool-call") {
injectClientToolObservability({
toolCallId: rawChunk.payload.toolCallId,
toolName: rawChunk.payload.toolName,
args: rawChunk.payload.args,
providerExecuted: rawChunk.payload.providerExecuted,
payload: clientChunk.payload
});
recordProviderToolCall({
toolCallId: rawChunk.payload.toolCallId,
toolName: rawChunk.payload.toolName,
args: rawChunk.payload.args,
providerExecuted: rawChunk.payload.providerExecuted
});
}
let processedChunk;
if (rawChunk.type === "step-finish") {
recordProcessedChunk(rawChunk);
registryEntry?.runScope?.set(require_run_registry.LOCAL_MODEL_REQUEST_KEY, request);
}
if (pubsub && rawChunk.type !== "error" && rawChunk.type !== "response-metadata") {
if (rawChunk.type === "step-finish") {
const { id, timestamp, modelId } = responseMetadata;
deferredStepFinishChunk = {
...clientChunk,
payload: {
...clientChunk.payload,
metadata: {
...id !== void 0 ? { id } : {},
...timestamp !== void 0 ? { timestamp } : {},
...clientChunk.payload?.metadata,
modelId: clientChunk.payload?.metadata?.modelId || modelId || model.modelId
}
}
};
} else if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) {
try {
processedChunk = await require_run_registry.processAndEmitChunk(clientChunk, {
runner: getToolResultRunner(),
processorStates: registryEntry.processorStates,
observabilityContext: require_observability.createObservabilityContext(modelSpanTracker?.getTracingContext() ?? tracingContext),
requestContext,
messageList,
streamWriter: outputStreamWriter,
emitChunk: async (chunk) => {
if (chunk.type === "tripwire") {
endTripwireSpans(chunk.payload);
outputStreamBlocked = true;
}
recordProcessedChunk(chunk);
require_run_registry.trackOpenReasoning(chunk, openReasoningIds);
try {
await require_run_registry.emitChunkEvent(pubsub, runId, chunk, true);
} catch (error) {
ownership?.throwIfLost();
throw new DurableChunkPublishError$1(error);
}
},
onProcessorError: (error) => {
throwIfInterrupted();
if (error instanceof DurableChunkPublishError$1) throw error.cause;
throw new DurableOutputProcessorError$1(error);
}
});
} catch (error) {
ownership?.throwIfLost();
throwIfInterrupted();
if (error instanceof DurableOutputProcessorError$1) {
const processorError = error.cause instanceof Error ? error.cause : error;
terminalAttemptContext?.recordTerminalError(processorError);
return emitFatalErrorBail(processorError, currentModel.modelId);
}
throw error;
}
if (outputStreamBlocked) break;
} else {
if (effectiveOutputProcessors.length === 0) recordProcessedChunk(clientChunk);
require_run_registry.trackOpenReasoning(clientChunk, openReasoningIds);
await require_run_registry.emitChunkEvent(pubsub, runId, clientChunk);
}
}
ownership?.throwIfLost();
if (processedChunk !== null) {
const persistedChunk = processedChunk ?? rawChunk;
collectedChunks.push({
type: persistedChunk.type,
payload: "payload" in persistedChunk ? persistedChunk.payload : void 0,
metadata: clientChunk.metadata
});
if (persistedChunk.type === "text-delta") {
const text = persistedChunk.payload.text;
textDeltas.push(text);
registryEntry?.streamedStepText?.push(text);
}
}
if (require_run_registry.STEP_CONTENT_CHUNK_TYPES.has(rawChunk.type)) hasStepContent = true;
switch (rawChunk.type) {
case "tool-call-input-streaming-start": {
const tool = toolInputStartToolDef || resolveToolDef(rawChunk.payload.toolName);
if (tool && "onInputStart" in tool) try {
await tool.onInputStart?.({
toolCallId: rawChunk.payload.toolCallId,
messages: inputMessages,
abortSignal: runAbortSignal
});
} catch (error) {
ownership?.throwIfLost();
logger?.error?.("Error calling onInputStart", error);
}
break;
}
case "tool-call-delta": {
const tool = resolvedToolByCallId.get(rawChunk.payload.toolCallId) ?? (rawChunk.payload.toolName ? resolveToolDef(rawChunk.payload.toolName) : void 0);
if (tool && "onInputDelta" in tool) try {
await tool.onInputDelta?.({
inputTextDelta: rawChunk.payload.argsTextDelta,
toolCallId: rawChunk.payload.toolCallId,
messages: inputMessages,
abortSignal: runAbortSignal
});
} catch (error) {
ownership?.throwIfLost();
logger?.error?.("Error calling onInputDelta", error);
}
break;
}
case "tool-call": {
const payload = rawChunk.payload;
const effectiveTool = currentTools?.[payload.toolName];
toolCalls.push({
toolCallId: payload.toolCallId,
toolName: payload.toolName,
args: payload.args,
providerMetadata: payload.providerMetadata,
providerExecuted: payload.providerExecuted,
output: payload.output,
activeTools: currentActiveTools ?? null,
...effectiveTool?.requireApproval ? { requireApproval: true } : {},
...effectiveTool?.hasSuspendSchema ? { hasSuspendSchema: true } : {}
});
break;
}
case "tool-result": {
const payload = rawChunk.payload;
if (payload.preliminary) break;
const pending = pendingProviderToolCallsByToolCallId.get(payload.toolCallId);
if (pending) {
require_run_registry.endPendingProviderToolSpan({
toolCallId: payload.toolCallId,
pending,
parentSpan: modelSpanTracker?.getTracingContext()?.currentSpan ?? pending.fallbackParentSpan,
result: {
output: payload.result,
isError: payload.isError
},
logger
});
pendingProviderToolCallsByToolCallId.delete(payload.toolCallId);
materializedProviderToolCallIds.add(payload.toolCallId);
} else if (tracingContext?.currentSpan && !materializedProviderToolCallIds.has(payload.toolCallId)) {
const resultToolDef2 = resolveToolDef(payload.toolName);
if (!require_run_registry.inferProviderExecuted(payload.providerExecuted, resultToolDef2)) break;
let spanInput = payload.args;
if (spanInput === void 0) {
const allMessages = messageList.get.all.db();
for (const msg of allMessages) {
if (!msg.content?.parts) continue;
for (const part of msg.content.parts) if (part.type === "tool-invocation" && part.toolInvocation?.toolCallId === payload.toolCallId) {
spanInput = part.toolInvocation.args;
break;
}
if (spanInput !== void 0) break;
}
}
require_run_registry.endPendingProviderToolSpan({
toolCallId: payload.toolCallId,
pending: {
toolName: payload.toolName,
args: spanInput,
startTime: /* @__PURE__ */ new Date(),
toolDescription: resultToolDef2?.description
},
parentSpan: modelSpanTracker?.getTracingContext()?.currentSpan ?? resolveAgentRunFallback(tracingContext.currentSpan),
result: {
output: payload.result,
isError: payload.isError
},
logger
});
materializedProviderToolCallIds.add(payload.toolCallId);
}
break;
}
case "step-finish": {
const payload = rawChunk.payload;
finishReason = payload.stepResult?.reason || payload.finishReason || "stop";
usage = payload.output?.usage || payload.usage || usage;
if (finishReason === "error") {
const rawReason = payload.stepResult?.rawReason;
throw new require_error.MastraError({
id: "AGENT_STREAM_ERROR",
text: rawReason ? `Agent stream finished with finishReason "error" (provider reported "${rawReason}") but no error payload was provided` : "Agent stream finished with finishReason \"error\" but no error payload was provided",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.SYSTEM,
details: {
runId,
...rawReason && { rawFinishReason: rawReason }
}
});
}
if (finishReason === "other" && !hasStepContent) {
const rawReason = payload.stepResult?.rawReason;
throw new require_error.MastraError({
id: "AGENT_STREAM_ERROR",
text: rawReason ? `Agent stream finished with finishReason "other" (provider reported "${rawReason}") without producing any output` : "Agent stream finished with finishReason \"other\" without producing any output",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.SYSTEM,
details: {
runId,
...rawReason && { rawFinishReason: rawReason }
}
});
}
break;
}
case "response-metadata": {
const payload = rawChunk.payload;
responseMetadata = {
id: payload.id ?? responseMetadata.id,
timestamp: payload.timestamp ?? responseMetadata.timestamp,
modelId: payload.modelId ?? responseMetadata.modelId,
headers: payload.headers ?? responseMetadata.headers
};
break;
}
case "error": {
const payload = rawChunk.payload;
if (payload?.error instanceof Error) throw payload.error;
const errorMessage = payload?.error?.message || payload?.message || "LLM execution error";
const errorObj = new Error(errorMessage, { cause: payload?.error ?? payload });
if (typeof payload?.error?.stack === "string") errorObj.stack = payload.error.stack;
if (typeof payload?.error?.name === "string" && payload.error.name) errorObj.name = payload.error.name;
throw errorObj;
}
}
}
if (pubsub && !outputStreamBlocked && !executionAbortSignal?.aborted && effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) {
const released = await getToolResultRunner().flushHeldParts(registryEntry.processorStates, require_observability.createObservabilityContext(modelSpanTracker?.getTracingContext() ?? tracingContext), requestContext, messageList, 0, outputStreamWriter);
for (const r of released) {
if (r.blocked) {
outputStreamBlocked = true;
endTripwireSpans({
reason: r.reason || "Output processor blocked content",
processorId: r.processorId,
metadata: r.tripwireOptions?.metadata
});
await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tripwire",
runId,
from: "AGENT",
payload: {
reason: r.reason || "Output processor blocked content",
retry: r.tripwireOptions?.retry,
metadata: r.tripwireOptions?.metadata,
processorId: r.processorId
}
}, true);
break;
}
if (r.part == null) continue;
require_run_registry.trackOpenReasoning(r.part, openReasoningIds);
await require_run_registry.emitChunkEvent(pubsub, runId, r.part, true);
if (r.part.type === "tool-result") releasedToolResultIds.push(r.part.payload.toolCallId);
collectedChunks.push({
type: r.part.type,
payload: "payload" in r.part ? r.part.payload : void 0,
metadata: r.part.metadata
});
if (r.part.type === "text-delta") textDeltas.push(r.part.payload.text);
}
}
throwIfInterrupted();
interruptible = false;
stopListening?.();
cleanupToolObservabilitySpans(!(toolCalls.length > 0 && finishReason !== "stop"));
} catch (error) {
ownership?.throwIfLost();
if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) {
const kept = await getToolResultRunner().discardHeldParts(registryEntry.processorStates);
if (pubsub) for (const part of kept) await require_run_registry.emitChunkEvent(pubsub, runId, part, true);
}
throwIfInterrupted();
cleanupToolObservabilitySpans(true);
logger?.error?.("Error processing LLM stream", {
error,
runId
});
const errorObj = error instanceof Error ? error : new Error(String(error));
if (modelSpanTracker) modelSpanTracker.reportGenerationError({
error: errorObj,
endSpan: false
});
else if (modelSpan) modelSpan.error({
error: errorObj,
endSpan: false
});
const innerTimeout = resolveTotalTimeoutAbort(executionAbortSignal, errorObj);
if (innerTimeout) throw innerTimeout;
if (executionAbortSignal?.aborted === true || errorObj.name === "AbortError") {
materializeStreamedMessages();
return {
...await storeStepTranscript(),
text: textDeltas.join(""),
toolCalls: [],
stepResult: {
reason: "abort",
warnings: [],
isContinued: false
},
metadata: { modelId: currentModel.modelId },
state: typedInput.state,
deferredStepFinishChunk: prepareDeferredStepFinishChunk({
reason: "abort",
isContinued: false
}),
...recordClocks()
};
}
lastError = errorObj;
const registryEntryInner = require_run_registry.getRunRegistryEntry(runId, mastra);
const canRetryErrorInner = maxProcessorRetries !== void 0 && processorRetryCount < maxProcessorRetries;
if (registryEntryInner?.errorProcessors?.length) try {
const { retry } = await new require_stream.ProcessorRunner({
lateSignalSink,
inputProcessors: registryEntryInner.inputProcessors ?? [],
outputProcessors: registryEntryInner.outputProcessors ?? [],
errorProcessors: registryEntryInner.errorProcessors,
logger,
agentName: typedInput.agentName ?? typedInput.agentId,
agent: registryEntryInner?.agent,
processorStates: registryEntryInner.processorStates
}).runProcessAPIError({
error: lastError,
messages: messageList.get.all.db(),
messageList,
messageId: currentMessageId,
rotateResponseMessageId,
stepNumber: inputData.stepIndex ?? 0,
steps: require_run_registry.expandDurableSteps(previousSteps),
retryCount: processorRetryCount,
requestContext
});
ownership?.throwIfLost();
if (retry && canRetryErrorInner) {
processorRetryCount++;
attempt--;
continue;
}
} catch (processorError) {
ownership?.throwIfLost();
logger?.debug?.(`processAPIError handler failed: ${processorError}`, { runId });
}
if (attempt < maxRetries) continue;
break;
} finally {
releaseStreamActivity();
settleRequest();
}
ownership?.throwIfLost();
const streamError = outputStream.error;
if (streamError) {
const streamErrorObj = streamError instanceof Error ? streamError : new Error(String(streamError));
logger?.error?.("Stream captured error", {
error: streamErrorObj,
runId
});
if (modelSpanTracker) modelSpanTracker.reportGenerationError({
error: streamErrorObj,
endSpan: false
});
else if (modelSpan) modelSpan.error({
error: streamErrorObj,
endSpan: false
});
const streamErrorTimeout = resolveTotalTimeoutAbort(executionAbortSignal, streamErrorObj);
if (streamErrorTimeout) throw streamErrorTimeout;
if (executionAbortSignal?.aborted === true || streamErrorObj.name === "AbortError") {
materializeStreamedMessages();
return {
...await storeStepTranscript(),
text: textDeltas.join(""),
toolCalls: [],
stepResult: {
reason: "abort",
warnings: [],
isContinued: false
},
metadata: { modelId: currentModel.modelId },
state: typedInput.state,
deferredStepFinishChunk: prepareDeferredStepFinishChunk({
reason: "abort",
isContinued: false
}),
...recordClocks()
};
}
lastError = streamErrorObj;
if (attempt < maxRetries) continue;
break;
}
if (toolResultTripwire || outputStreamBlocked) {
if (toolResultTripwire) endTripwireSpans(toolResultTripwire);
if (toolResultTripwire && pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tripwire",
runId,
from: "AGENT",
payload: {
processorId: toolResultTripwire.processorId,
reason: toolResultTripwire.message,
retry: toolResultTripwire.options?.retry,
metadata: toolResultTripwire.options?.metadata
}
});
return {
...await storeStepTranscript(),
text: textDeltas.join(""),
toolCalls: [],
stepResult: {
reason: "tripwire",
warnings,
isContinued: false
},
metadata: { modelId: currentModel.modelId },
state: typedInput.state,
deferredStepFinishChunk: prepareDeferredStepFinishChunk({
reason: "tripwire",
isContinued: false
}),
...recordClocks(),
tracingTermination
};
}
if (!cachedResponse && requestStepRunner) try {
await requestStepRunner.runProcessLLMResponse({
chunks: collectedChunks,
model: currentModel,
stepNumber: inputData.stepIndex ?? 0,
steps: require_run_registry.expandDurableSteps(previousSteps),
warnings,
request,
rawResponse,
fromCache: false,
retryCount: processorRetryCount,
requestContext,
tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
writer: requestStepWriter,
abortSignal: runAbortSignal
});
ownership?.throwIfLost();
} catch (error) {
ownership?.throwIfLost();
if (error instanceof require_stream.TripWire) {
endTripwireSpans(error);
logger?.warn?.("Streaming response processor tripwire triggered", {
reason: error.message,
processorId: error.processorId,
retry: error.options?.retry
});
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tripwire",
runId,
from: "AGENT",
payload: {
processorId: error.processorId,
reason: error.message,
retry: error.options?.retry,
metadata: error.options?.metadata
}
});
return {
...await storeStepTranscript(),
text: textDeltas.join(""),
toolCalls: [],
stepResult: {
reason: "tripwire",
warnings,
isContinued: false
},
metadata: { modelId: currentModel.modelId },
state: typedInput.state,
deferredStepFinishChunk: prepareDeferredStepFinishChunk({
reason: "tripwire",
isContinued: false
}),
...recordClocks(),
tracingTermination
};
}
logger?.error?.("Error in processLLMResponse processors:", error);
throw error;
}
materializeStreamedMessages();
if (currentModel.provider && currentModel.modelId) messageList.enrichLastStepStart(`${currentModel.provider}/${currentModel.modelId}`);
const isContinued = toolCalls.length > 0 && !require_run_registry.TERMINAL_FINISH_REASONS.includes(finishReason);
const hasToolCalls = toolCalls.length > 0;
let processOutputStepTripwire;
if (effectiveOutputProcessors.length > 0) {
const outputStepRunner = new require_stream.ProcessorRunner({
lateSignalSink,
inputProcessors: [],
outputProcessors: effectiveOutputProcessors,
logger,
agentName: typedInput.agentName ?? typedInput.agentId,
agent: registryEntry?.agent,
processorStates: registryEntry?.processorStates
});
const toolCallInfos = toolCalls.map((tc) => ({
toolName: tc.toolName,
toolCallId: tc.toolCallId,
args: tc.args
}));
const outputStepWriter = pubsub ? { custom: async (data, writerOptions) => {
ownership?.throwIfLost();
require_stream.persistProcessorDataChunk(messageList, writerOptions?.messageId ?? currentMessageId, data);
await require_run_registry.emitChunkEvent(pubsub, runId, data);
} } : void 0;
try {
await outputStepRunner.runProcessOutputStep({
steps: require_run_registry.expandDurableSteps(previousSteps),
messages: messageList.get.all.db(),
messageList,
stepNumber: inputData.stepIndex ?? 0,
finishReason,
providerMetadata: responseMetadata,
toolCalls: toolCallInfos.length > 0 ? toolCallInfos : void 0,
text: textDeltas.join(""),
usage,
requestContext,
tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
writer: outputStepWriter,
retryCount: processorRetryCount
});
ownership?.throwIfLost();
} catch (error) {
ownership?.throwIfLost();
if (!(error instanceof require_stream.TripWire)) throw error;
processOutputStepTripwire = error;
}
}
if (registryEntry?.timeoutTotalMs && !processOutputStepTripwire) registryEntry.completedStepsState = JSON.parse(JSON.stringify(messageList.serialize()));
if (registryEntry) registryEntry.streamedStepText = void 0;
const retryRequested = processOutputStepTripwire?.options?.retry === true;
const canRetry = typedInput.options?.maxProcessorRetries !== void 0 && processorRetryCount < typedInput.options.maxProcessorRetries;
const shouldRetry = retryRequested && canRetry;
if (processOutputStepTripwire) messageList.rollbackToStepBoundary(materializationMessageId, iterationBoundary);
const stepTripwire = processOutputStepTripwire ? {
reason: processOutputStepTripwire.message,
retry: processOutputStepTripwire.options?.retry,
metadata: processOutputStepTripwire.options?.metadata,
processorId: processOutputStepTripwire.processorId
} : void 0;
prepareDeferredStepFinishChunk({
reason: processOutputStepTripwire ? shouldRetry ? "retry" : "tripwire" : void 0,
isContinued: shouldRetry || !processOutputStepTripwire && isContinued,
tripwire: stepTripwire
});
const stepSpanData = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.exportCurrentStep() : void 0;
const stepFinishPayload = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.getPendingStepFinishPayload() : void 0;
const output = {
...await storeStepTranscript(),
text: processOutputStepTripwire ? "" : textDeltas.join(""),
toolCalls: processOutputStepTripwire ? [] : toolCalls,
stepResult: {
reason: shouldRetry ? "retry" : processOutputStepTripwire ? "tripwire" : finishReason,
warnings,
isContinued: shouldRetry || !processOutputStepTripwire && isContinued,
totalUsage: usage,
headers: rawResponse?.headers,
tripwire: stepTripwire,
messageId: currentMessageId
},
metadata: {
id: responseMetadata.id,
modelId: responseMetadata.modelId || currentModel.modelId,
timestamp: responseMetadata.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
providerMetadata: responseMetadata,
headers: rawResponse?.headers
},
response: deferredStepFinishChunk ? {
id: deferredStepFinishChunk.payload?.metadata?.id,
modelId: require_run_registry.resolveResponseModelId(deferredStepFinishChunk.payload?.metadata?.providerMetadata, deferredStepFinishChunk.payload?.metadata?.modelId)
} : void 0,
state: typedInput.state,
modelSpanData: hasToolCalls && !processOutputStepTripwire ? modelSpan?.snapshot?.() ?? modelSpan?.exportSpan() : void 0,
stepSpanData,
stepFinishPayload,
deferredStepFinishChunk: deferredStepFinishChunk ?? void 0,
...recordClocks(),
...releasedToolResultIds.length ? { releasedToolResultIds } : {},
tracingTermination
};
if (!hasToolCalls || processOutputStepTripwire) {
const pendingPayload = modelSpanTracker?.getPendingStepFinishPayload();
if (pendingPayload) {
const stepSpan = modelSpanTracker?.exportCurrentStep();
if (stepSpan && observability) observability.rebuildSpan(stepSpan)?.end({
...require_observability.agentLoopTermination({
stopCause: "model_finished",
finishReason,
tripwire: stepTripwire
}),
output: {
text: textDeltas.join(""),
toolCalls: []
},
attributes: {
usage: require_observability.extractUsageMetrics(pendingPayload.output?.usage, pendingPayload.metadata?.providerMetadata),
finishReason: pendingPayload.stepResult?.reason,
isContinued: pendingPayload.stepResult?.isContinued
}
});
}
}
return output;
} catch (error) {
ownership?.throwIfLost();
if (interruption.signal.aborted) return finishInterruptedRequest(error, modelEntry.config.modelId);
if (error instanceof require_stream.TripWire) throw error;
lastError = error instanceof Error ? error : new Error(String(error));
const selectedOuterAbortSignal = require_run_registry.getRunRegistryEntry(runId, mastra)?.abortSignal ?? abortSignal;
const outerAbortSignal = ownership?.composeSignal(selectedOuterAbortSignal) ?? selectedOuterAbortSignal;
const totalTimeout = resolveTotalTimeoutAbort(outerAbortSignal, lastError);
if (totalTimeout) {
materializeStreamedMessages?.();
return emitFatalErrorBail(totalTimeout, modelEntry.config.modelId);
}
if (outerAbortSignal?.aborted === true || lastError.name === "AbortError") {
terminateAttemptSpans?.({
outcome: "abort",
stopReason: "caller_cancelled"
});
materializeStreamedMessages?.();
return {
...await storeStepTranscript(),
text: textDeltas.join(""),
toolCalls: [],
stepResult: {
reason: "abort",
warnings: [],
isContinued: false
},
metadata: { modelId: modelEntry.config.modelId },
state: typedInput.state,
deferredStepFinishChunk: prepareDeferredStepFinishChunk({
reason: "abort",
isContinued: false
}),
...recordClocks?.()
};
}
const modelId = modelEntry.config.modelId;
failInference?.(lastError);
logger?.error?.(`Error executing model ${modelId}, attempt ${attempt + 1}/${maxRetries + 1}`, {
error: lastError,
runId,
modelIndex,
attempt
});
const registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
const canRetryError = maxProcessorRetries !== void 0 && processorRetryCount < maxProcessorRetries;
if (registryEntry?.errorProcessors?.length) try {
const { retry } = await new require_stream.ProcessorRunner({
lateSignalSink,
inputProcessors: registryEntry.inputProcessors ?? [],
outputProcessors: registryEntry.outputProcessors ?? [],
errorProcessors: registryEntry.errorProcessors,
logger,
agentName: typedInput.agentName ?? typedInput.agentId,
agent: registryEntry?.agent,
processorStates: registryEntry.processorStates
}).runProcessAPIError({
error: lastError,
messages: messageList.get.all.db(),
messageList,
messageId: currentMessageId,
rotateResponseMessageId,
stepNumber: inputData.stepIndex ?? 0,
steps: require_run_registry.expandDurableSteps(previousSteps),
retryCount: processorRetryCount,
requestContext,
tracingContext
});
ownership?.throwIfLost();
if (retry && canRetryError) {
processorRetryCount++;
attempt--;
continue;
}
} catch (processorError) {
ownership?.throwIfLost();
logger?.debug?.(`processAPIError handler failed: ${processorError}`, { runId });
}
if (attempt >= maxRetries && modelIndex === modelList.length - 1 && !skipUnavailableAttachments && require_message_list.isDownloadAssetsError(lastError)) {
logger?.warn?.("Could not download an attachment; retrying without unavailable attachments", {
runId,
error: lastError.message
});
skipUnavailableAttachments = true;
attempt--;
continue;
}
if (attempt >= maxRetries) {
logger?.debug?.(`Exhausted retries for model ${modelId}, trying next model`, { runId });
break;
}
const delayMs = Math.min(1e3 * Math.pow(2, attempt), 1e4);
logger?.debug?.(`Retrying model ${modelId} after ${delayMs}ms`, {
runId,
attempt
});
await new Promise((resolve) => setTimeout(resolve, delayMs));
} finally {
removeAttemptAbortListener?.();
}
}
}
const fatalError = lastError ?? /* @__PURE__ */ new Error("Exhausted all fallback models and reached the maximum number of retries.");
terminalAttemptContext?.recordTerminalError(fatalError);
return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? "unknown");
})
});
}
// src/agent/durable/utils/serialize-state.ts
/**
* Extract serializable metadata from a CoreTool
* This strips out the execute function and converts the schema to JSON Schema
*/
function serializeToolMetadata(name, tool) {
let inputSchema = { type: "object" };
if (tool.parameters) {
if ("type" in tool.parameters && typeof tool.parameters.type === "string") inputSchema = tool.parameters;
else if ("jsonSchema" in tool.parameters) inputSchema = tool.parameters.jsonSchema;
else if ("_def" in tool.parameters) inputSchema = { type: "object" };
}
return {
id: "id" in tool && typeof tool.id === "string" ? tool.id : name,
name,
description: tool.description,
inputSchema,
requireApproval: tool.requireApproval,
hasSuspendSchema: tool.hasSuspendSchema
};
}
/**
* Extract serializable metadata from all tools
*/
function serializeToolsMetadata(tools) {
return Object.entries(tools).map(([name, tool]) => serializeToolMetadata(name, tool));
}
/**
* Extract serializable model configuration
*/
function serializeModelConfig(model) {
return {
provider: model.provider,
modelId: model.modelId,
specificationVersion: model.specificationVersion,
originalConfig: `${model.provider}/${model.modelId}`
};
}
/**
* Extract serializable model list entry from AgentModelManagerConfig
*/
function serializeModelListEntry(entry) {
const model = entry.model;
const settings = serializeModelSettings(entry.modelSettings);
return {
id: entry.id,
config: {
provider: model.provider,
modelId: model.modelId,
specificationVersion: model.specificationVersion,
originalConfig: `${model.provider}/${model.modelId}`,
...settings ? { settings } : {},
providerOptions: entry.providerOptions
},
maxRetries: entry.maxRetries,
enabled: entry.enabled
};
}
/**
* Serialize an array of model configs into a model list.
* Filters out disabled models since they shouldn't be included in durable execution.
*/
function serializeModelList(models) {
return models.filter((m) => m.enabled !== false).map(serializeModelListEntry);
}
/**
* Serialize scorers configuration for durable execution.
*
* This extracts the scorer name (for resolution at runtime) and sampling config.
* The actual scorer objects are resolved from Mastra at step execution time.
*
* @param scorers The agent's scorers configuration (from agent.scorers or options.scorers)
* @returns Serializable scorer configuration
*/
function serializeScorersConfig(scorers) {
const result = {};
for (const [key, entry] of Object.entries(scorers)) {
const scorerEntry = { scorerName: typeof entry.scorer === "string" ? entry.scorer : entry.scorer.name };
if (entry.sampling) scorerEntry.sampling = entry.sampling;
if (entry.filter) scorerEntry.filter = entry.filter;
result[key] = scorerEntry;
}
return result;
}
/**
* Extract serializable state from _internal-like objects
*/
function serializeDurableState(params) {
return {
memoryConfig: params.memoryConfig,
threadId: params.threadId,
resourceId: params.resourceId,
threadExists: params.threadExists,
savePerStep: params.savePerStep,
observationalMemory: params.observationalMemory,
fixedMemory: params.fixedMemory
};
}
/**
* Pick the JSON-safe call settings out of an arbitrary `modelSettings` input.
* Drops any field that is not a primitive value of the expected type so that
* non-serializable fields (functions, AbortSignal, etc.) never reach the
* workflow input.
*/
function serializeModelSettings(settings) {
if (!settings || typeof settings !== "object") return void 0;
const source = settings;
const out = {};
const pickNumber = (key) => {
const value = source[key];
if (typeof value === "number" && Number.isFinite(value)) out[key] = value;
};
pickNumber("maxOutputTokens");
pickNumber("temperature");
pickNumber("topP");
pickNumber("topK");
pickNumber("presencePenalty");
pickNumber("frequencyPenalty");
pickNumber("seed");
pickNumber("maxRetries");
if (Array.isArray(source.stopSequences) && source.stopSequences.every((v) => typeof v === "string")) out.stopSequences = source.stopSequences;
if (source.timeout && typeof source.timeout === "object") {
const timeoutSource = source.timeout;
const timeout = {};
for (const key of [
"totalMs",
"stepMs",
"firstChunkMs"
]) {
const value = timeoutSource[key];
if (typeof value === "number" && Number.isFinite(value) && value > 0) timeout[key] = value;
}
if (Object.keys(timeout).length > 0) out.timeout = timeout;
}
return Object.keys(out).length > 0 ? out : void 0;
}
/**
* Snapshot call-time client tools from their converted CoreTools so a worker in
* another process can rebuild them. Provider tools (no JSON input schema to
* carry) are skipped.
*/
function serializeClientTools(clientTools, tools) {
if (!clientTools) return void 0;
const out = {};
for (const name of Object.keys(clientTools)) {
const tool = tools[name];
if (!tool || tool.type === "provider-defined" || tool.type === "provider") continue;
const meta = serializeToolMetadata(name, tool);
out[name] = {
id: meta.id,
description: meta.description,
inputSchema: meta.inputSchema,
requireApproval: meta.requireApproval
};
}
return Object.keys(out).length > 0 ? out : void 0;
}
/**
* Collect the tool names from call-time toolsets so a cross-process worker can
* detect that they are unavailable.
*/
function serializeToolsetToolNames(toolsets) {
if (!toolsets) return void 0;
const names = /* @__PURE__ */ new Set();
for (const toolset of Object.values(toolsets)) for (const name of Object.keys(toolset ?? {})) names.add(name);
return names.size > 0 ? [...names] : void 0;
}
/**
* Extract serializable options from agent execution options
*/
function serializeDurableOptions(options) {
let serializedToolChoice;
if (options.toolChoice) {
if (typeof options.toolChoice === "string") serializedToolChoice = options.toolChoice;
else if (typeof options.toolChoice === "object" && "type" in options.toolChoice) {
if (options.toolChoice.type === "tool" && "toolName" in options.toolChoice) serializedToolChoice = {
type: "tool",
toolName: options.toolChoice.toolName
};
}
}
return {
clientTools: options.clientTools,
toolsetToolNames: options.toolsetToolNames,
maxSteps: options.maxSteps,
toolChoice: serializedToolChoice,
activeTools: options.activeTools,
modelSettings: serializeModelSettings(options.modelSettings),
agentMaxRetries: options.agentMaxRetries,
agentMaxRetriesConfigured: options.agentMaxRetriesConfigured,
requireToolApproval: options.requireToolApproval,
toolCallConcurrency: options.toolCallConcurrency,
autoResumeSuspendedTools: options.autoResumeSuspendedTools,
maxProcessorRetries: options.maxProcessorRetries,
includeRawChunks: options.includeRawChunks,
returnScorerData: options.returnScorerData,
hasErrorProcessors: options.hasErrorProcessors,
emptyErrorProcessorOverride: options.emptyErrorProcessorOverride,
providerOptions: options.providerOptions,
structuredOutput: options.structuredOutput,
skipBgTaskWait: options.skipBgTaskWait,
disableBackgroundTasks: options.disableBackgroundTasks,
backgroundTaskPolicy: options.backgroundTaskPolicy,
tracingOptions: options.tracingOptions,
actor: options.actor,
instructionsOverride: options.instructionsOverride,
systemMessage: options.systemMessage,
transform: options.transform,
isTaskComplete: options.isTaskComplete
};
}
/**
* Create the full workflow input from all components
*/
function createWorkflowInput(params) {
const metadataJson = params.inputTripwire ? require_utils_safe_stringify.boundedStringify(params.inputTripwire.metadata) : void 0;
const inputTripwire = params.inputTripwire ? {
reason: params.inputTripwire.reason,
retry: params.inputTripwire.retry,
processorId: params.inputTripwire.processorId,
...metadataJson === void 0 ? {} : { metadata: JSON.parse(metadataJson) }
} : void 0;
return {
__workflowKind: "durable-agent",
runId: params.runId,
agentId: params.agentId,
agentName: params.agentName,
agentVersionId: params.agentVersionId,
messageListState: params.messageList.serialize(),
toolsMetadata: serializeToolsMetadata(params.tools),
modelConfig: serializeModelConfig(params.model),
modelList: params.modelList ? serializeModelList(params.modelList) : void 0,
scorers: params.scorers ? serializeScorersConfig(params.scorers) : void 0,
options: serializeDurableOptions(params.options),
state: serializeDurableState(params.state),
messageId: params.messageId,
agentSpanData: params.agentSpanData,
modelSpanData: params.modelSpanData,
requestContextEntries: params.requestContextEntries,
inputTripwire
};
}
/**
* Serialize an error for workflow state
*/
function serializeError(error) {
if (error instanceof Error) return {
name: error.name,
message: error.message,
stack: error.stack,
__mastraSpanErrorOrigin: require_error_count.getSpanErrorOrigin(error)
};
return {
name: "Error",
message: String(error)
};
}
// src/agent/durable/workflows/steps/tool-call.ts
/**
* Input schema for the durable tool call step.
* Each tool call flows through this schema when using .foreach()
*/
const durableToolCallInputSchema = zod.z.object({
toolCallId: zod.z.string(),
toolName: zod.z.string(),
args: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerMetadata: zod.z.record(zod.z.string(), zod.z.any()).optional(),
providerExecuted: zod.z.boolean().optional(),
output: zod.z.any().optional(),
activeTools: zod.z.array(zod.z.string()).nullable().optional(),
requireApproval: zod.z.boolean().optional(),
hasSuspendSchema: zod.z.boolean().optional(),
stepSpanData: zod.z.any().optional(),
completionStartTime: zod.z.coerce.date().optional(),
timeToFirstTokenMs: zod.z.number().optional(),
stepUsage: zod.z.any().optional()
});
/**
* Output schema for the durable tool call step.
*
* NOTE on field declarations: nothing strips undeclared fields today — both
* loop builders run with `validateInputs: false` and the workflows engine has
* no output-side validation — so undeclared fields still cross step
* boundaries at runtime. Every field the step emits is declared anyway for
* type/schema honesty and so the contract survives if validation is ever
* (re-)enabled (e.g. by the Phase 2 evented port, which may use different
* validation defaults). If validation is enabled, an undeclared field would
* be silently stripped at the boundary — declare new output fields here.
*/
const serializedErrorSchema = zod.z.object({
name: zod.z.string(),
message: zod.z.string(),
stack: zod.z.string().optional(),
__mastraSpanErrorOrigin: zod.z.object({
traceId: zod.z.string(),
spanId: zod.z.string(),
occurrenceId: zod.z.string(),
attemptId: zod.z.string().optional()
}).optional()
});
const durableToolCallOutputSchema = durableToolCallInputSchema.extend({
result: zod.z.any().optional(),
modelOutputComputed: zod.z.boolean().optional(),
mappingError: serializedErrorSchema.optional(),
aborted: zod.z.boolean().optional(),
resultBlocked: zod.z.boolean().optional(),
resultHidden: zod.z.boolean().optional(),
tripwire: zod.z.object({
reason: zod.z.string(),
retry: zod.z.boolean().optional(),
metadata: zod.z.unknown().optional(),
processorId: zod.z.string().optional()
}).optional(),
error: serializedErrorSchema.optional(),
approval: zod.z.object({
id: zod.z.string(),
approved: zod.z.boolean(),
reason: zod.z.string().optional()
}).optional(),
processorDataParts: zod.z.array(zod.z.object({
type: zod.z.string(),
data: zod.z.any().optional(),
id: zod.z.string().optional(),
messageId: zod.z.string().optional()
})).optional(),
transformMetadata: zod.z.record(zod.z.string(), zod.z.any()).optional(),
delegationBailed: zod.z.boolean().optional(),
tracingDelegationFailure: zod.z.custom().optional(),
deadlineTimeout: zod.z.object({
timeoutType: zod.z.literal("total"),
timeoutMs: zod.z.number()
}).optional(),
runAborted: zod.z.boolean().optional()
});
/**
* Marks a tool call the run was stopped during, however the tool settled: the total deadline or
* abort(). The next step may run on a worker that never received the abort request, so the mark
* travels on the step output. An abort only this execution saw (lost ownership) is not the run's.
*/
function runStopOf(signal, runSignal) {
if (!signal?.aborted || !runSignal?.aborted) return {};
const reason = runSignal.reason;
if (require_stream.isMastraTimeoutError(reason)) return reason.timeoutType === "total" ? { deadlineTimeout: {
timeoutType: "total",
timeoutMs: reason.timeoutMs
} } : {};
return { runAborted: true };
}
/**
* Flush messages to memory before suspending.
* Mirrors the base Agent's flushMessagesBeforeSuspension() to ensure
* the thread exists and all pending messages are persisted.
*
* Skips entirely when memoryConfig.readOnly is set, mirroring the readOnly
* guard on the durable finish path — a readOnly run shouldn't get a thread
* created or messages written just because it happened to suspend mid-run.
*/
async function flushMessagesBeforeSuspension({ saveQueueManager, messageList, memory, threadId, resourceId, memoryConfig, threadExists, onThreadCreated, beforePersist }) {
if (!saveQueueManager || !messageList || !threadId || memoryConfig?.readOnly) return true;
try {
if (memory && !threadExists && resourceId) {
if (!await memory.getThreadById?.({ threadId })) await memory.createThread?.({
threadId,
resourceId,
memoryConfig
});
onThreadCreated?.();
}
await saveQueueManager.flushMessages(messageList, threadId, memoryConfig, {
beforePersist,
throwOnError: true
});
return true;
} catch (error) {
if (require_run_registry.isExecutionFenceError(error)) throw error;
return false;
}
}
var DurableOutputProcessorError = class extends Error {
constructor(error) {
super(error instanceof Error ? error.message : String(error), { cause: error });
this.name = "DurableOutputProcessorError";
}
};
var DurableChunkPublishError = class extends Error {
constructor(error) {
super(error instanceof Error ? error.message : String(error), { cause: error });
this.name = "DurableChunkPublishError";
}
};
/**
* Run a tool-result or tool-error chunk through the run's output processor
* pipeline and emit it (or a tripwire when blocked) via pubsub. Returns the
* processed chunk, or `null` if a processor blocked it. `onEmit` sees every
* chunk emitted, including parts a processor stashed for reprocessing.
*
* Thin glue over the shared per-chunk pipeline core; mirrors the regular
* agent's `processAndEnqueueChunk` in llm-mapping-step.ts.
*/
async function processChunkThroughOutputProcessors(chunk, registryEntry, pubsub, runId, agentName, logger, messageList, observabilityContext, collectDataPart, onEmit) {
const runner = registryEntry?.outputProcessors?.length && registryEntry.processorStates ? new require_stream.ProcessorRunner({
inputProcessors: [],
outputProcessors: registryEntry.outputProcessors,
logger,
agentName,
agent: registryEntry.agent,
processorStates: registryEntry.processorStates
}) : void 0;
return require_run_registry.processAndEmitChunk(chunk, {
runner,
processorStates: registryEntry?.processorStates,
observabilityContext,
requestContext: registryEntry?.requestContext,
messageList,
streamWriter: pubsub ? { custom: async (data, writerOptions) => {
if (data.type.startsWith("data-") && !data.transient) collectDataPart?.({
type: data.type,
data: data.data,
messageId: writerOptions?.messageId
});
try {
await require_run_registry.emitChunkEvent(pubsub, runId, data);
} catch (error) {
throw new DurableChunkPublishError(error);
}
} } : void 0,
emitChunk: async (c) => {
if (pubsub) try {
await require_run_registry.emitChunkEvent(pubsub, runId, c, !!runner);
} catch (error) {
throw new DurableChunkPublishError(error);
}
onEmit?.(c);
},
onProcessorError: (error) => {
if (error instanceof DurableChunkPublishError) throw error.cause;
throw new DurableOutputProcessorError(error);
},
endSpansAfterProcessing: true
});
}
/**
* Create a durable tool call step.
*
* This step mirrors the base Agent's createToolCallStep pattern:
* 1. Resolves the tool from the run registry or Mastra
* 2. Checks if approval is required (global or per-tool)
* 3. If approval required, emits suspended event, persists messages, and suspends
* 4. Executes the tool with a suspend callback for in-execution suspension
* 5. Emits tool-result or tool-error chunks via PubSub
* 6. Returns the result or error
*
* Tool suspension is handled via workflow suspend/resume mechanism:
* - Tool approval: step suspends with approval payload
* - In-execution suspension: tool calls suspend() callback, step suspends with suspension payload
* - Message persistence: messages are flushed before any suspension
*
* Deliberate divergence from the main loop: main cannot pause its
* request-scoped loop, so pending client tools ride the finish payload for
* browser-side handling and results come back on a follow-up request (#21688
* family). Durable has first-class suspension — the whole workflow parks at
* this step and resumes with the decision/result — so none of main's
* pending-tool plumbing applies here.
*/
function createDurableToolCallStep() {
return require_run_registry.createStep$1({
id: require_run_registry.DurableStepIds.TOOL_CALL,
inputSchema: durableToolCallInputSchema,
outputSchema: durableToolCallOutputSchema,
execute: async (params) => {
const { inputData, mastra, suspend, resumeData: workflowResumeData, requestContext, actor, getInitData, getStepResultAsync } = params;
const ownership = require_run_registry.getExecutionOwnershipGuard(params);
const pubsub = params[require_workflows_constants.PUBSUB_SYMBOL];
const typedInput = inputData;
const { toolCallId, toolName, args: rawArgs, providerExecuted, output, activeTools } = typedInput;
const suspendData = require_run_registry.ownToolCallSuspendData(params.suspendData, toolCallId);
let resumeDataFromArgs = void 0;
let args = rawArgs;
if (typeof rawArgs === "object" && rawArgs !== null) {
const { resumeData: resumeDataFromInput, ...argsFromInput } = rawArgs;
args = argsFromInput;
resumeDataFromArgs = resumeDataFromInput;
}
const processorDataParts = [];
const collectProcessorDataPart = (part) => {
ownership?.throwIfLost();
processorDataParts.push(part);
};
const resumeData = resumeDataFromArgs ?? workflowResumeData;
const approvalDecision = workflowResumeData != null && typeof workflowResumeData === "object" && typeof workflowResumeData.approved === "boolean" ? workflowResumeData : void 0;
const initData = getInitData();
const { runId, options: agentOptions, state } = initData;
const logger = mastra?.getLogger?.();
const endSpansAsSuspended = (info) => {
try {
const obs = mastra?.observability?.getSelectedInstance({ requestContext });
if (!obs) return;
const output = {
status: "suspended",
reason: info.reason,
toolName: info.toolName,
toolCallId: info.toolCallId
};
const reg = require_run_registry.getRunRegistryEntry(runId, mastra);
const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;
const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;
const attributes = carriedSpanClocks(reg, initData.completionStartTime ? {
completionStartTime: initData.completionStartTime,
timeToFirstTokenMs: initData.timeToFirstTokenMs
} : {
completionStartTime: typedInput.completionStartTime,
timeToFirstTokenMs: typedInput.timeToFirstTokenMs
});
if (typedInput.stepSpanData) obs.rebuildSpan(typedInput.stepSpanData)?.end({
output,
outcome: "suspend",
stopReason: info.reason === "approval" ? "approval_required" : null,
stopReasonContext: info.reason === "approval" ? require_observability.compactStopReasonContext("approval_required", {
toolCallId: info.toolCallId,
toolName: info.toolName
}) : null
});
if (modelSpanData) obs.rebuildSpan(modelSpanData)?.end({
output,
attributes,
outcome: "suspend",
stopReason: info.reason === "approval" ? "approval_required" : null,
stopReasonContext: info.reason === "approval" ? require_observability.compactStopReasonContext("approval_required", {
toolCallId: info.toolCallId,
toolName: info.toolName
}) : null
});
if (agentSpanData) obs.rebuildSpan(agentSpanData)?.end({
output,
attributes,
outcome: "suspend",
stopReason: info.reason === "approval" ? "approval_required" : null,
stopReasonContext: info.reason === "approval" ? require_observability.compactStopReasonContext("approval_required", {
toolCallId: info.toolCallId,
toolName: info.toolName
}) : null
});
} catch (error) {
logger?.warn?.(`[DurableAgent] Failed to end spans on suspend: ${error}`);
}
};
if (providerExecuted) return {
...typedInput,
...output !== void 0 ? { result: output } : {}
};
let registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
const registryModel = registryEntry?.model;
const hasAuthoritativeToolSnapshot = !!registryEntry && registryEntry.isPlaceholder !== true && !!registryModel && registryModel.__metadataOnly !== true && (registryEntry.baseTools !== void 0 || registryEntry.tools !== void 0);
const observability = mastra?.observability?.getSelectedInstance({ requestContext });
const processorAgentSpanData = registryEntry?.resumeAgentSpanData ?? initData.agentSpanData;
const processorAgentSpan = registryEntry?.resumeAgentSpan ?? registryEntry?.agentSpan ?? (processorAgentSpanData && observability ? observability.rebuildSpan(processorAgentSpanData) : void 0);
const processorObservabilityContext = processorAgentSpan ? require_observability.createObservabilityContext({ currentSpan: processorAgentSpan }) : void 0;
let tool = registryEntry?.tools?.[toolName];
let mastraTools;
let rebuiltTools;
let rebuiltWorkspace;
let rebuiltMemory;
let rebuiltSaveQueueManager;
let rebuiltRequestContext;
if (!tool) tool = require_run_registry.findProviderToolByName(registryEntry?.tools, toolName);
if (!tool) tool = Object.values(registryEntry?.tools ?? {}).find((t) => t && typeof t === "object" && "id" in t && t.id === toolName);
const needsSaveQueueForFlush = !registryEntry?.saveQueueManager && !!state?.threadId;
const needsProcessorPipeline = !registryEntry?.outputProcessors || !registryEntry.processorStates;
if ((!tool && !hasAuthoritativeToolSnapshot || needsSaveQueueForFlush || needsProcessorPipeline) && mastra) {
const rebuilt = await rebuildRunToolsFromMastra({
mastra,
runId,
agentId: initData.agentId,
state,
options: agentOptions,
requestContextEntries: initData.requestContextEntries,
requestContext,
rehydrateProcessors: true,
logger
});
if (rebuilt) {
registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
rebuiltTools = rebuilt.tools;
rebuiltWorkspace = rebuilt.workspace;
rebuiltMemory = rebuilt.memory;
rebuiltSaveQueueManager = rebuilt.saveQueueManager;
rebuiltRequestContext = rebuilt.requestContext;
if (!tool && !hasAuthoritativeToolSnapshot) tool = rebuiltTools[toolName];
if (!tool && !hasAuthoritativeToolSnapshot) tool = require_run_registry.findProviderToolByName(rebuiltTools, toolName);
if (!tool && !hasAuthoritativeToolSnapshot) tool = Object.values(rebuiltTools).find((t) => t && typeof t === "object" && "id" in t && t.id === toolName);
}
}
if (!tool && !hasAuthoritativeToolSnapshot) tool = resolveTool(toolName, mastra);
if (!tool && !hasAuthoritativeToolSnapshot && mastra) {
mastraTools = mastra.listTools?.();
if (mastraTools) {
tool = require_run_registry.findProviderToolByName(mastraTools, toolName);
if (!tool) tool = Object.values(mastraTools).find((t) => t && typeof t === "object" && "id" in t && t.id === toolName);
}
}
const toolKey = registryEntry?.tools?.[toolName] || rebuiltTools?.[toolName] ? toolName : Object.entries(registryEntry?.tools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0] ?? Object.entries(rebuiltTools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0] ?? Object.entries(mastraTools ?? {}).find(([, registeredTool]) => registeredTool === tool)?.[0];
const effectiveActiveTools = activeTools === null ? void 0 : activeTools ?? agentOptions.activeTools;
const activeToolKey = toolKey ?? toolName;
const isHiddenByActiveTools = effectiveActiveTools !== void 0 && !effectiveActiveTools.includes(activeToolKey);
if (!tool || isHiddenByActiveTools) {
const availableToolNames = effectiveActiveTools ?? Object.keys(hasAuthoritativeToolSnapshot ? registryEntry?.tools ?? {} : rebuiltTools ?? registryEntry?.tools ?? {});
const error = {
name: "ToolNotFoundError",
message: `Tool "${toolName}" not found.${availableToolNames.length > 0 ? ` Available tools: ${availableToolNames.join(", ")}` : ""}. Call tools by their exact name only — never add prefixes, namespaces, or colons.`
};
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tool-error",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
error
}
});
return {
...typedInput,
error
};
}
if (args === null || args === void 0) {
const error = serializeError(/* @__PURE__ */ new Error(`Tool "${toolName}" received invalid arguments — the provided JSON could not be parsed. Please provide valid JSON arguments.`));
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tool-error",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
error
}
});
return {
...typedInput,
error
};
}
const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
const memory = registryEntry?.memory ?? rebuiltMemory;
const workspace = registryEntry?.workspace ?? rebuiltWorkspace;
const toolPayloadTransform = require_run_registry.getRunRegistryEntry(runId, mastra)?.toolPayloadTransform ?? Object.values(mastra?.listAgents?.() ?? {}).find((agent) => agent.id === initData.agentId)?.getToolPayloadTransform?.() ?? mastra?.getToolPayloadTransform?.();
let threadExists = state?.threadExists ?? false;
const toolsForTransform = require_run_registry.getRunRegistryEntry(runId, mastra)?.tools ?? rebuiltTools;
const messageList = require_run_registry.getRunRegistryEntry(runId, mastra)?.messageList;
const publishAfterPersist = async (publish) => {
const entry = require_run_registry.getRunRegistryEntry(runId, mastra);
const resumedToolCallId = entry?.resumeToolCallId;
const clearAndPublish = async () => {
if (resumedToolCallId !== void 0) require_run_registry.clearResumeInFlight(runId, resumedToolCallId);
await publish();
};
const pending = entry?.pendingSuspensionEvents;
if (pending) pending.push(clearAndPublish);
else await clearAndPublish();
};
let resumeMessageList = messageList;
const hasInvocation = (msg) => msg.role === "assistant" && (msg.content?.parts ?? []).some((part) => part?.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCallId);
if (workflowResumeData !== void 0 && memory && state?.threadId && !messageList?.get.all.db().some(hasInvocation)) {
const { messages } = await memory.recall({
threadId: state.threadId,
resourceId: state.resourceId,
perPage: false
});
if (messageList) {
const invocation = [...messages].reverse().find(hasInvocation);
if (invocation) messageList.add(invocation, "memory");
} else if (messages.length) resumeMessageList = createRunMessageList({
mastra,
threadId: state.threadId,
resourceId: state.resourceId
}).add(messages, "memory");
}
let contextMessageList = messageList;
if (!contextMessageList) {
const messageListState = await readMessageListState(params, await getStepResultAsync?.(require_run_registry.DurableStepIds.LLM_EXECUTION) ?? {});
if (messageListState) contextMessageList = createRunMessageList({
mastra,
threadId: state?.threadId,
resourceId: state?.resourceId
}).deserialize(messageListState);
}
const assertOwned = () => require_run_registry.assertExecutionOwned({
runId,
agentId: initData.agentId,
requestContext,
mastra
});
const assertNotSuperseded = () => require_run_registry.assertExecutionNotSuperseded({
runId,
agentId: initData.agentId,
requestContext,
mastra
});
const assertSuspensionNotSuperseded = () => require_run_registry.assertExecutionNotSupersededInStorage({
runId,
agentId: initData.agentId,
requestContext,
mastra
});
const claimFenceArgs = {
requestContext,
runId,
memoryStore: async () => memory?.storage.getStore("memory")
};
const doFlush = async (messagesToFlush = messageList ?? resumeMessageList, beforePersist = assertOwned) => {
if (!messagesToFlush && processorDataParts.length) {
const invocation = [...contextMessageList?.get.all.db() ?? []].reverse().find(hasInvocation);
if (invocation) messagesToFlush = createRunMessageList({
mastra,
threadId: state?.threadId,
resourceId: state?.resourceId
}).add(invocation, "memory");
}
if (saveQueueManager && messagesToFlush && memory && state?.threadId && state.resourceId && !state.memoryConfig?.readOnly) {
const authorizationRequestContext = registryEntry?.requestContext ?? require_run_registry.restoreRequestContext(initData.requestContextEntries, requestContext);
const authorizeMemory = (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
mastra,
user: authorizationRequestContext.get("user"),
threadId: state.threadId,
resourceId: state.resourceId,
agentId: initData.agentId,
requestContext: authorizationRequestContext,
permission,
actor: agentOptions.actor
});
await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_WRITE);
if (!threadExists) await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_READ);
}
let flushedDataParts = [];
if (messagesToFlush && processorDataParts.length) {
const invocation = [...messagesToFlush.get.all.db()].reverse().find(hasInvocation);
if (invocation) {
flushedDataParts = processorDataParts.splice(0);
for (const part of flushedDataParts) require_stream.persistProcessorDataChunk(messagesToFlush, part.messageId ?? invocation.id, part);
}
}
if (!await flushMessagesBeforeSuspension({
saveQueueManager,
messageList: messagesToFlush,
memory,
threadId: state?.threadId,
resourceId: state?.resourceId,
memoryConfig: state?.memoryConfig,
threadExists,
onThreadCreated: () => {
threadExists = true;
},
beforePersist
})) {
logger?.warn?.("Failed to persist messages before durable tool suspension", {
runId,
toolCallId
});
processorDataParts.unshift(...flushedDataParts);
}
};
const registryRequireToolApproval = registryEntry?.requireToolApproval;
const effectiveRequireToolApproval = registryRequireToolApproval !== void 0 ? registryRequireToolApproval : agentOptions.requireToolApproval;
const approvalRequestContext = registryEntry?.requestContext ?? require_run_registry.restoreRequestContext(initData.requestContextEntries, requestContext);
const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {
toolName,
requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => !require_run_registry.INTERNAL_APPROVAL_KEYS.has(key))),
workspace
});
const addToolMetadata = (opts) => {
const metadataMessageList = messageList ?? resumeMessageList;
if (!metadataMessageList) return;
const metadataKey = opts.type === "suspension" ? "suspendedTools" : "pendingToolApprovals";
const entry = {
toolCallId,
toolName: opts.approvalToolName ?? toolName,
args: opts.approvalArgs ?? args,
...opts.approvalToolName ? {
parentToolName: toolName,
parentArgs: args
} : {},
type: opts.type,
runId,
...opts.delegatedRunId && opts.delegatedRunId !== runId ? { delegatedRunId: opts.delegatedRunId } : {},
...opts.delegatedToolCallId ? { delegatedToolCallId: opts.delegatedToolCallId } : {},
...opts.delegatedToolName ? { delegatedToolName: opts.delegatedToolName } : {},
...opts.type === "suspension" ? { suspendPayload: opts.suspendPayload } : {},
...opts.resumeSchema ? { resumeSchema: opts.resumeSchema } : {}
};
const carriesToolCall = (msg) => msg.role === "assistant" && (msg.content?.parts ?? []).some((part) => part?.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCallId);
const lastAssistantMessage = [...metadataMessageList.get.response.db()].reverse().find(carriesToolCall);
if (lastAssistantMessage?.content) {
let metadata;
if (typeof lastAssistantMessage.content.metadata === "object" && lastAssistantMessage.content.metadata !== null) metadata = lastAssistantMessage.content.metadata;
else {
metadata = {};
lastAssistantMessage.content.metadata = metadata;
}
metadata[metadataKey] = metadata[metadataKey] || {};
metadata[metadataKey][toolCallId] = entry;
return;
}
const target = [...metadataMessageList.get.all.db()].reverse().find(carriesToolCall);
if (!target?.content) {
logger?.warn?.(`[DurableAgent] addToolMetadata could not find an assistant message for tool call ${toolCallId} (${toolName}); ${metadataKey} entry was not persisted.`);
return;
}
const existingEntries = (typeof target.content.metadata === "object" && target.content.metadata !== null ? target.content.metadata : {})[metadataKey] ?? {};
metadataMessageList.updateMessageMetadataByToolCallId(toolCallId, { [metadataKey]: {
...existingEntries,
[toolCallId]: entry
} });
};
const removeToolMetadata = async (target, type) => {
if (!resumeMessageList) return;
const metadataKey = type === "suspension" ? "suspendedTools" : "pendingToolApprovals";
const expectedPartType = type === "suspension" ? "data-tool-call-suspended" : "data-tool-call-approval";
const entryMatches = (entry, fallbackToolCallId) => {
const entryToolCallId = typeof entry?.toolCallId === "string" ? entry.toolCallId : fallbackToolCallId;
const entryToolName = entry?.parentToolName ?? entry?.toolName;
const entryRunId = type === "approval" ? entry?.delegatedRunId : entry?.delegatedRunId ?? entry?.runId;
if (target.toolCallId) return entryToolCallId === target.toolCallId;
return entryToolName === target.toolName && !!target.runId && entryRunId === target.runId;
};
const changedMessages = [];
let matchedEntry;
for (const message of resumeMessageList.get.all.db()) {
if (message.role !== "assistant") continue;
let messageChanged = false;
const metadata = typeof message.content.metadata === "object" && message.content.metadata !== null ? message.content.metadata : void 0;
const entries = metadata?.[metadataKey];
if (entries) {
for (const [key, entry] of Object.entries(entries)) if (entryMatches(entry, key)) {
matchedEntry ??= {
...entry,
toolCallId: entry?.toolCallId ?? key
};
delete entries[key];
messageChanged = true;
}
if (Object.keys(entries).length === 0) delete metadata[metadataKey];
}
message.content.parts = message.content.parts?.map((part) => {
if (part.type !== expectedPartType || !entryMatches(part.data)) return part;
matchedEntry ??= { ...part.data };
if (part.data.resumed) return part;
messageChanged = true;
return {
...part,
data: {
...part.data,
resumed: true
}
};
});
if (messageChanged) changedMessages.push(message);
}
if (changedMessages.length > 0) {
resumeMessageList.add(changedMessages, "response");
await doFlush(resumeMessageList);
}
if (matchedEntry && pubsub) {
const displayed = await require_run_registry.applyToolPayloadTransformToChunk({
type: type === "approval" ? "tool-call-approval" : "tool-call-suspended",
runId,
from: "AGENT",
payload: {
toolCallId: matchedEntry.toolCallId ?? toolCallId,
toolName: matchedEntry.toolName ?? toolName,
args: matchedEntry.args,
...type === "suspension" ? { suspendPayload: matchedEntry.suspendPayload } : {},
resumeSchema: matchedEntry.resumeSchema
},
metadata: void 0
}, {
policy: toolPayloadTransform,
tools: toolsForTransform,
logger
});
await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tool-call-resumed",
runId,
from: "AGENT",
payload: {
toolCallId: matchedEntry.toolCallId ?? toolCallId,
toolName: matchedEntry.toolName ?? toolName,
kind: type,
args: displayed.payload.args,
...typeof matchedEntry.delegatedToolCallId === "string" ? { delegatedToolCallId: matchedEntry.delegatedToolCallId } : {},
...typeof matchedEntry.delegatedToolName === "string" ? { delegatedToolName: matchedEntry.delegatedToolName } : {},
...type === "suspension" ? { suspendPayload: displayed.payload.suspendPayload } : {},
resumeSchema: displayed.payload.resumeSchema
},
...displayed.metadata ? { metadata: displayed.metadata } : {}
});
}
};
const suspendedForApproval = suspendData != null && typeof suspendData === "object" && suspendData.type === "approval";
const isFreshCall = suspendData === void 0;
const approvalGated = suspendedForApproval || requiresApproval && isFreshCall;
if (approvalGated && !approvalDecision && isFreshCall) {
const rejection = await require_run_registry.runBeforeApprovalChecks({
tool,
input: args,
context: {
toolCallId,
toolName,
requestContext: approvalRequestContext,
workspace,
actor
},
logger
});
if (rejection) {
const result = rejection.output;
const validationError = require_tool.getModelFacingValidationError(result);
const mappingTool = require_run_registry.getRunRegistryEntry(runId, mastra)?.tools?.[toolName] ?? tool;
const validationErrorOutput = validationError && mappingTool.toModelOutput ? {
providerMetadata: await require_stream.computeModelOutputProviderMetadata({
tool: mappingTool,
toolName,
toolCallId,
result,
validationError,
existingProviderMetadata: typedInput.providerMetadata
}),
modelOutputComputed: true
} : void 0;
if (pubsub) try {
await processChunkThroughOutputProcessors(await require_run_registry.applyToolPayloadTransformToChunk({
type: "tool-result",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
result,
...validationErrorOutput ? { providerMetadata: validationErrorOutput.providerMetadata } : {},
providerExecuted
}
}, {
policy: toolPayloadTransform,
toolTransform: tool?.transform,
tools: toolsForTransform,
logger
}), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
} catch (emitError) {
if (emitError instanceof DurableOutputProcessorError) throw emitError;
logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);
}
return {
...typedInput,
result,
...validationErrorOutput ?? {},
...processorDataParts.length ? { processorDataParts } : {}
};
}
}
if (approvalGated && !approvalDecision) {
await require_run_registry.stopGoalActivity({
agentId: initData.agentId,
runId
});
addToolMetadata({
type: "approval",
resumeSchema: require_run_registry.approvalResumeSchema
});
await doFlush();
if (pubsub) {
const approvalChunk = await require_run_registry.applyToolPayloadTransformToChunk({
type: "tool-call-approval",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
resumeSchema: require_run_registry.approvalResumeSchema,
updatedAt: Date.now(),
usage: typedInput.stepUsage
}
}, {
policy: toolPayloadTransform,
tools: toolsForTransform,
logger
});
await publishAfterPersist(() => require_run_registry.emitChunkEvent(pubsub, runId, approvalChunk));
}
if (pubsub) await publishAfterPersist(() => require_run_registry.emitSuspendedEvent(pubsub, runId, {
toolCallId,
toolName,
args,
type: "approval",
resumeSchema: require_run_registry.approvalResumeSchema
}));
endSpansAsSuspended({
toolCallId,
toolName,
reason: "approval"
});
return suspend({
type: "approval",
toolCallId,
toolName,
args
}, { resumeLabel: toolCallId });
}
const isResumableTool = toolName?.startsWith("agent-") || toolName?.startsWith("workflow-");
const needsRunIdLookup = isResumableTool && resumeData !== void 0;
const hasModelResumeData = resumeDataFromArgs != null && !(approvalGated && approvalDecision);
const resolvedSuspensionIdentity = needsRunIdLookup ? require_run_registry.resolveFrameworkSuspendedToolIdentity({
toolCallId,
toolName,
resumeSource: hasModelResumeData ? "model" : "framework",
modelSuppliedSuspendedToolCallId: hasModelResumeData ? args?.suspendedToolCallId : void 0,
modelSuppliedSuspendedToolRunId: hasModelResumeData ? args?.suspendedToolRunId : void 0,
suspendData,
messages: messageList?.get.all.db() ?? []
}) : void 0;
const suspendedToolRunId = resolvedSuspensionIdentity?.runId;
const isDelegatedApprovalResume = approvalGated && !!approvalDecision && !!suspendData?.requireToolApproval && resolvedSuspensionIdentity?.type === "approval" && !!suspendedToolRunId;
if (approvalGated && approvalDecision) {
await removeToolMetadata({
toolCallId,
toolName
}, "approval");
if (!approvalDecision.approved && !isDelegatedApprovalResume) {
const approval = {
id: toolCallId,
approved: false,
reason: require_run_registry.resolveDeclineReason(approvalDecision)
};
if (pubsub) try {
await processChunkThroughOutputProcessors(await require_run_registry.applyToolPayloadTransformToChunk({
type: "tool-output-denied",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
approval
}
}, {
policy: toolPayloadTransform,
tools: toolsForTransform,
logger
}), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
} catch (emitError) {
if (emitError instanceof DurableOutputProcessorError) throw emitError;
logger?.warn?.(`[DurableAgent] Failed to emit tool-output-denied chunk for ${toolName}: ${emitError}`);
}
return {
...typedInput,
approval,
...processorDataParts.length ? { processorDataParts } : {}
};
}
}
const approvalGrant = approvalGated && approvalDecision?.approved === true ? { approval: {
id: toolCallId,
approved: true
} } : void 0;
const isResumingFromSuspension = resumeData !== void 0 && !approvalGated;
const bgManager = registryEntry?.backgroundTaskManager;
const bgConfig = registryEntry?.backgroundTasksConfig;
const toolBgConfig = tool.backgroundConfig;
const llmBgOverrides = typeof args === "object" && args !== null && "_background" in args ? args._background : void 0;
const cleanedArgs = { ...args };
const isAgentTool = toolName?.startsWith("agent-");
if ("_background" in cleanedArgs) delete cleanedArgs._background;
if (toolName?.startsWith("agent-") && "prompt" in cleanedArgs) {
cleanedArgs.threadId = state?.threadId;
cleanedArgs.resourceId = state?.resourceId;
}
delete cleanedArgs.suspendedToolRunId;
delete cleanedArgs.suspendedToolCallId;
const hasCustomApprovalResumeData = approvalGated && typeof resumeData === "object" && resumeData !== null && "approved" in resumeData && Object.keys(resumeData).length > 1;
if ((isResumingFromSuspension || isDelegatedApprovalResume) && suspendedToolRunId) cleanedArgs.suspendedToolRunId = suspendedToolRunId;
if (isResumingFromSuspension) {
const plainResumeIdentity = !isResumableTool && hasModelResumeData ? require_run_registry.resolveFrameworkSuspendedToolIdentity({
toolCallId,
toolName,
resumeSource: "model",
modelSuppliedSuspendedToolCallId: args?.suspendedToolCallId,
modelSuppliedSuspendedToolRunId: args?.suspendedToolRunId,
suspendData,
messages: messageList?.get.all.db() ?? []
}) : void 0;
const cleanupTarget = isResumableTool ? resolvedSuspensionIdentity : plainResumeIdentity ?? {
toolCallId,
toolName
};
if (cleanupTarget) await removeToolMetadata(cleanupTarget, resolvedSuspensionIdentity?.type ?? "suspension");
}
if (tool && "onInputAvailable" in tool && typeof tool.onInputAvailable === "function") try {
await tool.onInputAvailable({
toolCallId,
input: cleanedArgs,
messages: messageList ? messageList.get.input.aiV5.model() : []
});
} catch (hookError) {
logger?.error?.("Error calling onInputAvailable", hookError);
}
if (!tool.execute) return {
...typedInput,
result: void 0,
...approvalGrant ?? {}
};
const stepSpan = typedInput.stepSpanData && observability ? observability.rebuildSpan(typedInput.stepSpanData) : void 0;
const toolTracingContext = stepSpan ? { currentSpan: stepSpan } : void 0;
let wasSuspended = false;
if (pubsub && registryEntry && !registryEntry.isPlaceholder && (!registryEntry.abortSignal || registryEntry.abortController)) try {
await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(requestContext));
registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra) ?? registryEntry;
} catch (error) {
logger?.warn?.("Failed to subscribe to cross-process abort requests", {
runId,
error: error instanceof Error ? error.message : String(error)
});
}
const toolAbortSignal = ownership?.composeSignal(registryEntry?.abortSignal) ?? registryEntry?.abortSignal;
if (toolAbortSignal?.aborted) return {
...typedInput,
result: require_utils.TOOL_ABORT_NOTICE,
aborted: true,
...runStopOf(toolAbortSignal, registryEntry?.abortSignal)
};
const outputWriter = pubsub ? async (chunk) => {
const dataPart = chunk?.type === "tool-output" ? chunk.payload?.output : chunk;
if (typeof dataPart?.type === "string" && dataPart.type.startsWith("data-") && !dataPart.transient) collectProcessorDataPart({
type: dataPart.type,
data: dataPart.data,
id: dataPart.id,
messageId: dataPart.messageId
});
await require_run_registry.emitChunkEvent(pubsub, runId, chunk);
} : void 0;
let delegationMessages = registryEntry?.runScope?.get(require_run_registry.STEP_MODEL_MESSAGES_KEY);
if (isAgentTool && !delegationMessages && contextMessageList) {
const delegationList = createRunMessageList({ mastra });
delegationList.add(contextMessageList.get.all.db().filter((message) => message.id !== "om-continuation"), "input");
delegationMessages = delegationList.get.all.aiV5.prompt();
}
const toolOptionsWithoutWriter = {
toolCallId,
messages: isAgentTool ? delegationMessages ?? [] : contextMessageList?.get.input.aiV5.model() ?? [],
getMessages: messageList ? () => messageList.get.all.db() : void 0,
workspace,
requestContext,
mcp: registryEntry?.mcp,
tracingContext: toolTracingContext,
actor,
resumeData: isDelegatedApprovalResume ? workflowResumeData : isResumingFromSuspension || hasCustomApprovalResumeData ? resumeData : void 0,
suspendedToolRunId,
...isResumingFromSuspension && suspendData != null && typeof suspendData === "object" && "toolCallSuspended" in suspendData ? { suspendPayload: suspendData.toolCallSuspended } : {},
...toolAbortSignal ? { abortSignal: toolAbortSignal } : {},
outputWriter,
suspend: (suspendPayload, suspendOptions) => suspendToolCall(suspendPayload, suspendOptions, assertOwned)
};
const suspendToolCall = async (suspendPayload, suspendOptions, beforePersist) => {
wasSuspended = true;
const delegatedRunId = typeof suspendOptions?.runId === "string" && suspendOptions.runId !== runId ? suspendOptions.runId : void 0;
const fromDelegate = suspendOptions?.isAgentSuspend === true;
const delegatedToolCallId = fromDelegate && typeof suspendOptions?.delegatedToolCallId === "string" ? suspendOptions.delegatedToolCallId : void 0;
const delegatedToolName = fromDelegate && typeof suspendOptions?.delegatedToolName === "string" ? suspendOptions.delegatedToolName : void 0;
if (suspendOptions?.requireToolApproval) {
const innerApproval = typeof suspendOptions.requireToolApproval === "object" && suspendOptions.requireToolApproval ? suspendOptions.requireToolApproval : typeof suspendPayload?.requireToolApproval === "object" && suspendPayload?.requireToolApproval ? suspendPayload.requireToolApproval : null;
const approvalToolName = innerApproval?.toolName ?? toolName;
const approvalArgs = innerApproval?.args !== void 0 ? innerApproval.args : args;
await require_run_registry.stopGoalActivity({
agentId: initData.agentId,
runId
});
addToolMetadata({
type: "approval",
resumeSchema: require_run_registry.approvalResumeSchema,
delegatedRunId,
delegatedToolCallId,
delegatedToolName,
...innerApproval ? {
approvalToolName,
approvalArgs
} : {}
});
await doFlush(void 0, beforePersist);
if (pubsub) {
const approvalChunk = await require_run_registry.applyToolPayloadTransformToChunk({
type: "tool-call-approval",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName: approvalToolName,
args: approvalArgs,
...delegatedToolCallId ? { delegatedToolCallId } : {},
...delegatedToolName ? { delegatedToolName } : {},
resumeSchema: require_run_registry.approvalResumeSchema,
updatedAt: Date.now(),
usage: typedInput.stepUsage
}
}, {
policy: toolPayloadTransform,
tools: toolsForTransform,
logger
});
await publishAfterPersist(() => require_run_registry.emitChunkEvent(pubsub, runId, approvalChunk));
}
if (pubsub) await publishAfterPersist(() => require_run_registry.emitSuspendedEvent(pubsub, runId, {
toolCallId,
toolName: approvalToolName,
args: approvalArgs,
type: "approval",
resumeSchema: require_run_registry.approvalResumeSchema
}));
endSpansAsSuspended({
toolCallId,
toolName: approvalToolName,
reason: "approval"
});
return suspend({
type: "approval",
requireToolApproval: {
toolCallId,
toolName: approvalToolName,
args: approvalArgs
},
...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
}, { resumeLabel: toolCallId });
}
const suspendedEventData = {
toolCallId,
toolName,
args,
suspendPayload,
type: "suspension",
resumeSchema: suspendOptions?.resumeSchema
};
addToolMetadata({
type: "suspension",
suspendPayload,
resumeSchema: suspendOptions?.resumeSchema,
delegatedRunId,
delegatedToolCallId,
delegatedToolName
});
await doFlush(void 0, beforePersist);
if (pubsub) {
const suspensionChunk = await require_run_registry.applyToolPayloadTransformToChunk({
type: "tool-call-suspended",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
...delegatedToolCallId ? { delegatedToolCallId } : {},
...delegatedToolName ? { delegatedToolName } : {},
suspendPayload,
args,
resumeSchema: suspendOptions?.resumeSchema,
usage: typedInput.stepUsage
}
}, {
policy: toolPayloadTransform,
tools: toolsForTransform,
logger
});
await publishAfterPersist(() => require_run_registry.emitChunkEvent(pubsub, runId, suspensionChunk));
await publishAfterPersist(() => require_run_registry.emitSuspendedEvent(pubsub, runId, suspendedEventData));
}
endSpansAsSuspended({
toolCallId,
toolName,
reason: "suspension"
});
return suspend({
type: "suspension",
toolCallSuspended: suspendPayload,
toolCallId,
toolName,
resumeLabel: suspendOptions?.resumeLabel,
...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
}, { resumeLabel: toolCallId });
};
const toolOptions = require_run_registry.defineLazyWriter(toolOptionsWithoutWriter, () => new require_stream$1.ToolStream({
prefix: "tool",
callId: toolCallId,
name: toolName,
runId
}, outputWriter));
let resolveReconciliation;
const reconciliationComplete = new Promise((resolve) => {
resolveReconciliation = resolve;
});
const backgroundResultMetadata = (taskId, status) => require_stream.withAgentWorkflowToolMarker({
...typedInput.providerMetadata,
mastra: {
...typeof typedInput.providerMetadata?.mastra === "object" ? typedInput.providerMetadata.mastra : {},
backgroundTask: {
taskId,
status
}
}
}, tool);
const bgOutcome = await require_run_registry.dispatchBackgroundTool({
existingRunningTask: "restart",
dispatchFailure: "fallback-to-sync",
backgroundTaskManager: bgManager,
agentBackgroundConfig: bgConfig,
managerConfig: bgManager?.config,
toolBackgroundConfig: toolBgConfig,
llmBgOverrides,
args: cleanedArgs,
toolName,
toolCallId,
agentId: initData.agentId,
threadId: state?.threadId,
resourceId: state?.resourceId,
runId,
resumeData: isResumingFromSuspension ? resumeData : void 0,
logger,
adoptPersistedTask: true,
emitTaskStarted: async (task) => {
if (pubsub) await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "background-task-started",
runId,
from: "AGENT",
payload: {
taskId: task.id,
toolName,
toolCallId
}
});
},
taskContext: (info) => ({
executor: { execute: async (taskArgs, taskContext) => {
const taskId = info.getTaskId();
const execution = await require_run_registry.executeAdoptedBackgroundOperation({
taskId,
disposition: info.disposition === "awaited" ? "awaited" : "deferred",
abortSignal: taskContext?.abortSignal ?? toolAbortSignal,
execute: (background) => tool.execute(taskArgs, {
...toolOptions,
isBackgroundTask: true,
abortSignal: taskContext?.abortSignal ?? toolAbortSignal,
background,
[require_run_registry.BACKGROUND_WORK_CONTEXT]: {
originRunId: runId,
originToolCallId: toolCallId,
taskId,
invocationKind: isAgentTool ? "agent" : "tool",
disposition: info.disposition === "awaited" ? "awaited" : "deferred"
},
...taskContext?.resumeData !== void 0 ? {
resumeData: taskContext.resumeData,
suspendPayload: taskContext.suspendPayload
} : {},
suspendedToolRunId: taskContext?.suspendedToolRunId,
suspend: async (data, options) => {
await require_run_registry.runFencedToClaim(claimFenceArgs, () => suspendToolCall(data, options, assertSuspensionNotSuperseded));
return taskContext?.suspend?.(data, options);
},
outputWriter: async (chunk) => {
await taskContext?.onProgress?.(chunk);
return toolOptions.outputWriter?.(chunk);
}
}),
onCancelError: (error) => logger?.warn("Failed to cancel adopted background operation", error)
});
if (!execution.adopted) return execution.result;
const outputValidation = require_tool.validateToolOutput(require_tool.resolveToolOutputValidationSchema(tool), execution.result, toolName, false);
return outputValidation.error ?? outputValidation.data;
} },
onChunk: (chunk) => {
if (!pubsub) return;
try {
const bgRunId = chunk.payload.runId;
if (bgRunId !== runId || bgRunId === runId && resumeData != null) require_run_registry.emitChunkEvent(pubsub, bgRunId, {
type: "tool-call",
runId: bgRunId,
from: "AGENT",
payload: {
toolCallId: chunk.payload.toolCallId,
toolName: chunk.payload.toolName,
args: cleanedArgs,
title: require_run_registry.getToolTitle(tool)
}
});
if (chunk.type === "background-task-completed") require_run_registry.emitChunkEvent(pubsub, bgRunId, {
type: "tool-result",
runId: bgRunId,
from: "AGENT",
payload: {
toolCallId: chunk.payload.toolCallId,
toolName: chunk.payload.toolName,
args: cleanedArgs,
result: info.disposition === "awaited" && chunk.payload.result === void 0 ? null : chunk.payload.result,
providerMetadata: backgroundResultMetadata(chunk.payload.taskId, "completed"),
providerExecuted
}
});
else if (chunk.type === "background-task-failed") require_run_registry.emitChunkEvent(pubsub, bgRunId, {
type: "tool-error",
runId: bgRunId,
from: "AGENT",
payload: {
toolCallId: chunk.payload.toolCallId,
toolName: chunk.payload.toolName,
error: chunk.payload.error,
args: cleanedArgs,
providerMetadata: backgroundResultMetadata(chunk.payload.taskId, "failed")
}
});
} catch {}
},
onResult: async (params) => {
if (!messageList) {
if (info.disposition === "awaited") {
const error = /* @__PURE__ */ new Error("Cannot reconcile an awaited background task without a message list");
resolveReconciliation({ error });
throw error;
}
resolveReconciliation({});
return;
}
try {
const liveEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
const mappingTool = liveEntry?.tools?.[toolName] ?? tool;
const baseProviderMetadata = require_stream.withAgentWorkflowToolMarker(typedInput.providerMetadata, mappingTool);
const transformForTranscript = async (result) => {
const failed = params.status === "failed";
const transformCarrier = await require_run_registry.applyToolPayloadTransformToChunk({
type: failed ? "tool-error" : "tool-result",
payload: {
toolCallId: params.toolCallId,
toolName: params.toolName,
args: cleanedArgs,
...failed ? { error: params.error } : { result: params.result }
},
metadata: {}
}, {
policy: toolPayloadTransform,
toolTransform: mappingTool?.transform,
tools: toolsForTransform,
logger,
transformInput: { providerMetadata: typedInput.providerMetadata }
});
const transcriptArgsTransform = require_payload_transform.getTransformedToolPayload(transformCarrier.metadata, "transcript", "input-available");
const transcriptResultTransform = require_payload_transform.getTransformedToolPayload(transformCarrier.metadata, "transcript", failed ? "error" : "output-available");
return {
transcriptArgs: require_payload_transform.hasTransformedToolPayload(transcriptArgsTransform) ? transcriptArgsTransform.transformed : cleanedArgs,
transcriptResult: require_payload_transform.hasTransformedToolPayload(transcriptResultTransform) ? transcriptResultTransform.transformed : result,
providerMetadata: require_payload_transform.withToolPayloadTransformProviderMetadata(baseProviderMetadata, transformCarrier.metadata)
};
};
const toModelOutput = mappingTool.toModelOutput;
let transcript;
let modelOutput;
const applyTo = (list, flush) => require_run_registry.applyBackgroundToolResult({
params,
currentRunId: runId,
hasResumeData: resumeData != null,
args: cleanedArgs,
messageList: list,
approvalGrant,
baseProviderMetadata,
transformForTranscript: (result) => transcript ??= transformForTranscript(result),
toModelOutput: toModelOutput && ((output) => modelOutput ??= Promise.resolve().then(() => toModelOutput(output))),
generateId: mastra ? () => mastra.generateId() : void 0,
logger,
flush
});
await applyTo(messageList, async () => {
const threadId = state?.threadId;
if (saveQueueManager && threadId && !state?.memoryConfig?.readOnly) await require_run_registry.runFencedToClaim(claimFenceArgs, () => saveQueueManager.flushMessages(messageList, threadId, state.memoryConfig, { beforePersist: assertNotSuperseded }));
});
if (info.disposition !== "awaited" && liveEntry) recordBackgroundResult(liveEntry, params.taskId, params.toolCallId, reconciliationComplete).apply = (list) => applyTo(list, async () => {});
resolveReconciliation({ validationError: params.status === "completed" ? require_tool.getModelFacingValidationError(params.result) : void 0 });
if (info.disposition !== "awaited" && state?.threadId && state?.resourceId) Object.values(mastra?.listAgents?.() ?? {}).find((agent) => agent.id === initData.agentId)?.__notifyBackgroundTaskFinished({
threadId: state.threadId,
resourceId: state.resourceId,
taskId: params.taskId,
toolCallId: params.toolCallId,
toolName: params.toolName,
status: params.status === "failed" ? "failed" : "completed",
requestContext: registryEntry?.requestContext ?? require_run_registry.restoreRequestContext(initData.requestContextEntries, requestContext)
});
} catch (error) {
resolveReconciliation({ error });
throw error;
}
},
onExecution: async (params) => {
if (!messageList) return;
await require_run_registry.applyBackgroundToolExecution({
params,
args: cleanedArgs,
messageList,
transformChunk: (chunk) => require_run_registry.applyToolPayloadTransformToChunk(chunk, {
policy: toolPayloadTransform,
tools: toolsForTransform,
logger
})
});
const threadId = state?.threadId;
if (saveQueueManager && threadId && !state?.memoryConfig?.readOnly) try {
await require_run_registry.runFencedToClaim(claimFenceArgs, () => saveQueueManager.flushMessages(messageList, threadId, state.memoryConfig, { beforePersist: assertNotSuperseded }));
} catch (error) {
if (!require_run_registry.isExecutionFenceError(error)) throw error;
logger?.debug?.("[DurableAgent] Skipped background-task metadata flush: execution superseded", {
runId,
toolCallId: params.toolCallId
});
}
},
onComplete: toolBgConfig?.onComplete ?? bgConfig?.onTaskComplete,
onFailed: toolBgConfig?.onFailed ?? bgConfig?.onTaskFailed
})
});
if (bgOutcome.status !== "sync") {
if (bgOutcome.disposition === "awaited") {
let completedTask;
try {
completedTask = await bgOutcome.waitForCompletion({ abortSignal: toolAbortSignal });
} catch (error) {
if (!toolAbortSignal?.aborted || error !== toolAbortSignal.reason) throw error;
return {
...typedInput,
args: cleanedArgs,
result: require_utils.TOOL_ABORT_NOTICE,
aborted: true,
...runStopOf(toolAbortSignal, registryEntry?.abortSignal)
};
}
let reconciledValidationError;
if (completedTask.status !== "cancelled") {
const reconciliation = await reconciliationComplete;
if (reconciliation.error) throw reconciliation.error;
reconciledValidationError = reconciliation.validationError;
}
if (completedTask.status !== "completed") throw new Error(completedTask.error?.message ?? `Background task ${completedTask.status.replace("_", " ")}: ${completedTask.id}`);
return {
...typedInput,
args: cleanedArgs,
result: completedTask.result === void 0 ? null : completedTask.result,
providerMetadata: backgroundResultMetadata(bgOutcome.taskId, "completed"),
...reconciledValidationError ? {
providerMetadata: await require_stream.computeModelOutputProviderMetadata({
tool: require_run_registry.getRunRegistryEntry(runId, mastra)?.tools?.[toolName] ?? tool,
toolName,
toolCallId,
result: completedTask.result,
validationError: reconciledValidationError,
existingProviderMetadata: backgroundResultMetadata(bgOutcome.taskId, "completed")
}),
modelOutputComputed: true
} : {},
...bgOutcome.status === "started" ? approvalGrant ?? {} : {},
...processorDataParts.length ? { processorDataParts } : {}
};
}
const dispatchEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
if (dispatchEntry) recordBackgroundResult(dispatchEntry, bgOutcome.taskId, toolCallId, reconciliationComplete);
if (bgOutcome.status === "started") return {
...typedInput,
args: cleanedArgs,
result: bgOutcome.placeholder,
providerMetadata: backgroundResultMetadata(bgOutcome.taskId, "running"),
...approvalGrant ?? {}
};
return {
...typedInput,
args: cleanedArgs,
result: bgOutcome.placeholder,
providerMetadata: backgroundResultMetadata(bgOutcome.taskId, "running")
};
}
const consumeDelegationBailSignal = () => {
let bailed = false;
let failure;
for (const rc of [
registryEntry?.requestContext,
rebuiltRequestContext,
requestContext
]) if (rc?.get("__mastra_delegationBailed")) {
bailed = true;
rc.set("__mastra_delegationBailed", false);
failure = require_run_registry.takeDelegationFailure(rc) ?? failure;
}
if (!bailed) return void 0;
if (registryEntry) registryEntry.tracingDelegationFailure = failure;
return {
delegationBailed: true,
...failure ? { tracingDelegationFailure: failure } : {}
};
};
let mappingFailure;
const settleRunTool = require_utils.startRunStep(registryEntry);
let outcomeRecorded;
const outcomeRecordedPromise = new Promise((resolve) => outcomeRecorded = resolve);
let recordedAtStepEnd = false;
let stepEnded = false;
try {
try {
ownership?.throwIfLost();
} catch (error) {
settleRunTool();
throw error;
}
const outcome = await require_run_registry.executeToolCall({
tool,
args: cleanedArgs,
toolOptions,
toolCallId,
toolName,
abortSignal: toolAbortSignal,
assertNotBailedOut: () => {
if (!registryEntry?.executionFence?.deadlineError) ownership?.throwIfLost();
},
acquireExecution: () => require_run_registry.markRunActive(runId),
onToolSettled: () => void outcomeRecordedPromise.then(() => {
if (!recordedAtStepEnd || stepEnded) settleRunTool();
}),
logger
}).then(async (settled) => {
if (registryEntry?.executionFence?.deadlineError || registryEntry?.timeoutTotalMs && settled.status === "error") {
const resultProcessed = registryEntry.outputProcessors?.some((processor) => require_stream.isProcessorWorkflow(processor) ? processor.__processToolResult !== false : typeof processor.processToolResult === "function");
let lateOutcome = settled.status === "error" ? {
kind: "error",
errorText: settled.error instanceof Error ? settled.error.message : String(settled.error)
} : {
kind: "result",
result: settled.status === "aborted" || resultProcessed ? require_utils.TOOL_ABORT_NOTICE : settled.result
};
let lateTransformMetadata;
try {
lateTransformMetadata = (await require_run_registry.applyToolPayloadTransformToChunk(settled.status === "error" ? {
type: "tool-error",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
error: serializeError(settled.error)
}
} : {
type: "tool-result",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
result: lateOutcome.result,
providerMetadata: typedInput.providerMetadata,
providerExecuted
}
}, {
transformInput: {
args,
providerMetadata: typedInput.providerMetadata
},
policy: toolPayloadTransform,
toolTransform: tool?.transform,
tools: toolsForTransform,
logger
})).metadata;
} catch (transformError) {
logger?.warn?.(`[DurableAgent] Failed to transform the late result of ${toolName}: ${transformError}`);
lateOutcome = {
kind: "result",
result: require_utils.TOOL_ABORT_NOTICE
};
}
let lateProviderMetadata = require_payload_transform.withToolPayloadTransformProviderMetadata(typedInput.providerMetadata, lateTransformMetadata);
if (settled.status === "success" && lateOutcome.kind === "result" && lateOutcome.result !== "Tool execution was aborted while running. The tool may still be running and its effects are unknown. Check its status before retrying.") try {
lateProviderMetadata = await require_stream.computeModelOutputProviderMetadata({
tool: require_run_registry.getRunRegistryEntry(runId, mastra)?.tools?.[toolName] ?? tool,
toolName,
toolCallId,
result: settled.rawResult,
validationError: require_tool.getModelFacingValidationError(settled.rawResult),
existingProviderMetadata: lateProviderMetadata,
parentSpan: stepSpan
});
} catch (mappingError) {
logger?.warn?.(`[DurableAgent] Failed to map the late result of ${toolName}: ${mappingError}`);
lateOutcome = {
kind: "result",
result: require_utils.TOOL_ABORT_NOTICE
};
}
(registryEntry.settledToolResults ??= []).push({
toolCallId,
toolName,
args: cleanedArgs,
outcome: lateOutcome,
...approvalGrant ?? {},
providerMetadata: lateProviderMetadata
});
} else if (registryEntry?.timeoutTotalMs) recordedAtStepEnd = true;
return settled;
}).finally(outcomeRecorded);
ownership?.throwIfLost();
if (outcome.status === "error") throw outcome.error;
let result = outcome.status === "aborted" ? require_utils.TOOL_ABORT_NOTICE : outcome.result;
let providerMetadata = typedInput.providerMetadata;
let modelOutputComputed;
const mappingTool = require_run_registry.getRunRegistryEntry(runId, mastra)?.tools?.[toolName] ?? tool;
const toModelOutput = mappingTool.toModelOutput;
const validationError = outcome.status === "success" ? require_tool.getModelFacingValidationError(outcome.rawResult) : void 0;
if (toModelOutput && outcome.status === "success" && validationError) {
modelOutputComputed = true;
providerMetadata = await require_stream.computeModelOutputProviderMetadata({
tool: mappingTool,
toolName,
toolCallId,
result: outcome.rawResult,
validationError,
existingProviderMetadata: providerMetadata,
parentSpan: stepSpan
});
} else if (toModelOutput && outcome.status === "success") {
modelOutputComputed = true;
const mappingSpan = stepSpan?.createChildSpan({
type: "mapping",
name: `tool output mapping: '${toolName}'`,
entityType: require_storage.EntityType.TOOL,
entityId: toolName,
entityName: toolName,
input: outcome.rawResult,
attributes: {
mappingType: "toModelOutput",
toolCallId
}
});
try {
const modelOutput = require_stream.normalizeModelOutput(await toModelOutput(outcome.rawResult));
mappingSpan?.end({ output: modelOutput });
if (modelOutput != null) {
const existingMastra = providerMetadata?.mastra;
providerMetadata = {
...providerMetadata,
mastra: {
...existingMastra,
modelOutput
}
};
}
} catch (mappingError) {
mappingSpan?.error({
error: mappingError,
endSpan: true
});
mappingFailure = { error: mappingError };
throw mappingError;
}
}
if (outcome.status === "success") providerMetadata = require_stream.withAgentWorkflowToolMarker(providerMetadata, mappingTool);
if (!wasSuspended && registryEntry?.outputProcessors?.length && registryEntry.processorStates && messageList) {
const resultProcessorRunner = new require_stream.ProcessorRunner({
inputProcessors: [],
outputProcessors: registryEntry.outputProcessors,
logger,
agentName: initData.agentId,
agent: registryEntry.agent,
processorStates: registryEntry.processorStates
});
const resultBeforeProcessors = result;
const resultSnapshotBeforeProcessors = mappingTool?.toModelOutput && require_stream.hasToolResultProcessor(registryEntry.outputProcessors) ? require_stream.snapshotToolResult(resultBeforeProcessors) : void 0;
let processorsSucceeded = false;
try {
await resultProcessorRunner.runProcessToolResult({
steps: [],
stepNumber: 0,
messages: messageList.get.all.db(),
messageList,
toolName,
toolCallId,
toolArgs: cleanedArgs,
result,
modelOutput: require_stream.readModelOutput(providerMetadata),
...processorObservabilityContext ?? {},
requestContext: registryEntry.requestContext,
retryCount: 0,
writer: pubsub ? { custom: async (data, writerOptions) => {
if (data.type.startsWith("data-") && !data.transient) collectProcessorDataPart({
type: data.type,
data: data.data,
messageId: writerOptions?.messageId
});
await require_run_registry.emitChunkEvent(pubsub, runId, data);
} } : void 0,
abortSignal: toolAbortSignal
});
ownership?.throwIfLost();
const postProcessorResult = require_run_registry.readToolResultFromMessageList(messageList, toolCallId);
if (postProcessorResult !== void 0 && postProcessorResult !== result) result = postProcessorResult;
processorsSucceeded = true;
} catch (processorError) {
ownership?.throwIfLost();
if (processorError instanceof require_stream.TripWire) {
const tripwire = {
reason: processorError.message || "Tool result blocked by processor",
retry: processorError.options?.retry,
metadata: processorError.options?.metadata,
processorId: processorError.processorId
};
if (pubsub) try {
await require_run_registry.emitChunkEvent(pubsub, runId, {
type: "tripwire",
runId,
from: "AGENT",
payload: tripwire
});
} catch (emitError) {
logger?.warn?.(`[DurableAgent] Failed to emit tripwire chunk for ${toolName}: ${emitError}`);
}
return {
...typedInput,
resultBlocked: true,
tripwire,
...processorDataParts.length ? { processorDataParts } : {}
};
}
logger?.warn?.(`[DurableAgent] processToolResult failed for tool "${toolName}": ${processorError}`);
result = { error: "Tool result processing failed" };
if (providerMetadata?.mastra && "modelOutput" in providerMetadata.mastra) {
const { modelOutput: _unprocessed, ...mastra } = providerMetadata.mastra;
providerMetadata = {
...providerMetadata,
mastra
};
}
}
if (processorsSucceeded && outcome.status === "success") {
let resolvedProviderMetadata;
try {
resolvedProviderMetadata = await require_stream.resolveModelOutputAfterToolResultProcessors({
messageList,
tool: mappingTool,
toolName,
toolCallId,
resultBeforeProcessors,
resultSnapshotBeforeProcessors,
providerMetadata,
validationError,
parentSpan: stepSpan
});
} catch (mappingError) {
mappingFailure = { error: mappingError };
throw mappingError;
}
ownership?.throwIfLost();
if (resolvedProviderMetadata !== providerMetadata) {
providerMetadata = resolvedProviderMetadata;
modelOutputComputed = true;
}
}
}
let transformMetadata;
let resultEmitted = false;
let resultHidden = false;
if (pubsub && !wasSuspended) {
try {
const resultChunk = await require_run_registry.applyToolPayloadTransformToChunk({
type: "tool-result",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
result,
providerMetadata,
providerExecuted
}
}, {
transformInput: {
args,
providerMetadata: typedInput.providerMetadata
},
policy: toolPayloadTransform,
toolTransform: tool?.transform,
tools: toolsForTransform,
logger
});
transformMetadata = resultChunk.metadata;
await processChunkThroughOutputProcessors(resultChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart, (chunk) => {
if (chunk.type === "tool-result" && chunk.payload.toolCallId === toolCallId) resultEmitted = true;
});
} catch (emitError) {
ownership?.throwIfLost();
if (emitError instanceof DurableOutputProcessorError) throw emitError;
logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);
}
resultHidden = !resultEmitted;
}
if (registryEntry?.timeoutTotalMs && !wasSuspended) (registryEntry.settledToolResults ??= []).push({
toolCallId,
toolName,
args: cleanedArgs,
outcome: {
kind: "result",
result
},
...approvalGrant ?? {},
providerMetadata: require_payload_transform.withToolPayloadTransformProviderMetadata(providerMetadata, transformMetadata)
});
return {
...typedInput,
providerMetadata,
result,
...outcome.status === "aborted" ? { aborted: true } : {},
...runStopOf(toolAbortSignal, registryEntry?.abortSignal),
modelOutputComputed,
...resultHidden ? { resultHidden: true } : {},
...approvalGrant ?? {},
...processorDataParts.length ? { processorDataParts } : {},
...transformMetadata ? { transformMetadata } : {},
...consumeDelegationBailSignal()
};
} catch (error) {
const deadlineReason = registryEntry?.abortSignal?.reason;
if (registryEntry && recordedAtStepEnd && (registryEntry.executionFence?.deadlineError || require_stream.isMastraTimeoutError(deadlineReason) && deadlineReason.timeoutType === "total") && ownership?.isLost() && !registryEntry.settledToolResults?.some((settled) => settled.toolCallId === toolCallId)) (registryEntry.settledToolResults ??= []).push({
toolCallId,
toolName,
args: cleanedArgs,
outcome: {
kind: "result",
result: require_utils.TOOL_ABORT_NOTICE
}
});
ownership?.throwIfLost();
if (mappingFailure?.error === error) return {
...typedInput,
mappingError: serializeError(error),
...runStopOf(toolAbortSignal, registryEntry?.abortSignal)
};
if (error instanceof DurableOutputProcessorError || error instanceof Error && error.name === "FGADeniedError") throw error;
const toolError = serializeError(error);
let errorTransformMetadata;
if (pubsub && !wasSuspended) try {
const errorChunk = await require_run_registry.applyToolPayloadTransformToChunk({
type: "tool-error",
runId,
from: "AGENT",
payload: {
toolCallId,
toolName,
args,
error: toolError
}
}, {
policy: toolPayloadTransform,
toolTransform: tool?.transform,
tools: toolsForTransform,
logger
});
errorTransformMetadata = errorChunk.metadata;
await processChunkThroughOutputProcessors(errorChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
} catch (emitError) {
ownership?.throwIfLost();
if (emitError instanceof DurableOutputProcessorError) throw emitError;
logger?.warn?.(`[DurableAgent] Failed to emit tool-error chunk for ${toolName}: ${emitError}`);
}
return {
...typedInput,
error: toolError,
...approvalGrant ?? {},
...processorDataParts.length ? { processorDataParts } : {},
...errorTransformMetadata ? { transformMetadata: errorTransformMetadata } : {},
...runStopOf(toolAbortSignal, registryEntry?.abortSignal),
...consumeDelegationBailSignal()
};
} finally {
stepEnded = true;
if (recordedAtStepEnd) settleRunTool();
}
}
});
}
// src/agent/durable/workflows/steps/llm-mapping.ts
/**
* Input schema for the durable LLM mapping step.
* This combines the LLM execution output with tool call results.
*/
const durableLLMMappingInputSchema = zod.z.object({
llmOutput: zod.z.any(),
toolResults: zod.z.array(zod.z.any()),
runId: zod.z.string(),
agentId: zod.z.string(),
messageId: zod.z.string(),
state: zod.z.any()
});
/**
* Output schema for the durable LLM mapping step
*/
const durableLLMMappingOutputSchema = zod.z.object({
messageListState: zod.z.any().optional(),
messageId: zod.z.string(),
stepResult: zod.z.any(),
toolResults: zod.z.array(zod.z.any()),
output: zod.z.object({
text: zod.z.string().optional(),
toolCalls: zod.z.array(zod.z.any()).optional(),
usage: zod.z.any(),
steps: zod.z.array(zod.z.any()),
content: zod.z.array(zod.z.any()).optional()
}),
state: zod.z.any(),
delegationBailed: zod.z.boolean().optional(),
tracingDelegationFailure: zod.z.custom().optional(),
tracingTermination: zod.z.custom().optional(),
deadlineTimeout: zod.z.object({
timeoutType: zod.z.literal("total"),
timeoutMs: zod.z.number()
}).optional(),
runAborted: zod.z.boolean().optional(),
processorRetryCount: zod.z.number().optional(),
processorRetryFeedback: zod.z.string().optional(),
releasedToolResultIds: zod.z.array(zod.z.string()).optional(),
deferredStepFinishChunk: zod.z.any().optional(),
completionStartTime: zod.z.coerce.date().optional(),
timeToFirstTokenMs: zod.z.number().optional(),
response: responseRecordSchema.optional()
});
/**
* Create a durable LLM mapping step.
*
* This step:
* 1. Takes the LLM execution output and tool call results
* 2. Updates the message list with tool results
* 3. Combines everything into the final iteration output
*
* This is the "merge" step that combines parallel tool call results
* back into a single coherent state.
*/
function createDurableLLMMappingStep() {
return require_run_registry.createStep$1({
id: require_run_registry.DurableStepIds.LLM_MAPPING,
inputSchema: durableLLMMappingInputSchema,
outputSchema: durableLLMMappingOutputSchema,
execute: async (params) => {
const { inputData, mastra, requestContext, getInitData } = params;
const { llmOutput, toolResults, runId: _runId, agentId: _agentId, messageId, state } = inputData;
const registryEntry = require_run_registry.getRunRegistryEntry(_runId, mastra);
const terminalBackgroundParts = /* @__PURE__ */ new Map();
const captureTerminalBackgroundParts = () => {
for (const message of registryEntry?.messageList?.get.all.db() ?? []) for (const part of message.content.parts) {
if (part.type !== "tool-invocation") continue;
const backgroundTask = part.providerMetadata?.mastra?.backgroundTask;
if (backgroundTask && typeof backgroundTask === "object" && "taskId" in backgroundTask && (backgroundTask.status === "completed" || backgroundTask.status === "failed") && toolResults.some((result) => result.toolCallId === part.toolInvocation.toolCallId && result.providerMetadata?.mastra?.backgroundTask?.taskId === backgroundTask.taskId && result.providerMetadata?.mastra?.backgroundTask?.status === "running")) {
const toolCallId = part.toolInvocation.toolCallId;
const backgroundTaskEntry = (message.content.metadata?.backgroundTasks)?.[toolCallId];
terminalBackgroundParts.set(toolCallId, {
restore: (list) => {
list.updateToolInvocation(part, {
mode: "stream",
...backgroundTaskEntry ? { backgroundTasks: { [toolCallId]: backgroundTaskEntry } } : {}
});
},
taskId: backgroundTask.taskId
});
}
}
};
captureTerminalBackgroundParts();
const snapshot = await readMessageListState(params, llmOutput);
captureTerminalBackgroundParts();
const messageList = (registryEntry?.messageList ?? new require_message_list.MessageList({
threadId: state.threadId,
resourceId: state.resourceId
})).deserialize(snapshot);
for (const { restore } of terminalBackgroundParts.values()) restore(messageList);
if (llmOutput.stepResult.signalPreempted) return {
...await storeMessageListState(params, messageList.serialize()),
messageId,
stepResult: llmOutput.stepResult,
toolResults: [],
output: {
text: "",
toolCalls: [],
usage: {
inputTokens: void 0,
outputTokens: void 0,
totalTokens: void 0
},
steps: []
},
state
};
const isDeniedApproval = (toolResult) => toolResult?.approval?.approved === false;
const isPendingClientCall = (toolResult) => toolResult.result === void 0 && !toolResult.error && !toolResult.aborted && !toolResult.resultBlocked && !toolResult.providerExecuted && !isDeniedApproval(toolResult);
const registryTools = registryEntry?.tools;
let stepSpan;
if (llmOutput.stepSpanData) try {
stepSpan = (mastra?.observability?.getSelectedInstance({ requestContext }))?.rebuildSpan(llmOutput.stepSpanData);
} catch {}
if (toolResults.length > 0) {
const runStopped = toolResults.some((result) => result.deadlineTimeout || result.runAborted);
for (const toolResult of toolResults) {
const backgroundTask = toolResult.providerMetadata?.mastra?.backgroundTask;
captureTerminalBackgroundParts();
const terminalPart = terminalBackgroundParts.get(toolResult.toolCallId);
if (backgroundTask?.status === "running" && terminalPart && terminalPart.taskId === backgroundTask.taskId) {
terminalPart.restore(messageList);
continue;
}
if (toolResult.mappingError) {
if (runStopped) continue;
const mappingError = new Error(toolResult.mappingError.message);
mappingError.name = toolResult.mappingError.name;
mappingError.stack = toolResult.mappingError.stack;
const origin = require_error_count.getSpanErrorOrigin(toolResult.mappingError);
if (origin) require_error_count.setSpanErrorOrigin(mappingError, origin);
throw mappingError;
}
if (toolResult.aborted && toolResult.result === void 0) continue;
if (toolResult.resultBlocked) continue;
if (toolResult.providerExecuted) continue;
if (isDeniedApproval(toolResult)) {
require_stream.commitToolResult({
messageList,
outcome: {
kind: "denied",
approval: {
id: toolResult.approval.id,
approved: false,
reason: toolResult.approval.reason
}
},
toolCallId: toolResult.toolCallId,
toolName: toolResult.toolName,
toolArgs: toolResult.args
});
continue;
}
if (isPendingClientCall(toolResult)) continue;
let providerMetadata = toolResult.providerMetadata;
if (!toolResult.error && !toolResult.aborted && toolResult.result != null && !toolResult.providerExecuted && !toolResult.modelOutputComputed) providerMetadata = await require_stream.computeModelOutputProviderMetadata({
tool: registryTools?.[toolResult.toolName],
toolName: toolResult.toolName,
toolCallId: toolResult.toolCallId,
result: toolResult.result,
existingProviderMetadata: toolResult.providerMetadata,
parentSpan: stepSpan
});
if (toolResult.transformMetadata) providerMetadata = require_payload_transform.withToolPayloadTransformProviderMetadata(providerMetadata, toolResult.transformMetadata);
captureTerminalBackgroundParts();
const settledPart = terminalBackgroundParts.get(toolResult.toolCallId);
if (backgroundTask?.status === "running" && settledPart && settledPart.taskId === backgroundTask.taskId) {
settledPart.restore(messageList);
continue;
}
require_stream.commitToolResult({
messageList,
outcome: toolResult.error ? {
kind: "error",
errorText: toolResult.error.message
} : {
kind: "result",
result: toolResult.result
},
toolCallId: toolResult.toolCallId,
toolName: toolResult.toolName,
toolArgs: toolResult.args,
approval: toolResult.approval,
providerMetadata,
fallbackAppend: true
});
}
}
for (const toolResult of toolResults) for (const part of toolResult.processorDataParts ?? []) require_stream.persistProcessorDataChunk(messageList, part.messageId ?? messageId, part);
if (registryEntry) registryEntry.messageList = messageList;
const recoverFromToolErrors = toolResults.some((r) => r.error !== void 0) && !require_run_registry.TOOL_CALL_TERMINAL_FINISH_REASONS.has(llmOutput.stepResult.reason);
const hasPendingHITL = toolResults.some(isPendingClientCall);
const tripwire = toolResults.find((r) => r.tripwire)?.tripwire;
const isContinued = hasPendingHITL ? false : recoverFromToolErrors ? true : llmOutput.stepResult.isContinued;
let delegationBailed = toolResults.some((r) => r?.delegationBailed === true);
if (requestContext?.get("__mastra_delegationBailed")) {
delegationBailed = true;
requestContext.set("__mastra_delegationBailed", false);
}
const tracingDelegationFailure = toolResults.find((r) => r?.tracingDelegationFailure)?.tracingDelegationFailure;
const deadlineTimeout = toolResults.find((r) => r?.deadlineTimeout)?.deadlineTimeout;
const runAborted = toolResults.some((r) => r?.runAborted === true);
const deferredChunk = llmOutput.deferredStepFinishChunk;
const deferredStepFinishChunk = deferredChunk ? {
...deferredChunk,
payload: {
...deferredChunk.payload,
stepResult: {
...deferredChunk.payload?.stepResult,
isContinued
}
}
} : void 0;
const serializedMessageList = messageList.serialize();
if (registryEntry?.timeoutTotalMs) {
registryEntry.completedStepsState = JSON.parse(JSON.stringify(serializedMessageList));
registryEntry.settledToolResults = void 0;
}
const output = {
...await storeMessageListState(params, serializedMessageList),
messageId,
stepResult: {
...llmOutput.stepResult,
isContinued
},
toolResults,
output: {
text: llmOutput.text,
toolCalls: llmOutput.toolCalls,
usage: llmOutput.stepResult.totalUsage ?? {
inputTokens: void 0,
outputTokens: void 0,
totalTokens: void 0
},
steps: [],
content: require_run_registry.compactDurableStepContent(messageList.get.response.aiV5.modelContent(-1, llmOutput.toolCalls.map((call) => call.toolCallId)), toolResults)
},
state: {
...state,
threadExists: state.threadExists
},
processorRetryCount: llmOutput.processorRetryCount,
processorRetryFeedback: llmOutput.processorRetryFeedback,
releasedToolResultIds: llmOutput.releasedToolResultIds,
delegationBailed,
tracingDelegationFailure,
tracingTermination: llmOutput.tracingTermination,
...deadlineTimeout ? { deadlineTimeout } : {},
...runAborted ? { runAborted } : {},
deferredStepFinishChunk,
completionStartTime: llmOutput.completionStartTime,
timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,
response: llmOutput.response
};
if (stepSpan) try {
const pendingPayload = llmOutput.stepFinishPayload;
const signal = require_run_registry.getRunRegistryEntry(_runId, mastra)?.abortSignal ?? params.abortSignal;
const abortReason = require_stream.getAbortReason(signal);
const interrupted = toolResults.some((result) => result.aborted);
const termination = interrupted ? require_stream.isMastraTimeoutError(abortReason) ? require_observability.executionFailureTermination(abortReason) : require_observability.agentLoopTermination({ finishReason: "abort" }) : require_observability.agentLoopTermination({
stopCause: "model_finished",
finishReason: tripwire ? "tripwire" : llmOutput.stepResult.reason,
tripwire
});
stepSpan.end({
...termination,
...interrupted ? { outcome: "interrupted" } : {},
output: {
text: llmOutput.text,
toolCalls: llmOutput.toolCalls
},
attributes: {
usage: require_observability.extractUsageMetrics(pendingPayload?.output?.usage, pendingPayload?.metadata?.providerMetadata),
finishReason: pendingPayload?.stepResult?.reason,
isContinued: pendingPayload?.stepResult?.isContinued
}
});
} catch (error) {
mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to close model_step span: ${error}`);
}
if (isContinued && state.savePerStep && !state.observationalMemory && !state.memoryConfig?.readOnly && state.threadId && state.resourceId) {
const authorizationEntry = require_run_registry.getRunRegistryEntry(_runId, mastra);
const authorizationRequestContext = authorizationEntry?.requestContext ?? requestContext;
const authorizeMemory = (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(authorizationEntry), {
mastra,
user: authorizationRequestContext?.get("user"),
threadId: state.threadId,
resourceId: state.resourceId,
agentId: _agentId,
requestContext: authorizationRequestContext,
permission,
actor: (getInitData?.())?.options?.actor
});
await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_WRITE);
if (!state.threadExists) await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_READ);
try {
let saveQueueManager = require_run_registry.getRunRegistryEntry(_runId, mastra)?.saveQueueManager;
let memory = require_run_registry.getRunRegistryEntry(_runId, mastra)?.memory;
if (!saveQueueManager && mastra) {
const rebuilt = await rebuildRunToolsFromMastra({
mastra,
runId: _runId,
agentId: _agentId,
state,
requestContext
});
saveQueueManager = rebuilt?.saveQueueManager;
memory = rebuilt?.memory;
}
if (saveQueueManager) {
if (!state.threadExists && memory) {
if (!await memory.getThreadById?.({ threadId: state.threadId })) await memory.createThread?.({
threadId: state.threadId,
resourceId: state.resourceId,
memoryConfig: state.memoryConfig
});
output.state = {
...output.state,
threadExists: true
};
}
await saveQueueManager.flushMessages(messageList, state.threadId, state.memoryConfig, { beforePersist: () => require_run_registry.assertExecutionOwned({
runId: _runId,
agentId: _agentId,
requestContext,
mastra
}) });
}
} catch (error) {
if (require_run_registry.isExecutionFenceError(error)) throw error;
mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to save step: ${error}`);
}
}
return output;
}
});
}
// src/agent/durable/utils/restore-completion.ts
/**
* Rebuild a run's `isTaskComplete` policy in a process that did not prepare it
* (recovery after a restart, or a worker that runs the completion step).
* Scorers and `onComplete` cannot be serialized, so only a policy taken from
* the agent defaults can be restored, and only when the defaults still resolve
* to the same scorers. Anything else logs a warning and returns undefined.
*/
async function restoreCompletionPolicy({ agent, persisted, requestContext, runId, logger }) {
if (!persisted) return void 0;
let configured;
if (persisted.fromAgentDefaults && agent) try {
configured = (await agent.getDefaultOptions({ requestContext }))?.isTaskComplete;
} catch (error) {
logger?.warn?.(`[DurableAgent] Failed to resolve agent defaults for run ${runId}: ${error}`);
}
const scorerIds = configured?.scorers?.map((scorer) => scorer.id);
if (!configured?.scorers || !persisted.scorerIds || JSON.stringify(scorerIds) !== JSON.stringify(persisted.scorerIds)) {
logger?.warn?.(`[DurableAgent] Cannot restore isTaskComplete for run ${runId}; completion checks will not run`);
return;
}
return {
scorers: configured.scorers,
onComplete: configured.onComplete,
strategy: persisted.strategy,
timeout: persisted.timeout,
parallel: persisted.parallel,
suppressFeedback: persisted.suppressFeedback
};
}
// src/agent/durable/workflows/steps/is-task-complete.ts
/**
* Create the durable isTaskComplete step. Behavior lives in the shared
* `evaluateTaskCompletion` core; this glue owns registry/init-data access,
* message-list rehydration/serialization, and projection back onto the
* IterationState.
*
* The scorer instances + `onComplete` closure come from the in-process run
* registry. They can't survive the wire, so a process that did not prepare
* the run rebuilds a policy taken from the agent defaults, and warns and falls
* back to `maxSteps` + `stopWhen` for one it cannot rebuild.
*/
function createDurableIsTaskCompleteStep(defaultMaxSteps = require_run_registry.DurableAgentDefaults.MAX_STEPS) {
return require_run_registry.createStep$1({
id: require_run_registry.DurableStepIds.IS_TASK_COMPLETE,
inputSchema: zod.z.any(),
outputSchema: zod.z.any(),
execute: async (params) => {
const { inputData, mastra, getInitData } = params;
const state = inputData;
if (state.lastStepResult?.signalPreempted) return state;
const pubsub = params[require_workflows_constants.PUBSUB_SYMBOL];
const initData = getInitData();
const registryEntry = require_run_registry.getRunRegistryEntry(state.runId, mastra);
let policy = registryEntry?.isTaskComplete;
if (initData.options?.isTaskComplete && !(registryEntry && "isTaskComplete" in registryEntry)) {
let agent;
try {
agent = initData.agentId ? mastra?.getAgentById(initData.agentId) : void 0;
} catch {}
const restored = await restoreCompletionPolicy({
agent,
persisted: initData.options.isTaskComplete,
requestContext: require_run_registry.restoreRequestContext(initData.requestContextEntries, registryEntry?.requestContext),
runId: state.runId,
logger: mastra?.getLogger?.()
});
if (registryEntry) registryEntry.isTaskComplete = restored;
policy = restored;
}
if (!policy?.scorers?.length) return state;
const messageListState = await readMessageListState(params, state);
let messageList;
const list = () => {
if (!messageList) {
messageList = new require_message_list.MessageList();
messageList.deserialize(messageListState);
}
return messageList;
};
const lastStep = (await loadAccumulatedSteps(params, state)).at(-1);
const outcome = await require_run_registry.evaluateTaskCompletion({
policy,
errorPolicy: "best-effort",
engineMode: "durable",
iteration: state.iterationCount,
maxIterations: state.options?.maxSteps ?? defaultMaxSteps,
llmSignaledDone: state.lastStepResult?.isContinued === false,
stepReason: state.lastStepResult?.reason,
backgroundTaskPending: state.backgroundTaskPending,
toolCalls: lastStep?.toolCalls ?? [],
toolResults: lastStep?.toolResults ?? [],
currentText: lastStep?.text || "",
messageList: list,
runId: state.runId,
agentId: initData.agentId,
agentName: initData.agentName,
threadId: initData.state?.threadId,
resourceId: initData.state?.resourceId,
customContext: restoreCustomContext(initData.requestContextEntries, registryEntry?.requestContext ?? params.requestContext),
generateId: () => mastra?.generateId?.(),
emitChunk: (chunk) => {
if (!pubsub) return;
return require_run_registry.emitChunkEvent(pubsub, state.runId, chunk);
},
logger: mastra?.getLogger?.()
});
if (!outcome.evaluated) return state;
const nextState = { ...state };
if (nextState.lastStepResult) nextState.lastStepResult = {
...nextState.lastStepResult,
isContinued: !outcome.complete
};
if (!outcome.complete && nextState.messageId) nextState.messageId = list().rotateResponseMessageId(nextState.messageId);
Object.assign(nextState, await storeMessageListState(params, list().serialize()));
return nextState;
}
});
}
// src/agent/durable/workflows/steps/goal.ts
/**
* Create the durable goal step.
*
* Behavior lives in the shared `evaluateGoal` core; this glue owns
* registry/init-data access, request-context reconstruction, message-list
* rehydration/serialization, and projection back onto the IterationState.
*
* The `goal` config (judge, scorer, tools closures) comes from the in-process
* run registry — closures can't survive the wire, so cross-process engines
* without this slot fall back to the agent's own config or skip goal
* evaluation. The objective and its progress are isolated by thread and
* loaded from storage inside the core.
*/
function createDurableGoalStep() {
return require_run_registry.createStep$1({
id: "durable-goal",
inputSchema: zod.z.any(),
outputSchema: zod.z.any(),
execute: async (params) => {
const { inputData, mastra, getInitData } = params;
const state = inputData;
if (state.lastStepResult?.signalPreempted) return state;
const pubsub = params[require_workflows_constants.PUBSUB_SYMBOL];
const initData = getInitData();
const registryEntry = require_run_registry.getRunRegistryEntry(state.runId, mastra);
let goalConfig = registryEntry?.goal;
if (!goalConfig && initData.agentId) goalConfig = mastra?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();
const liveRequestContext = registryEntry?.requestContext ?? params.requestContext;
const requestContext = require_run_registry.restoreRequestContext(initData.requestContextEntries, liveRequestContext);
const customContext = restoreCustomContext(initData.requestContextEntries, liveRequestContext);
if (!goalConfig) return state;
const messageListState = await readMessageListState(params, state);
let messageList;
const list = () => {
if (!messageList) messageList = createRunMessageList({ mastra }).deserialize(messageListState);
return messageList;
};
const lastStep = (await loadAccumulatedSteps(params, state)).at(-1);
const outcome = await require_run_registry.evaluateGoal({
goal: goalConfig,
stepReason: state.lastStepResult?.reason,
backgroundTaskPending: state.backgroundTaskPending,
isContinued: state.lastStepResult?.isContinued,
toolCalls: lastStep?.toolCalls ?? [],
toolResults: lastStep?.toolResults ?? [],
currentText: lastStep?.text || "",
runId: state.runId,
agentId: initData.agentId,
agentName: initData.agentName,
threadId: initData.state?.threadId,
resourceId: initData.state?.resourceId,
customContext,
mastra,
requestContext,
messageList: list,
messageId: state.messageId,
rotateMessageId: (current) => list().rotateResponseMessageId(current),
writeSignal: pubsub ? async (data) => {
await require_run_registry.emitChunkEvent(pubsub, state.runId, data);
} : void 0,
emitChunk: (chunk) => {
if (!pubsub) return;
return require_run_registry.emitChunkEvent(pubsub, state.runId, chunk);
}
});
if (!outcome.evaluated) return state;
const nextState = { ...state };
if (nextState.lastStepResult) nextState.lastStepResult = {
...nextState.lastStepResult,
isContinued: outcome.shouldContinue
};
if (outcome.kind === "judged") {
nextState.messageId = outcome.messageId;
Object.assign(nextState, await storeMessageListState(params, list().serialize()));
}
return nextState;
}
});
}
// src/agent/durable/workflows/durable-loop-builder.ts
const COLLECT_TOOL_RESULTS_STEP_ID = "collect-tool-results";
/**
* The outer step that publishes FINISH. Recovery reads its saved status to tell
* whether FINISH already went out before a crash.
*/
/**
* Copies step params with some fields overridden, keeping accessors intact.
* A spread would invoke the lazy `writer` getter (see `defineLazyWriter`) and
* allocate a ToolStream the step never uses.
*/
function withParams(params, overrides) {
const descriptors = Object.getOwnPropertyDescriptors(params);
for (const [key, value] of Object.entries(overrides)) descriptors[key] = {
value,
enumerable: true,
configurable: true,
writable: true
};
return Object.defineProperties({}, descriptors);
}
const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
/**
* Historical default persistence policy for durable agent workflows.
*
* A persisted snapshot record supports both:
* - `resumeStream()` after a suspend (records with status
* `pending` / `paused` / `suspended`)
* - boot-time recovery of orphaned RUNNING runs after a process restart,
* via `DurableAgent.recoverActiveRuns()` — this requires the row to
* actually be stamped `running` while the loop is in-flight (issue #19056).
*
* The engine's persist path guards against overwriting a `suspended` /
* `paused` snapshot with a later `running` update from the same run (see
* `persistStepUpdate` in workflows/handlers/entry.ts), so it is safe to
* return true for `running` here.
*/
const defaultShouldPersistSnapshot = (params) => {
return params.workflowStatus === "pending" || params.workflowStatus === "paused" || params.workflowStatus === "suspended" || params.workflowStatus === "running";
};
/**
* Input schema for the durable agentic workflow.
* Extends base schema with model list for fallback support.
*/
const durableAgenticInputSchema = zod.z.object({
__workflowKind: zod.z.literal("durable-agent"),
runId: zod.z.string(),
agentId: zod.z.string(),
agentName: zod.z.string().optional(),
agentVersionId: zod.z.string().optional(),
messageListState: zod.z.any(),
toolsMetadata: zod.z.array(zod.z.any()),
modelConfig: modelConfigSchema,
modelList: zod.z.array(modelListEntrySchema).optional(),
scorers: zod.z.record(zod.z.string(), zod.z.any()).optional(),
options: durableOptionsSchema,
state: zod.z.any(),
messageId: zod.z.string(),
agentSpanData: zod.z.any().optional(),
modelSpanData: zod.z.any().optional(),
stepIndex: zod.z.number().optional(),
requestContextEntries: zod.z.record(zod.z.string(), zod.z.any()).optional(),
inputTripwire: baseIterationStateSchema.shape.inputTripwire
});
/**
* Schema for the iteration state that flows through the dowhile loop.
* Extends base schema with model list for fallback support.
*/
const iterationStateSchema = baseIterationStateSchema.extend({ modelList: zod.z.array(zod.z.any()).optional() });
/**
* Whether a reader that attaches mid-run can read the run's earlier events. Steps publish on the
* engine's bus, but `observe()` reads through the agent's own stream bus, which has no replay
* when the agent was created with `cache: false`; both have to keep the topic.
*/
function runTopicReplays(rt) {
const topic = require_run_registry.AGENT_STREAM_TOPIC(rt.runId);
if (!rt.pubsub?.__replaysTopic(topic)) return false;
return (Object.values(rt.mastra?.listAgents() ?? {}).find((registered) => registered.id === rt.agentId)?.pubsub)?.__replaysTopic?.(topic) ?? true;
}
/**
* Builds the durable agent loop on the shared `AgenticLoopBuilder` topology.
*
* The durable loop implements the same agentic loop pattern as the main loop
* (LLM execution → tool-call foreach → mapping → background check → signal
* drain → isTaskComplete → goal, wrapped in a dowhile) but flows all state
* through workflow input/output so it is durable across process restarts and
* execution engine replays.
*
* Migration status: every method is still a whole-method
* override delegating to the durable step files. As the shared cores land,
* these overrides shrink until only the runtime hooks remain (state
* resolution via registry + serialized `messageListState`, pubsub chunk
* transport, the evented `workflowFactory`, and snapshot policies).
*/
var DurableAgenticLoopBuilder = class extends require_run_registry.AgenticLoopBuilder {
#options;
#maxSteps;
#shouldPersistSnapshot;
constructor(options) {
super();
this.#options = options;
this.#maxSteps = options?.maxSteps ?? require_run_registry.DurableAgentDefaults.MAX_STEPS;
this.#shouldPersistSnapshot = options?.shouldPersistSnapshot ?? defaultShouldPersistSnapshot;
}
/**
* Engine selection: EventedAgent opts into the evented execution engine;
* DurableAgent stays on the default in-process engine.
*/
workflowFactory() {
return this.#options?.engine === "evented" ? require_run_registry.createEventedWorkflow : require_run_registry.createWorkflow;
}
/**
* Engine-aware snapshot pruning. The `running`-only history strip (#20747)
* keeps what a crash-restart reads back, including `stepResultReads`: steps
* that read an earlier step's result via `getStepResultAsync` (reader → sources).
* The evented engine also reads persisted step results during normal
* execution, but the only such reads are the declared ones below, so the
* strip keeps exactly what it reads. Retaining *all* terminal history instead
* (the old blanket `retainRunningHistory`) copied every completed step's
* payload/output and ballooned snapshots into a heap OOM on long runs
* (COR-1431). What remains then stores messages memory already holds as refs
* (see `dehydrateSnapshotTranscripts`).
*/
pruneSnapshotHook(stepResultReads = {}) {
return (args) => dehydrateSnapshotTranscripts(require_run_registry.pruneAgentLoopSnapshot({
...args,
stepResultReads
}));
}
/**
* Resolve the runtime from serialized iteration state + the run registry
* (see {@link DurableLoopRuntime}). Cross-process engines (e.g. Inngest
* after a worker restart) won't have a registry entry; every
* registry-derived field is then undefined and the loop falls back to
* maxSteps-only continuation.
*
* Callable from both the continuation predicate (inputData = iteration
* state) and steps inside the iteration workflow (inputData = an
* intermediate execution shape without run identity); the latter falls
* back to init data, which inside the iteration workflow is the iteration
* state itself.
*/
resolveRuntime(predicateParams) {
const state = predicateParams.inputData ?? {};
const initData = predicateParams.getInitData();
const mastra = predicateParams.mastra;
const runId = state.runId ?? initData.runId;
const registryEntry = require_run_registry.getRunRegistryEntry(runId, mastra);
const agentId = state.agentId ?? initData.agentId;
const pubsub = predicateParams[require_workflows_constants.PUBSUB_SYMBOL];
return {
runId,
agentId,
agentName: state.agentName ?? initData.agentName,
threadId: initData?.state?.threadId,
resourceId: initData?.state?.resourceId,
maxSteps: state.options?.maxSteps ?? initData.options?.maxSteps ?? this.#maxSteps,
mastra,
logger: mastra?.getLogger?.(),
abortSignal: registryEntry?.abortSignal,
stopWhen: registryEntry?.stopWhen,
onIterationComplete: registryEntry?.onIterationComplete,
drainPendingSignals: registryEntry?.drainPendingSignals,
pubsub: pubsub && require_run_registry.withExecutionStreamProducer(pubsub, {
runId,
agentId,
mastra,
claim: require_run_registry.getExecutionClaim(predicateParams.requestContext, runId)
})
};
}
/**
* TODO: always use pubsub, it's better
* Chunk transport: publish through pubsub instead of enqueueing onto a live
* stream controller. No-op when the run has no pubsub transport — callers
* that must not consume input without a transport (signal drain) guard on
* `pubsub` before draining.
*/
emitChunk(runtime, chunk) {
if (!runtime.pubsub) return;
return require_run_registry.emitChunkEvent(runtime.pubsub, runtime.runId, chunk);
}
llmExecutionStep() {
return createDurableLLMExecutionStep();
}
/** Each tool call runs as its own step with suspend support. */
toolCallStep() {
return createDurableToolCallStep();
}
llmMappingStep() {
return createDurableLLMMappingStep();
}
backgroundTaskCheckStep() {
return createDurableBackgroundTaskCheckStep();
}
/**
* Mirrors the non-durable `signalDrainStep` which drains signals queued
* during tool execution. Behavior lives in `drainSignalsToTranscript`
* (shared with the main loop); this override owns the
* serialization glue: the `MessageList` is materialized lazily from
* serialized state only once signals actually arrive (drain-first
* ordering), and re-serialized into the projected output. Signals are
* appended to the transcript even without a pubsub transport (`emitChunk`
* no-ops), matching prior behavior. Signals only queue in the process
* running the agent, so other processes skip the step.
*/
signalDrainStep() {
return require_run_registry.createStep$1({
id: `${require_run_registry.DurableStepIds.AGENTIC_EXECUTION}-signal-drain`,
inputSchema: zod.z.any(),
outputSchema: zod.z.any(),
execute: async (stepParams) => {
const execOutput = stepParams.inputData;
if (execOutput.stepResult?.signalPreempted && !execOutput.stepResult.isContinued) return execOutput;
const rt = this.resolveRuntime(stepParams);
if (!rt.drainPendingSignals) return execOutput;
try {
const messageListState = await readMessageListState(stepParams, execOutput);
let drainList;
const list = () => drainList ??= createRunMessageList({ mastra: rt.mastra }).deserialize(messageListState);
const outcome = await require_run_registry.drainSignalsToTranscript({
drainPendingSignals: rt.drainPendingSignals,
rotateResponseMessageId: (sealMessageId) => list().rotateResponseMessageId(sealMessageId),
addSignal: (signal) => list().addSignal(signal),
emitChunk: (chunk) => this.emitChunk(rt, chunk),
sealMessageId: execOutput.messageId,
errorPolicy: "best-effort",
logger: rt.logger
});
if (!outcome.drained || !drainList) return execOutput;
return {
...execOutput,
...await storeMessageListState(stepParams, drainList.serialize()),
messageId: outcome.nextMessageId,
stepResult: {
...execOutput.stepResult,
messageId: outcome.nextMessageId,
reason: "other",
isContinued: true
}
};
} catch {
return execOutput;
}
}
});
}
/**
* The isTaskComplete evaluation step (mirrors the non-durable
* createIsTaskCompleteStep). Lives as a real step (not predicate logic)
* so it shows up in workflow traces and produces a proper state transition.
*/
isTaskCompleteStep() {
return createDurableIsTaskCompleteStep(this.#maxSteps);
}
/**
* The goal evaluation step — mirrors the non-durable `createGoalStep`.
* Runs after isTaskComplete so the goal judge sees whether isTaskComplete
* already stopped the loop.
*/
goalStep() {
return createDurableGoalStep();
}
/**
* The single iteration workflow (LLM -> Tool Calls -> Mapping).
* Note: tool-call foreach concurrency is resolved per run at execution time
* (see resolveDurableToolCallConcurrency) — approval/suspend flows force
* sequential execution; otherwise the run's `toolCallConcurrency` applies.
* This deliberately differs from the main loop, which resolves concurrency
* once at loop build from the active tool set (#15978): the durable workflow
* graph is built once and shared across runs, so anything per-run must be a
* resolver evaluated at execution time.
*/
buildIterationWorkflow() {
const llmExecutionStep = require_run_registry.withExecutionFence(this.llmExecutionStep());
const toolCallStep = require_run_registry.withExecutionFence(this.toolCallStep());
const llmMappingStep = require_run_registry.withExecutionFence(this.llmMappingStep());
const backgroundTaskCheckStep = require_run_registry.withExecutionFence(this.backgroundTaskCheckStep());
const signalDrainStep = require_run_registry.withExecutionFence(this.signalDrainStep());
const isTaskCompleteStep = require_run_registry.withExecutionFence(this.isTaskCompleteStep());
const goalStep = require_run_registry.withExecutionFence(this.goalStep());
const executeLLM = llmExecutionStep.execute;
llmExecutionStep.execute = async (stepParams) => {
let written = {};
const params = withParams(stepParams, { setState: async (update) => {
written = {
...written,
...update
};
await stepParams.setState(written);
} });
const llmOutput = await executeLLM(params);
if (llmOutput && llmOutput.stepResult.reason === "abort") {
const initData = params.getInitData();
const executionOutput = await llmMappingStep.execute(withParams(params, {
bail: params.bail,
inputData: {
llmOutput,
toolResults: [],
runId: initData.runId,
agentId: initData.agentId,
messageId: initData.messageId,
state: llmOutput.state ?? initData.state
}
}));
if (!executionOutput) return executionOutput;
const { accumulatedSteps, ...update } = createBaseIterationStateUpdate({
currentState: {
...initData,
accumulatedSteps: await loadAccumulatedSteps(params, initData)
},
executionOutput
});
return params.bail({
...update,
...await storeAccumulatedSteps(params, accumulatedSteps),
modelList: initData.modelList
});
}
return llmOutput;
};
return this.workflowFactory()({
id: require_run_registry.DurableStepIds.AGENTIC_EXECUTION,
inputSchema: iterationStateSchema,
outputSchema: iterationStateSchema,
options: {
shouldPersistSnapshot: this.#shouldPersistSnapshot,
allowUnclaimedResumes: true,
isOwnershipLostError: require_run_registry.isExecutionFenceError,
isForeignExecution: require_run_registry.isForeignExecutionContext,
watchExecutionLoss: require_run_registry.watchExecutionLoss,
pruneSnapshot: this.pruneSnapshotHook({
[toolCallStep.id]: [llmExecutionStep.id],
[COLLECT_TOOL_RESULTS_STEP_ID]: [llmExecutionStep.id]
}),
validateInputs: false,
emitStepEvents: false,
sharePubsub: true,
autoRestartActiveRuns: false,
tracingPolicy: { internal: 1 }
}
}).map(async ({ inputData }) => {
const state = inputData;
return {
runId: state.runId,
agentId: state.agentId,
agentName: state.agentName,
messageListState: state.messageListState,
initialUntaggedSystemMessages: state.initialUntaggedSystemMessages,
toolsMetadata: state.toolsMetadata,
modelConfig: state.modelConfig,
modelList: state.modelList,
options: state.options,
state: state.state,
messageId: state.messageId,
requestContextEntries: state.requestContextEntries,
inputTripwire: state.inputTripwire,
stepIndex: state.iterationCount,
signalPreempted: state.lastStepResult?.signalPreempted,
accumulatedSteps: state.accumulatedSteps,
agentSpanData: state.agentSpanData,
modelSpanData: state.modelSpanData,
completionStartTime: state.completionStartTime,
timeToFirstTokenMs: state.timeToFirstTokenMs
};
}, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
const llmOutput = inputData;
return (llmOutput.toolCalls ?? []).map((toolCall) => ({
...toolCall,
stepSpanData: llmOutput.stepSpanData,
completionStartTime: llmOutput.completionStartTime,
timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,
stepUsage: llmOutput.stepResult?.totalUsage
}));
}, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
const state = getInitData();
return resolveDurableToolCallConcurrency({
options: state?.options,
toolsMetadata: state?.toolsMetadata,
toolCalls: inputData
});
} }).map(async ({ inputData, getStepResultAsync, getInitData }) => {
const toolResults = inputData;
const llmOutput = await getStepResultAsync(llmExecutionStep.id);
const initData = getInitData();
return {
llmOutput,
toolResults,
runId: initData.runId,
agentId: initData.agentId,
messageId: llmOutput?.stepResult?.messageId ?? initData.messageId,
state: llmOutput?.state ?? initData.state
};
}, { id: COLLECT_TOOL_RESULTS_STEP_ID }).then(llmMappingStep).then(backgroundTaskCheckStep).then(signalDrainStep).map(async (params) => {
const executionOutput = params.inputData;
const initData = params.getInitData();
const { accumulatedSteps, ...baseUpdate } = createBaseIterationStateUpdate({
currentState: {
...initData,
accumulatedSteps: await loadAccumulatedSteps(params, initData)
},
executionOutput
});
return {
...baseUpdate,
...await storeAccumulatedSteps(params, accumulatedSteps),
modelList: initData.modelList
};
}, { id: "update-iteration-state" }).then(isTaskCompleteStep).then(goalStep).commit();
}
/**
* The dowhile predicate: abort check, feedback two-phase stop, stopWhen
* evaluation, delegation bail, inter-iteration signal drain, the
* onIterationComplete hook, response-message boundary rotation, and the
* iteration-complete observability event.
*/
buildContinuationPredicate() {
return async (params) => {
const state = params.inputData;
const steps = await loadAccumulatedSteps(params, state);
const initData = params.getInitData();
const rt = this.resolveRuntime(params);
let transcript;
const emitStepFinish = async (isContinued) => {
if (state.lastStepResult) state.lastStepResult.isContinued = isContinued;
const deferredChunk = require_run_registry.buildDeferredStepFinishChunk({
...state,
accumulatedSteps: steps
}, isContinued);
state.deferredStepFinishChunk = void 0;
if (!deferredChunk) return;
let nextCursor;
try {
const list = createRunMessageList({ mastra: rt.mastra }).deserialize((transcript ?? await openMessageListState(params, state)).read());
const producer = require_run_registry.getExecutionClaim(params.requestContext, state.runId)?.executionId ?? `${state.runId}:${require_run_registry.currentRunGeneration(state.runId) ?? 0}`;
let cursor = state.responseMessagesCursor?.producer === producer ? state.responseMessagesCursor : { producer };
if ("fingerprints" in cursor && !runTopicReplays(rt)) cursor = {
...cursor,
fingerprints: []
};
const { diff, cursor: next } = require_run_registry.diffResponseMessages(cursor, list.get.response.aiV5.model());
deferredChunk.payload._durableResponseMessagesDiff = diff;
nextCursor = next;
} catch (error) {
rt.logger?.warn?.(`[DurableAgent] Could not rebuild step-finish messages: ${error}`);
}
try {
await this.emitChunk(rt, deferredChunk);
if (nextCursor) state.responseMessagesCursor = nextCursor;
} catch (error) {
rt.logger?.warn?.(`[DurableAgent] Failed to emit deferred step-finish: ${error}`);
if (nextCursor) state.responseMessagesCursor = {
...nextCursor,
fingerprints: []
};
}
};
if (rt.abortSignal?.aborted) {
const abortReason = require_stream.getAbortReason(rt.abortSignal);
const isTotalTimeout = require_stream.isMastraTimeoutError(abortReason) && abortReason.timeoutType === "total";
if (isTotalTimeout && state.lastStepResult?.reason !== "error") {
await emitStepFinish(true);
return true;
}
await emitStepFinish(state.lastStepResult?.isContinued === true);
if (state.lastStepResult) state.lastStepResult.reason = isTotalTimeout ? "error" : "abort";
return false;
}
transcript = await openMessageListState(params, state);
let drainForcedContinue = false;
if (rt.pubsub && rt.drainPendingSignals) try {
let drainList;
const list = () => drainList ??= createRunMessageList({ mastra: rt.mastra }).deserialize(transcript.read());
const drainOutcome = await require_run_registry.drainSignalsToTranscript({
drainPendingSignals: rt.drainPendingSignals,
rotateResponseMessageId: () => list().rotateResponseMessageId(),
addSignal: (signal) => list().addSignal(signal),
emitChunk: (chunk) => this.emitChunk(rt, chunk),
errorPolicy: "best-effort",
logger: rt.logger
});
if (drainOutcome.drained && drainList) {
state.messageId = drainOutcome.nextMessageId;
transcript.write(drainList.serialize());
if (state.lastStepResult) state.lastStepResult.isContinued = true;
drainForcedContinue = true;
}
} catch {}
if (state.lastStepResult?.signalPreempted) return state.lastStepResult.isContinued === true;
const runMaxSteps = rt.maxSteps;
let callbackListInstance;
const callbackList = () => {
if (!callbackListInstance) {
callbackListInstance = createRunMessageList({ mastra: rt.mastra });
try {
callbackListInstance.deserialize(transcript.read());
} catch {}
}
return callbackListInstance;
};
const stopWhen = rt.stopWhen ? (Array.isArray(rt.stopWhen) ? rt.stopWhen : [rt.stopWhen]).map((condition) => async (context) => {
try {
return await condition(context);
} catch (error) {
const originalError = require_error.getErrorFromUnknown(error);
throw require_run_registry.markNonRedeliverable(new require_error.MastraError({
id: require_run_registry.DURABLE_STOP_WHEN_ERROR_ID,
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: originalError.message,
details: {
name: originalError.name,
message: originalError.message
}
}, originalError));
}
}) : void 0;
const decision = await require_run_registry.decideContinuation({
policy: { mode: "durable" },
pendingFeedbackStop: state.pendingFeedbackStop ?? false,
llmWantsToContinue: state.lastStepResult?.isContinued === true || drainForcedContinue,
underMaxSteps: steps.filter((s) => s.finishReason !== "retry").length < runMaxSteps,
steps: require_run_registry.durableStopConditionSteps(steps),
stopWhen,
consumeDelegationBail: () => {
if (state.delegationBailed) {
state.delegationBailed = false;
return true;
}
return false;
},
backgroundTaskPending: state.backgroundTaskPending,
onIterationComplete: rt.onIterationComplete,
buildIterationContext: (isFinal) => {
const lastStep = steps[steps.length - 1];
return {
iteration: steps.length,
maxIterations: runMaxSteps,
text: lastStep?.text ?? "",
toolCalls: (lastStep?.toolCalls ?? []).map((tc) => ({
id: tc.toolCallId || tc.id || "",
name: tc.toolName || tc.name || "",
args: tc.args || {}
})),
toolResults: (lastStep?.toolResults ?? []).map((tr) => ({
id: tr.toolCallId || tr.id || "",
name: tr.toolName || tr.name || "",
result: require_message_list.normalizeToolOutput(tr.result).output,
error: tr.error
})),
isFinal,
finishReason: lastStep?.finishReason ?? "unknown",
runId: state.runId,
threadId: rt.threadId,
resourceId: rt.resourceId,
agentId: rt.agentId,
agentName: rt.agentName ?? rt.agentId,
messages: callbackList().get.all.db()
};
},
injectFeedback: (feedback) => {
const feedbackId = rt.mastra?.generateId?.() ?? globalThis.crypto?.randomUUID?.() ?? `msg_${Date.now()}`;
callbackList().add({
id: feedbackId,
createdAt: /* @__PURE__ */ new Date(),
type: "text",
role: "assistant",
content: {
parts: [{
type: "text",
text: feedback
}],
metadata: {
mode: "stream",
completionResult: { suppressFeedback: true }
},
format: 2
}
}, "response");
transcript.write(callbackList().serialize());
},
logger: rt.logger
}).catch(async (error) => {
if (error?.id !== "DURABLE_AGENT_STOP_WHEN_FAILED") await emitStepFinish(state.lastStepResult?.isContinued === true);
throw error;
});
state.pendingFeedbackStop = decision.nextPendingFeedbackStop;
state.tracingStopCause = decision.stopCause;
const tracingRegistry = require_run_registry.getRunRegistryEntry(state.runId, rt.mastra);
if (tracingRegistry) tracingRegistry.tracingStopCause = decision.stopCause;
const isFinal = decision.isFinal;
await emitStepFinish(!isFinal);
if (rt.pubsub) {
const lastStep = steps[steps.length - 1];
await require_run_registry.emitIterationCompleteEvent(rt.pubsub, state.runId, {
iteration: state.iterationCount,
maxIterations: runMaxSteps,
text: lastStep?.text,
toolCalls: lastStep?.toolCalls,
toolResults: lastStep?.toolResults,
isFinal,
finishReason: lastStep?.finishReason,
runId: state.runId,
threadId: rt.threadId,
resourceId: rt.resourceId,
agentId: initData.agentId,
agentName: initData.agentName
});
}
return !isFinal;
};
}
/**
* The outer loop workflow: init iteration state → dowhile(single iteration,
* continuation predicate) → finalize (output mapping, memory persistence,
* finish event, span closure) → fire-and-forget scorers.
*/
build() {
return this.workflowFactory()({
id: require_run_registry.DurableStepIds.AGENTIC_LOOP,
inputSchema: durableAgenticInputSchema,
outputSchema: durableAgenticOutputSchema,
options: {
shouldPersistSnapshot: this.#shouldPersistSnapshot,
allowUnclaimedResumes: true,
persistResumeClaim: true,
isOwnershipLostError: require_run_registry.isExecutionFenceError,
isForeignExecution: require_run_registry.isForeignExecutionContext,
watchExecutionLoss: require_run_registry.watchExecutionLoss,
pruneSnapshot: this.pruneSnapshotHook(),
autoStorageVersion: this.#options?.autoStorageVersion,
onFinish: ({ getInitData }) => {
releaseMessageListState({ getInitData });
},
validateInputs: false,
emitStepEvents: false,
autoRestartActiveRuns: false,
tracingPolicy: { internal: 1 }
}
}).map(async (params) => {
const { messageListState: inputMessageListState, ...input } = params.inputData;
const messageListState = await hydrateMessageListState(params, inputMessageListState);
const initialMessageList = createRunMessageList({ mastra: params.mastra }).deserialize(messageListState);
await params.setState({
accumulatedSteps: [],
messageListState: await dehydrateMessageListState(params, messageListState)
});
return {
...input,
initialUntaggedSystemMessages: initialMessageList.getSystemMessages(),
iterationCount: 0,
accumulatedUsage: {
inputTokens: 0,
outputTokens: 0,
totalTokens: 0
},
usageAggregationVersion: 1,
lastStepResult: void 0
};
}, { id: "init-iteration-state" }).dowhile(this.buildIterationWorkflow(), require_run_registry.markFrameworkCondition(this.buildContinuationPredicate())).map(async (params) => {
const { inputData, mastra, requestContext, tracingContext } = params;
const state = inputData;
const initData = params.getInitData();
const runPubsub = params[require_workflows_constants.PUBSUB_SYMBOL];
const pubsub = runPubsub && require_run_registry.withExecutionStreamProducer(runPubsub, {
runId: state.runId,
agentId: state.agentId,
mastra,
claim: require_run_registry.getExecutionClaim(requestContext, state.runId)
});
const logger = mastra?.getLogger?.();
const storedSteps = await loadAccumulatedSteps(params, state);
const steps = require_run_registry.expandDurableSteps(storedSteps);
const lastStep = storedSteps[storedSteps.length - 1];
let finalText = lastStep?.text;
const messageListState = await readMessageListState(params, state);
const finalMessageList = createRunMessageList({}).deserialize(messageListState);
const finishMessages = {
all: finalMessageList.get.all.aiV5.model(),
user: finalMessageList.get.input.aiV5.model(),
nonUser: finalMessageList.get.response.aiV5.model()
};
const finishResult = await runDurableFinishSideEffects({
runId: state.runId,
initData,
messageListState,
mastra,
requestContext,
tracingContext,
logger,
messageId: state.messageId,
outputResult: {
text: finalText ?? "",
usage: state.accumulatedUsage,
finishReason: state.lastStepResult?.reason ?? "unknown",
steps
}
});
const textRewritten = !!lastStep && finishResult.outputTextChanged;
if (lastStep && finishResult.outputTextChanged) {
lastStep.text = finishResult.outputText;
steps[steps.length - 1] = {
...steps[steps.length - 1],
text: finishResult.outputText
};
finalText = finishResult.outputText;
}
const tripwire = finishResult.tripwire;
if (pubsub && !tripwire) for (const chunk of finishResult.structuredOutputChunks ?? []) await require_run_registry.emitChunkEvent(pubsub, state.runId, {
...chunk,
runId: state.runId
});
if (pubsub) for (const chunk of finishResult.outputResultChunks ?? []) await require_run_registry.emitChunkEvent(pubsub, state.runId, chunk, true);
if (tripwire && pubsub) await require_run_registry.emitChunkEvent(pubsub, state.runId, {
type: "tripwire",
runId: state.runId,
from: "AGENT",
payload: tripwire
});
if (pubsub && !tripwire && finishResult.titleForStream) {
const title = await finishResult.titleForStream;
if (title && initData.state?.threadId) await require_run_registry.emitChunkEvent(pubsub, state.runId, {
type: "data-thread-title",
data: {
threadId: initData.state.threadId,
title
},
transient: true
});
}
const finalOutput = {
messageListState: finishResult.messageListState,
messageId: state.messageId,
stepResult: tripwire ? {
...state.lastStepResult ?? { warnings: [] },
reason: "tripwire",
isContinued: false
} : state.lastStepResult || {
reason: "stop",
warnings: [],
isContinued: false
},
output: {
text: finalText,
usage: state.accumulatedUsage,
steps: storedSteps
},
state: state.state
};
if (pubsub) await require_run_registry.emitFinishEvent(pubsub, state.runId, {
output: finalOutput.output,
stepResult: finalOutput.stepResult,
messages: finishMessages,
...textRewritten && { textRewritten }
});
await finishResult.titleGeneration;
try {
const observability = mastra?.observability?.getSelectedInstance({ requestContext });
const reg = require_run_registry.getRunRegistryEntry(initData.runId, mastra);
const modelSpanData = reg?.resumeModelSpanData ?? initData.modelSpanData;
const agentSpanData = reg?.resumeAgentSpanData ?? initData.agentSpanData;
const clocks = carriedSpanClocks(reg, state);
const finishReason = finalOutput.stepResult?.reason;
const stopCause = state.tracingStopCause ?? reg?.tracingStopCause;
const recordedTermination = state.tracingTermination ?? reg?.tracingTermination;
if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) logger?.warn?.(`[DurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : require_observability.agentLoopTermination({
stopCause,
delegationFailure: state.tracingDelegationFailure ?? reg?.tracingDelegationFailure,
finishReason,
tripwire: tripwire ?? state.lastStepResult?.tripwire,
maxSteps: initData.options?.maxSteps
});
if (observability) {
if (modelSpanData) {
const modelSpan = reg?.resumeModelSpan ?? reg?.modelSpan ?? observability.rebuildSpan(modelSpanData);
const toolCalls = steps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
toolCallId: tc.toolCallId,
toolName: tc.toolName,
args: tc.args
})));
const usageIncomplete = require_observability.isUsageIncomplete(state.accumulatedUsage);
modelSpan?.createTracker()?.endGeneration({
...termination,
output: {
text: finalText,
toolCalls: toolCalls.length ? toolCalls : void 0
},
attributes: {
finishReason: finalOutput.stepResult?.reason,
...usageIncomplete ? { usageIncomplete: true } : {},
...clocks,
responseId: state.lastResponse?.id,
responseModel: state.lastResponse?.modelId
},
usage: usageIncomplete ? require_observability.calculateObservedUsage(steps) : state.accumulatedUsage
});
}
if (agentSpanData) (reg?.resumeAgentSpan ?? reg?.agentSpan ?? observability.rebuildSpan(agentSpanData))?.end({
...termination,
output: { text: finalText },
...clocks ? { attributes: clocks } : {}
});
}
} catch (error) {
logger?.warn?.(`[DurableAgent] Error ending observability spans: ${error}`);
}
return finalOutput;
}, { id: MAP_FINAL_OUTPUT_STEP_ID }).map(async (params) => {
const { inputData, getInitData, mastra, requestContext, tracingContext } = params;
const initData = getInitData();
if (initData.scorers && Object.keys(initData.scorers).length > 0) try {
const [initial, final] = await Promise.all([hydrateMessageListState(params, initData.messageListState), hydrateMessageListState(params, inputData.messageListState)]);
executeDurableAgentScorers({
initData: {
...initData,
messageListState: initial
},
finalOutput: {
...inputData,
messageListState: final
},
mastra,
requestContext,
tracingContext,
loadStoredMessages: loadRunStoredMessages(params),
scorerInstances: require_run_registry.takeRunScorerInstances(initData.runId, mastra)
}).catch((error) => mastra?.getLogger?.()?.warn?.(`[DurableAgent] Skipped scorers: ${error}`));
} catch (error) {
mastra?.getLogger?.()?.warn?.(`[DurableAgent] Skipped scorers: ${error}`);
}
return inputData;
}, { id: "execute-scorers" }).commit();
}
};
// src/agent/durable/workflows/create-durable-agentic-workflow.ts
/**
* Composes the durable agentic workflow. The topology, workflow options, and
* continuation predicate live on `DurableAgenticLoopBuilder` (which shares its
* shape with the main loop's `AgenticLoopBuilder`); this wrapper preserves the
* existing call surface.
*
* Note: tools and model are resolved from Mastra at runtime, so this workflow
* is created once at startup and reused for all runs.
*/
function createDurableAgenticWorkflow(options) {
return new DurableAgenticLoopBuilder(options).build();
}
// src/agent/durable/execution-engine.ts
const unfencedStoresWarned = /* @__PURE__ */ new WeakSet();
var DurableExecutionEngine = class {
id;
mastra;
#workflow = null;
#resolvedWorkflowEngine = null;
#warnedPersistencePolicy = false;
/** Canceled parked runs whose abort terminal this process already published. */
#canceledRunTerminals = /* @__PURE__ */ new Set();
constructor(id, mastra) {
this.id = id;
this.mastra = mastra;
}
registerMastra(mastra) {
this.mastra = mastra;
}
get workflow() {
return this.#workflow;
}
raceFenceLoss(operation, executionFence) {
const lost = new Promise((_, reject) => executionFence.onLost(reject));
lost.catch(() => {});
return Promise.race([operation, lost]);
}
/**
* Record the abort of a parked run in shared storage, so a resume on any server
* refuses it. The in-process resume fence only covers this process. The status
* moves from `suspended` to `canceled` with a guarded write: a resume that claimed
* the run first has already moved it to `running`, and that run is stopped by the
* abort request instead. Stores that cannot enforce the guard atomically get the
* same check on a best-effort basis, so a finished or running run is never marked
* canceled. Stores without concurrent updates (some don't implement
* `updateWorkflowState`) get the canceled status by rewriting the run's snapshot,
* which every store supports. Resolves whether this call canceled the parked run.
* Storage errors propagate: an abort acknowledged without this write would not stop
* another server from resuming the run.
*/
async cancelParkedRun(runId) {
const workflowsStore = await this.mastra?.getStorage()?.getStore("workflows");
if (!workflowsStore) return false;
const workflowName = require_run_registry.DurableStepIds.AGENTIC_LOOP;
if (workflowsStore.supportsConcurrentUpdates()) {
if (await workflowsStore.loadWorkflowRunStatus({
workflowName,
runId
}) !== "suspended") return false;
return await workflowsStore.updateWorkflowState({
workflowName,
runId,
opts: {
status: "canceled",
expectedStatus: "suspended"
}
}) !== void 0;
}
const run = await workflowsStore.getWorkflowRunById({
runId,
workflowName
});
const snapshot = typeof run?.snapshot === "string" ? JSON.parse(run.snapshot) : run?.snapshot;
if (snapshot?.status !== "suspended") return false;
return await workflowsStore.persistWorkflowSnapshot({
workflowName,
runId,
resourceId: run?.resourceId,
snapshot: {
...snapshot,
status: "canceled"
},
expectedStatus: "suspended"
}) !== false;
}
/**
* Publish the abort terminal for a parked run this call just canceled. The bus is
* shared, so observers on every server close now, whichever server later refuses
* the approval. Only the call that won the cancel publishes. A failed publish does
* not undo the abort: the cancel is already stored, and a refused resume on this
* server retries the publish.
*/
async announceCanceledRun(runId, pubsub) {
try {
await this.publishCanceledRunTerminal(runId, pubsub);
} catch (error) {
this.mastra?.getLogger?.()?.warn?.(`Failed to publish the abort of canceled run ${runId}`, {
runId,
error
});
}
}
/**
* Publish the abort terminal of a canceled run once per process. Reserved before the
* publish, so concurrent callers publish once; released if the publish fails, so the
* next caller retries it.
*/
async publishCanceledRunTerminal(runId, pubsub) {
if (this.#canceledRunTerminals.has(runId)) return;
this.#canceledRunTerminals.add(runId);
if (this.#canceledRunTerminals.size > 1e3) this.#canceledRunTerminals.delete(this.#canceledRunTerminals.values().next().value);
try {
await require_run_registry.emitAbortEvent(pubsub, runId, {
steps: [],
text: ""
});
} catch (error) {
this.#canceledRunTerminals.delete(runId);
throw error;
}
}
async isRunCanceledInStorage(runId) {
return await (await this.mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowRunStatus({
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP,
runId
}) === "canceled";
}
async claimExecution(runId, mode, pubsub, logger, untrackedRun) {
return await require_run_registry.ExecutionFence.claim({
leaseProvider: require_run_registry.resolveLeaseProvider(pubsub),
workflowsStore: await this.mastra?.getStorage()?.getStore("workflows"),
agentId: this.id,
runId,
mode,
untrackedRun,
logger
});
}
async warnIfUnfenced(store, domain, guardrailLogger) {
if (!store || await require_run_registry.supportsRunFencing(store).catch(() => true)) return false;
if (unfencedStoresWarned.has(store)) return true;
unfencedStoresWarned.add(store);
const consequence = domain === "workflows" ? `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.` : `When recovery takes a run over, the memory writes (messages, threads, working memory) of the execution that lost it are not rejected.`;
guardrailLogger?.warn(`DurableAgent '${this.id}': the ${domain} store (${store.constructor.name}) can't fence run writes. ${consequence} Use a storage adapter that supports run fencing.`);
return true;
}
fenceRunPubSub(executionFence, abortController, pubsub, workflowEngine, logger) {
if (executionFence) pubsub = require_run_registry.withExecutionStreamProducer(pubsub, {
runId: executionFence.runId,
agentId: this.id,
mastra: this.mastra,
claim: executionFence.claim
});
if (!executionFence || this.resolveWorkflowEngine(workflowEngine, logger) !== "default") return pubsub;
executionFence.onLost((error) => {
if (abortController && !abortController.signal.aborted) abortController.abort(error);
});
return require_run_registry.fencePubSub(pubsub, executionFence);
}
async deleteRunSnapshots(runId, workflow) {
try {
await workflow.deleteWorkflowRunById(runId);
await (await this.mastra?.getStorage()?.getStore("workflows"))?.deleteWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_EXECUTION
});
} catch (error) {
this.mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to delete workflow snapshot rows after terminal state`, {
runId,
error
});
}
}
resolveWorkflowEngine(workflowEngine, logger) {
if (this.#resolvedWorkflowEngine) return this.#resolvedWorkflowEngine;
let engine = workflowEngine;
if (engine === "evented" && !this.mastra) {
engine = "default";
logger.warn(`EventedAgent '${this.id}' has no Mastra host; running on the default in-process engine. Register the agent on a Mastra instance (with storage) to get evented execution.`);
} else if (engine === "evented") {
const storage = this.mastra?.getStorage();
const workflowsStore = storage?.stores?.workflows;
if (workflowsStore && !(workflowsStore.supportsConcurrentUpdates?.() ?? false)) {
engine = "default";
logger.warn(`EventedAgent '${this.id}' is registered with ${storage?.name ?? "a"} storage, which does not apply concurrent workflow updates atomically (\`supportsConcurrentUpdates()\`); running the durable loop on the default in-process engine instead. In-flight runs will not resume on their own after a process restart. Use a storage adapter that supports atomic concurrent updates (for example @mastra/libsql, @mastra/pg or @mastra/mysql) to get evented execution.`);
}
}
this.#resolvedWorkflowEngine = engine;
return engine;
}
async ensureEngineWorkersStarted(workflowEngine, logger) {
if (this.resolveWorkflowEngine(workflowEngine, logger) === "evented") await this.mastra?.__ensureExecutionWorkersStarted();
}
createWorkflow(options) {
return createDurableAgenticWorkflow({
maxSteps: options.maxSteps,
engine: this.resolveWorkflowEngine(options.workflowEngine, options.logger),
shouldPersistSnapshot: this.resolveShouldPersistSnapshot(options.shouldPersistSnapshot),
autoStorageVersion: options.storesRunsInJournal
});
}
recoveryAwarePersistencePolicy = ({ workflowStatus }) => {
return workflowStatus === "pending" || workflowStatus === "paused" || workflowStatus === "suspended" || workflowStatus === "running" && (this.mastra?.recoveryConfig?.durableAgents === "auto" || this.mastra?.__shuttingDown === true);
};
getWorkflow(options) {
if (!this.#workflow) {
this.#workflow = this.createWorkflow(options);
this.warnOnRiskyPersistencePolicy(options.shouldPersistSnapshot, options.guardrailLogger);
if (this.mastra) {
this.#workflow.__registerMastra(this.mastra);
this.#workflow.__registerPrimitives({
logger: this.mastra.getLogger(),
storage: this.mastra.getStorage()
});
if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
}
}
return this.#workflow;
}
warnOnRiskyPersistencePolicy(predicate, guardrailLogger) {
if (this.#warnedPersistencePolicy) return;
this.#warnedPersistencePolicy = true;
if (!predicate) return;
const probe = (workflowStatus) => {
try {
return predicate({
workflowStatus,
stepResults: {}
});
} catch {
return true;
}
};
if (!probe("suspended") || !probe("paused")) guardrailLogger?.warn(`DurableAgent '${this.id}': the custom shouldPersistSnapshot policy does not persist 'suspended'/'paused' snapshots. Suspended runs cannot be resumed — human-in-the-loop flows will break.`);
if (this.mastra?.recoveryConfig?.durableAgents === "auto" && !probe("running")) guardrailLogger?.warn(`DurableAgent '${this.id}': recovery.durableAgents is 'auto' but the custom shouldPersistSnapshot policy does not persist 'running' snapshots. In-flight runs of this agent are invisible to crash recovery (listActiveRuns/recoverActiveRuns).`);
}
workflowFailureError(workflowError, fallbackMessage) {
const serialized = workflowError ?? {};
if (serialized.code === "DURABLE_AGENT_STOP_WHEN_FAILED" || serialized.id === "DURABLE_AGENT_STOP_WHEN_FAILED") {
const error = new Error(typeof serialized.details?.message === "string" ? serialized.details.message : typeof serialized.message === "string" ? serialized.message : fallbackMessage);
error.name = typeof serialized.details?.name === "string" ? serialized.details.name : "Error";
return require_run_registry.markErrorForStreamRejection(error);
}
return new Error(typeof serialized.message === "string" ? serialized.message : fallbackMessage);
}
workflowExecutionError(workflowError, fallbackMessage) {
const serialized = workflowError ?? {};
if (serialized.code === "DURABLE_AGENT_STOP_WHEN_FAILED" || serialized.id === "DURABLE_AGENT_STOP_WHEN_FAILED") return this.workflowFailureError(workflowError, fallbackMessage);
return require_error.getErrorFromUnknown(workflowError, { fallbackMessage });
}
async loadRunSnapshot(runId) {
const persisted = await (await this.mastra?.getStorage()?.getStore("workflows"))?.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
return typeof persisted?.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted?.snapshot;
}
createRun(workflow, options) {
return workflow.createRun(options);
}
releaseRun(workflow, runId, run, status) {
if (status !== "suspended" && workflow.runs.get(runId) === run) workflow.runs.delete(runId);
}
finishExecution(_runId, _executionFence, _sharedExecution, completion) {
if ("error" in completion) return {
owner: "agent",
error: this.workflowExecutionError(completion.error, "Workflow execution failed")
};
return {
owner: "agent",
status: completion.result?.status,
error: completion.result?.status === "failed" ? this.workflowFailureError(completion.result.error, "Workflow execution failed") : void 0
};
}
startRun(run, workflowInput, requestContext, observabilityContext) {
return run.start({
inputData: workflowInput,
requestContext,
actor: workflowInput.options?.actor,
...observabilityContext
});
}
resolveShouldPersistSnapshot(predicate) {
return predicate ?? this.recoveryAwarePersistencePolicy;
}
prepareExecution(_pubsub, _fence, _workflowEngine, _logger, _guardrailLogger) {
return {
sharedExecution: false,
usesRunPubSub: true
};
}
};
// src/agent/durable/persist-run-input.ts
/**
* Save the run's accepted input to memory through its in-process registry
* entry, before the run starts. No-op when the entry lacks memory or a message
* list, the thread is unknown, memory is read-only, or an input processor
* tripped the run.
* @internal
*/
async function persistDurableRunInput(runId, workflowInput, mastra) {
const entry = require_run_registry.getRunRegistryEntry(runId, mastra);
const state = workflowInput.state;
if (!entry?.saveQueueManager || !entry.memory || !entry.messageList || !state?.threadId || !state.resourceId || state.memoryConfig?.readOnly || entry.tripwire) return;
const requestContext = entry.requestContext;
await authorizeDurableMemory(getDurableMemoryAuthorizationChecks(entry), {
mastra,
user: requestContext?.get("user"),
threadId: state.threadId,
resourceId: state.resourceId,
agentId: workflowInput.agentId,
requestContext,
permission: require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_WRITE,
actor: workflowInput.options?.actor
});
const inputCopy = entry.messageList.clone();
await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {
throwOnError: true,
beforePersist: () => require_run_registry.assertExecutionOwned({
runId,
agentId: workflowInput.agentId,
mastra,
requestContext
})
});
const embedded = entry.messageList.getEmbeddedMessages();
for (const [messageId, textHash] of inputCopy.getEmbeddedMessages()) embedded.set(messageId, textHash);
}
// src/agent/durable/preparation.ts
/**
* Mirror of Agent#convertInstructionsToString — used for the AGENT_RUN span
* `attributes.instructions` field so durable runs publish the same shape as
* non-durable runs. Kept local to avoid promoting the private method.
*/
function convertInstructionsToString(instructions) {
if (!instructions) return "";
if (typeof instructions === "string") return instructions;
if (Array.isArray(instructions)) return instructions.map((msg) => typeof msg === "string" ? msg : typeof msg.content === "string" ? msg.content : "").filter(Boolean).join("\n\n");
return typeof instructions.content === "string" ? instructions.content : "";
}
/**
* Extract signal messages already present in the messageList at run start
* (from persisted history) so they can be echoed as data-signal stream parts
* on the first LLM step. Mirrors `prepare-memory-step.ts#getInitialSignalEchoes`.
*/
function getInitialSignalEchoes(messageList) {
const inputMessageIds = messageList.makeMessageSourceChecker().input;
return messageList.get.all.db().filter((message) => message.role === "signal" && inputMessageIds.has(message.id)).map(require_signals.mastraDBMessageToSignal);
}
/**
* Prepare for durable agent execution.
*
* This function performs the non-durable preparation phase:
* 1. Generates run ID and message ID
* 2. Resolves thread/memory context
* 3. Creates MessageList with instructions and messages
* 4. Converts tools to CoreTool format
* 5. Gets the model configuration
* 6. Creates serialized workflow input
* 7. Creates run registry entry for non-serializable state
*
* The result includes both the serialized workflow input (for the durable
* workflow) and the run registry entry (for non-serializable state).
*/
async function prepareForDurableExecution(options) {
const { agent, messages, options: rawExecOptions, optionsAreResolved = false, resolvedDefaultOptions, scopesResolved = false, resumedSpanData, runId: providedRunId, requestContext: providedRequestContext, logger, mastra, methodType = "stream", durableAgentId, durableAgentName } = options;
const publicAgentId = durableAgentId ?? agent.id;
const publicAgentName = durableAgentName ?? agent.name ?? agent.id;
const typedAgent = agent;
const runId = providedRunId ?? crypto.randomUUID();
const messageId = crypto.randomUUID();
let requestContext = providedRequestContext ?? new require_request_context.RequestContext();
if (typedAgent.requestContextSchema) {
const contextValues = require_tool.getRequestContextInputValues(requestContext);
const validation = await typedAgent.requestContextSchema["~standard"].validate(contextValues);
if (validation.issues) {
const errorMessages = validation.issues.map((e) => {
return `- ${e.path?.map((p) => typeof p === "object" ? p.key : p).join(".")}: ${e.message}`;
}).join("\n");
throw new require_error.MastraError({
id: "AGENT_REQUEST_CONTEXT_VALIDATION_FAILED",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `Request context validation failed for agent '${publicAgentId}':\n${errorMessages}`,
details: {
agentId: publicAgentId,
agentName: publicAgentName
}
});
}
}
let defaultOptions = resolvedDefaultOptions;
const loadDefaultOptions = async () => defaultOptions ??= await typedAgent.getDefaultOptions({ requestContext }) ?? {};
let execOptions = optionsAreResolved ? rawExecOptions ?? {} : require_utils.deepMerge(require_run_registry.withDefaultToolCallConcurrencyLimit(await loadDefaultOptions(), rawExecOptions), rawExecOptions ?? {});
const callScopes = "callScopes" in options ? options.callScopes : rawExecOptions?.scopes;
if (!scopesResolved) {
const defaultScopes = (await loadDefaultOptions()).scopes ?? [];
const incoming = require_run_registry.incomingAgentScopes({
requestContext,
callScopes,
defaultScopes,
mastra
});
const agentScopes = typedAgent.getScopes ? await typedAgent.getScopes({
requestContext,
scopes: incoming
}) : incoming;
if (agentScopes.length || callScopes?.length || requestContext.has("mastra__scopes")) {
const resolved = require_run_registry.resolveAgentScopes({
requestContext,
agentScopes,
incomingScopes: incoming,
callScopes,
memory: execOptions.memory,
mastra
});
execOptions = require_run_registry.applyResolvedAgentScopes({
...execOptions,
requestContext
}, resolved, requestContext);
requestContext = execOptions.requestContext ?? requestContext;
}
}
require_run_registry.validateModelTimeoutSettings(execOptions.modelSettings?.timeout);
if (execOptions.eagerToolExecution) throw new Error("eagerToolExecution is not supported by durable agents");
const requestVersions = requestContext.get(require_request_context.MASTRA_VERSIONS_KEY);
let mergedVersions = require_request_context.mergeVersionOverrides(mastra?.getVersionOverrides?.(), requestVersions);
if (execOptions?.versions) mergedVersions = require_request_context.mergeVersionOverrides(mergedVersions, execOptions.versions);
if (mergedVersions) requestContext.set(require_request_context.MASTRA_VERSIONS_KEY, mergedVersions);
const { model, modelList, fallbackTimeouts } = await typedAgent.__getModelAndModelList({
requestContext,
model: execOptions.model
});
if (!model) throw new Error("Agent model not available");
for (const timeout of fallbackTimeouts) require_run_registry.validateModelTimeoutSettings(timeout);
const thread = typeof execOptions?.memory?.thread === "string" ? { id: execOptions.memory.thread } : execOptions?.memory?.thread;
const threadId = thread?.id;
const resourceId = execOptions?.memory?.resource;
let threadObject;
let threadExists = false;
const messageList = new require_message_list.MessageList({
threadId,
resourceId
});
const instructions = execOptions?.instructions || await typedAgent.getInstructions({ requestContext });
if (instructions) {
if (typeof instructions === "string") messageList.addSystem(instructions);
else if (Array.isArray(instructions)) for (const inst of instructions) messageList.addSystem(inst);
else messageList.addSystem(instructions);
}
const workspace = await typedAgent.getWorkspace({ requestContext });
if (workspace) {
const hasFs = typeof workspace.hasFilesystemConfig === "function" ? workspace.hasFilesystemConfig() : !!workspace.filesystem;
const hasSb = typeof workspace.hasSandboxConfig === "function" ? workspace.hasSandboxConfig() : !!workspace.sandbox;
if (hasFs || hasSb) {
const wsInstructions = typeof workspace.getInstructionsAsync === "function" ? await workspace.getInstructionsAsync({ requestContext }) : workspace.getInstructions({ requestContext });
if (wsInstructions) messageList.addSystem({
role: "system",
content: wsInstructions
});
}
}
if (execOptions?.context) messageList.add(execOptions.context, "context");
if (execOptions?.system) {
const sys = execOptions.system;
if (typeof sys === "string") messageList.addSystem(sys);
else if (Array.isArray(sys)) for (const s of sys) messageList.addSystem(s);
else messageList.addSystem(sys);
}
messageList.add(messages, "input");
const memory = await typedAgent.getMemory({ requestContext });
const memoryConfig = execOptions?.memory?.options;
const memoryAuthorizationChecks = /* @__PURE__ */ new Map();
const authorizeMemory = (permission) => authorizeDurableMemory(memoryAuthorizationChecks, {
mastra,
user: requestContext.get("user"),
threadId,
resourceId,
agentId: publicAgentId,
requestContext,
permission,
actor: execOptions?.actor
});
if (memory && threadId && resourceId) {
await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_READ);
const existingThread = await memory.getThreadById({ threadId });
if (existingThread) require_run_registry.assertThreadOwnedByResource({
thread: existingThread,
resourceId,
agentName: publicAgentName
});
else await authorizeMemory(require_ee_iTj2bRDt.MastraFGAPermissions.MEMORY_WRITE);
threadObject = existingThread ?? await memory.createThread({
threadId,
metadata: thread?.metadata,
title: thread?.title,
memoryConfig,
resourceId,
saveThread: true
});
threadExists = true;
requestContext.set("MastraMemory", {
thread: threadObject,
resourceId,
memoryConfig
});
} else requestContext.delete("MastraMemory");
const processorStates = /* @__PURE__ */ new Map();
let inputProcessors = [];
let llmRequestInputProcessors = [];
let outputProcessors = [];
let errorProcessors = [];
let hasConfiguredErrorProcessors = false;
inputProcessors = await typedAgent.listInputProcessors(requestContext);
outputProcessors = execOptions?.outputProcessors ? execOptions.outputProcessors : await typedAgent.listOutputProcessors(requestContext);
({errorProcessors, hasConfiguredErrorProcessors} = await typedAgent.__resolveRunErrorProcessors(requestContext, execOptions?.errorProcessors));
llmRequestInputProcessors = await typedAgent.__listLLMRequestProcessors(requestContext, errorProcessors);
const resolvedVersionId = (typeof agent.toRawConfig === "function" ? agent.toRawConfig() : void 0)?.resolvedVersionId;
const agentTracingPolicy = typeof agent.getTracingPolicy === "function" ? agent.getTracingPolicy() : void 0;
const startingSignal = require_signals.signalSpanAttributes(messages);
const { agentSpanData, modelSpanData } = resumedSpanData ?? {};
const agentSpanId = agentSpanData?.id;
const resumedObservability = typeof agentSpanId === "string" && agentSpanId !== "no-op" ? mastra?.observability?.getSelectedInstance({ requestContext }) : void 0;
let resumedSpans;
if (resumedSpanData) {
resumedSpans = {};
try {
resumedSpans.agentSpan = resumedObservability?.rebuildSpan(agentSpanData);
if (modelSpanData) resumedSpans.modelSpan = resumedObservability?.rebuildSpan(modelSpanData);
} catch (error) {
resumedSpans = {};
(logger ?? mastra?.getLogger?.())?.warn?.(`[DurableAgent] Failed to rebuild the spans of run ${runId}: ${error}`);
}
}
const agentSpan = resumedSpans ? resumedSpans.agentSpan : require_utils$1.getOrCreateSpan({
type: "agent_run",
outcome: null,
name: `agent run: '${publicAgentId}'`,
entityType: require_storage.EntityType.AGENT,
entityId: publicAgentId,
entityName: publicAgentName,
input: messages,
attributes: {
conversationId: threadId,
instructions: convertInstructionsToString(instructions),
...require_run_registry.modelSpanAttributes(model),
...startingSignal ? { signal: startingSignal } : {},
...resolvedVersionId ? { resolvedVersionId } : {}
},
metadata: {
runId,
resourceId,
threadId,
...resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}
},
tracingPolicy: agentTracingPolicy,
tracingContext: execOptions?.tracingContext,
tracingOptions: execOptions?.tracingOptions,
requestContext,
mastra
});
let tripwireData;
if (inputProcessors.length > 0) try {
const { ProcessorRunner } = await Promise.resolve().then(() => require("../../stream-hnlwNJ12.cjs")).then((n) => n.runner_exports);
await new ProcessorRunner({
inputProcessors,
outputProcessors,
errorProcessors,
logger,
agentName: publicAgentName,
agent,
processorStates
}).runInputProcessors(messageList, require_observability.createObservabilityContext({ currentSpan: agentSpan }), requestContext, 0);
} catch (error) {
if (error instanceof require_stream.TripWire) {
tripwireData = {
reason: error.message,
retry: error.options?.retry,
metadata: error.options?.metadata,
processorId: error.processorId
};
logger?.warn?.("Input processor tripwire triggered", {
agent: publicAgentName,
reason: error.message,
processorId: error.processorId,
retry: error.options?.retry
});
} else {
const inputProcessorError = new require_error.MastraError({
id: "AGENT_INPUT_PROCESSOR_ERROR",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `[Agent:${publicAgentName}] - Input processor error`
}, error);
if (!resumedSpans) agentSpan?.error({
error: inputProcessorError,
...require_observability.executionFailureTermination(inputProcessorError),
endTree: true
});
throw inputProcessorError;
}
}
let requestContextEntriesSnapshot = require_run_registry.snapshotRequestContextEntries(requestContext);
if (!Array.isArray(requestContextEntriesSnapshot?.["mastra__scopes"])) requestContextEntriesSnapshot = {
...requestContextEntriesSnapshot,
[require_request_context.MASTRA_SCOPES_KEY]: []
};
if (requestVersions !== void 0) {
const requestVersionsJson = require_utils_safe_stringify.boundedStringify(requestVersions);
if (requestVersionsJson !== void 0) requestContextEntriesSnapshot = {
...requestContextEntriesSnapshot,
[require_request_context.MASTRA_VERSIONS_KEY]: JSON.parse(requestVersionsJson)
};
}
const backgroundTasksConfig = typedAgent.getBackgroundTasksConfig?.();
const backgroundTaskManager = execOptions?.disableBackgroundTasks || execOptions?.backgroundTaskPolicy?.allowToolDispatch === false ? void 0 : mastra?.backgroundTaskManager;
let tools = {};
try {
tools = await typedAgent.getToolsForExecution({
toolsets: execOptions?.toolsets,
clientTools: execOptions?.clientTools,
threadId,
resourceId,
runId,
requestContext,
memoryConfig: execOptions?.memory?.options,
autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,
hooks: execOptions?.hooks,
delegation: execOptions?.delegation,
methodType,
backgroundTaskEnabled: Boolean(backgroundTaskManager),
backgroundTaskPolicy: execOptions?.backgroundTaskPolicy,
model
});
} catch (error) {
logger?.warn?.(`[DurableAgent] Error converting tools: ${error}`);
}
if (!tripwireData) {
await require_run_registry.fireClientToolOutputHooks({
messages,
tools,
abortSignal: execOptions?.abortSignal,
logger
});
await require_run_registry.applyClientToolModelOutput({
messageList,
tools,
logger
});
}
const overrideScorers = execOptions?.scorers;
let scorers;
if (overrideScorers) scorers = overrideScorers;
else try {
const agentScorers = await typedAgent.listScorers({ requestContext });
if (agentScorers && Object.keys(agentScorers).length > 0) scorers = agentScorers;
} catch (error) {
logger?.debug?.(`[DurableAgent] Error getting scorers: ${error}`);
}
if (scorers) require_run_registry.setRunScorerInstances(runId, Object.fromEntries(Object.entries(scorers).flatMap(([key, entry]) => entry?.scorer && typeof entry.scorer === "object" ? [[key, entry.scorer]] : [])), mastra);
const saveQueueManager = memory ? new require_run_registry.SaveQueueManager({
logger,
memory,
onSaved: recordRunSavedMessages(runId)
}) : void 0;
let serializedStructuredOutput;
const nullToUndefined = Boolean(execOptions?.structuredOutput?.schema) && !(execOptions?.structuredOutput)?.model && (modelList ?? [{
model,
providerOptions: void 0
}]).some((candidate) => needsNullToUndefined(candidate.model, require_run_registry.mergeProviderOptions(execOptions?.providerOptions, candidate.providerOptions)));
const structuredOutputSchema = execOptions?.structuredOutput?.schema ? toLiveStructuredOutputSchema(execOptions.structuredOutput.schema, nullToUndefined) : void 0;
if (execOptions?.structuredOutput) {
const so = execOptions.structuredOutput;
if (structuredOutputSchema) serializedStructuredOutput = {
jsonPromptInjection: so.jsonPromptInjection,
instructions: so.instructions,
useAgent: so.useAgent,
hasStructuringModel: so.model ? true : void 0,
nullToUndefined: nullToUndefined ? true : void 0,
structuringModelConfig: typeof so.model === "string" ? {
provider: so.model.split("/")[0] ?? "",
modelId: so.model,
originalConfig: so.model
} : so.model && typeof so.model.provider === "string" && typeof so.model.modelId === "string" ? serializeModelConfig(so.model) : void 0,
errorStrategy: so.errorStrategy,
fallbackValue: isJsonSafe(so.fallbackValue) ? so.fallbackValue : void 0,
schema: require_stream.asJsonSchema(structuredOutputSchema)
};
}
const toolPayloadTransform = require_payload_transform.normalizeToolPayloadTransformPolicy(execOptions?.transform) ?? typedAgent.getToolPayloadTransform?.() ?? require_payload_transform.normalizeToolPayloadTransformPolicy(mastra?.getToolPayloadTransform?.() ?? mastra?.getToolPayloadProjection?.());
const savePerStep = execOptions?.savePerStep;
const observationalMemory = require_stream.isObservationalMemoryEnabled(memoryConfig?.observationalMemory);
if (execOptions.isTaskComplete) await loadDefaultOptions();
const modelSpan = resumedSpans ? resumedSpans.modelSpan : agentSpan?.createChildSpan({
type: "model_generation",
outcome: null,
name: `llm: '${model.modelId}'`,
attributes: {
model: model.modelId,
provider: model.provider,
streaming: true
},
metadata: {
runId,
threadId,
resourceId
},
requestContext
});
return {
runId,
messageId,
workflowInput: createWorkflowInput({
runId,
agentId: publicAgentId,
agentName: publicAgentName,
agentVersionId: resolvedVersionId,
messageList,
tools,
model,
modelList: modelList ?? void 0,
scorers,
options: {
clientTools: serializeClientTools(execOptions?.clientTools, tools),
toolsetToolNames: serializeToolsetToolNames(execOptions?.toolsets),
maxSteps: execOptions?.maxSteps,
toolChoice: execOptions?.toolChoice,
activeTools: execOptions?.activeTools,
modelSettings: execOptions?.modelSettings,
agentMaxRetries: typedAgent.maxRetries,
agentMaxRetriesConfigured: typedAgent.__getMaxRetriesConfigured?.() ?? false,
requireToolApproval: typeof execOptions?.requireToolApproval === "function" ? true : execOptions?.requireToolApproval,
toolCallConcurrency: execOptions?.toolCallConcurrency,
autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,
maxProcessorRetries: execOptions?.maxProcessorRetries ?? typedAgent.__getMaxProcessorRetries?.(),
includeRawChunks: execOptions?.includeRawChunks,
returnScorerData: execOptions?.returnScorerData,
hasErrorProcessors: hasConfiguredErrorProcessors,
emptyErrorProcessorOverride: execOptions?.errorProcessors?.length === 0 ? true : void 0,
providerOptions: execOptions?.providerOptions,
structuredOutput: serializedStructuredOutput,
skipBgTaskWait: execOptions?._skipBgTaskWait,
disableBackgroundTasks: execOptions?.disableBackgroundTasks,
backgroundTaskPolicy: execOptions?.backgroundTaskPolicy,
tracingOptions: execOptions?.tracingOptions,
actor: execOptions?.actor,
instructionsOverride: execOptions?.instructions,
systemMessage: execOptions?.system,
transform: toolPayloadTransform?.targets ? { targets: toolPayloadTransform.targets } : void 0,
isTaskComplete: execOptions?.isTaskComplete ? {
fromAgentDefaults: (() => {
const configured = defaultOptions?.isTaskComplete;
const active = execOptions.isTaskComplete;
return !!configured && !!active.scorers && !!configured.scorers && active.scorers.length === configured.scorers.length && active.scorers.every((scorer, index) => scorer === configured.scorers?.[index]) && active.onComplete === configured.onComplete;
})(),
scorerIds: execOptions.isTaskComplete.scorers?.map((s) => s.id),
scorerNames: execOptions.isTaskComplete.scorers?.map((s) => s.name).filter((n) => !!n),
strategy: execOptions.isTaskComplete.strategy,
timeout: execOptions.isTaskComplete.timeout,
parallel: execOptions.isTaskComplete.parallel,
suppressFeedback: execOptions.isTaskComplete.suppressFeedback
} : void 0
},
state: {
memoryConfig,
threadId,
resourceId,
threadExists,
savePerStep,
observationalMemory,
fixedMemory: typedAgent.__hasFixedMemory()
},
messageId,
agentSpanData: agentSpan?.snapshot?.() ?? agentSpan?.exportSpan(),
modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
requestContextEntries: requestContextEntriesSnapshot,
inputTripwire: tripwireData
}),
registryEntry: {
mastra,
tools,
requestTools: tools,
methodType,
saveQueueManager,
memory,
memoryAuthorizationChecks,
model,
modelList: modelList ? modelList.map((entry) => ({
id: entry.id,
model: entry.model,
maxRetries: entry.maxRetries ?? 0,
enabled: entry.enabled ?? true,
headers: entry.headers
})) : void 0,
workspace,
requestContext,
mcp: execOptions?.mcp,
inputProcessors,
llmRequestInputProcessors,
outputProcessors,
errorProcessors,
processorStates,
agent,
backgroundTaskManager,
backgroundTasksConfig,
agentSpan,
modelSpan,
stopWhen: execOptions?.stopWhen,
onIterationComplete: execOptions?.onIterationComplete,
prepareStep: execOptions?.prepareStep,
toolPayloadTransform,
isTaskComplete: execOptions?.isTaskComplete,
requireToolApproval: execOptions?.requireToolApproval,
delegation: execOptions?.delegation,
drainPendingSignals: (scope) => typedAgent.__getDrainPendingSignals()(runId, scope),
subscribePendingSignals: (listener) => typedAgent.__getSubscribePendingSignals()(runId, listener),
enqueuePendingSignal: (signalInput) => typedAgent.__getEnqueuePendingSignal()({
runId,
resourceId,
threadId
}, signalInput),
generateThreadTitle: memory ? async (args) => generateDurableThreadTitle({
agent,
memory,
...args
}) : void 0,
streamThreadTitle: methodType === "stream" && !!memory && !!agent.resolveTitleGenerationConfig(memory.getMergedThreadConfig(memoryConfig).generateTitle).emitEvent,
onTitleGenerated: execOptions?.memory?.onTitleGenerated,
initialSignalEchoes: getInitialSignalEchoes(messageList),
goal: agent.__getGoalConfig(),
tripwire: tripwireData,
callTimeHeaders: extractCallTimeHeaders(execOptions?.modelSettings),
timeoutTotalMs: (execOptions?.modelSettings)?.timeout?.totalMs,
structuredOutput: structuredOutputSchema ? {
...execOptions.structuredOutput,
schema: structuredOutputSchema
} : void 0,
returnScorerData: execOptions?.returnScorerData,
cleanup: () => {}
},
messageList,
threadId,
resourceId
};
}
/**
* Extract string-valued headers from `modelSettings.headers` for storage on the
* in-process `RunRegistryEntry`. Returns `undefined` when no valid headers are
* present so the registry slot stays empty rather than carrying an empty object.
*/
function extractCallTimeHeaders(modelSettings) {
const raw = modelSettings?.headers;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
const headers = {};
for (const [key, value] of Object.entries(raw)) if (typeof value === "string") headers[key] = value;
return Object.keys(headers).length > 0 ? headers : void 0;
}
// src/agent/durable/run-cleanup.ts
function createRunCleanup({ scheduleTimer, release, releaseOnTimer }) {
let done = false;
let timer = null;
const run = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (done) return;
release();
done = true;
};
const onTimer = releaseOnTimer ? () => {
if (done) return;
releaseOnTimer();
done = true;
} : run;
return {
get done() {
return done;
},
run,
schedule() {
if (timer || done) return;
timer = scheduleTimer(onTimer) ?? null;
}
};
}
// src/agent/durable/utils/resume-generate-args.ts
/**
* Normalize `resumeGenerate` arguments for durable agents.
*
* Accepts the `Agent` signature `(resumeData, { runId, ...options })` and the
* deprecated durable-only signature `(runId, resumeData, options?)`.
*/
function normalizeResumeGenerateArgs(args) {
const [first, second, third] = args;
const secondRunId = second && typeof second === "object" && typeof second.runId === "string" ? second.runId : void 0;
if (secondRunId !== void 0 && args.length <= 2) {
if (typeof first === "string") throw new Error("resumeGenerate received a string as the first argument and an object with runId as the second, which matches both call forms. Use resumeGenerate(resumeData, { runId }) with non-string resume data, or pass the deprecated form with an explicit options argument: resumeGenerate(runId, resumeData, {}).");
const { runId: _runId, ...options } = second;
return {
runId: secondRunId,
resumeData: first,
options
};
}
if (typeof first === "string") return {
runId: first,
resumeData: second,
options: third ?? {}
};
throw new Error("resumeGenerate requires a runId: call resumeGenerate(resumeData, { runId, ...options })");
}
// src/agent/durable/durable-agent.ts
function createLocalRequestReader(runId, entry, mastra) {
const scope = entry.runScope ??= require_stream.createRunScope();
scope.delete(require_run_registry.LOCAL_MODEL_REQUEST_KEY);
const fence = entry.executionFence;
return () => {
const current = require_run_registry.getRunRegistryEntry(runId, mastra);
if (current?.runScope !== scope || current.executionFence !== fence || fence?.isLost()) return void 0;
return scope.get(require_run_registry.LOCAL_MODEL_REQUEST_KEY);
};
}
const RESOLVED_EXECUTION_OPTIONS = Symbol("mastra.durable.resolvedExecutionOptions");
const RESOLVED_DEFAULT_OPTIONS = Symbol("mastra.durable.resolvedDefaultOptions");
/** Marks `prepare()` options whose scopes the caller applies itself (a resume rebuilt from storage). */
const SCOPES_ALREADY_APPLIED = Symbol("mastra.durable.scopesAlreadyApplied");
/** Carries the persisted spans a resume rebuilt from storage reattaches to into `prepare()`. */
const RESUMED_SPAN_DATA = Symbol("mastra.durable.resumedSpanData");
/** Recoveries in progress in this process, keyed by agent and run. */
const localRecoveryClaims = /* @__PURE__ */ new Map();
const RECOVER_SHUTDOWN_ERROR_ID = "DURABLE_AGENT_RECOVER_SHUTDOWN";
const OBSERVED_MESSAGE_LIST_REFRESH_TIMEOUT_MS = 5e3;
/**
* Reserved request-context keys win over `memory` options, matching the base Agent: server
* middleware sets them from the authenticated identity so a request body cannot route memory
* to another user's thread or resource.
*/
function applyReservedMemoryContextKeys(options) {
const requestContext = options?.requestContext;
if (!options || !requestContext) return options;
const threadId = requestContext.get(require_request_context.MASTRA_THREAD_ID_KEY);
const resourceId = requestContext.get(require_request_context.MASTRA_RESOURCE_ID_KEY);
if (!threadId && !resourceId) return options;
const memory = { ...options.memory ?? {} };
if (threadId) memory.thread = require_stream.resolveThreadIdFromArgs({
memory,
overrideId: threadId
});
if (resourceId) memory.resource = resourceId;
return {
...options,
memory
};
}
const TRANSIENT_RECOVERY_RETRY_DELAY_MS = 3e4;
const TRANSIENT_RECOVERY_ERROR_CODES = /* @__PURE__ */ new Set([
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"ESOCKETTIMEDOUT",
"LOADING"
]);
function isTransientRecoveryError(error) {
const seen = /* @__PURE__ */ new Set();
let transient = false;
while (typeof error === "object" && error !== null && !seen.has(error)) {
seen.add(error);
if ("name" in error && error.name === "AbortError") return false;
if ("code" in error && typeof error.code === "string" && TRANSIENT_RECOVERY_ERROR_CODES.has(error.code)) transient = true;
if ("message" in error && typeof error.message === "string" && /^LOADING(?:\s|$)/.test(error.message)) transient = true;
error = "cause" in error ? error.cause : void 0;
}
return transient;
}
/** Why `recover()` should be deferred, or `undefined` for a permanent failure. */
function recoverySkip(error) {
const { id, details } = error ?? {};
switch (id) {
case require_run_registry.RUN_ACTIVE_ERROR_ID: return typeof details?.retryAt === "number" ? {
reason: "run-active",
retryAt: details.retryAt
} : { reason: "run-active" };
case require_run_registry.RECOVER_RUN_ACTIVE_LOCALLY_ERROR_ID: return { reason: "run-active-locally" };
case require_run_registry.RECOVER_ALREADY_IN_PROGRESS_ERROR_ID: return { reason: "already-in-progress" };
default: return isTransientRecoveryError(error) ? {
reason: "transient-error",
retryAt: Date.now() + TRANSIENT_RECOVERY_RETRY_DELAY_MS
} : void 0;
}
}
/** Whether a failed owned recovery should terminate observers of the run. */
function shouldReportRecoveryFailure(error) {
const errorId = error?.id;
return errorId !== "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND" && errorId !== "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE" && errorId !== "DURABLE_AGENT_RECOVER_RUN_SUSPENDED" && errorId !== "DURABLE_AGENT_RECOVER_RUN_NOT_ACTIVE" && errorId !== RECOVER_SHUTDOWN_ERROR_ID;
}
/**
* Whether a crashed run's persisted AGENT_RUN/MODEL_GENERATION spans were
* already ended: map-final-output ends them on completion, and a suspension
* ends them as `suspended` (a recorded `resumedAt` means one happened). The
* spans of a segment after a resume live only in the lost process.
*/
function originalSpansEndedBeforeCrash(snapshot) {
const context = snapshot.context;
if (context?.["map-final-output"]?.status === "success") return true;
return Object.values(context ?? {}).some((result) => result?.resumedAt != null);
}
function rebindRecoveredModelList(persisted, enabledLive) {
const pool = [...enabledLive];
const bound = persisted.map((entry) => {
const i = pool.findIndex((live) => live.id === entry.id);
return i === -1 ? void 0 : pool.splice(i, 1)[0];
});
const boundById = bound.filter(Boolean).length;
if (persisted.length - boundById === pool.length) for (let i = 0; i < bound.length; i++) bound[i] ??= pool.shift();
const modelList = [];
persisted.forEach((entry, i) => {
const live = bound[i];
if (live) modelList.push({
id: entry.id,
model: live.model,
maxRetries: live.maxRetries ?? 0,
enabled: true,
headers: live.headers
});
});
return {
modelList: modelList.length ? modelList : void 0,
boundById,
boundByPosition: modelList.length - boundById,
unbound: persisted.length - modelList.length
};
}
/**
* How many candidate `running` rows `listActiveRuns()` fetches from storage
* per batch. Bounds peak memory to one batch of hydrated snapshots instead of
* every matching row's snapshot at once (#21501).
*/
const LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE = 100;
/** The most recent transcript in a snapshot: workflow state, else the last step output carrying one. */
function latestMessageListState(snapshot) {
if (snapshot.context?.__state?.messageListState) return snapshot.context.__state.messageListState;
if (snapshot.value?.messageListState) return snapshot.value.messageListState;
if (snapshot.state?.messageListState) return snapshot.state.messageListState;
let latest;
for (const step of Object.values(snapshot.context ?? {})) {
const value = step?.output?.messageListState;
const at = step?.endedAt ?? step?.startedAt ?? 0;
if (value && (!latest || at >= latest.at)) latest = {
at,
value
};
}
return latest?.value;
}
var DurableAgent = class extends require_run_registry.Agent {
#beginSegment(runId) {
const segment = Symbol(runId);
this.#segmentOwner.set(runId, segment);
return segment;
}
#releaseSegment(runId, segment, entry) {
if (this.#segmentOwner.get(runId) !== segment) return false;
this.#segmentOwner.delete(runId);
if (this.#runRegistry.get(runId) === entry) this.#runRegistry.cleanup(runId);
return true;
}
#hasRecoveryAttempt(runId) {
return this.#recoveryAttempts.has(runId);
}
#startRecoveryAttempt(runId, recover) {
const attempt = Promise.resolve().then(recover);
this.#recoveryAttempts.set(runId, attempt);
const removeAttempt = () => {
if (this.#recoveryAttempts.get(runId) === attempt) this.#recoveryAttempts.delete(runId);
};
attempt.then(removeAttempt, removeAttempt);
return attempt;
}
#executionEngine;
/** @internal One execution owner per Agent, initialized without starting a workflow. */
get executionEngine() {
return this.#executionEngine ??= this.createExecutionEngine(this.#mastra);
}
/** @internal Subclasses supply their default engine without changing workflow fallback policy. */
createExecutionEngine(mastra) {
return new DurableExecutionEngine(this.id, mastra);
}
/** The wrapped agent */
#wrappedAgent;
#streamConfig;
#wrapperStreamBus;
/** Registry for per-run non-serializable state */
#runRegistry;
#recoveryAttempts = /* @__PURE__ */ new Map();
/** Maximum steps for the agentic loop */
#maxSteps;
/** Mastra instance (set via __setMastra when registered) */
#mastra;
/** Active streamUntilIdle wrappers keyed by scope (threadId|resourceId) */
#activeStreamUntilIdle = /* @__PURE__ */ new Map();
/** The stream segment (stream() or resume()) that currently owns each run id's shared state. */
#segmentOwner = /* @__PURE__ */ new Map();
#timedOutExecutions = /* @__PURE__ */ new WeakSet();
/**
* Accepted input of stream()/generate() executions. A total deadline that
* settles the execution saves the turn from it as a terminal write.
*/
#runInputs = /* @__PURE__ */ new WeakMap();
/**
* Registry entries of recovered executions whose memory is fenced but which are not registered yet,
* so a total deadline in that window still saves the turn.
*/
#recoveredEntries = /* @__PURE__ */ new WeakMap();
/**
* User-supplied snapshot-persistence policy
* (see DurableAgentConfig.shouldPersistSnapshot). Protected so subclasses
* that pin their own policy (EventedAgent) can detect and warn when set.
*/
userShouldPersistSnapshot;
/** Storage version for new runs (see DurableAgentConfig.storageVersion) */
#storageVersion;
/**
* Create a new DurableAgent that wraps an existing Agent
*/
constructor(config) {
const { agent, id: idOverride, name: nameOverride, pubsub, cache, maxSteps, cleanupTimeoutMs, shouldCache, shouldPersistSnapshot, storageVersion } = config;
const agentId = idOverride ?? agent.id;
const agentName = nameOverride ?? agent.name ?? agent.id;
super({
id: agentId,
name: agentName,
instructions: ({ requestContext }) => agent.getInstructions({ requestContext }),
model: ({ requestContext }) => agent.getModel({ requestContext }),
notifications: agent.__getNotificationConfig()
});
this.#wrappedAgent = agent;
this.#runRegistry = new require_run_registry.ExtendedRunRegistry();
this.#maxSteps = maxSteps;
this.#streamConfig = {
pubsub,
cache,
cleanupTimeoutMs,
shouldCache
};
this.userShouldPersistSnapshot = shouldPersistSnapshot;
this.#storageVersion = storageVersion ?? 1;
this.#wrappedAgent.getChannels()?.__setDispatchAgent(this);
}
/** @internal Read one request-context value captured in a suspended durable run snapshot. */
async __getSuspendedRunRequestContextValue({ runId, key }) {
if (!this.#mastra) throw new require_error.MastraError({
id: "DURABLE_AGENT_RECOVER_NO_MASTRA",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" __getSuspendedRunRequestContextValue() requires the agent to be registered on a Mastra instance.`,
details: {
agentName: this.name,
runId
}
});
const workflowsStore = await this.#mastra.getStorage()?.getStore("workflows");
if (!workflowsStore) throw new require_error.MastraError({
id: "DURABLE_AGENT_RECOVER_NO_STORAGE",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" __getSuspendedRunRequestContextValue() requires persistent storage to load the run snapshot.`,
details: {
agentName: this.name,
runId
}
});
const persisted = await workflowsStore.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
if (!persisted) return void 0;
const workflowInput = (typeof persisted.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted.snapshot)?.context?.input;
if (workflowInput?.__workflowKind !== "durable-agent" || workflowInput.agentId !== this.id) return void 0;
return workflowInput.requestContextEntries?.[key];
}
/**
* Get the resolved cache instance.
* Lazily initialized to allow inheriting from Mastra.
*/
get cache() {
return this.__getStreamBus().forRun(this.__usesSharedRunLog()).cache;
}
/**
* Get the PubSub instance.
* Returns CachingPubSub if caching is enabled, otherwise the inner pubsub.
*/
get pubsub() {
return this.__getStreamBus().forRun(this.__usesSharedRunLog()).pubsub;
}
/** Durable runs always publish on their stream topic. */
hasResumableStreams() {
return true;
}
__usesSharedRunLog() {
return !!this.#mastra && this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger) === "evented";
}
/** Durable execution uses its lifecycle publisher, not the plain Agent entry point. @internal */
__ownsPlainStreamPublisher() {
return false;
}
/** Kept `false`, the value this getter has always reported for durable agents. */
get durable() {
return false;
}
/** @internal */
__getStreamBus() {
const bus = this.#wrappedAgent.__getStreamBus(true);
if (!Object.values(this.#streamConfig).some((value) => value !== void 0)) return bus;
return this.#wrapperStreamBus ??= bus.withConfig(this.#streamConfig);
}
/**
* Owner of a run this process still tracks (until its auto-cleanup clears
* the replay history), or undefined.
* @internal
*/
__getRunOwner(runId) {
if (!this.#runRegistry.has(runId)) return void 0;
return { ...this.#runRegistry.getMemoryInfo(runId) };
}
async __getRunRecord(runId) {
const bus = this.__getStreamBus();
return require_run_registry.readAgentRunRecord(bus.getRunRecordCache(this.__usesSharedRunLog()), this.id, runId, require_run_registry.durableReplayOwnerKey(this.id, runId));
}
/**
* Owner of a run whose replay history is still retained: the local owner,
* else the shared record, including legacy records without stream status.
* Undefined once the run's topic is cleared. Only used for replay access.
* Rejects when the shared cache cannot be read.
* @internal
*/
async __getReplayOwner(runId) {
const local = this.__getRunOwner(runId);
if (local) return local;
const shared = await require_run_registry.readDurableReplayOwner(this.__getStreamBus().getRunRecordCache(this.__usesSharedRunLog()), this.id, runId);
if (!shared) return void 0;
return {
resourceId: shared.resourceId,
threadId: shared.threadId
};
}
/**
* Share the owner of a run this process registered, so other replicas can
* authorize replay of its history. Lives until {@link #clearPubsubTopic}. A
* failed write only leaves other replicas refusing to replay the run.
*/
async #attachStreamPublisher(runId, owner) {
const claim = require_run_registry.getRunRegistryEntry(runId, this.#mastra)?.executionFence?.claim;
await require_run_registry.getExecutionStreamOwner({
runId,
agentId: this.id,
mastra: this.#mastra,
agent: this,
claim: claim && {
...claim,
...owner
}
})?.ready.catch((error) => {
this.logger.warn(`[DurableAgent:${this.id}] run ${runId}: failed to attach its stream publisher`, { error });
});
}
#unverifiedReaderFences = /* @__PURE__ */ new WeakSet();
#scheduleReaderCleanup(executionFence, cleanup) {
if (this.#unverifiedReaderFences.has(executionFence)) return;
return this.__getStreamBus().scheduleCleanup(() => {
if (!this.#unverifiedReaderFences.has(executionFence)) cleanup();
});
}
#owningReaderTerminal(runId, executionFence) {
const publisher = require_run_registry.getExecutionStreamOwner({
runId,
agentId: this.id,
mastra: this.#mastra,
agent: this,
claim: executionFence.claim
});
return async (status, generation) => {
if (generation !== executionFence.generation || !executionFence.ownsRunTopics()) return;
const currentFence = require_run_registry.getRunRegistryEntry(runId, this.#mastra)?.executionFence;
if (currentFence && currentFence !== executionFence) return;
try {
await publisher?.settle(status);
} catch (error) {
if (!(error instanceof require_run_registry.DurableExecutionFenceError) || error.id !== "DURABLE_AGENT_EXECUTION_UNVERIFIED") throw error;
this.#unverifiedReaderFences.add(executionFence);
this.logger.warn(`[DurableAgent:${this.id}] run ${runId}: terminal ownership could not be verified`, { error });
}
};
}
/**
* Mark `runId` as being recovered by this process, and return the release.
* A second `recover()` of the same run in this process fails fast instead
* of contending for the claim. Across processes the run's execution claim
* picks the winner.
*/
#claimLocalRecovery(runId) {
const key = JSON.stringify([this.id, runId]);
if (localRecoveryClaims.has(key)) throw new require_error.MastraError({
id: require_run_registry.RECOVER_ALREADY_IN_PROGRESS_ERROR_ID,
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover(${runId}): this process is already recovering this run.`,
details: {
agentName: this.name,
runId
}
});
const token = crypto.randomUUID();
localRecoveryClaims.set(key, token);
return () => {
if (localRecoveryClaims.get(key) === token) localRecoveryClaims.delete(key);
};
}
/**
* Liveness of a run without an execution claim, i.e. one started before runs
* were claimed: a live run keeps renewing its thread's lease. A run without a
* thread has no signal and counts as not live.
*/
#untrackedRunLiveness(runId, workflowInput) {
const memoryInfo = workflowInput.messageListState?.memoryInfo;
const threadId = workflowInput.state?.threadId ?? memoryInfo?.threadId;
if (!threadId) return void 0;
const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;
return {
isLive: () => require_run_registry.agentThreadStreamRuntime.isRunHoldingThreadLease(this.getPubSub(), runId, threadId, resourceId),
ttlMs: require_run_registry.agentThreadStreamRuntime.threadLeaseTtlMs
};
}
/**
* Whether the run's persisted snapshot is still `running`. Without storage,
* or with an unreadable snapshot, answers true so `recover()` reports why.
*/
async #isRunningSnapshot(runId) {
const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
if (!workflowsStore) return true;
const persisted = await workflowsStore.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
if (!persisted) return false;
if (typeof persisted.snapshot !== "string") return persisted.snapshot?.status === "running";
try {
return JSON.parse(persisted.snapshot)?.status === "running";
} catch {
return true;
}
}
/**
* The transcript as of the crash. The loop snapshot's input only has the one the run
* started with; later steps keep it in the nested execution workflow's state.
*/
async #loadLatestMessageListState(workflowsStore, runId, fallbackSnapshot) {
let latest;
try {
const nestedRunId = fallbackSnapshot.context?.[require_run_registry.DurableStepIds.AGENTIC_EXECUTION]?.metadata?.nestedRunId;
const nested = await workflowsStore.getWorkflowRunById({
runId: typeof nestedRunId === "string" ? nestedRunId : runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_EXECUTION
});
const snapshot = typeof nested?.snapshot === "string" ? JSON.parse(nested.snapshot) : nested?.snapshot;
latest = snapshot && latestMessageListState(snapshot);
} catch {}
latest ??= latestMessageListState(fallbackSnapshot);
if (!latest) return void 0;
return hydrateMessageListState({
getInitData: () => fallbackSnapshot.context?.input,
mastra: this.#mastra
}, latest);
}
async #loadRecoverableSnapshot(workflowsStore, runId) {
const persisted = await workflowsStore.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
if (!persisted) throw new require_error.MastraError({
id: require_run_registry.RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID,
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover(${runId}): no persisted workflow snapshot found. The run may have already completed or been cleaned up.`,
details: {
agentName: this.name,
runId
}
});
const snapshot = typeof persisted.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted.snapshot;
if (snapshot?.status === "pending" && snapshot.context != null && typeof snapshot.context === "object" && !Array.isArray(snapshot.context) && !Object.prototype.hasOwnProperty.call(snapshot.context, "input")) throw new require_error.MastraError({
id: require_run_registry.RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID,
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover(${runId}): no restartable checkpoint has been persisted yet. Enable recovery: { durableAgents: 'auto' } or a shouldPersistSnapshot policy that includes "running" before starting the run. Even with persistence enabled, recovery is unavailable until the first running checkpoint is saved.`,
details: {
agentName: this.name,
runId,
snapshotStatus: snapshot.status
}
});
const workflowInput = snapshot?.context?.input;
if (!workflowInput || workflowInput.__workflowKind !== "durable-agent") throw new require_error.MastraError({
id: "DURABLE_AGENT_RECOVER_INVALID_SNAPSHOT",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.SYSTEM,
text: `DurableAgent "${this.name}" recover(${runId}): persisted snapshot does not contain a durable-agent workflow input.`,
details: {
agentName: this.name,
runId
}
});
if (workflowInput.agentId !== this.id) throw new require_error.MastraError({
id: "DURABLE_AGENT_RECOVER_AGENT_MISMATCH",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover(${runId}): persisted run belongs to agent "${workflowInput.agentId}", not "${this.id}".`,
details: {
agentName: this.name,
runId,
ownerAgentId: workflowInput.agentId
}
});
if (!(snapshot.status === "running" || snapshot.status === "waiting" || snapshot.status === "success" || snapshot.status === "failed" || snapshot.status === "tripwire" || snapshot.status === "pending" && snapshot.context != null && Object.prototype.hasOwnProperty.call(snapshot.context, "input"))) throw new require_error.MastraError({
id: snapshot.status === "suspended" ? require_run_registry.RECOVER_RUN_SUSPENDED_ERROR_ID : require_run_registry.RECOVER_RUN_NOT_ACTIVE_ERROR_ID,
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover(${runId}): run status is "${snapshot.status}", so the run cannot be recovered. Runs suspended on a tool call or an approval are continued with resume(${runId}, ...), not recover().`,
details: {
agentName: this.name,
runId,
snapshotStatus: snapshot.status
}
});
return {
snapshot,
workflowInput
};
}
async #loadSuspendedIteration(runId) {
const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
const outerRun = await workflowsStore?.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
if (!outerRun) return { toolCalls: [] };
const nestedRunId = ((typeof outerRun.snapshot === "string" ? JSON.parse(outerRun.snapshot) : outerRun.snapshot).context?.[require_run_registry.DurableStepIds.AGENTIC_EXECUTION])?.metadata?.nestedRunId ?? runId;
const persisted = await workflowsStore?.getWorkflowRunById({
runId: nestedRunId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_EXECUTION
});
if (!persisted) return { toolCalls: [] };
const snapshot = typeof persisted.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted.snapshot;
const llmStep = snapshot.context?.[require_run_registry.DurableStepIds.LLM_EXECUTION];
if (llmStep?.status !== "success") return { toolCalls: [] };
const accumulatedSteps = readAccumulatedSteps(snapshot.value, snapshot.context.input);
const toolCalls = [...accumulatedSteps.flatMap((step) => step.toolCalls ?? []), ...llmStep.output.toolCalls ?? []];
const stepText = llmStep.output.text ?? "";
const priorText = accumulatedSteps.filter((step) => step.finishReason !== "retry").map((step) => step.text ?? "").join("");
return {
toolCalls: toolCalls.map((toolCall) => ({
type: "tool-call",
runId,
from: "AGENT",
payload: {
toolCallId: toolCall.toolCallId,
toolName: toolCall.toolName,
args: toolCall.args,
providerMetadata: toolCall.providerMetadata,
providerExecuted: toolCall.providerExecuted,
output: toolCall.output
}
})),
resumedText: {
priorText,
stepText
}
};
}
/**
* Loads the recalled messages a persisted run keeps as refs in its transcript
* before resume() or recover() runs anything. A memory storage failure then
* rejects the call and leaves the run as it was. Failing in a step instead,
* after a resumed tool already ran, would end the run.
*/
async #loadRecalledMessages(runId, snapshot, requestContext) {
if (!snapshot) {
const persisted = await (await this.#mastra?.getStorage()?.getStore("workflows"))?.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
snapshot = typeof persisted?.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted?.snapshot;
}
if (!snapshot) return;
await loadMessageListStateForResume({
state: snapshot.context?.__state ?? snapshot.value,
getInitData: () => snapshot.context?.input,
mastra: this.#mastra,
requestContext
});
}
/**
* Rebuild and register the stream for a claimed recovery attempt. Rolls back
* every partial registration and releases the claim if setup fails.
*/
async #setupRecoveredStream({ runId, workflowInput, requestContext, threadId, resourceId, messageList, registryEntry, options, scheduleAutoCleanup, executionFence }) {
let streamCleanup;
let streamOutput;
let threadRegistration;
try {
this.#assertRecoveryActive();
executionFence.throwIfLost();
registryEntry.messageList = messageList;
registryEntry.agentId = this.id;
this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, {
threadId,
resourceId
});
require_run_registry.globalRunRegistry.set(runId, registryEntry);
await this.#attachStreamPublisher(runId, {
threadId,
resourceId
});
const defaultOptions = await this.getDefaultOptions({ requestContext });
const onFinish = async (result) => {
await defaultOptions?.onFinish?.(result);
await options?.onFinish?.(result);
};
const onErrorCallback = async (error) => {
await defaultOptions?.onError?.(error);
await options?.onError?.(error);
};
const onAbortCallback = async (data) => {
await defaultOptions?.onAbort?.(data);
await options?.onAbort?.(data);
};
const recoverOffset = await this.#getPubsubOffset(runId);
this.#assertRecoveryActive();
executionFence.throwIfLost();
const stream = require_run_registry.createDurableAgentStream({
pubsub: this.pubsub,
runId,
minGeneration: executionFence.generation,
onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),
messageId: workflowInput.messageId ?? crypto.randomUUID(),
model: {
modelId: workflowInput.modelConfig?.modelId,
provider: workflowInput.modelConfig?.provider,
version: "v3"
},
threadId,
resourceId,
offset: recoverOffset,
onChunk: options?.onChunk,
experimentalTransform: options?.experimentalTransform,
onStepFinish: options?.onStepFinish,
onFinish,
onStreamFinished: scheduleAutoCleanup,
onError: async (error) => {
await onErrorCallback(error);
scheduleAutoCleanup();
},
onAbort: async (data) => {
try {
await onAbortCallback(data);
} finally {
scheduleAutoCleanup();
}
},
onSuspended: options?.onSuspended,
closeOnSuspend: false,
messageList,
structuredOutput: registryEntry.structuredOutput,
requestContext: registryEntry.requestContext,
returnScorerData: workflowInput.options?.returnScorerData
});
streamCleanup = stream.cleanup;
streamOutput = stream.output;
await this.#raceFenceLoss(stream.ready, executionFence).catch((error) => {
if (this.#timedOutExecutions.has(executionFence)) return stream.ready;
throw error;
});
if (await this.#redeliverDeadlineError(registryEntry, executionFence) || this.#timedOutExecutions.has(executionFence)) return {
stream,
threadRegistration
};
this.#assertRecoveryActive();
const recoverStreamOptions = {
runId,
requestContext,
...threadId ? { memory: {
thread: threadId,
...resourceId ? { resource: resourceId } : {}
} } : {}
};
executionFence.throwIfLost();
threadRegistration = await require_run_registry.agentThreadStreamRuntime.registerRun(this, stream.output, recoverStreamOptions, this.getPubSub(), {
strict: true,
...options?.closeOnSuspend ? {} : { continuation: "across-suspension" },
validate: () => {
this.#assertRecoveryActive();
executionFence.throwIfLost();
},
generation: executionFence.generation,
ownershipLost: () => executionFence.isLost(),
stepOwner: () => require_run_registry.getRunRegistryEntry(runId, this.#mastra)
});
this.#assertRecoveryActive();
executionFence.throwIfLost();
return {
stream,
threadRegistration
};
} catch (error) {
const settlement = await executionFence.settle(async () => {});
try {
await threadRegistration?.rollback({ releaseLease: settlement !== "superseded" });
} catch (rollbackError) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) failed to roll back thread registration: ${rollbackError}`);
}
if (streamOutput) require_run_registry.agentThreadStreamRuntime.closeRunContinuation(streamOutput, this.getPubSub());
streamCleanup?.();
if (this.#runRegistry.get(runId) === registryEntry) this.#runRegistry.cleanup(runId);
if (require_run_registry.getRunRegistryEntry(runId, this.#mastra) === registryEntry) require_run_registry.globalRunRegistry.delete(runId);
if (settlement !== "superseded") await this.#reportRecoveryFailure(runId, error, executionFence.generation);
throw error;
}
}
#assertRecoveryActive() {
if (this.#mastra?.__shuttingDown) throw new require_error.MastraError({
id: RECOVER_SHUTDOWN_ERROR_ID,
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.SYSTEM,
text: "Durable recovery stopped because Mastra is shutting down"
});
}
async #reportRecoveryFailure(runId, error, generation) {
if (this.#mastra?.__shuttingDown || !shouldReportRecoveryFailure(error)) return false;
const normalizedError = error instanceof Error ? error : new Error(String(error));
if (normalizedError instanceof require_run_registry.AgentThreadLeaseConflictError) return false;
try {
await this.emitError(runId, normalizedError, generation);
return true;
} catch (reportingError) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) failed to publish terminal error: ${reportingError}`);
return false;
}
}
/**
* Settle `operation`, or throw the loss error as soon as the execution loses
* its claim. A superseded recovery then unwinds even when the work it waits
* on ignores the abort signal.
*/
#raceFenceLoss(operation, executionFence) {
return this.executionEngine.raceFenceLoss(operation, executionFence);
}
/** Rebuilds process-local recovery state from the persisted durable workflow input. */
async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, latestMessageListState }) {
const requestContext = workflowInput.requestContextEntries ? new require_request_context.RequestContext(Object.entries(workflowInput.requestContextEntries)) : new require_request_context.RequestContext();
require_run_registry.restoreRunAgentScopes(requestContext);
const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
const threadId = workflowInput.state?.threadId ?? messageListMemoryInfo?.threadId;
const resourceId = workflowInput.state?.resourceId ?? messageListMemoryInfo?.resourceId;
if (threadId && resourceId) requestContext.set("MastraMemory", {
thread: { id: threadId },
resourceId,
memoryConfig: workflowInput.state?.memoryConfig
});
else requestContext.delete("MastraMemory");
const messageList = new require_message_list.MessageList({
threadId,
resourceId
});
try {
messageList.deserialize(await hydrateMessageListState({
getInitData: () => workflowInput,
mastra: this.#mastra
}, workflowInput.messageListState));
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) messageList deserialize skipped: ${error}`);
}
const wrapped = this.#wrappedAgent;
let model;
try {
model = await wrapped.getModel({ requestContext });
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to resolve model during recover(${runId}): ${error}`);
}
const persistedModelId = workflowInput.modelConfig?.modelId;
if (model && persistedModelId && model.modelId !== persistedModelId) this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) continues with the agent's model '${model.modelId}'; the run started with '${persistedModelId}', which cannot be restored.`);
executionFence.throwIfLost();
let modelList;
const persistedModelList = workflowInput.modelList;
if (persistedModelList?.length) try {
const enabledLive = (await wrapped.getModelList(requestContext) ?? []).filter((entry) => entry.enabled !== false);
const rebound = rebindRecoveredModelList(persistedModelList, enabledLive);
modelList = rebound.modelList;
if (rebound.unbound > 0) this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) model list drifted (persisted ${persistedModelList.length} enabled entries, resolved ${enabledLive.length}); bound ${rebound.boundById} by id, ${rebound.boundByPosition} by position; ${rebound.unbound} will resolve from serialized config`);
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to resolve model list during recover(${runId}): ${error}`);
}
executionFence.throwIfLost();
let memory;
try {
memory = await wrapped.getMemory({ requestContext });
} catch (error) {
this.#mastra?.getLogger?.()?.error?.(`[DurableAgent] Failed to resolve memory during recover(${runId}): ${error}`);
throw new DurableProcessorRebuildError(this.id, error);
}
executionFence.throwIfLost();
let tools = {};
let workspace;
try {
tools = await wrapped.getToolsForExecution({
runId,
threadId,
resourceId,
requestContext,
memoryConfig: workflowInput.state?.memoryConfig,
autoResumeSuspendedTools: workflowInput.options?.autoResumeSuspendedTools,
clientTools: workflowInput.options?.clientTools,
runMessages: latestMessageListState ? new require_message_list.MessageList({
threadId,
resourceId
}).deserialize(latestMessageListState).get.all.db() : void 0
});
workspace = await wrapped.getWorkspace({ requestContext });
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] recover(${runId}) tool resolution failed: ${error}`);
}
executionFence.throwIfLost();
const saveQueueManager = memory ? new require_run_registry.SaveQueueManager({
logger: this.#mastra?.getLogger?.(),
memory,
onSaved: recordRunSavedMessages(runId)
}) : void 0;
const backgroundTasksConfig = this.getBackgroundTasksConfig?.();
const backgroundTaskManager = this.#mastra?.backgroundTaskManager;
let inputProcessors = [];
let llmRequestInputProcessors = [];
let outputProcessors = [];
let errorProcessors = [];
try {
inputProcessors = await wrapped.listInputProcessors?.(requestContext) ?? [];
llmRequestInputProcessors = await wrapped.__listLLMRequestProcessors?.(requestContext) ?? [];
outputProcessors = await wrapped.listOutputProcessors?.(requestContext) ?? [];
errorProcessors = await wrapped.listErrorProcessors?.(requestContext) ?? [];
} catch (error) {
this.#mastra?.getLogger?.()?.error?.(`[DurableAgent] recover(${runId}) processor resolution failed: ${error}`);
throw new DurableProcessorRebuildError(this.id, error);
}
executionFence.throwIfLost();
const processorStates = /* @__PURE__ */ new Map();
const origAgentSpanData = workflowInput.agentSpanData;
const origModelSpanData = workflowInput.modelSpanData;
let recoverAgentSpan;
let recoverModelSpan;
if (this.#mastra?.observability) {
if (!originalSpansEnded) try {
const observability = this.#mastra.observability.getSelectedInstance({ requestContext });
const output = {
status: "interrupted",
reason: "run recovered after its process stopped"
};
if (origModelSpanData) observability?.rebuildSpan(origModelSpanData)?.end({
output,
outcome: "interrupted",
stopReason: null,
stopReasonContext: null
});
if (origAgentSpanData) observability?.rebuildSpan(origAgentSpanData)?.end({
output,
outcome: "interrupted",
stopReason: null,
stopReasonContext: null
});
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to end interrupted spans: ${error}`);
}
try {
const persistedHead = persistedModelList?.find((entry) => entry.enabled);
const resolvedVersionId = (typeof wrapped.toRawConfig === "function" ? wrapped.toRawConfig() : void 0)?.resolvedVersionId;
const agentTracingPolicy = typeof wrapped.getTracingPolicy === "function" ? wrapped.getTracingPolicy() : void 0;
recoverAgentSpan = require_utils$1.getOrCreateSpan({
type: "agent_run",
outcome: null,
name: `agent run: '${wrapped.id}' (recovered)`,
entityType: require_storage.EntityType.AGENT,
entityId: wrapped.id,
entityName: wrapped.name,
attributes: require_run_registry.modelSpanAttributes(modelList?.find((entry) => entry.id === persistedHead?.id)?.model ?? persistedHead?.config ?? model),
metadata: {
runId,
recovered: true,
...origAgentSpanData?.id ? { recoveredFromSpanId: origAgentSpanData.id } : {},
...resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}
},
tracingPolicy: agentTracingPolicy,
resumeFrom: require_utils$1.getResumeTracingContext(origAgentSpanData),
requestContext,
mastra: this.#mastra
});
recoverModelSpan = recoverAgentSpan?.createChildSpan({
type: "model_generation",
outcome: null,
name: `llm: '${model?.modelId ?? ""}'`,
attributes: {
model: model?.modelId,
provider: model?.provider,
streaming: true
},
metadata: {
runId,
recovered: true
},
requestContext
});
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open recover span: ${error}`);
}
}
executionFence.throwIfLost();
const registryEntry = {
isTaskComplete: await restoreCompletionPolicy({
agent: wrapped,
persisted: workflowInput.options?.isTaskComplete,
requestContext,
runId,
logger: this.#mastra?.getLogger?.()
}),
isPlaceholder: (workflowInput.options?.toolsetToolNames?.length ?? 0) > 0,
returnScorerData: workflowInput.options?.returnScorerData,
mastra: this.#mastra,
agent: wrapped,
model,
modelList,
tools,
workspace,
memory,
saveQueueManager,
requestContext,
agentSpan: recoverAgentSpan,
resumeAgentSpan: recoverAgentSpan,
resumeModelSpan: recoverModelSpan,
resumeAgentSpanData: recoverAgentSpan?.snapshot?.() ?? recoverAgentSpan?.exportSpan(),
resumeModelSpanData: recoverModelSpan?.snapshot?.() ?? recoverModelSpan?.exportSpan(),
timeoutTotalMs: workflowInput.options?.modelSettings?.timeout?.totalMs,
structuredOutput: workflowInput.options?.structuredOutput?.schema ? {
...workflowInput.options.structuredOutput,
schema: toLiveStructuredOutputSchema(workflowInput.options.structuredOutput.schema, workflowInput.options.structuredOutput.nullToUndefined)
} : void 0,
backgroundTaskManager,
backgroundTasksConfig,
inputProcessors,
llmRequestInputProcessors,
outputProcessors,
errorProcessors,
processorStates,
drainPendingSignals: (scope) => wrapped.__getDrainPendingSignals()(runId, scope),
subscribePendingSignals: (listener) => wrapped.__getSubscribePendingSignals()(runId, listener),
enqueuePendingSignal: (signalInput) => wrapped.__getEnqueuePendingSignal()({
runId,
resourceId,
threadId
}, signalInput),
cleanup: () => {}
};
this.#installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
this.#runInputs.set(executionFence, {
...workflowInput,
messageListState: latestMessageListState ?? workflowInput.messageListState
});
return {
requestContext,
threadId,
resourceId,
messageList,
recoverAgentSpan,
recoverModelSpan,
registryEntry
};
}
/**
* Get the wrapped agent instance.
*/
get agent() {
return this.#wrappedAgent;
}
/**
* File-based schedules live on the wrapped agent: `assembleAgentFromFsEntry`
* attaches them to the inner `Agent` before it is wrapped for durable
* execution, and `#declaredSchedules` is private to each instance. Without
* this delegate the wrapper would report none of its own and Mastra would
* never sync a durable agent's `schedules/` directory.
*/
getDeclaredSchedules() {
return this.#wrappedAgent.getDeclaredSchedules();
}
/**
* Mirrors {@link getDeclaredSchedules} so attaching schedules to an
* already-wrapped agent lands on the instance the getter reads from.
*/
__setDeclaredSchedules(schedules) {
this.#wrappedAgent.__setDeclaredSchedules(schedules);
}
/**
* Get the run registry (for testing and advanced usage)
*/
get runRegistry() {
return this.#runRegistry;
}
/**
* Get the max steps configured for this agent
*/
get maxSteps() {
return this.#maxSteps;
}
/**
* Get the cleanup timeout in milliseconds.
* Returns 0 if auto-cleanup is disabled.
*/
get cleanupTimeoutMs() {
return this.__getStreamBus().cleanupTimeoutMs;
}
__setLogger(logger) {
super.__setLogger(logger);
this.#wrappedAgent.__setLogger(logger);
}
getModel(options) {
return this.#wrappedAgent.getModel(options);
}
getLLM(options) {
return this.#wrappedAgent.getLLM(options);
}
async getModelList(requestContext) {
return this.#wrappedAgent.getModelList(requestContext);
}
getInstructions(options) {
return this.#wrappedAgent.getInstructions(options);
}
getDescription() {
return this.#wrappedAgent.getDescription();
}
getMetadata(options) {
return this.#wrappedAgent.getMetadata(options);
}
getTracingPolicy() {
return this.#wrappedAgent.getTracingPolicy();
}
listTools(options) {
return this.#wrappedAgent.listTools(options);
}
getConfiguredToolHooks() {
return this.#wrappedAgent.getConfiguredToolHooks();
}
getDefaultOptions(options) {
return this.#wrappedAgent.getDefaultOptions(options);
}
async #resolveExecutionOptions(options, snapshot) {
if (options?.[RESOLVED_EXECUTION_OPTIONS]) return options;
const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
const resolvedOptions = require_utils.deepMerge(require_run_registry.withDefaultToolCallConcurrencyLimit(defaultOptions ?? {}, options), options ?? {});
if (options?.actor !== void 0) resolvedOptions.actor = options.actor;
const scopedOptions = await this.#applyScopes(resolvedOptions, {
callScopes: options?.scopes,
defaultScopes: defaultOptions?.scopes,
snapshot
});
Object.defineProperty(scopedOptions, RESOLVED_EXECUTION_OPTIONS, {
value: true,
enumerable: true
});
Object.defineProperty(scopedOptions, RESOLVED_DEFAULT_OPTIONS, {
value: defaultOptions,
enumerable: true
});
return scopedOptions;
}
/**
* Applies agent scopes to durable execution options. Durable runs resolve their thread and
* resource from `memory` only, so options are returned unchanged unless the run has scopes.
*/
async #applyScopes(options, { callScopes, defaultScopes, snapshot }) {
const requestContext = options.requestContext ?? new require_request_context.RequestContext();
const incomingScopes = snapshot?.scopes ? void 0 : require_run_registry.incomingAgentScopes({
requestContext,
callScopes,
defaultScopes,
mastra: this.#mastra
});
const agentScopes = incomingScopes ? await this.getScopes({
requestContext,
scopes: incomingScopes
}) : void 0;
if (!agentScopes?.length && !callScopes?.length && !requestContext.has("mastra__scopes") && !snapshot?.scopes) return options;
const resolved = require_run_registry.resolveAgentScopes({
requestContext,
agentScopes,
incomingScopes,
callScopes,
memory: options.memory,
snapshot,
mastra: this.#mastra
});
return require_run_registry.applyResolvedAgentScopes(options, resolved, requestContext);
}
getDefaultGenerateOptionsLegacy(options) {
return this.#wrappedAgent.getDefaultGenerateOptionsLegacy(options);
}
getDefaultStreamOptionsLegacy(options) {
return this.#wrappedAgent.getDefaultStreamOptionsLegacy(options);
}
getDefaultNetworkOptions(options) {
return this.#wrappedAgent.getDefaultNetworkOptions(options);
}
getMemory(options) {
return this.#wrappedAgent.getMemory(options);
}
getScopes(options) {
return this.#wrappedAgent.getScopes(options);
}
hasOwnMemory() {
return this.#wrappedAgent.hasOwnMemory();
}
getWorkspace(options) {
return this.#wrappedAgent.getWorkspace(options);
}
hasOwnWorkspace() {
return this.#wrappedAgent.hasOwnWorkspace?.() ?? false;
}
getVoice(options) {
return this.#wrappedAgent.getVoice(options);
}
get voice() {
return this.#wrappedAgent.voice;
}
get requestContextSchema() {
return this.#wrappedAgent.requestContextSchema;
}
async getConfiguredProcessorWorkflows() {
return this.#wrappedAgent.getConfiguredProcessorWorkflows();
}
async listInputProcessors(requestContext) {
return this.#wrappedAgent.listInputProcessors(requestContext);
}
async listOutputProcessors(requestContext) {
return this.#wrappedAgent.listOutputProcessors(requestContext);
}
async listErrorProcessors(requestContext) {
return this.#wrappedAgent.listErrorProcessors(requestContext);
}
async resolveProcessorById(processorId, requestContext) {
return this.#wrappedAgent.resolveProcessorById(processorId, requestContext);
}
async listConfiguredInputProcessors(requestContext) {
return this.#wrappedAgent.listConfiguredInputProcessors(requestContext);
}
async listConfiguredOutputProcessors(requestContext) {
return this.#wrappedAgent.listConfiguredOutputProcessors(requestContext);
}
async getConfiguredProcessorIds(requestContext) {
return this.#wrappedAgent.getConfiguredProcessorIds(requestContext);
}
async getConfiguredErrorProcessorIds(requestContext) {
return this.#wrappedAgent.getConfiguredErrorProcessorIds(requestContext);
}
async __resolveRunErrorProcessors(requestContext, overrides) {
return this.#wrappedAgent.__resolveRunErrorProcessors(requestContext, overrides);
}
async __listLLMRequestProcessors(requestContext, errorProcessorOverrides) {
return this.#wrappedAgent.__listLLMRequestProcessors(requestContext, errorProcessorOverrides);
}
listAgents(options) {
return this.#wrappedAgent.listAgents(options);
}
__getStaticAgents() {
return this.#wrappedAgent.__getStaticAgents();
}
__hasSubAgentsConfigured() {
return this.#wrappedAgent.__hasSubAgentsConfigured();
}
async listWorkflows(options) {
return this.#wrappedAgent.listWorkflows(options);
}
async getSkill(skillName, options) {
return this.#wrappedAgent.getSkill(skillName, options);
}
async listSkills(options) {
return this.#wrappedAgent.listSkills(options);
}
async listScorers(options) {
return this.#wrappedAgent.listScorers(options);
}
getBackgroundTasksConfig() {
return this.#wrappedAgent.getBackgroundTasksConfig();
}
disableBackgroundTasks() {
this.#wrappedAgent.disableBackgroundTasks();
}
enableBackgroundTasks() {
this.#wrappedAgent.enableBackgroundTasks();
}
getToolPayloadTransform() {
return this.#wrappedAgent.getToolPayloadTransform();
}
__getGoalConfig() {
return this.#wrappedAgent.__getGoalConfig();
}
get browser() {
return this.#wrappedAgent.browser;
}
setBrowser(browser) {
this.#wrappedAgent.setBrowser(browser);
}
hasOwnBrowser() {
return this.#wrappedAgent.hasOwnBrowser();
}
getChannels() {
return this.#wrappedAgent.getChannels();
}
setChannels(agentChannels) {
this.#wrappedAgent.setChannels(agentChannels);
agentChannels.__setDispatchAgent(this);
}
hasOwnPubSub() {
return this.#wrappedAgent.hasOwnPubSub();
}
getPubSub() {
return this.#wrappedAgent.getPubSub();
}
__setMemory(memory) {
super.__setMemory(memory);
this.#wrappedAgent.__setMemory(memory);
}
__setPubSub(pubsub) {
super.__setPubSub(pubsub);
this.#wrappedAgent.__setPubSub(pubsub);
}
__setWorkspace(workspace) {
super.__setWorkspace(workspace);
this.#wrappedAgent.__setWorkspace(workspace);
}
__getEditorConfig() {
return this.#wrappedAgent.__getEditorConfig();
}
__getOverridableFields() {
return this.#wrappedAgent.__getOverridableFields();
}
__updateInstructions(instructions) {
this.#wrappedAgent.__updateInstructions(instructions);
}
__updateModel(config) {
this.#wrappedAgent.__updateModel(config);
}
__setTools(tools) {
this.#wrappedAgent.__setTools(tools);
}
/**
* Raw stored config lives on the wrapped agent for the same reason as the
* mutators above: durable preparation and tracing read
* `resolvedVersionId` from the wrapped agent's rawConfig, and the editor
* stamps it on the outer fork via `__setRawConfig` after
* `applyStoredOverrides`. Without this delegation the stamp lands on the
* (unread) DurableAgent-level field and version metadata silently
* disappears from spans and suspend snapshots.
*/
toRawConfig() {
return this.#wrappedAgent.toRawConfig();
}
__setRawConfig(rawConfig) {
this.#wrappedAgent.__setRawConfig(rawConfig);
}
/**
* Create a per-request clone for applying stored editor overrides.
*
* The base `Agent.__fork()` builds a bare `new Agent(...)`, which for a
* DurableAgent would drop the wrapped agent and every delegating override
* (tools, model, memory, voice, durable streaming) — the served fork ends up a
* plain `Agent` with no tools. Instead, fork the wrapped agent (so overrides
* applied to this fork don't mutate the singleton) and re-wrap it in the same
* durable subclass, preserving pubsub/cache/run configuration.
*
* @internal
*/
__fork() {
const sharedChannels = this.#wrappedAgent.getChannels();
const innerFork = this.#wrappedAgent.__fork();
const Ctor = this.constructor;
const fork = new Ctor({
agent: innerFork,
...this.#streamConfig,
id: this.id,
name: this.name,
maxSteps: this.#maxSteps,
shouldPersistSnapshot: this.userShouldPersistSnapshot,
storageVersion: this.#storageVersion
});
if (sharedChannels && sharedChannels === innerFork.getChannels()) {
sharedChannels.__setAgent(this.#wrappedAgent);
sharedChannels.__setDispatchAgent(this);
}
if (this.#mastra) {
fork.__inheritMastraForFork(this.#mastra);
fork.#mastra = this.#mastra;
}
fork.source = this.source;
fork.#activeStreamUntilIdle = this.#activeStreamUntilIdle;
fork._agentNetworkAppend = this._agentNetworkAppend;
return fork;
}
/**
* Get the run registry for use by subclasses.
* @internal
*/
get runRegistryInternal() {
return this.#runRegistry;
}
/**
* Which workflow execution engine the durable agentic loop runs on.
* Subclasses override this (EventedAgent → 'evented').
* @internal
*/
get workflowEngine() {
return "default";
}
/** Whether new runs opt into journal storage. @internal */
get storesRunsInJournal() {
return this.#storageVersion === 2;
}
/**
* Warns once when `storageVersion: 2` is set but the registered store can't
* store version 2 runs. The loop workflow's `autoStorageVersion` then stores
* new runs as version 1. An agent with no registered store isn't warned.
*/
#warnIfStorageVersionUnsupported() {
if (this.#storageVersion !== 2) return;
const storage = this.#mastra?.getStorage();
const workflowsStore = storage?.stores?.workflows;
if (workflowsStore && !workflowsStore.supportsRunJournal()) this.guardrailLogger?.warn(`DurableAgent '${this.id}' sets storageVersion: 2, which ${storage?.name ?? "the configured"} storage doesn't support yet; storing new runs as version 1.`);
}
/**
* Resolve the engine this agent's workflow instance actually runs on.
*
* An evented agent without a Mastra host cannot execute evented runs — the
* evented engine's `createRun` requires the host's registries, storage, and
* event workers. Before the evented engine was re-enabled, a hostless
* EventedAgent silently streamed on the default in-process engine; that is
* released behavior, so we preserve it here as a fallback (with a warning)
* instead of throwing.
*
* The same applies to a host whose storage cannot apply concurrent workflow
* updates atomically. The evented engine advances a run from concurrent
* workers, so `createRun()` refuses to start on such a store. Letting that
* throw would turn a working durable agent into a hard failure on upgrade
* for stores like Redis, so durable agents degrade to the in-process engine
* the same way a hostless one does. A workflow that opts into the evented
* engine directly (by declaring a `schedule`) still gets the error, because
* there is no other engine it could have meant.
*
* The result is memoized: `getWorkflow()` caches the created workflow, so
* an agent that first streamed hostless keeps its default-engine workflow
* even if it is registered on a Mastra instance afterwards — identical to
* the previously shipped behavior. The cache is deliberately not
* invalidated.
*
* @internal
*/
resolveWorkflowEngine() {
return this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger);
}
/**
* Evented-engine runs execute via pubsub events consumed by in-process
* workers — without them `run.start()`/`resume()`/`restart()` never
* resolve (they wait on the `workflows-finish` topic). No-op on the
* default engine; idempotent on Mastra's side.
* @internal
*/
async ensureEngineWorkersStarted() {
return this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);
}
async persistInitialInput(runId, workflowInput) {
await persistDurableRunInput(runId, workflowInput, this.#mastra);
}
/**
* Execute the durable workflow.
*
* Subclasses override this method to customize how the workflow is executed:
* - DurableAgent (this): Runs the workflow directly via createRun + start
* - EventedAgent: Runs steps through event workers and tracks completion
* - InngestAgent: Uses inngest.send() to trigger Inngest function
*
* @param runId - The unique run ID
* @param workflowInput - The serialized workflow input
* @internal
*/
async executeWorkflow(runId, workflowInput) {
const workflow = this.getWorkflow();
const entry = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
const requestContext = entry?.requestContext;
const executionFence = entry?.executionFence;
const memoryInfo = workflowInput.messageListState?.memoryInfo;
const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;
const run = await this.executionEngine.createRun(workflow, {
runId,
resourceId,
pubsub: this.fenceRunPubSub(executionFence, entry?.abortController)
});
let result;
try {
result = await this.withSuspensionAfterPersist(runId, () => this.executionEngine.startRun(run, workflowInput, requestContext, require_observability.createObservabilityContext({ currentSpan: entry?.agentSpan })));
const outcome = this.executionEngine.finishExecution(runId, executionFence, false, { result });
if (outcome.owner === "agent") await this.settleExecution(runId, executionFence, outcome);
return result;
} finally {
this.executionEngine.releaseRun(workflow, runId, run, result?.status);
}
}
/**
* Run a workflow leg with suspension chunks/events held back until the leg
* returns, i.e. until the engine has saved the suspended snapshot. Without
* this a crash between publishing the question and saving the snapshot
* leaves a run that `resume()` rejects (#26435).
*/
async withSuspensionAfterPersist(runId, execute) {
const entry = this.suspendPersistedOnReturn ? require_run_registry.getRunRegistryEntry(runId, this.#mastra) : void 0;
if (!entry) return execute();
const pending = [];
entry.pendingSuspensionEvents = pending;
let result;
try {
result = await execute();
} finally {
if (entry.pendingSuspensionEvents === pending) delete entry.pendingSuspensionEvents;
}
if (result?.status === "suspended") for (const publish of pending) try {
await publish();
} catch (error) {
this.logger.warn("Failed to publish deferred suspension event", {
runId,
error
});
}
return result;
}
/**
* Whether `executeWorkflow()` resolves only after a suspended snapshot has
* been persisted, reporting `{ status: 'suspended' }`. When true,
* `closeOnSuspend` streams close on that result instead of on the SUSPENDED
* pubsub event (which the tool-call step publishes before persistence), so
* an immediate cold resume finds the `suspended` snapshot.
* @internal
*/
get suspendPersistedOnReturn() {
return true;
}
/**
* Create the durable workflow for this agent.
*
* Retained for direct calls and subclass super calls. Run execution creates
* workflows through the execution engine, not through overrides of this method.
*
* @internal
*/
createWorkflow() {
return this.executionEngine.createWorkflow({
maxSteps: this.#maxSteps,
workflowEngine: this.workflowEngine,
storesRunsInJournal: this.storesRunsInJournal,
shouldPersistSnapshot: this.userShouldPersistSnapshot,
logger: this.logger,
guardrailLogger: this.guardrailLogger
});
}
/**
* Resolve the effective snapshot-persistence policy for this agent's
* workflows: the user-supplied predicate when set, otherwise the
* recovery-aware default. Engine variants own this policy during execution;
* overriding this compatibility method does not change running workflows.
*
* @internal
*/
resolveShouldPersistSnapshot() {
return this.executionEngine.resolveShouldPersistSnapshot(this.userShouldPersistSnapshot);
}
workflowFailureError(workflowError, fallbackMessage) {
return this.executionEngine.workflowFailureError(workflowError, fallbackMessage);
}
workflowExecutionError(workflowError, fallbackMessage) {
return this.executionEngine.workflowExecutionError(workflowError, fallbackMessage);
}
/**
* Emit an error event to pubsub.
*
* @param runId - The run ID
* @param error - The error to emit
* @param generation - Claim generation of the execution reporting the error
* @internal
*/
async emitError(runId, error, generation) {
require_run_registry.endRunSpansWithError(runId, error);
await require_run_registry.runOutsideRunFenceScope(() => require_run_registry.emitErrorEvent(this.pubsub, runId, error, generation, require_run_registry.shouldRejectStream(error) ? "reject" : void 0));
}
/**
* Claim the run's execution fence (#23734): `acquire` for a new execution
* segment, `takeover` when recovering an orphaned run. With a
* `requestContext`, the claim also covers the run's memory store (see
* {@link DurableAgent.#coverMemory}).
*/
async #claimExecution(runId, mode, requestContext, untrackedRun) {
const fence = await this.executionEngine.claimExecution(runId, mode, this.pubsub, this.logger, untrackedRun);
if (requestContext) await this.#coverMemory(fence, requestContext);
return fence;
}
/**
* Raise the memory store the run writes to to the fence's claim before the
* run touches memory. Settles the fence if a newer claim already covers
* memory. Memory that cannot be resolved stays unfenced: the run's own
* memory writes fail the same way. Warns about a memory store that can't
* fence when the run is being recovered, or when recovery is automatic.
*/
async #coverMemory(fence, requestContext, recovering = false) {
if (fence.generation === void 0) return;
let store;
try {
const memory = await this.getMemory({ requestContext });
store = memory ? await memory.storage.getStore("memory") : void 0;
} catch (error) {
this.logger.warn(`[DurableAgent] run ${fence.runId}: memory is not fenced, failed to resolve its store`, {
runId: fence.runId,
error
});
}
if (recovering || this.#mastra?.recoveryConfig?.durableAgents === "auto") await this.#warnIfUnfenced(store, "memory");
try {
await fence.coverMemory(store);
} catch (error) {
await fence.settle(async () => {});
throw error;
}
}
/**
* Warn, once per store, that a store recovery relies on can't fence run
* writes (#23734). Returns whether it can't. A store that can't tell yet
* isn't warned about: claims on it fail until it can.
*/
async #warnIfUnfenced(store, domain) {
return this.executionEngine.warnIfUnfenced(store, domain, this.guardrailLogger);
}
/**
* The pubsub a run's workflow publishes on, bound to its execution.
*
* Once the execution loses the run, `abortController` is aborted so the LLM
* stream and tool calls stop, and the execution's publishes are dropped:
* the run's topics are shared with the new owner's consumers, which must not
* see this execution's chunks or the `finish` its abort produces.
*
* The evented engine publishes on `mastra.pubsub` instead of this pubsub.
* Its shared workflow controller must not be aborted on ownership loss:
* that would publish a cancellation to the recovering execution. Durable
* step guards instead cancel invocation-local work and suppress its stream
* publications, leaving engine failure and settlement events untouched.
*
* @internal
*/
fenceRunPubSub(executionFence, abortController, pubsub = this.pubsub) {
return this.executionEngine.fenceRunPubSub(executionFence, abortController, pubsub, this.workflowEngine, this.logger);
}
/**
* End an execution segment: publish the error of a failed segment and delete
* the snapshots of a run that reached a non-suspended terminal status.
*
* With an execution fence these writes happen only while the segment still
* owns the run, and the fence is released afterwards. A superseded segment
* writes nothing — the run belongs to the execution that took it over. A
* segment that lost its lease without being replaced still reports its error
* but keeps the snapshots so the run stays recoverable.
*
* Never rejects: a pubsub that is already closing (for example during
* shutdown) must not turn a run's own failure into an unhandledRejection.
*
* @internal
*/
async settleExecution(runId, fence, outcome) {
const { status, error } = outcome;
if (fence && this.#timedOutExecutions.has(fence)) return;
const totalTimeout = require_stream.isMastraTimeoutError(error) && error.timeoutType === "total";
if (fence && totalTimeout) this.#timedOutExecutions.add(fence);
const reportError = async (reported) => {
try {
await this.emitError(runId, reported, fence?.generation);
} catch (publishError) {
this.logger.warn(`Failed to publish error event for run ${runId}`, {
runId,
error: publishError
});
}
};
const finished = totalTimeout || status !== void 0 && status !== "suspended";
const runInput = totalTimeout && fence ? this.#runInputs.get(fence) : void 0;
const runInputEntry = runInput && (require_run_registry.getRunRegistryEntry(runId, this.#mastra) ?? (fence && this.#recoveredEntries.get(fence)));
let wrote = false;
let deadlineSave;
const writeTerminalState = async () => {
wrote = true;
if (totalTimeout && fence) fence.deadlineError = error;
if (runInput && runInputEntry && !runInputEntry.tripwire) {
this.#runInputs.delete(fence);
deadlineSave = (async () => {
await require_stream.settledOrElapsed(new Promise((resolve) => require_utils.whenRunStepsSettle(runInputEntry, resolve)), 500);
const deadlineSpan = runInputEntry.resumeAgentSpan ?? runInputEntry.agentSpan;
await runDurableDeadlineOutputPass({
runId,
initData: runInput,
...deadlineMessageListState(runInputEntry, runInput.messageListState),
entry: runInputEntry,
mastra: this.#mastra,
tracingContext: deadlineSpan ? { currentSpan: deadlineSpan } : void 0,
logger: this.logger
});
})().catch((saveError) => {
this.logger.warn(`Failed to save run ${runId} at its total deadline`, {
runId,
error: saveError
});
});
await require_stream.settledOrElapsed(deadlineSave, require_stream.DEADLINE_SAVE_WAIT_MS);
}
if (error) await reportError(error);
if (finished) await this.deleteRunSnapshots(runId);
if (deadlineSave) await require_stream.settledOrElapsed(deadlineSave, require_stream.DEADLINE_SAVE_CLAIM_HOLD_MS);
};
if (!fence) return writeTerminalState();
let settlement;
try {
settlement = await fence.settle(writeTerminalState, totalTimeout);
} catch (settlementError) {
if (totalTimeout && !wrote && error) await reportError(error);
throw settlementError;
}
if (!wrote && error && (settlement === "orphaned" || !totalTimeout && settlement === "owned")) await reportError(error);
}
/**
* Abort the thread's active run.
*
* The base implementation flips the run's prepared `AbortController`, which a
* durable run never has: its controller lives on this agent's run registry,
* and the steps reading it may execute in another process. Without the abort
* request below, aborting a thread whose active run is durable records an
* intent nothing reads and lets the run stream on.
*/
/** @internal Durable `untilIdle` streams are tracked on this agent, not the wrapped one. */
__untilIdleHandlesBackgroundTask(threadId, resourceId, taskId) {
return require_run_registry.untilIdleHandlesBackgroundTask(this.#activeStreamUntilIdle, threadId, resourceId, taskId);
}
abortThreadStream(options) {
const aborted = this.#abortThreadStreamLocally(options);
if (!aborted && !options.localOnly) this.#abortThreadLeaseOwner(options).catch((error) => {
this.#mastra?.getLogger?.()?.warn?.("Failed to abort durable agent thread run on another process", {
agentId: this.id,
threadId: options.threadId,
error: error instanceof Error ? error.message : String(error)
});
});
return aborted;
}
/** @internal Like {@link abortThreadStream}, but reports whether a run on another process was asked to stop. */
async __abortThreadStreamAcrossProcesses(options) {
const aborted = this.#abortThreadStreamLocally(options);
if (aborted || options.localOnly) return aborted;
return this.#abortThreadLeaseOwner(options);
}
#abortThreadStreamLocally(options) {
const scopeKey = `${options.threadId ?? ""}|${options.resourceId ?? ""}`;
const wrapperClose = require_run_registry.getScopeStreamSlot(this.#activeStreamUntilIdle, scopeKey, options.expectedRunId);
if (wrapperClose) {
wrapperClose();
return true;
}
const runId = require_run_registry.agentThreadStreamRuntime.getActiveThreadRunId(options, this.getPubSub());
const aborted = super.abortThreadStream(options);
if (!aborted || !runId) return aborted;
if (!options.localOnly) {
this.#abortLocalController(runId);
this.requestRemoteAbort(runId);
}
return true;
}
/**
* A process only knows another process's run while it subscribes to the
* thread, so a server answering a bare abort request usually knows none.
* The thread lease names the run holding the thread wherever it executes;
* stop that run the way {@link abortRunStream} does (#28310).
*/
async #abortThreadLeaseOwner(options) {
const runId = await require_run_registry.agentThreadStreamRuntime.getThreadLeaseOwnerRunId(this.getPubSub(), options);
if (!runId) return false;
if (options.expectedRunId !== void 0 && options.expectedRunId !== runId) return false;
await Promise.all([require_run_registry.agentThreadStreamRuntime.requestThreadRunAbort(this.getPubSub(), options, runId), options.clearPendingSignals ? void 0 : require_run_registry.publishAbortRequest(this.pubsub, runId)]);
return true;
}
abortRunStream(runId) {
return super.abortRunStream(runId) || this.#runRegistry.get(runId) !== void 0 || require_run_registry.getRunRegistryEntry(runId, this.#mastra) !== void 0 || require_run_registry.agentThreadStreamRuntime.hasThreadRun(runId, this.getPubSub());
}
__abortLocalRun(runId) {
const wrapperClose = require_run_registry.getRunStreamSlot(this.#activeStreamUntilIdle, runId);
if (wrapperClose) {
wrapperClose();
return true;
}
const aborted = super.__abortLocalRun(runId);
const controller = (this.#runRegistry.get(runId) ?? require_run_registry.getRunRegistryEntry(runId, this.#mastra))?.abortController;
this.#abortLocalController(runId);
return aborted || this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger) === "default" && controller !== void 0;
}
/**
* Abort `runId` and resolve whether the abort was confirmed.
*
* Only a close this process performs itself counts as local confirmation. A
* run-registry entry does not: an evented run keeps one here while another
* process executes its steps, possibly a dead one. Every other run gets a
* single correlated request, and only the executor's answer confirms it.
* The local controller is flipped after that answer, so an executor in this
* process cannot unwind and drop its listener before the request reaches it.
*
* @internal Used by the server's run abort route.
*/
async __abortRunAcknowledged(runId) {
const wrapperClose = require_run_registry.getRunStreamSlot(this.#activeStreamUntilIdle, runId);
if (wrapperClose) {
wrapperClose();
return true;
}
if (require_run_registry.agentThreadStreamRuntime.abortRun(runId, this.getPubSub())) {
this.#abortLocalController(runId);
this.requestRemoteAbort(runId);
if (await this.#cancelParkedRun(runId)) await this.#announceCanceledRun(runId);
return true;
}
try {
const canceled = await this.#cancelParkedRun(runId);
if (canceled) await this.#announceCanceledRun(runId);
return await require_run_registry.requestAcknowledgedAbort(this.pubsub, runId) || canceled;
} finally {
this.#abortLocalController(runId);
}
}
/**
* Record the abort of a parked run in shared storage, so a resume on any server
* refuses it. The in-process resume fence only covers this process. The status
* moves from `suspended` to `canceled` with a guarded write: a resume that claimed
* the run first has already moved it to `running`, and that run is stopped by the
* abort request instead. Stores that cannot enforce the guard atomically get the
* same check on a best-effort basis, so a finished or running run is never marked
* canceled. Stores without concurrent updates (some don't implement
* `updateWorkflowState`) get the canceled status by rewriting the run's snapshot,
* which every store supports. Resolves whether this call canceled the parked run.
* Storage errors propagate: an abort acknowledged without this write would not stop
* another server from resuming the run.
*/
async #cancelParkedRun(runId) {
return this.executionEngine.cancelParkedRun(runId);
}
/**
* Publish the abort terminal for a parked run this call just canceled. The bus is
* shared, so observers on every server close now, whichever server later refuses
* the approval. Only the call that won the cancel publishes. A failed publish does
* not undo the abort: the cancel is already stored, and a refused resume on this
* server retries the publish.
*/
async #announceCanceledRun(runId) {
return this.executionEngine.announceCanceledRun(runId, this.pubsub);
}
async #isRunCanceledInStorage(runId) {
return this.executionEngine.isRunCanceledInStorage(runId);
}
/**
* A durable run parked on a suspension has no prepared run in this process, so the
* base abort cannot tell it was parked and never deletes its snapshot. Once a resume
* is rejected by the abort fence the run can never continue; delete its snapshot rows
* if they are still suspended so it drops out of `listSuspendedRuns()` (#27619), and
* publish the abort terminal so observers still attached to the parked run close.
* Done here rather than at abort time: a run still executing in this process unwinds
* through its own abort path, which reads the snapshot.
* A run the abort already marked `canceled` keeps its row, since that row is what
* stops other servers from resuming it; its abort terminal was published by the
* abort, and is published here only if that publish failed.
*/
async #deleteFencedSuspendedRun(runId) {
try {
const snapshot = await this.executionEngine.loadRunSnapshot(runId);
if (snapshot?.status === "canceled") {
await this.executionEngine.publishCanceledRunTerminal(runId, this.pubsub);
return;
}
if (snapshot?.status !== "suspended") return;
await this.deleteRunSnapshots(runId);
await require_run_registry.emitAbortEvent(this.pubsub, runId, {
steps: [],
text: ""
});
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`Failed to delete snapshot of aborted suspended run ${runId}`, {
runId,
error
});
}
}
/** Flip the controller this process holds for `runId`, if it holds one. */
#abortLocalController(runId) {
const controller = (this.#runRegistry.get(runId) ?? require_run_registry.getRunRegistryEntry(runId, this.#mastra))?.abortController;
if (controller && !controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("Aborted"));
}
async #redeliverDeadlineError(entry, fence) {
if (!fence.deadlineError) return false;
if (!entry.deadlineErrorRedelivered) {
entry.deadlineErrorRedelivered = true;
await this.emitError(fence.runId, fence.deadlineError, fence.generation);
}
return true;
}
/**
* Install `abortController` on a registry entry with the run-level execution
* budget (`modelSettings.timeout.totalMs`, #21724 parity port) composed in.
*
* Every durable step reads `abortSignal` off the registry, so composing here
* bounds the whole session — every loop iteration, tool call and retry.
* Pass-through when no budget is configured. The budget is armed per
* execution session (stream/generate/resume), matching the main loop where
* each session gets a fresh timer. The timer is torn down via the entry's
* `cleanup` slot, which every settle path invokes through the run registry.
*/
#installAbortWithTotalTimeout(entry, abortController, executionFence) {
entry.abortController = abortController;
entry.deadlineErrorRedelivered = false;
const totalTimeout = require_stream.createTimeoutAbortSignal({
parentSignal: abortController.signal,
timeoutMs: entry.timeoutTotalMs,
timeoutType: "total",
detachParentOnCleanup: false
});
entry.abortSignal = totalTimeout.signal;
if (totalTimeout.timeoutPromise) totalTimeout.timeoutPromise.catch(async (error) => {
if (!require_stream.isMastraTimeoutError(error) || error.timeoutType !== "total" || totalTimeout.signal?.reason !== error) return;
await this.settleExecution(executionFence.runId, executionFence, {
status: "failed",
error
});
}).catch((error) => {
this.logger.warn("Failed to settle durable agent at its total deadline", { error });
});
executionFence.whenSettled.then(() => totalTimeout.cleanup());
const previousCleanup = entry.cleanup;
entry.cleanup = () => {
totalTimeout.cleanup();
previousCleanup?.();
};
}
/**
* Delete the persisted workflow snapshot rows for a completed durable run.
*
* A durable agent write two rows per run: one for the outer `AGENTIC_LOOP`
* workflow and one for the nested `AGENTIC_EXECUTION` workflow (persisted
* under the same `runId`). Once the run reaches a non-suspended terminal
* state neither row is needed again — leaving them behind fills snapshot
* storage with stale `pending`/`running` rows for every completed run and
* pollutes `listActiveRuns` / `recoverActiveRuns` on the next boot.
*
* Best-effort: a cleanup failure must never turn a finished run into an
* error — a stale row is preferable to a broken exit path.
*
* @internal
*/
async deleteRunSnapshots(runId) {
try {
await this.executionEngine.deleteRunSnapshots(runId, this.getWorkflow());
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to delete workflow snapshot rows after terminal state`, {
runId,
error
});
}
}
/**
* Stream a response from the agent using durable execution.
*/
async stream(messages, options) {
options = await this.#resolveExecutionOptions(applyReservedMemoryContextKeys(options));
if (options?.untilIdle) {
const { untilIdle, ...rest } = options;
const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
return runDurableStreamUntilIdle({
id: this.id,
getDefaultOptions: () => ({}),
getMemory: (args) => this.getMemory(args),
stream: (innerMessages, innerOptions) => this.stream(innerMessages, innerOptions)
}, messages, {
...rest,
maxIdleMs
}, {
activeStreams: this.#activeStreamUntilIdle,
bgManager: this.#mastra?.backgroundTaskManager
});
}
await this.requireAgentExecutionFGA({
requestContext: options?.requestContext,
memory: options?.memory,
runId: options?.runId,
actor: options?.actor
});
require_run_registry.validateModelTimeoutSettings(options?.modelSettings?.timeout);
const runId = options?.runId ?? crypto.randomUUID();
const requestContext = options?.requestContext ?? new require_request_context.RequestContext();
const executionFence = await this.#claimExecution(runId, "acquire", requestContext);
let preparation;
try {
preparation = await prepareForDurableExecution({
agent: this.#wrappedAgent,
messages,
options,
runId,
requestContext,
optionsAreResolved: true,
resolvedDefaultOptions: options?.[RESOLVED_DEFAULT_OPTIONS],
scopesResolved: true,
mastra: this.#mastra,
durableAgentId: this.id,
durableAgentName: this.name
});
} catch (error) {
await executionFence.settle(async () => {});
throw error;
}
const { messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;
require_run_registry.setExecutionClaim(requestContext, runId, executionFence.claim);
registryEntry.executionFence = executionFence;
this.#runInputs.set(executionFence, workflowInput);
const { controller: abortController } = require_run_registry.createRunAbortController(options?.abortSignal);
if (require_run_registry.agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
this.#installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);
registryEntry.agentId = this.id;
this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, {
threadId,
resourceId
});
const globalRegistryEntry = {
...registryEntry,
messageList
};
require_run_registry.globalRunRegistry.set(runId, globalRegistryEntry);
await this.#attachStreamPublisher(runId, {
threadId,
resourceId
});
const segment = this.#beginSegment(runId);
let streamCleanup;
const runCleanup = createRunCleanup({
scheduleTimer: (cleanup) => this.#scheduleReaderCleanup(executionFence, cleanup),
release: () => {
require_run_registry.agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
streamCleanup?.();
if (this.#releaseSegment(runId, segment, registryEntry)) {
if (require_run_registry.getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {
require_run_registry.globalRunRegistry.delete(runId);
if (!this.#unverifiedReaderFences.has(executionFence) && (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)) this.#clearPubsubTopic(runId, globalRegistryEntry);
}
}
}
});
const performCleanup = runCleanup.run;
const scheduleAutoCleanup = runCleanup.schedule;
const closeOnSuspend = options?.closeOnSuspend ?? false;
const closeOnPersistedSuspend = closeOnSuspend && this.suspendPersistedOnReturn;
const { output, cleanup: createdStreamCleanup, detach: detachStream, waitForEventDelivery, ready } = require_run_registry.createDurableAgentStream({
pubsub: this.pubsub,
runId,
minGeneration: executionFence.generation,
onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),
readLocalRequest,
messageId,
model: {
modelId: workflowInput.modelConfig.modelId,
provider: workflowInput.modelConfig.provider,
version: "v3"
},
threadId,
resourceId,
onChunk: options?.onChunk,
experimentalTransform: options?.experimentalTransform,
onStepFinish: options?.onStepFinish,
onFinish: options?.onFinish,
onStreamFinished: scheduleAutoCleanup,
onError: async (error) => {
await options?.onError?.(error);
scheduleAutoCleanup();
},
onSuspended: options?.onSuspended,
onAbort: async (data) => {
try {
await (options?.onAbort)?.(data);
} finally {
scheduleAutoCleanup();
}
},
closeOnSuspend: closeOnSuspend && !closeOnPersistedSuspend,
hideSignals: options?.hideSignals,
structuredOutput: registryEntry.structuredOutput,
outputProcessors: registryEntry.outputProcessors,
processorStates: registryEntry.processorStates,
agent: registryEntry.agent,
requestContext: registryEntry.requestContext,
returnScorerData: workflowInput.options.returnScorerData,
tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
messageList
});
streamCleanup = createdStreamCleanup;
const workflowExecution = executionFence.run(() => ready.then(async () => {
if (await this.#redeliverDeadlineError(registryEntry, executionFence)) return;
await require_run_registry.emitChunkEvent(require_run_registry.fencePubSub(this.pubsub, executionFence), runId, {
type: "start",
runId,
from: "AGENT",
payload: {
id: workflowInput.agentId,
messageId
}
});
if (this.__getGoalConfig()) await require_run_registry.beginGoalActivity({
mastra: this.#mastra,
agentId: workflowInput.agentId,
threadId,
runId,
requestContext: require_run_registry.getRunRegistryEntry(runId, this.#mastra)?.requestContext
});
let result;
try {
await this.persistInitialInput(runId, workflowInput);
result = await this.executeWorkflow(runId, workflowInput);
} finally {
await require_run_registry.stopGoalActivity({
agentId: workflowInput.agentId,
runId
});
}
if (closeOnPersistedSuspend && result?.status === "suspended") {
await this.pubsub.flush();
await waitForEventDelivery();
detachStream();
}
}).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
const trackedEntry = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
await require_run_registry.agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
continuation: closeOnSuspend ? void 0 : "across-suspension",
generation: executionFence.generation,
ownershipLost: () => executionFence.isLost(),
stepOwner: () => require_run_registry.getRunRegistryEntry(runId, this.#mastra)
});
const cleanup = () => {
if (runCleanup.done || output.status !== "running") return performCleanup();
Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
};
const abort = async (reason) => {
if (!abortController.signal.aborted) abortController.abort(reason);
await this.requestRemoteAbort(runId);
if (require_run_registry.agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);
};
return {
output,
get fullStream() {
return output.fullStream;
},
runId,
threadId,
resourceId,
cleanup,
abort
};
}
/**
* Resume a suspended workflow execution.
*/
async resume(runId, resumeData, options) {
const abortedRunError = () => new require_error.MastraError({
id: "AGENT_RESUME_ABORTED_RUN",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" cannot resume aborted run "${runId}".`,
details: {
agentName: this.name,
runId
}
});
if (require_run_registry.agentThreadStreamRuntime.isResumeFenced(runId, this.getPubSub())) {
await this.#deleteFencedSuspendedRun(runId);
throw abortedRunError();
}
const toolCallId = options?.toolCallId;
let releaseResumeMarker = () => {};
if (toolCallId !== void 0) {
const release = require_run_registry.markResumeInFlight(runId, toolCallId);
if (!release) throw new require_error.MastraError({
id: "AGENT_RESUME_ALREADY_CLAIMED",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" resume(${runId}) cannot resume the run because another resume of it is already running.`,
details: {
agentName: this.name,
runId,
toolCallId
}
});
releaseResumeMarker = release;
}
try {
if (await this.#isRunCanceledInStorage(runId)) throw abortedRunError();
return await this.#resumeRun(runId, resumeData, options, releaseResumeMarker);
} catch (error) {
releaseResumeMarker();
throw error;
}
}
/**
* A resume claims the run by marking it `running` (#27619). When the process holding
* that claim dies, nothing else moves the run on, so the run would stay unresumable.
* Recover the run once the claim's lease has lapsed: when no running progress was
* checkpointed (the default snapshot policy) recovery parks it at its suspension
* again and this resume goes on; otherwise recovery finishes it.
*/
async #takeOverResumeClaim(runId, workflowsStore) {
const outcome = (await this.recoverActiveRuns({ runId })).recovered[0];
if (outcome?.status === "skipped") throw new require_error.MastraError({
id: "AGENT_RESUME_ALREADY_CLAIMED",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" resume(${runId}) cannot resume the run because another resume of it is still running.`,
details: {
agentName: this.name,
runId,
reason: outcome.reason ?? "",
retryAt: outcome.retryAt ?? ""
}
});
if (outcome?.status === "failed" && outcome.error) throw outcome.error;
const persisted = await workflowsStore.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
if (!persisted) throw new require_error.MastraError({
id: "AGENT_RESUME_RUN_FINISHED",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
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.`,
details: {
agentName: this.name,
runId
}
});
return typeof persisted.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted.snapshot;
}
async #resumeRun(runId, resumeData, options, releaseResumeMarker) {
let entry = this.#runRegistry.get(runId);
let rehydratedScopes;
let coldSnapshot;
if (!entry) {
const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
const persisted = await workflowsStore?.getWorkflowRunById({
runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP
});
if (!persisted) throw new require_error.MastraError({
id: "AGENT_RESUME_NO_SNAPSHOT_FOUND",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `No registry entry found for run ${runId}. Cannot resume.`,
details: {
agentName: this.name,
runId
}
});
let snapshot = typeof persisted.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted.snapshot;
const readWorkflowInput = (snapshot, allowRunning = false) => {
if (snapshot?.status !== "suspended" && !(allowRunning && snapshot?.status === "running")) throw new require_error.MastraError({
id: "AGENT_RESUME_RUN_NOT_SUSPENDED",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" resume(${runId}) cannot resume the run because it is not waiting to be resumed (status: ${snapshot?.status}).`,
details: {
agentName: this.name,
runId,
status: snapshot?.status
}
});
const input = snapshot?.context?.input;
if (!input || input.__workflowKind !== "durable-agent") throw new require_error.MastraError({
id: "DURABLE_AGENT_RESUME_INVALID_SNAPSHOT",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.SYSTEM,
text: `DurableAgent "${this.name}" resume(${runId}): persisted snapshot does not contain a durable-agent workflow input.`,
details: {
agentName: this.name,
runId
}
});
if (input.agentId !== this.id) throw new require_error.MastraError({
id: "DURABLE_AGENT_RESUME_AGENT_MISMATCH",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" resume(${runId}): persisted run belongs to agent "${input.agentId}", not "${this.id}".`,
details: {
agentName: this.name,
runId,
ownerAgentId: input.agentId
}
});
return input;
};
let workflowInput = readWorkflowInput(snapshot, true);
const pinnedVersionId = workflowInput.agentVersionId;
if (pinnedVersionId && this.#mastra && !this.__isStoredVersionApplied()) {
const callSiteSelector = options?.versions?.agents?.[this.id];
const hasExplicitVersion = !!callSiteSelector && "versionId" in callSiteSelector;
const currentVersionId = this.toRawConfig()?.resolvedVersionId;
if (!hasExplicitVersion && pinnedVersionId !== currentVersionId) {
let resolved;
try {
resolved = await this.#mastra.resolveVersionedAgent(this, { versionId: pinnedVersionId });
} catch (versionError) {
this.logger.warn("Failed to resolve pinned agent version for durable resume, using current definition", {
agentId: this.id,
runId,
pinnedVersionId,
error: versionError
});
}
if (resolved && resolved !== this) {
releaseResumeMarker();
return resolved.resume(runId, resumeData, options);
}
}
}
if (snapshot?.status === "running" && workflowsStore) {
this.#wrappedAgent.__validateStaticModelTimeoutSettings(options?.modelSettings);
require_run_registry.validateModelTimeoutSettings((options?.modelSettings ?? workflowInput.options?.modelSettings)?.timeout);
snapshot = await this.#takeOverResumeClaim(runId, workflowsStore);
workflowInput = readWorkflowInput(snapshot);
}
coldSnapshot = snapshot;
const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
const threadId = workflowInput.state?.threadId ?? messageListMemoryInfo?.threadId;
const resourceId = workflowInput.state?.resourceId ?? messageListMemoryInfo?.resourceId;
const snapshotRequestContext = workflowInput.requestContextEntries ? new require_request_context.RequestContext(Object.entries(require_request_context.withoutLiveRequestKeys(workflowInput.requestContextEntries))) : void 0;
if (snapshotRequestContext) require_run_registry.restoreRunAgentScopes(snapshotRequestContext);
const persistedScopes = workflowInput.requestContextEntries?.[require_request_context.MASTRA_SCOPES_KEY];
if (persistedScopes !== void 0 && (!Array.isArray(persistedScopes) || persistedScopes.some((scope) => typeof scope !== "string"))) throw new require_error.MastraError({
id: "AGENT_SCOPES_INVALID",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.SYSTEM,
text: `DurableAgent "${this.name}" resume(${runId}): persisted run scopes are malformed; expected an array of strings.`,
details: {
agentName: this.name,
runId
}
});
rehydratedScopes = persistedScopes;
const memory = threadId ? {
...options?.memory,
thread: threadId,
resource: resourceId ?? options?.memory?.resource
} : options?.memory;
await this.prepare([], {
[SCOPES_ALREADY_APPLIED]: true,
[RESUMED_SPAN_DATA]: {
agentSpanData: workflowInput.agentSpanData,
modelSpanData: workflowInput.modelSpanData
},
...options,
runId,
requestContext: options?.requestContext ?? snapshotRequestContext,
memory,
returnScorerData: options?.returnScorerData ?? workflowInput.options?.returnScorerData,
modelSettings: options?.modelSettings ?? workflowInput.options?.modelSettings
});
entry = this.#runRegistry.get(runId);
}
if (!entry) throw new Error(`Failed to rehydrate registry entry for run ${runId}. Cannot resume.`);
const memoryInfo = this.#runRegistry.getMemoryInfo(runId);
const registeredMemory = memoryInfo?.threadId ? {
...options?.memory,
thread: memoryInfo.threadId,
resource: memoryInfo.resourceId ?? options?.memory?.resource
} : options?.memory;
const snapshotScopes = coldSnapshot ? rehydratedScopes : entry.requestContext?.get("mastra__scopes") ?? [];
const resumeScopesSnapshot = {
resourceId: memoryInfo?.resourceId,
threadId: memoryInfo?.threadId,
scopes: Array.isArray(snapshotScopes) ? snapshotScopes : void 0
};
const carriedEntries = entry.requestContext ? Object.entries(require_request_context.withoutLiveRequestKeys(Object.fromEntries(entry.requestContext.entries()))) : void 0;
const droppedStartingUser = carriedEntries !== void 0 && carriedEntries.length < entry.requestContext.size();
let resumeRequestContext = droppedStartingUser ? new require_request_context.RequestContext(carriedEntries) : entry.requestContext;
if (options?.requestContext) {
resumeRequestContext = options.requestContext;
for (const [key, value] of carriedEntries ?? []) {
if (key === "mastra__scopes") continue;
if (!resumeRequestContext.has(key)) resumeRequestContext.set(key, value);
}
if (entry.requestContext?.has("MastraMemory")) resumeRequestContext.set("MastraMemory", entry.requestContext.get("MastraMemory"));
else resumeRequestContext.delete("MastraMemory");
}
resumeRequestContext ??= new require_request_context.RequestContext();
const resolvedOptions = await this.#resolveExecutionOptions({
...options,
requestContext: resumeRequestContext,
memory: registeredMemory ?? options?.memory
}, resumeScopesSnapshot);
require_run_registry.validateModelTimeoutSettings(resolvedOptions.modelSettings?.timeout);
resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
entry.requestContext = resumeRequestContext;
const globalEntryForContext = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
if (globalEntryForContext) globalEntryForContext.requestContext = resumeRequestContext;
if (resolvedOptions.untilIdle) {
const { untilIdle, ...rest } = resolvedOptions;
const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
releaseResumeMarker();
return runResumeDurableStreamUntilIdle({
id: this.id,
getDefaultOptions: () => ({}),
getMemory: (args) => this.getMemory(args),
resume: (innerRunId, innerResumeData, innerOptions) => this.resume(innerRunId, innerResumeData, innerOptions),
stream: (innerMessages, innerOptions) => this.stream(innerMessages, innerOptions)
}, runId, resumeData, {
...rest,
maxIdleMs
}, {
activeStreams: this.#activeStreamUntilIdle,
bgManager: this.#mastra?.backgroundTaskManager
});
}
await this.requireAgentExecutionFGA({
requestContext: resolvedOptions.requestContext,
memory: resolvedOptions.memory,
runId,
snapshotMemoryInfo: memoryInfo,
actor: resolvedOptions.actor
});
const priorExecution = require_run_registry.getRunRegistryEntry(runId, this.#mastra)?.workflowExecution;
await priorExecution?.catch(() => {});
if (!coldSnapshot && (options?.requestContext || options?.delegation || options?.hooks || droppedStartingUser)) try {
const requestTools = await this.#wrappedAgent.getToolsForExecution({
toolsets: resolvedOptions.toolsets,
clientTools: resolvedOptions.clientTools,
threadId: memoryInfo?.threadId,
resourceId: memoryInfo?.resourceId,
runId,
requestContext: resumeRequestContext,
memoryConfig: resolvedOptions.memory?.options,
autoResumeSuspendedTools: resolvedOptions.autoResumeSuspendedTools,
delegation: options?.delegation ? resolvedOptions.delegation : entry.delegation ?? resolvedOptions.delegation,
hooks: resolvedOptions.hooks,
methodType: entry.methodType ?? "stream",
backgroundTaskEnabled: Boolean(entry.backgroundTaskManager),
backgroundTaskPolicy: resolvedOptions.backgroundTaskPolicy,
model: entry.model
});
const refresh = (current, previous) => {
const next = { ...current };
for (const [name, tool] of Object.entries(requestTools)) if (name in current ? current[name] === previous?.[name] : !previous || !(name in previous)) next[name] = tool;
return next;
};
for (const reg of /* @__PURE__ */ new Set([entry, require_run_registry.getRunRegistryEntry(runId, this.#mastra)])) {
if (!reg) continue;
reg.tools = require_utils.rebindProcessorTools(refresh(reg.tools ?? {}, reg.requestTools), resumeRequestContext);
if (reg.baseTools) reg.baseTools = require_utils.rebindProcessorTools(refresh(reg.baseTools, reg.requestTools), resumeRequestContext);
reg.requestTools = {
...reg.requestTools,
...requestTools
};
if (options?.delegation) reg.delegation = resolvedOptions.delegation;
}
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] resume(${runId}) tool resolution failed: ${error}`);
}
const executionFence = await this.#claimExecution(runId, "acquire");
let initialToolCalls;
let resumedText;
let resumeOffset;
let persistedInput;
try {
const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
const current = await workflowsStore?.loadWorkflowSnapshot({
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP,
runId
});
if (workflowsStore && !current && priorExecution) throw new require_error.MastraError({
id: "AGENT_RESUME_NO_SNAPSHOT_FOUND",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
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.`,
details: {
agentName: this.name,
runId
}
});
if (current && ![
"suspended",
"running",
"pending",
"waiting"
].includes(current.status)) throw new require_error.MastraError({
id: "AGENT_RESUME_ALREADY_CLAIMED",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" resume(${runId}) cannot resume the run because another resume of it already ran.`,
details: {
agentName: this.name,
runId
}
});
if (resumeRequestContext) await this.#coverMemory(executionFence, resumeRequestContext);
await this.#loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);
({toolCalls: initialToolCalls, resumedText} = await this.#loadSuspendedIteration(runId));
resumeOffset = await this.#getPubsubOffset(runId);
persistedInput = current?.context?.input;
await require_run_registry.agentThreadStreamRuntime.reacquireParkedRunLease(runId, this.getPubSub());
} catch (error) {
await executionFence.settle(async () => {});
throw error;
}
require_run_registry.setExecutionClaim(resumeRequestContext, runId, executionFence.claim);
for (const reg of [entry, require_run_registry.getRunRegistryEntry(runId, this.#mastra)]) {
if (!reg) continue;
reg.executionFence = executionFence;
reg.resumeToolCallId = resolvedOptions.toolCallId;
}
const { controller: abortController, detach: detachExternalAbort } = require_run_registry.createRunAbortController(resolvedOptions.abortSignal);
if (require_run_registry.agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
const resumeTotalMs = resolvedOptions.modelSettings?.timeout?.totalMs;
if (resumeTotalMs !== void 0) entry.timeoutTotalMs = resumeTotalMs;
if (persistedInput) this.#runInputs.set(executionFence, persistedInput);
this.#installAbortWithTotalTimeout(entry, abortController, executionFence);
const globalEntryForAbort = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
if (globalEntryForAbort) {
globalEntryForAbort.abortController = abortController;
globalEntryForAbort.abortSignal = entry.abortSignal;
}
const segment = this.#beginSegment(runId);
let streamCleanup;
let lostResumeRace = false;
const runCleanup = createRunCleanup({
scheduleTimer: (cleanup) => this.#scheduleReaderCleanup(executionFence, cleanup),
release: () => {
require_run_registry.agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
streamCleanup?.();
if (this.#releaseSegment(runId, segment, entry)) {
if (require_run_registry.getRunRegistryEntry(runId, this.#mastra) === globalEntryForAbort) {
require_run_registry.globalRunRegistry.delete(runId);
if (!this.#unverifiedReaderFences.has(executionFence) && !lostResumeRace && (globalEntryForAbort?.executionFence ?? executionFence).ownsRunTopics()) this.#clearPubsubTopic(runId, globalEntryForAbort);
}
}
}
});
const performCleanup = runCleanup.run;
const scheduleAutoCleanup = runCleanup.schedule;
const globalEntry = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
const resumeModel = globalEntry?.model;
const origTraceId = entry.agentSpan?.traceId;
const origSpanId = entry.agentSpan?.id;
const ownResumeSpans = [];
if (origTraceId && this.#mastra?.observability) try {
const ag = this.#wrappedAgent;
const resolvedVersionId = (typeof ag.toRawConfig === "function" ? ag.toRawConfig() : void 0)?.resolvedVersionId;
const agentTracingPolicy = typeof ag.getTracingPolicy === "function" ? ag.getTracingPolicy() : void 0;
const resumeAgentSpan = require_utils$1.getOrCreateSpan({
type: "agent_run",
outcome: null,
name: `agent run: '${ag.id}' (resumed)`,
entityType: require_storage.EntityType.AGENT,
entityId: ag.id,
entityName: ag.name,
attributes: require_run_registry.modelSpanAttributes(resumeModel),
metadata: {
runId,
resumed: true,
...origSpanId ? { resumedFromSpanId: origSpanId } : {},
...resolvedVersionId ? { entityVersionId: resolvedVersionId } : {}
},
resumeFrom: require_utils$1.getResumeTracingContext(entry.agentSpan),
tracingPolicy: agentTracingPolicy,
tracingOptions: {
traceId: origTraceId,
...entry.agentSpan?.traceState
},
traceState: entry.agentSpan?.traceState,
samplingDecision: entry.agentSpan?.isValid,
requestContext: resolvedOptions.requestContext,
mastra: this.#mastra
});
const resumeModelSpan = resumeAgentSpan?.createChildSpan({
type: "model_generation",
outcome: null,
name: `llm: '${resumeModel?.modelId ?? ""}'`,
attributes: {
model: resumeModel?.modelId,
provider: resumeModel?.provider,
streaming: true
},
metadata: {
runId,
resumed: true
},
requestContext: resolvedOptions.requestContext
});
ownResumeSpans.push(resumeModelSpan, resumeAgentSpan);
for (const reg of [entry, require_run_registry.getRunRegistryEntry(runId, this.#mastra)]) {
if (!reg) continue;
reg.resumeAgentSpan = resumeAgentSpan;
reg.resumeModelSpan = resumeModelSpan;
reg.resumeAgentSpanData = resumeAgentSpan?.snapshot?.() ?? resumeAgentSpan?.exportSpan();
reg.resumeModelSpanData = resumeModelSpan?.snapshot?.() ?? resumeModelSpan?.exportSpan();
reg.resumeCompletionStartTime = void 0;
reg.resumeTimeToFirstTokenMs = void 0;
}
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open resume spans: ${error}`);
}
const resumeSegmentSpan = entry.resumeAgentSpan ?? entry.agentSpan;
const closeOnSuspend = resolvedOptions.closeOnSuspend ?? false;
const { output, cleanup: createdStreamCleanup, detach: detachResumeStream, fail: failResumeStream, waitForEventDelivery, ready } = require_run_registry.createDurableAgentStream({
pubsub: this.pubsub,
runId,
minGeneration: executionFence.generation,
onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),
messageId: crypto.randomUUID(),
initialToolCalls,
resumedText,
model: {
modelId: resumeModel?.modelId,
provider: resumeModel?.provider,
version: "v3"
},
threadId: memoryInfo?.threadId,
resourceId: memoryInfo?.resourceId,
offset: resumeOffset,
onChunk: resolvedOptions.onChunk,
experimentalTransform: resolvedOptions.experimentalTransform,
hideSignals: resolvedOptions.hideSignals,
onStepFinish: resolvedOptions.onStepFinish,
onFinish: resolvedOptions.onFinish,
onStreamFinished: scheduleAutoCleanup,
onError: async (error) => {
await resolvedOptions.onError?.(error);
scheduleAutoCleanup();
},
onAbort: async (data) => {
try {
await resolvedOptions.onAbort?.(data);
} finally {
scheduleAutoCleanup();
}
},
onSuspended: resolvedOptions.onSuspended,
closeOnSuspend: false,
structuredOutput: entry.structuredOutput,
outputProcessors: entry.outputProcessors,
processorStates: entry.processorStates,
agent: entry.agent,
requestContext: resolvedOptions.requestContext,
returnScorerData: options?.returnScorerData ?? entry.returnScorerData ?? resolvedOptions.returnScorerData,
tracingContext: resumeSegmentSpan ? { currentSpan: resumeSegmentSpan } : void 0,
messageList: globalEntry?.messageList ?? this.#runRegistry.getMessageList(runId)
});
streamCleanup = createdStreamCleanup;
const requestContext = resolvedOptions.requestContext;
const workflowExecution = executionFence.run(() => ready.then(async () => {
if (await this.#redeliverDeadlineError(entry, executionFence)) return;
const workflow = this.getWorkflow();
await this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);
const run = await workflow.createRun({
runId,
resourceId: memoryInfo?.resourceId,
pubsub: this.fenceRunPubSub(executionFence, abortController)
});
if (this.__getGoalConfig()) await require_run_registry.beginGoalActivity({
mastra: this.#mastra,
agentId: this.id,
threadId: memoryInfo?.threadId,
runId,
requestContext
});
let result;
try {
result = await this.withSuspensionAfterPersist(runId, () => run.resume({
resumeData,
label: resolvedOptions.toolCallId,
requestContext,
actor: resolvedOptions.actor,
...require_observability.createObservabilityContext({ currentSpan: entry.resumeAgentSpan ?? entry.agentSpan })
}));
} catch (error) {
if (error instanceof require_error.MastraError && (error.id === "WORKFLOW_RUN_NOT_SUSPENDED" || error.id === "WORKFLOW_RESUME_ALREADY_CLAIMED")) {
const lost = new require_error.MastraError({
id: "AGENT_RESUME_ALREADY_CLAIMED",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" resume(${runId}) cannot resume the run because another resume of it already ran.`,
details: {
agentName: this.name,
runId
}
});
lostResumeRace = true;
await executionFence.settle(async () => {});
for (const span of ownResumeSpans) span?.error({
error: lost,
endSpan: true
});
await failResumeStream(lost);
return;
}
throw error;
} finally {
await require_run_registry.stopGoalActivity({
agentId: this.id,
runId
});
if (result?.status !== "suspended" && workflow.runs.get(runId) === run) workflow.runs.delete(runId);
}
await this.settleExecution(runId, executionFence, {
status: result?.status,
error: result?.status === "failed" ? this.executionEngine.workflowFailureError(result.error, "Workflow resume failed") : void 0
});
if (result?.status === "suspended" && closeOnSuspend) {
await this.pubsub.flush();
await waitForEventDelivery();
detachResumeStream();
}
}).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow resume failed") })).finally(detachExternalAbort));
const trackedResumeEntry = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
if (trackedResumeEntry) trackedResumeEntry.workflowExecution = workflowExecution;
workflowExecution.then(releaseResumeMarker, releaseResumeMarker);
const resumeStreamOptions = {
...resolvedOptions,
runId
};
if (!require_run_registry.agentThreadStreamRuntime.continueRun(this, output, resumeStreamOptions, this.getPubSub(), {
generation: executionFence.generation,
ownershipLost: () => executionFence.isLost()
})) await require_run_registry.agentThreadStreamRuntime.registerRun(this, output, resumeStreamOptions, this.getPubSub(), {
continuation: closeOnSuspend ? void 0 : "across-suspension",
generation: executionFence.generation,
ownershipLost: () => executionFence.isLost(),
stepOwner: () => require_run_registry.getRunRegistryEntry(runId, this.#mastra)
});
const cleanup = performCleanup;
const abort = async (reason) => {
if (!abortController.signal.aborted) abortController.abort(reason);
await this.requestRemoteAbort(runId);
if (require_run_registry.agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);
};
return {
output,
get fullStream() {
return output.fullStream;
},
runId,
threadId: memoryInfo?.threadId,
resourceId: memoryInfo?.resourceId,
cleanup,
abort
};
}
/**
* Recover a single durable run whose in-process agentic loop was orphaned by
* a process restart. Streamable counterpart to
* {@link DurableAgent.recoverActiveRuns} — where the bulk API only re-drives
* the workflow and returns counts, `recover()` rebuilds the run's
* non-serializable state (message list, model, tools, memory,
* saveQueueManager, request context, agent span) from the persisted workflow
* snapshot and returns a fresh {@link DurableAgentStreamResult} whose
* `fullStream` observes the recovered run through pubsub.
*
* Because the rebuilt registry entry carries `memory` + `saveQueueManager`,
* the durable agentic workflow's terminal step will flush new messages to
* memory just like a fresh `stream()` call would. The single-run form is
* useful when operators want to attach listeners to a specific recovered
* run; for boot-time bulk recovery of every orphaned run, use
* `recoverActiveRuns()`.
*
* Only orphaned runs are recovered. If another execution still owns the run
* (its lease is live), this throws `DURABLE_AGENT_RUN_ACTIVE` with the
* holder and a `retryAt` hint; pass `{ force: true }` to take the run over,
* which aborts the other execution and rejects its later writes. A run this
* process is already driving or recovering, or one that is suspended, is
* refused with its own error id (use `resume()` for suspended runs).
*
* When the store doesn't fence runs, an execution whose lease lapsed with
* nobody taking the run over keeps the thread's lease until that expires,
* up to 15 seconds later. Until then this throws `DURABLE_AGENT_RUN_ACTIVE`
* with `retryAt` no earlier than the expiry. The lease can't be released
* sooner: an execution that recovers the run in the same process holds it
* under the same run id.
*
* @example
* ```typescript
* const { fullStream, output, cleanup } = await durableAgent.recover(runId, {
* onChunk: chunk => process.stdout.write(chunk.payload?.text ?? ''),
* });
* for await (const chunk of fullStream) {
* // ...
* }
* cleanup();
* ```
*/
async recover(runId, options) {
if (!this.#mastra) throw new require_error.MastraError({
id: "DURABLE_AGENT_RECOVER_NO_MASTRA",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover() requires the agent to be registered on a Mastra instance.`,
details: {
agentName: this.name,
runId
}
});
this.#assertRecoveryActive();
const workflowsStore = await this.#mastra.getStorage()?.getStore("workflows");
if (!workflowsStore) throw new require_error.MastraError({
id: "DURABLE_AGENT_RECOVER_NO_STORAGE",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover() requires persistent storage to load the run snapshot. Register the agent on a Mastra instance with persistent storage (e.g. PostgreSQL, LibSQL).`,
details: {
agentName: this.name,
runId
}
});
await this.#warnIfUnfenced(workflowsStore, "workflows");
let { workflowInput } = await this.#loadRecoverableSnapshot(workflowsStore, runId);
this.#assertRecoveryActive();
const pinnedVersionId = workflowInput.agentVersionId;
if (pinnedVersionId && this.#mastra && !this.__isStoredVersionApplied()) {
if (pinnedVersionId !== this.toRawConfig()?.resolvedVersionId) try {
const resolved = await this.#mastra.resolveVersionedAgent(this, { versionId: pinnedVersionId });
if (resolved !== this) return resolved.recover(runId, options);
} catch (versionError) {
this.logger.warn("Failed to resolve pinned agent version for durable recovery, using current definition", {
agentId: this.id,
runId,
pinnedVersionId,
error: versionError
});
}
}
this.#assertRecoveryActive();
const releaseLocalRecovery = this.#claimLocalRecovery(runId);
const { controller: abortController } = require_run_registry.createRunAbortController(options?.abortSignal);
let executionFence;
let recoveryState;
let finishPublishedBeforeCrash;
let claimedSnapshot;
try {
const localExecution = require_run_registry.ExecutionFence.getLocalActive(runId);
if (localExecution && !localExecution.isLost()) throw new require_error.MastraError({
id: require_run_registry.RECOVER_RUN_ACTIVE_LOCALLY_ERROR_ID,
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" recover(${runId}): this process is still executing the run. Wait for it to finish instead of recovering it.`,
details: {
agentName: this.name,
runId
}
});
executionFence = await this.#claimExecution(runId, options?.force ? "takeover" : "recover", void 0, this.#untrackedRunLiveness(runId, workflowInput));
this.#assertRecoveryActive();
const loaded = await this.#loadRecoverableSnapshot(workflowsStore, runId);
workflowInput = loaded.workflowInput;
claimedSnapshot = loaded.snapshot;
finishPublishedBeforeCrash = loaded.snapshot.context?.[MAP_FINAL_OUTPUT_STEP_ID]?.status === "success";
await this.#loadRecalledMessages(runId, loaded.snapshot);
executionFence.throwIfLost();
recoveryState = await this.#rehydrateRecoveryState({
runId,
workflowInput,
abortController,
executionFence,
originalSpansEnded: originalSpansEndedBeforeCrash(loaded.snapshot),
latestMessageListState: await this.#loadLatestMessageListState(workflowsStore, runId, loaded.snapshot)
});
await this.#coverMemory(executionFence, recoveryState.requestContext, true);
this.#recoveredEntries.set(executionFence, recoveryState.registryEntry);
this.#assertRecoveryActive();
} catch (error) {
const settlement = await executionFence?.settle(async () => {});
if (executionFence && settlement !== "superseded" && shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
releaseLocalRecovery();
throw error;
}
const { requestContext, threadId, resourceId, messageList, recoverAgentSpan, recoverModelSpan, registryEntry } = recoveryState;
if (executionFence.generation !== void 0) {
const supersededFrom = await this.#supersededFrom(workflowsStore, runId, claimedSnapshot);
await require_run_registry.emitOwnershipClaimedEvent(this.pubsub, runId, executionFence.generation, supersededFrom).catch((error) => {
this.logger.warn(`[DurableAgent] recover(${runId}) failed to announce its claim on the run stream`, {
runId,
error
});
});
}
require_run_registry.setExecutionClaim(requestContext, runId, executionFence.claim);
registryEntry.executionFence = executionFence;
let streamCleanup;
const cleanupOwnedRegistryState = () => {
if (registryEntry.executionFence !== executionFence) return;
if (this.#runRegistry.get(runId) === registryEntry) this.#runRegistry.cleanup(runId);
if (require_run_registry.getRunRegistryEntry(runId, this.#mastra) === registryEntry) {
require_run_registry.globalRunRegistry.delete(runId);
if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.#clearPubsubTopic(runId, registryEntry);
}
};
const runCleanup = createRunCleanup({
scheduleTimer: (cleanup) => this.#scheduleReaderCleanup(executionFence, cleanup),
release: () => {
require_run_registry.agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
streamCleanup?.();
cleanupOwnedRegistryState();
}
});
const performCleanup = runCleanup.run;
const scheduleAutoCleanup = runCleanup.schedule;
let workflow;
try {
this.#assertRecoveryActive();
workflow = this.getWorkflow();
} catch (error) {
if (await executionFence.settle(async () => {}) !== "superseded" && shouldReportRecoveryFailure(error)) await this.#reportRecoveryFailure(runId, error, executionFence.generation);
releaseLocalRecovery();
throw error;
}
const { stream, threadRegistration } = await this.#setupRecoveredStream({
runId,
workflowInput,
requestContext,
threadId,
resourceId,
messageList,
registryEntry,
options,
scheduleAutoCleanup,
executionFence
}).catch((error) => {
releaseLocalRecovery();
throw error;
});
const { output, cleanup: createdStreamCleanup, ready } = stream;
streamCleanup = createdStreamCleanup;
const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
const workflowExecution = executionFence.run(() => this.#raceFenceLoss(ready, executionFence).then(async () => {
executionFence.throwIfLost();
this.#assertRecoveryActive();
await this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);
executionFence.throwIfLost();
this.#assertRecoveryActive();
const run = await this.#raceFenceLoss(workflow.createRun({
runId,
resourceId,
pubsub: recoveryPubsub
}), executionFence);
executionFence.throwIfLost();
this.#assertRecoveryActive();
const result = await this.#raceFenceLoss(run.restart({
requestContext,
...require_observability.createObservabilityContext({ currentSpan: recoverAgentSpan })
}), executionFence);
executionFence.throwIfLost();
if (finishPublishedBeforeCrash && result?.status === "success") {
const { output: finalOutput, stepResult } = result.result;
recoverModelSpan?.end();
recoverAgentSpan?.end({ output: { text: finalOutput?.text } });
await require_run_registry.emitFinishEvent(recoveryPubsub, runId, {
output: finalOutput,
stepResult
});
}
if (result?.status === "suspended" && options?.closeOnSuspend) {
await this.pubsub.flush();
await stream.waitForEventDelivery();
executionFence.throwIfLost();
stream.detach();
}
const finished = !!result?.status && result.status !== "suspended";
await executionFence.settle(async () => {
if (finished) await this.deleteRunSnapshots(runId);
});
if (result?.status === "failed") throw this.executionEngine.workflowFailureError(result.error, "Workflow recover failed");
}).catch(async (error) => {
if (error?.id === RECOVER_SHUTDOWN_ERROR_ID) await executionFence.abandon();
const executionError = this.executionEngine.workflowExecutionError(error, "Workflow recover failed");
if (await executionFence.settle(async () => {}) === "superseded") {
const output = {
status: "interrupted",
reason: "recovery superseded"
};
recoverModelSpan?.end({
output,
outcome: "interrupted",
stopReason: null,
stopReasonContext: null
});
recoverAgentSpan?.end({
output,
outcome: "interrupted",
stopReason: null,
stopReasonContext: null
});
await threadRegistration?.rollback({ releaseLease: false });
performCleanup();
} else if (!this.#timedOutExecutions.has(executionFence) && !await this.#reportRecoveryFailure(runId, executionError, executionFence.generation)) {
await threadRegistration?.rollback();
performCleanup();
}
throw executionError;
}).finally(releaseLocalRecovery));
const trackedRecoverEntry = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
if (trackedRecoverEntry) trackedRecoverEntry.workflowExecution = workflowExecution;
workflowExecution.catch(() => {});
const cleanup = performCleanup;
const abort = async (reason) => {
if (!abortController.signal.aborted) abortController.abort(reason);
await this.requestRemoteAbort(runId);
if (require_run_registry.agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);
};
return {
output,
get fullStream() {
return output.fullStream;
},
runId,
threadId,
resourceId,
cleanup,
abort
};
}
/**
* Override the inherited `resumeStream()` so that callers using the base
* `Agent` API (including `approveToolCall` / `declineToolCall`) are routed
* through the durable `resume()` path instead of the regular Agent's
* snapshot-based resume.
*
* Returns just the `MastraModelOutput` (matching the base Agent's return
* type) while internally delegating to `this.resume()`.
*/
async resumeStream(resumeData, streamOptions) {
const runId = streamOptions?.runId;
if (!runId) throw new Error("resumeStream() on DurableAgent requires a runId in streamOptions.");
const { runId: _runId, ...resumeOptions } = streamOptions;
return (await this.resume(runId, resumeData, {
...resumeOptions,
closeOnSuspend: resumeOptions.closeOnSuspend ?? true
})).output;
}
/** @deprecated Use `resumeStream(resumeData, { untilIdle: true })` instead. */
async resumeStreamUntilIdle(resumeData, streamOptions) {
const { maxIdleMs, ...options } = streamOptions ?? {};
return this.resumeStream(resumeData, {
...options,
untilIdle: maxIdleMs === void 0 ? true : { maxIdleMs }
});
}
/**
* Override the inherited `approveToolCall()` to route through the durable
* `resume()` path.
*/
async approveToolCall(options) {
return this.resumeStream({ approved: true }, options);
}
/**
* Override the inherited `declineToolCall()` to route through the durable
* `resume()` path.
*/
async declineToolCall(options) {
const { reason, ...resumeOptions } = options;
return this.resumeStream({
approved: false,
...reason !== void 0 ? { reason } : {}
}, resumeOptions);
}
async approveToolCallGenerate(options) {
const { runId, ...resumeOptions } = options;
return this.resumeGenerate({ approved: true }, {
...resumeOptions,
runId
});
}
async declineToolCallGenerate(options) {
const { runId, reason, ...resumeOptions } = options;
return this.resumeGenerate({
approved: false,
...reason !== void 0 ? { reason } : {}
}, {
...resumeOptions,
runId
});
}
/**
* Generate a complete response from the agent using durable execution.
*
* Drains the underlying durable stream to completion and returns the same
* {@link FullOutput} shape as non-durable `Agent.generate`. The underlying
* workflow is identical to `stream()` — it just collects the final result
* for callers that don't want to consume chunks themselves.
*
* This method intentionally re-implements the `stream()` setup rather than
* delegating to `this.stream(...)` so that `prepareForDurableExecution` (and
* downstream `convertTools`) receives `methodType: 'generate'`. Tool
* factories that vary their `CoreTool` output based on the calling method
* (e.g. `clientTools` vs server-side tools) rely on this signal — calling
* `stream()` here would silently pass `methodType: 'stream'`.
*
* If the run suspends (e.g. tool approval or `suspend()` from a tool), the
* returned output's `finishReason` will be `'suspended'` and
* `suspendPayload` will be populated. Use {@link DurableAgent.resumeGenerate}
* to continue.
*
* Note on suspend persistence: both `DurableAgent` and `EventedAgent` track
* the workflow engine's `run.start()` through snapshot persistence, so
* awaiting `workflowExecution` on suspend is sufficient for a subsequent
* `resumeGenerate()` to find the snapshot.
*/
async generate(messages, options) {
options = await this.#resolveExecutionOptions(applyReservedMemoryContextKeys(options));
await this.requireAgentExecutionFGA({
requestContext: options?.requestContext,
memory: options?.memory,
runId: options?.runId,
actor: options?.actor
});
require_run_registry.validateModelTimeoutSettings(options?.modelSettings?.timeout);
const runId = options?.runId ?? crypto.randomUUID();
const requestContext = options?.requestContext ?? new require_request_context.RequestContext();
const executionFence = await this.#claimExecution(runId, "acquire", requestContext);
let preparation;
try {
preparation = await prepareForDurableExecution({
agent: this.#wrappedAgent,
messages,
options,
runId,
requestContext,
optionsAreResolved: true,
resolvedDefaultOptions: options?.[RESOLVED_DEFAULT_OPTIONS],
scopesResolved: true,
mastra: this.#mastra,
methodType: "generate",
durableAgentId: this.id,
durableAgentName: this.name
});
} catch (error) {
await executionFence.settle(async () => {});
throw error;
}
const { messageId, workflowInput, registryEntry, messageList, threadId, resourceId } = preparation;
require_run_registry.setExecutionClaim(requestContext, runId, executionFence.claim);
registryEntry.executionFence = executionFence;
this.#runInputs.set(executionFence, workflowInput);
const { controller: abortController } = require_run_registry.createRunAbortController(options?.abortSignal);
if (require_run_registry.agentThreadStreamRuntime.isRunAborted(runId, this.getPubSub())) abortController.abort();
this.#installAbortWithTotalTimeout(registryEntry, abortController, executionFence);
const readLocalRequest = createLocalRequestReader(runId, registryEntry, this.#mastra);
registryEntry.agentId = this.id;
this.#runRegistry.registerWithMessageList(runId, registryEntry, messageList, {
threadId,
resourceId
});
const globalRegistryEntry = {
...registryEntry,
messageList
};
require_run_registry.globalRunRegistry.set(runId, globalRegistryEntry);
await this.#attachStreamPublisher(runId, {
threadId,
resourceId
});
const releaseRunState = () => {
if (this.#runRegistry.get(runId) === registryEntry) this.#runRegistry.cleanup(runId);
if (require_run_registry.getRunRegistryEntry(runId, this.#mastra) === globalRegistryEntry) {
require_run_registry.globalRunRegistry.delete(runId);
if (!this.#unverifiedReaderFences.has(executionFence) && (globalRegistryEntry.executionFence?.ownsRunTopics() ?? true)) this.#clearPubsubTopic(runId, globalRegistryEntry);
}
};
const runCleanup = createRunCleanup({
scheduleTimer: (cleanup) => this.#scheduleReaderCleanup(executionFence, cleanup),
release: () => {
require_run_registry.agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
streamCleanup();
releaseRunState();
},
releaseOnTimer: releaseRunState
});
const scheduleAutoCleanup = runCleanup.schedule;
const { output, cleanup: streamCleanup, ready } = require_run_registry.createDurableAgentStream({
pubsub: this.pubsub,
runId,
minGeneration: executionFence.generation,
onTerminalEvent: this.#owningReaderTerminal(runId, executionFence),
readLocalRequest,
messageId,
model: {
modelId: workflowInput.modelConfig.modelId,
provider: workflowInput.modelConfig.provider,
version: "v3"
},
threadId,
resourceId,
onChunk: options?.onChunk,
experimentalTransform: options?.experimentalTransform,
onStepFinish: options?.onStepFinish,
onFinish: options?.onFinish,
onStreamFinished: scheduleAutoCleanup,
onError: async (error) => {
await options?.onError?.(error);
scheduleAutoCleanup();
},
onSuspended: options?.onSuspended,
onAbort: async (data) => {
try {
await (options?.onAbort)?.(data);
} finally {
scheduleAutoCleanup();
}
},
closeOnSuspend: true,
structuredOutput: registryEntry.structuredOutput,
outputProcessors: registryEntry.outputProcessors,
processorStates: registryEntry.processorStates,
agent: registryEntry.agent,
requestContext: registryEntry.requestContext,
returnScorerData: workflowInput.options.returnScorerData,
tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
messageList
});
const workflowExecution = executionFence.run(() => ready.then(async () => {
if (await this.#redeliverDeadlineError(registryEntry, executionFence)) return;
await require_run_registry.emitChunkEvent(require_run_registry.fencePubSub(this.pubsub, executionFence), runId, {
type: "start",
runId,
from: "AGENT",
payload: {
id: workflowInput.agentId,
messageId
}
});
if (this.__getGoalConfig()) await require_run_registry.beginGoalActivity({
mastra: this.#mastra,
agentId: workflowInput.agentId,
threadId,
runId,
requestContext: require_run_registry.getRunRegistryEntry(runId, this.#mastra)?.requestContext
});
try {
await this.persistInitialInput(runId, workflowInput);
return await this.executeWorkflow(runId, workflowInput);
} finally {
await require_run_registry.stopGoalActivity({
agentId: workflowInput.agentId,
runId
});
}
}).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
const trackedEntry = require_run_registry.getRunRegistryEntry(runId, this.#mastra);
if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
const cleanup = runCleanup.run;
let suspended = false;
try {
const fullOutput = await output.getFullOutput();
if (fullOutput.error) throw fullOutput.error;
suspended = fullOutput.finishReason === "suspended";
if (suspended) await require_run_registry.getRunRegistryEntry(runId, this.#mastra)?.workflowExecution;
if (!fullOutput.runId) fullOutput.runId = runId;
return fullOutput;
} finally {
if (!suspended) cleanup();
}
}
async resumeGenerate(...args) {
const { runId, resumeData, options } = normalizeResumeGenerateArgs(args);
const result = await this.resume(runId, resumeData, {
...options ?? {},
closeOnSuspend: true
});
let suspended = false;
try {
const fullOutput = await result.output.getFullOutput();
if (fullOutput.error) throw fullOutput.error;
suspended = fullOutput.finishReason === "suspended";
if (suspended) await require_run_registry.getRunRegistryEntry(result.runId, this.#mastra)?.workflowExecution;
if (!fullOutput.runId) fullOutput.runId = result.runId;
return fullOutput;
} finally {
if (!suspended) result.cleanup();
}
}
/**
* List durable agent runs currently reported as `running` in workflow
* snapshot storage.
*
* A `running` snapshot is a durable agent run whose agentic loop was
* mid-execution the last time the workflow engine persisted its state. On a
* healthy process these transition to `suspended` (waiting on
* tool approval / resume) or a terminal status. On a crashed / restarted
* process they are orphaned in the `running` state with no in-process
* driver — this is the discovery API used to enumerate them for recovery
* (see {@link DurableAgent.recoverActiveRuns} and workflow `restart`).
*
* Requires persistent workflow storage. Filters `agentId` against the
* persisted `DurableAgenticWorkflowInput.agentId`, so runs started by other
* durable agents sharing the same storage are not surfaced.
*
* @example
* ```typescript
* const { runs } = await durableAgent.listActiveRuns({ resourceId });
* for (const run of runs) {
* await durableAgent.recoverActiveRuns({ runId: run.runId });
* }
* ```
*/
async listActiveRuns(options = {}) {
const { threadId, resourceId, fromDate, toDate, perPage, page } = options;
if (perPage !== void 0 && (!Number.isInteger(perPage) || perPage <= 0)) throw new require_error.MastraError({
id: "DURABLE_AGENT_LIST_ACTIVE_RUNS_INVALID_PER_PAGE",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" listActiveRuns() requires perPage to be a positive integer.`,
details: {
agentName: this.name,
perPage
}
});
if (page !== void 0 && (!Number.isInteger(page) || page < 0)) throw new require_error.MastraError({
id: "DURABLE_AGENT_LIST_ACTIVE_RUNS_INVALID_PAGE",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" listActiveRuns() requires page to be a non-negative integer.`,
details: {
agentName: this.name,
page
}
});
const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
if (!workflowsStore) throw new require_error.MastraError({
id: "DURABLE_AGENT_LIST_ACTIVE_RUNS_NO_STORAGE",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" listActiveRuns() requires storage to discover running runs. Register the agent on a Mastra instance with persistent storage (e.g. PostgreSQL, LibSQL). See https://mastra.ai/docs/storage`,
details: { agentName: this.name }
});
const matchedRuns = [];
for (let storagePage = 0;; storagePage++) {
const { runs, total: storageTotal } = await workflowsStore.listWorkflowRuns({
workflowName: require_run_registry.DurableStepIds.AGENTIC_LOOP,
status: "running",
resourceId,
fromDate,
toDate,
perPage: LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE,
page: storagePage
});
for (const run of runs) {
let snapshot = run.snapshot;
if (typeof snapshot === "string") try {
snapshot = JSON.parse(snapshot);
} catch {
continue;
}
if (snapshot?.status !== "running") continue;
const input = snapshot.context?.input;
if (input?.agentId !== this.id) continue;
const memoryInfo = input?.messageListState?.memoryInfo;
const runThreadId = memoryInfo?.threadId;
const runResourceId = run.resourceId ?? memoryInfo?.resourceId;
if (threadId && runThreadId !== threadId) continue;
if (resourceId && runResourceId !== resourceId) continue;
matchedRuns.push({
runId: run.runId,
status: "running",
threadId: runThreadId,
resourceId: runResourceId,
updatedAt: run.updatedAt
});
}
if (runs.length !== LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE) break;
if ((storagePage + 1) * LIST_ACTIVE_RUNS_STORAGE_BATCH_SIZE >= storageTotal) break;
}
const total = matchedRuns.length;
return {
runs: perPage !== void 0 && page !== void 0 ? matchedRuns.slice(page * perPage, (page + 1) * perPage) : matchedRuns,
total
};
}
/**
* Bulk recover durable agent runs whose in-process agentic loop was orphaned
* by a process restart. This is the recovery half of the discovery API
* paired with {@link DurableAgent.listActiveRuns} and is the typical
* boot-time hook.
*
* Each targeted run is delegated to {@link DurableAgent.recover}, which
* rebuilds the run's non-serializable state (message list, model, memory,
* save-queue manager, request context, agent span), re-subscribes to the
* run's pubsub topic, and restarts the workflow in the background. Because
* `recover()` registers `memory` + `saveQueueManager` on the run entry, the
* durable agentic workflow's terminal step flushes new messages to memory
* just like a fresh `stream()` call would.
*
* The per-run stream returned by `recover()` is discarded — this method
* awaits each run's workflow settlement and reports summary counts instead
* of surfacing live event streams. Callers who want to observe a specific
* recovered run's events should use {@link DurableAgent.recover} directly
* (or {@link DurableAgent.observe} with the returned `runId`).
*
* Failures are captured per-run so a single bad run does not block
* recovery of the rest.
*
* Only orphaned runs are recovered. A run another execution still drives,
* in this process or another, is reported as `skipped`; for one live in
* another process, `retryAt` says when to check again. A run that finished
* or suspended before its turn is left out.
*
* @example
* ```typescript
* // Recover every orphaned run for this agent (typical boot-time hook).
* const { recovered, succeeded, failed } = await durableAgent.recoverActiveRuns();
* logger.info('Recovered durable agent runs', { succeeded, failed });
*
* // Recover a single run by ID.
* await durableAgent.recoverActiveRuns({ runId });
* ```
*/
async recoverActiveRuns(options = {}) {
if (this.#mastra?.__shuttingDown) return {
recovered: [],
succeeded: 0,
failed: 0
};
const { runId, ...discoveryOptions } = options;
const storage = this.#mastra?.getStorage();
if (!await this.#warnIfUnfenced(await storage?.getStore("workflows"), "workflows")) await this.#warnIfUnfenced(await storage?.getStore("memory"), "memory");
let targetRunIds;
if (runId) targetRunIds = await this.#isRunningSnapshot(runId) ? [runId] : [];
else {
const { runs } = await this.listActiveRuns(discoveryOptions);
targetRunIds = runs.map((r) => r.runId);
}
const outcomes = new Array(targetRunIds.length);
const timeoutOutcome = (targetRunId) => ({
runId: targetRunId,
status: "skipped",
reason: "recovery-timeout",
retryAt: Date.now() + TRANSIENT_RECOVERY_RETRY_DELAY_MS
});
await require_run_registry.runWithConcurrency(targetRunIds.map((targetRunId, index) => ({
targetRunId,
index
})), 5, async ({ targetRunId, index }) => {
if (this.#mastra?.__shuttingDown) return;
if (this.#hasRecoveryAttempt(targetRunId)) {
outcomes[index] = timeoutOutcome(targetRunId);
return;
}
const attempt = this.#startRecoveryAttempt(targetRunId, async () => {
if (this.#mastra?.__shuttingDown) return;
let runError;
let started = false;
try {
let releaseAfterTerminal;
const onTerminal = () => {
if (this.__getStreamBus().cleanupTimeoutMs === 0) setTimeout(() => releaseAfterTerminal?.(), 0);
};
const { cleanup } = await this.recover(targetRunId, {
onError: ({ error }) => {
runError = error instanceof Error ? error : new Error(String(error));
onTerminal();
},
onFinish: onTerminal,
onAbort: onTerminal
});
started = true;
releaseAfterTerminal = cleanup;
try {
const workflowExecution = require_run_registry.getRunRegistryEntry(targetRunId, this.#mastra)?.workflowExecution;
if (workflowExecution) await workflowExecution;
} catch (error) {
cleanup();
throw error;
}
if (runError) throw runError;
return {
runId: targetRunId,
status: "success"
};
} catch (error) {
const errorId = error?.id;
if (!runError && (errorId === RECOVER_SHUTDOWN_ERROR_ID || errorId === "DURABLE_AGENT_EXECUTION_ABANDONED")) return {
runId: targetRunId,
status: "skipped"
};
if (!started) {
if (errorId === "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND" || errorId === "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE" || errorId === "DURABLE_AGENT_RECOVER_RUN_SUSPENDED") return;
const skipped = recoverySkip(error);
if (skipped) {
if (skipped.reason === "transient-error") this.#mastra?.getLogger()?.warn(`[DurableAgent] Deferring recovery of run ${targetRunId} after a transient error`, {
error,
retryAt: skipped.retryAt
});
return {
runId: targetRunId,
status: "skipped",
...skipped
};
}
}
const err = runError ?? (error instanceof Error ? error : new Error(String(error)));
this.#mastra?.getLogger?.()?.error?.(`[DurableAgent] Failed to recover run ${targetRunId}: ${err.message}`, { error: err });
return {
runId: targetRunId,
status: "failed",
error: err
};
}
});
const bounded = this.#mastra ? await this.#mastra.__awaitDurableRecoveryAttempt(attempt, `durable agent ${this.id} run ${targetRunId}`) : { value: await attempt };
outcomes[index] = bounded ? bounded.value : timeoutOutcome(targetRunId);
});
const recovered = outcomes.filter((outcome) => outcome !== void 0);
return {
recovered,
succeeded: recovered.filter((outcome) => outcome.status === "success").length,
failed: recovered.filter((outcome) => outcome.status === "failed").length
};
}
/** Locate the start of the model step that recovery will re-execute, if it was published. */
async #supersededFrom(workflowsStore, runId, parentSnapshot) {
try {
const nestedRunId = parentSnapshot.context?.[require_run_registry.DurableStepIds.AGENTIC_EXECUTION]?.metadata?.nestedRunId;
const nested = await workflowsStore.getWorkflowRunById({
runId: typeof nestedRunId === "string" ? nestedRunId : runId,
workflowName: require_run_registry.DurableStepIds.AGENTIC_EXECUTION
});
const snapshot = typeof nested?.snapshot === "string" ? JSON.parse(nested.snapshot) : nested?.snapshot;
if (!snapshot || snapshot.context?.[require_run_registry.DurableStepIds.LLM_EXECUTION]?.status === "success") return;
const stepIndex = snapshot.context?.input?.iterationCount;
if (typeof stepIndex !== "number") return;
const starts = (await this.pubsub.getHistory(require_run_registry.AGENT_STREAM_TOPIC(runId), 0)).filter((event) => (event.type === require_run_registry.AgentStreamEventTypes.ITERATION_START || event.type === require_run_registry.AgentStreamEventTypes.STEP_START) && event.stepIndex === stepIndex);
const latestGeneration = starts.reduce((latest, event) => typeof event.generation === "number" ? Math.max(latest ?? event.generation, event.generation) : latest, void 0);
return (starts.find((event) => event.type === require_run_registry.AgentStreamEventTypes.ITERATION_START && event.generation === latestGeneration) ?? starts.find((event) => event.generation === latestGeneration))?.index;
} catch (error) {
this.logger.warn(`[DurableAgent] recover(${runId}) couldn't locate the uncheckpointed stream tail`, { error });
}
}
/**
* A replay from an offset can start past the marker of the execution that
* took the run over, and would then accept what the lost execution still
* publishes, its finish included. Start the reader with the floor it would
* have reached by reading the skipped events: the highest generation among
* them. Ordinary suspend/resume segments then still replay, since each
* segment's events precede the next claim. When the transport keeps no
* history to read, follow the run's current claim instead.
* Runs fenced by a pubsub lease have no generation and are unaffected.
* The floor only adds protection, so a failed read must not fail the reconnect;
* the reader reads the claim again before an event can end its stream.
*/
async #readReplayFloor(runId, offset) {
try {
const history = await this.pubsub.getHistory(require_run_registry.AGENT_STREAM_TOPIC(runId), 0);
const initialFilter = require_run_registry.createSupersededEventFilter(history);
let refreshedFilter;
let currentFilter;
const refreshReplayFilter = () => {
refreshedFilter ??= this.pubsub.getHistory(require_run_registry.AGENT_STREAM_TOPIC(runId), 0).then((entries) => currentFilter = require_run_registry.createSupersededEventFilter(entries)).catch(() => currentFilter = initialFilter);
return refreshedFilter;
};
const keepReplayEvent = (event) => {
if (event.index === void 0) return (currentFilter ?? initialFilter)(event);
if (currentFilter) return currentFilter(event);
return refreshReplayFilter().then((filter) => filter(event));
};
if (!offset) return {
keepReplayEvent,
refreshReplayFilter
};
const skipped = history.slice(0, offset);
if (skipped.length === offset) {
let floor;
for (const event of skipped) {
const generation = event.generation;
if (typeof generation === "number" && (floor === void 0 || generation > floor)) floor = generation;
}
return {
minGeneration: floor,
keepReplayEvent,
refreshReplayFilter
};
}
return {
minGeneration: await require_run_registry.readRunGeneration(this.#mastra, runId),
keepReplayEvent,
refreshReplayFilter
};
} catch (error) {
this.logger.warn(`[DurableAgent] Couldn't read the claim of run ${runId}; observing it without a floor`, { error });
return { rereadMinGeneration: () => require_run_registry.readRunGeneration(this.#mastra, runId) };
}
}
/** Reconcile only after subscribing, so a completion racing attachment is not lost. */
async #isObservationComplete(runId) {
try {
const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
for (let attempt = 0; attempt < 2; attempt++) {
const history = await this.pubsub.getHistory(require_run_registry.AGENT_STREAM_TOPIC(runId), 0);
const historyGeneration = history.reduce((floor, event) => event.generation === void 0 ? floor : Math.max(floor ?? event.generation, event.generation), void 0);
const latest = history.findLast((event) => event.generation === void 0 || historyGeneration === void 0 || event.generation >= historyGeneration);
if (latest) {
const type = latest.type === require_run_registry.AgentStreamEventTypes.CHUNK ? latest.data?.type : latest.type;
if (type !== "finish" && type !== "error" && type !== "abort") return false;
}
const ownership = workflowsStore && await require_run_registry.supportsRunFencing(workflowsStore) ? await workflowsStore.getRunOwnership({ runId }) : void 0;
const minGeneration = history.reduce((floor, event) => event.generation === void 0 ? floor : Math.max(floor ?? event.generation, event.generation), ownership?.generation);
const keepGeneration = require_run_registry.createRunGenerationFilter({ minGeneration });
let hasHistory = false;
let terminal = false;
for (const event of history) {
if (!await keepGeneration(event)) continue;
hasHistory = true;
const type = event.type === require_run_registry.AgentStreamEventTypes.CHUNK ? event.data?.type : event.type;
if (type === "finish" || type === "error" || type === "abort") terminal = true;
}
if (!terminal) {
if (hasHistory || ownership?.live) return false;
if (require_run_registry.getRunRegistryEntry(runId, this.#mastra) || this.#runRegistry.get(runId)) return false;
if (await require_run_registry.resolveLeaseProvider(this.pubsub).getLeaseOwner(require_run_registry.executionLeaseKey(this.id, runId))) return false;
if (workflowsStore) for (const workflowName of [require_run_registry.DurableStepIds.AGENTIC_LOOP, require_run_registry.DurableStepIds.AGENTIC_EXECUTION]) {
const record = await workflowsStore.getWorkflowRunById({
runId,
workflowName
});
if (!record) continue;
const snapshot = typeof record.snapshot === "string" ? JSON.parse(record.snapshot) : record.snapshot;
const input = snapshot?.context?.input;
if (input?.__workflowKind === "durable-agent" && input.agentId !== this.id) throw new require_error.MastraError({
id: "DURABLE_AGENT_OBSERVE_AGENT_MISMATCH",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" observe(${runId}): persisted run belongs to agent "${input.agentId}", not "${this.id}".`,
details: {
agentName: this.name,
runId,
ownerAgentId: input.agentId
}
});
if (!snapshot || ![
"success",
"failed",
"tripwire",
"canceled",
"bailed",
"skipped"
].includes(snapshot.status)) return false;
}
}
}
return true;
} catch (error) {
if (error instanceof require_error.MastraError && error.id === "DURABLE_AGENT_OBSERVE_AGENT_MISMATCH") throw error;
return false;
}
}
/**
* Subscribe to a run's raw AgentStreamEvents, filtering out events from
* executions that lost ownership and takeover markers. Callers must map
* these events to the public frame contract produced by stream-adapter.ts's
* createDurableAgentStream before sending them to clients; raw event
* envelopes are not public stream frames. Resolves once subscribed, with
* a function that unsubscribes.
*
* @internal
*/
async __subscribeToRunStream(runId, options, onEvent) {
const replayFloor = await this.#readReplayFloor(runId, options.offset);
const keepGeneration = require_run_registry.createRunGenerationFilter(replayFloor);
const topic = require_run_registry.AGENT_STREAM_TOPIC(runId);
let subscribed = true;
let activityVersion = 0;
let bufferingReplay = true;
const bufferedEvents = [];
let responseMessages = { messages: [] };
const offset = options.offset;
if (offset !== void 0 && offset > 0 && this.pubsub.supportsOffsets) try {
const skipped = (await this.pubsub.getHistory(topic, 0)).filter((event) => typeof event.index === "number" && event.index < offset);
responseMessages = require_run_registry.replayResponseMessages(skipped);
} catch (error) {
this.logger.warn(`[DurableAgent] Couldn't read run ${runId}'s history before offset ${offset}`, { error });
}
const deliver = (event) => {
activityVersion++;
if (!subscribed || event.type === require_run_registry.AgentStreamEventTypes.OWNERSHIP_CLAIMED || event.type === require_run_registry.AgentStreamEventTypes.ITERATION_START) return;
const chunk = event.type === require_run_registry.AgentStreamEventTypes.CHUNK ? event.data : void 0;
if (chunk?.type === "step-finish" && chunk.payload) event = {
...event,
data: {
...chunk,
payload: require_run_registry.withRebuiltResponseMessages(responseMessages, chunk.payload)
}
};
onEvent(event);
};
const filterEvent = (streamEvent) => {
const filterGeneration = () => {
const keep = keepGeneration(streamEvent);
if (typeof keep === "boolean") {
if (keep) deliver(streamEvent);
return;
}
return keep.then((kept) => {
if (kept) deliver(streamEvent);
});
};
const keepReplay = replayFloor.keepReplayEvent?.(streamEvent);
if (keepReplay === void 0 || keepReplay === true) return filterGeneration();
if (keepReplay === false) return;
return keepReplay.then((keep) => {
if (keep) return filterGeneration();
});
};
const acknowledge = require_output_helpers.withAck((event) => filterEvent(event));
const callback = (event, ...args) => {
if (!subscribed) return args[0]?.() ?? Promise.resolve();
activityVersion++;
if (bufferingReplay) {
bufferedEvents.push(async () => {
await acknowledge(event, ...args);
});
return Promise.resolve();
}
return acknowledge(event, ...args);
};
const unsubscribe = async () => {
if (!subscribed) return;
subscribed = false;
await this.pubsub.unsubscribe(topic, callback);
};
try {
await (options.offset !== void 0 ? this.pubsub.subscribeFromOffset(topic, options.offset, callback) : this.pubsub.subscribeWithReplay(topic, callback));
await replayFloor.refreshReplayFilter?.();
for (let i = 0; i < bufferedEvents.length; i++) await bufferedEvents[i]();
bufferedEvents.length = 0;
bufferingReplay = false;
const reconciledVersion = activityVersion;
if (options.onComplete && await this.#isObservationComplete(runId) && activityVersion === reconciledVersion) options.onComplete();
return unsubscribe;
} catch (error) {
await unsubscribe();
throw error;
}
}
/**
* Observe an existing stream.
* Use this to reconnect to a stream after a network disconnection.
*
* To stop observing without affecting the run, call the returned `detach()`
* or leave the `for await` loop over `fullStream` (break, return, or throw).
* Both unsubscribe this observer only; the run keeps going and other
* observers can still replay it. To stop observing when a request is
* cancelled, wire its signal to `detach`:
*
* ```ts
* const { fullStream, detach } = await agent.observe(runId, { offset });
* req.signal.addEventListener('abort', detach, { once: true });
* if (req.signal.aborted) detach();
* for await (const chunk of fullStream) send(chunk);
* ```
*
* **Warning:** The returned `cleanup()` function destroys the run's registry
* entries and cached PubSub events (replay history), including for other
* observers. Only call it when you are done with the run entirely. If the
* workflow is suspended and you intend to resume later, do not call cleanup —
* let the auto-cleanup timer handle it after FINISH/ERROR. Auto-cleanup does
* not fire on SUSPENDED events.
*
* Pass `idleTimeoutMs` to bound how long the stream waits on a silent topic:
* a durable run whose driving process crashed stops emitting chunks but never
* publishes a terminal event, so without this `observe()` hangs forever on a
* producerless topic. When the idle timeout fires, the optional `isAlive`
* probe is consulted first — returning true (e.g. a live run-liveness
* heartbeat, or a suspended HITL gate) re-arms the timer and keeps waiting,
* while false/absent terminates the stream with an error chunk. Only an
* `isAlive` that returns false schedules the run's full cleanup; a bare
* `idleTimeoutMs` (no `isAlive`) only detaches this observer, so pass
* `isAlive` if you rely on the timeout to reclaim a crashed run's state. Both
* options are opt-in; omit them for the current unbounded behavior.
*/
async observe(runId, options) {
let memoryInfo = this.#runRegistry.getMemoryInfo(runId);
let terminalCompleted = false;
let abortPending = false;
let cleanupRequested = false;
let streamCleanup;
const localEntry = this.#runRegistry.get(runId);
const observedEntry = localEntry ?? require_run_registry.getRunRegistryEntry(runId, this.#mastra);
const observedFence = observedEntry?.executionFence;
const runCleanup = createRunCleanup({
scheduleTimer: (cleanup) => observedFence ? this.#scheduleReaderCleanup(observedFence, cleanup) : this.__getStreamBus().scheduleCleanup(cleanup),
release: () => {
streamCleanup?.();
if (observedFence && (this.#unverifiedReaderFences.has(observedFence) || !observedFence.ownsRunTopics() || require_run_registry.getRunRegistryEntry(runId, this.#mastra)?.executionFence !== observedFence || localEntry && (this.#runRegistry.get(runId) !== localEntry || localEntry.executionFence !== observedFence))) return;
this.#runRegistry.cleanup(runId);
require_run_registry.deleteRunRegistryEntry(runId, this.#mastra);
this.#clearPubsubTopic(runId, observedEntry);
}
});
const performCleanup = runCleanup.run;
const scheduleAutoCleanup = runCleanup.schedule;
const completeTerminalLifecycle = () => {
terminalCompleted = true;
abortPending = false;
if (cleanupRequested) performCleanup();
else scheduleAutoCleanup();
};
const observedAgentSpan = observedEntry?.resumeAgentSpan ?? observedEntry?.agentSpan;
let structuredOutput = observedEntry?.structuredOutput;
let outputProcessors = observedEntry?.outputProcessors;
const processorStates = observedEntry?.processorStates;
let streamAgent = observedEntry?.agent ?? this.#wrappedAgent;
let returnScorerData = observedEntry?.returnScorerData;
let requestContext = observedEntry?.requestContext;
let messageList = observedEntry?.messageList ?? this.#runRegistry.getMessageList(runId);
const liveEntry = messageList ? observedEntry : void 0;
if (liveEntry?.agentId !== void 0 && liveEntry.agentId !== this.id) throw new require_error.MastraError({
id: "DURABLE_AGENT_OBSERVE_AGENT_MISMATCH",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" observe(${runId}): live run belongs to agent "${liveEntry.agentId}", not "${this.id}".`,
details: {
agentName: this.name,
runId,
ownerAgentId: liveEntry.agentId
}
});
let workflowInput;
let loopSnapshot;
let workflowInputSnapshot;
const workflowsStore = !liveEntry ? await this.#mastra?.getStorage()?.getStore("workflows") : void 0;
if (!structuredOutput || !liveEntry) {
const snapshotStore = workflowsStore ?? await this.#mastra?.getStorage()?.getStore("workflows");
for (const workflowName of [require_run_registry.DurableStepIds.AGENTIC_LOOP, require_run_registry.DurableStepIds.AGENTIC_EXECUTION]) {
const persisted = await snapshotStore?.getWorkflowRunById({
runId,
workflowName
});
if (!persisted) continue;
const snapshot = typeof persisted.snapshot === "string" ? JSON.parse(persisted.snapshot) : persisted.snapshot;
if (workflowName === require_run_registry.DurableStepIds.AGENTIC_LOOP) loopSnapshot = snapshot;
const persistedInput = snapshot?.context?.input;
if (persistedInput?.__workflowKind !== "durable-agent") continue;
workflowInput = persistedInput;
workflowInputSnapshot = snapshot;
break;
}
}
if (!liveEntry && workflowInput && workflowInput.agentId !== this.id) throw new require_error.MastraError({
id: "DURABLE_AGENT_OBSERVE_AGENT_MISMATCH",
domain: require_error.ErrorDomain.AGENT,
category: require_error.ErrorCategory.USER,
text: `DurableAgent "${this.name}" observe(${runId}): persisted run belongs to agent "${workflowInput.agentId}", not "${this.id}".`,
details: {
agentName: this.name,
runId,
ownerAgentId: workflowInput.agentId
}
});
if (!structuredOutput && workflowInput) {
const persistedStructuredOutput = workflowInput.options?.structuredOutput;
if (persistedStructuredOutput?.schema) {
const { errorStrategy, fallbackValue, ...rest } = persistedStructuredOutput;
const schema = toLiveStructuredOutputSchema(persistedStructuredOutput.schema, persistedStructuredOutput.nullToUndefined);
structuredOutput = errorStrategy === "fallback" ? fallbackValue === void 0 ? {
...rest,
schema
} : {
...rest,
schema,
errorStrategy,
fallbackValue
} : {
...rest,
schema,
errorStrategy
};
}
}
if (!liveEntry && workflowInput) {
requestContext = workflowInput.requestContextEntries ? new require_request_context.RequestContext(Object.entries(workflowInput.requestContextEntries)) : new require_request_context.RequestContext();
const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
const threadId = workflowInput.state?.threadId ?? messageListMemoryInfo?.threadId;
const resourceId = workflowInput.state?.resourceId ?? messageListMemoryInfo?.resourceId;
memoryInfo = threadId && resourceId ? {
threadId,
resourceId
} : void 0;
if (threadId && resourceId) requestContext.set("MastraMemory", {
thread: { id: threadId },
resourceId,
memoryConfig: workflowInput.state?.memoryConfig
});
else requestContext.delete("MastraMemory");
messageList = new require_message_list.MessageList({
threadId,
resourceId
});
try {
const snapshot = workflowInputSnapshot ?? loopSnapshot;
const storedState = workflowInput.messageListState ?? (snapshot ? latestMessageListState(snapshot) : void 0);
if (storedState) {
const initialState = await hydrateMessageListState({
getInitData: () => workflowInput,
mastra: this.#mastra
}, storedState);
messageList.deserialize(initialState);
}
if (workflowsStore && snapshot) {
const inputMessages = messageList.get.input.db();
const latestState = await this.#loadLatestMessageListState(workflowsStore, runId, snapshot);
if (latestState) {
messageList.deserialize(latestState);
if (messageList.get.input.db().length === 0 && inputMessages.length > 0) messageList.add(inputMessages, "input");
}
}
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] observe(${runId}) messageList deserialize skipped: ${error}`);
}
let processorAgent = this.#wrappedAgent;
const pinnedVersionId = workflowInput.agentVersionId;
if (pinnedVersionId && this.#mastra && !this.__isStoredVersionApplied()) {
if (pinnedVersionId !== this.toRawConfig()?.resolvedVersionId) try {
processorAgent = await this.#mastra.resolveVersionedAgent(this, { versionId: pinnedVersionId });
} catch (error) {
this.#mastra.getLogger?.()?.warn?.(`[DurableAgent] Failed to resolve pinned agent version for durable observe, using current definition: ${error}`);
}
}
streamAgent = require_run_registry.isDurableAgentLike(processorAgent) && processorAgent.agent !== processorAgent ? processorAgent.agent : processorAgent;
try {
outputProcessors = await processorAgent.listOutputProcessors(requestContext) ?? [];
} catch (error) {
outputProcessors = [];
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] observe(${runId}) processor resolution failed: ${error}`);
}
returnScorerData = workflowInput.options?.returnScorerData;
}
const refreshObservedMessageList = async (isExpired) => {
const targetMessageList = messageList;
const snapshot = workflowInputSnapshot ?? loopSnapshot;
if (!workflowsStore || !snapshot || !targetMessageList) return;
try {
const inputMessages = targetMessageList.get.input.db();
const latestState = await this.#loadLatestMessageListState(workflowsStore, runId, snapshot);
if (latestState && !isExpired()) {
targetMessageList.deserialize(latestState);
if (targetMessageList.get.input.db().length === 0 && inputMessages.length > 0) targetMessageList.add(inputMessages, "input");
}
} catch (error) {
this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] observe(${runId}) messageList refresh failed: ${error}`);
}
};
const refreshObservedMessageListWithTimeout = async () => {
const refreshTimeoutMs = Math.min(options?.idleTimeoutMs && options.idleTimeoutMs > 0 ? options.idleTimeoutMs : OBSERVED_MESSAGE_LIST_REFRESH_TIMEOUT_MS, OBSERVED_MESSAGE_LIST_REFRESH_TIMEOUT_MS);
let expired = false;
let timeout;
const timedOut = new Promise((resolve) => {
timeout = setTimeout(() => {
expired = true;
resolve(true);
}, refreshTimeoutMs);
});
try {
if (await Promise.race([refreshObservedMessageList(() => expired).then(() => false), timedOut])) this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] observe(${runId}) messageList refresh timed out after ${refreshTimeoutMs}ms`);
} finally {
if (timeout) clearTimeout(timeout);
}
};
let observedResponseText = "";
const handleObservedChunk = async (chunk) => {
if (chunk.type === "text-delta" && typeof chunk.payload.text === "string") observedResponseText += chunk.payload.text;
if (chunk.type === "step-finish") {
await refreshObservedMessageListWithTimeout();
if (messageList && messageList.get.response.db().length === 0 && observedResponseText) messageList.add({
role: "assistant",
content: observedResponseText
}, "response");
}
await options?.onChunk?.(chunk);
};
const replayFloor = await this.#readReplayFloor(runId, options?.offset);
const stream = require_run_registry.createDurableAgentStream({
pubsub: this.pubsub,
runId,
messageId: crypto.randomUUID(),
model: {
modelId: void 0,
provider: void 0,
version: "v3"
},
threadId: memoryInfo?.threadId,
resourceId: memoryInfo?.resourceId,
offset: options?.offset,
replayResponseMessagesBeforeOffset: true,
...replayFloor,
idleTimeoutMs: options?.idleTimeoutMs,
isAlive: options?.isAlive,
onChunk: handleObservedChunk,
experimentalTransform: options?.experimentalTransform,
onStepFinish: options?.onStepFinish,
onFinish: options?.onFinish,
onStreamFinished: completeTerminalLifecycle,
onError: async ({ error, runDead }) => {
try {
await options?.onError?.({ error });
} finally {
if (runDead !== false) completeTerminalLifecycle();
}
},
onAbort: async (data) => {
try {
await options?.onAbort?.(data);
} finally {
completeTerminalLifecycle();
}
},
onSuspended: options?.onSuspended,
structuredOutput,
agent: streamAgent,
outputProcessors,
processorStates,
returnScorerData,
requestContext,
tracingContext: observedAgentSpan ? { currentSpan: observedAgentSpan } : void 0,
messageList
});
const { output, ready, detach } = stream;
streamCleanup = stream.cleanup;
require_run_registry.detachFullStreamOnEnd(output, detach);
try {
await ready;
await replayFloor.refreshReplayFilter?.();
await stream.waitForEventDelivery();
const reconciledVersion = stream.activityVersion;
if (await this.#isObservationComplete(runId) && stream.activityVersion === reconciledVersion) detach();
} catch (error) {
detach();
throw error;
}
const cleanup = () => {
if (abortPending) {
cleanupRequested = true;
scheduleAutoCleanup();
return;
}
performCleanup();
};
const abort = async (reason) => {
abortPending = !terminalCompleted;
const controller = (require_run_registry.getRunRegistryEntry(runId, this.#mastra) ?? this.#runRegistry.get(runId))?.abortController;
if (controller && !controller.signal.aborted) controller.abort(reason);
await this.requestRemoteAbort(runId);
if (require_run_registry.agentThreadStreamRuntime.isRunParked(runId, this.getPubSub())) super.abortRunStream(runId);
};
return {
output,
get fullStream() {
return output.fullStream;
},
runId,
threadId: memoryInfo?.threadId,
resourceId: memoryInfo?.resourceId,
cleanup,
detach,
abort
};
}
/**
* Clear retained pubsub state for a run's topics (cached history and, for
* persistent transports, the underlying stream). Fire-and-forget: the
* `clearTopic` contract is best-effort and non-throwing.
*
* Clears both the agent stream topic and `workflow.events.v2.<runId>`.
* The agent stream topic is cleared only here, on both engines. For the
* workflow events topic the engines differ:
* - Default engine (`DurableAgent`): no other cleanup exists — without
* this, CachingPubSub permanently orphans a no-TTL counter key per
* completed run.
* - Evented engine (`EventedAgent`): the WorkflowEventProcessor also
* clears `workflow.events.v2.<runId>` via its own delayed,
* restart-guarded terminal cleanup. The two clears overlap safely:
* `clearTopic` is idempotent and clearing an empty topic is a no-op.
*
* This needs no restart guard of its own — the lifecycle facts are
* engine-agnostic: cleanup timers arm only on terminal outcomes
* (FINISH/ERROR/ABORT — never SUSPENDED), `resume()` rejects runs whose
* snapshot isn't `suspended`, and `untilIdle` continuations mint a fresh
* runId per segment. An execution that lost its run never calls this:
* the execution that took the run over, in this or another process, may
* still be writing to both topics, so it clears them when it ends. The one
* evented-only edge — at-least-once redelivery writing to the workflow
* events topic after this clear — is covered by the WEP's own cleanup,
* which reschedules deletion on that run's terminal end.
*/
#clearPubsubTopic(runId, entry = require_run_registry.getRunRegistryEntry(runId, this.#mastra)) {
const publisher = require_run_registry.getExecutionStreamOwner({
runId,
agentId: this.id,
mastra: this.#mastra,
agent: this,
entry
});
if (publisher) publisher.cleanup();
else this.pubsub.clearTopic(require_run_registry.AGENT_STREAM_TOPIC(runId));
this.pubsub.clearTopic(`workflow.events.v2.${runId}`);
}
/**
* Resolve the replay position for this run's stream topic.
* Returns the cached event count when history is available, or `latest` when it is unavailable.
* Resume and recovery use this position so they don't re-deliver events emitted by the prior segment
* (notably the SUSPENDED chunk that paused it) from a persistent transport.
*/
async #getPubsubOffset(runId) {
const pubsub = this.pubsub;
if (typeof pubsub.getHistory !== "function") return "latest";
try {
const history = await pubsub.getHistory(require_run_registry.AGENT_STREAM_TOPIC(runId));
return Array.isArray(history) && history.length > 0 ? history.length : "latest";
} catch {
return "latest";
}
}
/**
* Get the workflow instance for direct execution.
* Lazily creates the workflow and registers Mastra on it (needed for
* getAgentById in execution steps).
*/
getWorkflow() {
if (!this.executionEngine.workflow) this.#warnIfStorageVersionUnsupported();
return this.executionEngine.workflow ?? this.executionEngine.getWorkflow({
maxSteps: this.#maxSteps,
workflowEngine: this.workflowEngine,
storesRunsInJournal: this.storesRunsInJournal,
shouldPersistSnapshot: this.userShouldPersistSnapshot,
logger: this.logger,
guardrailLogger: this.guardrailLogger
});
}
/**
* One-time guardrail warnings for user-supplied `shouldPersistSnapshot`
* policies. Probes the predicate with an empty `stepResults`, so predicates
* that read `stepResults` may probe inaccurately — the warnings are
* best-effort and never block execution.
*
* Engine variants own their warnings during workflow creation. This method
* remains available for direct calls and subclass super calls.
*
* @internal
*/
warnOnRiskyPersistencePolicy() {
this.executionEngine.warnOnRiskyPersistencePolicy(this.userShouldPersistSnapshot, this.guardrailLogger);
}
/**
* Logger for the persistence-policy guardrail warnings. The durable
* registration path rewires the *underlying* agent's logger but not the
* wrapper's, so prefer the Mastra-configured logger (which also respects
* `logger: false`) and fall back to the base logger for unregistered
* agents.
*
* @internal
*/
get guardrailLogger() {
return this.#mastra?.getLogger() ?? this.logger;
}
/**
* @deprecated Use `stream(messages, { untilIdle: true })` instead.
*
* Stream until all background tasks complete and the agent is idle.
* Mirrors the regular Agent's streamUntilIdle but adapted for durable execution.
*/
async streamUntilIdle(messages, streamOptions) {
const { maxIdleMs, ...options } = streamOptions ?? {};
return this.stream(messages, {
...options,
untilIdle: maxIdleMs === void 0 ? true : { maxIdleMs }
});
}
/**
* Prepare for durable execution without starting it.
*/
async prepare(messages, options) {
const preparation = await prepareForDurableExecution({
agent: this.#wrappedAgent,
messages,
options,
runId: options?.runId,
requestContext: options?.requestContext,
scopesResolved: !!options?.[SCOPES_ALREADY_APPLIED],
resumedSpanData: options?.[RESUMED_SPAN_DATA],
mastra: this.#mastra,
durableAgentId: this.id,
durableAgentName: this.name
});
preparation.registryEntry.agentId = this.id;
this.#runRegistry.registerWithMessageList(preparation.runId, preparation.registryEntry, preparation.messageList, {
threadId: preparation.threadId,
resourceId: preparation.resourceId
});
await this.#attachStreamPublisher(preparation.runId, {
threadId: preparation.threadId,
resourceId: preparation.resourceId
});
require_run_registry.globalRunRegistry.set(preparation.runId, {
...preparation.registryEntry,
messageList: preparation.messageList
});
return {
runId: preparation.runId,
messageId: preparation.messageId,
workflowInput: preparation.workflowInput,
registryEntry: preparation.registryEntry,
threadId: preparation.threadId,
resourceId: preparation.resourceId
};
}
/**
* Get the durable workflows required by this agent.
* Called by Mastra during agent registration.
* @internal
*/
getDurableWorkflows() {
return [this.getWorkflow()];
}
/**
* Set the Mastra instance.
* Called by the durable agent registration path in addAgent().
* Delegates to __registerMastra so the pubsub wiring and agent
* registration happen regardless of which entry point is called first.
* @internal
*/
__setMastra(mastra) {
this.__registerMastra(mastra);
}
/**
* Register the Mastra instance.
* Called by Mastra during agent registration (normal Agent path).
*
* Also wires mastra.pubsub as the inner pubsub (if the user didn't provide
* a custom one), so that the OBSERVE_AGENT_STREAM_ROUTE handler can subscribe
* to the same PubSub instance that this agent publishes to.
* @internal
*/
__registerMastra(mastra) {
super.__registerMastra(mastra);
this.#mastra = mastra;
this.#executionEngine?.registerMastra(mastra);
this.#wrappedAgent.__registerMastra(mastra);
this.#wrapperStreamBus?.registerMastra(mastra.pubsub);
}
};
// src/agent/durable/create-durable-agent.ts
/**
* Create a DurableAgent that wraps an existing Agent.
*
* This factory function is the recommended way to add checkpoint-backed durable
* execution to an agent. The `durable` option on `AgentConfig` only configures
* resumable streams and never wraps the agent.
*
* Wrapping does not change the wrapped Agent's direct runs, including runs already
* in flight. Without explicit stream settings, the wrapper shares the Agent's
* stream bus; pubsub, cache, cleanupTimeoutMs, and shouldCache overrides apply
* only to the wrapper's runs. Evented wrapper runs use Mastra's shared run log
* without changing the wrapped Agent's native stream routing.
*
* @param options - Configuration options
* @returns A DurableAgent instance
*
* @example
* ```typescript
* const agent = new Agent({
* id: 'my-agent',
* instructions: 'You are helpful',
* model: openai('gpt-4'),
* });
*
* const durableAgent = createDurableAgent({ agent });
*
* const mastra = new Mastra({
* agents: { myAgent: durableAgent },
* });
* ```
*
* @example
* ```typescript
* // Equivalent, using the durable config flag:
* const agent = new Agent({
* id: 'my-agent',
* instructions: 'You are helpful',
* model: openai('gpt-4'),
* durable: true,
* });
*
* const mastra = new Mastra({ agents: { myAgent: agent } });
* ```
*/
function createDurableAgent(options) {
const { agent, id, name, cache, pubsub, maxSteps, cleanupTimeoutMs, shouldCache, shouldPersistSnapshot, storageVersion } = options;
return new DurableAgent({
agent,
id,
name,
cache,
pubsub,
maxSteps,
cleanupTimeoutMs,
shouldCache,
shouldPersistSnapshot,
storageVersion
});
}
/**
* Check if an object is a DurableAgent
*/
function isDurableAgent(obj) {
return obj instanceof DurableAgent;
}
/**
* Alias for isDurableAgent for backwards compatibility
* @deprecated Use isDurableAgent instead
*/
const isLocalDurableAgent = isDurableAgent;
// src/agent/durable/evented-execution-engine.ts
var EventedExecutionEngine = class extends DurableExecutionEngine {
#warnedUnfencedSharedExecution = false;
prepareExecution(pubsub, fence, workflowEngine, logger, guardrailLogger) {
const engine = this.resolveWorkflowEngine(workflowEngine, logger);
const sharedTransport = engine === "evented" && pubsub !== void 0 && !(pubsub.__rawBus() instanceof require_output_helpers.EventEmitterPubSub);
const sharedExecution = sharedTransport && fence?.generation !== void 0;
if (sharedTransport && !sharedExecution && !this.#warnedUnfencedSharedExecution) {
this.#warnedUnfencedSharedExecution = true;
guardrailLogger?.warn(`EventedAgent '${this.id}': shared execution without storage-backed run fencing keeps its existing behavior: API shutdown or loss can interrupt remote workers. Use a shared fencing-capable storage adapter to keep workers running independently of the API process.`);
}
return {
sharedExecution,
usesRunPubSub: engine === "default"
};
}
finishExecution(runId, executionFence, sharedExecution, completion) {
if (!sharedExecution) return super.finishExecution(runId, executionFence, sharedExecution, completion);
executionFence?.detach();
if ("error" in completion) {
if (completion.error instanceof require_run_registry.DurableExecutionFenceError && completion.error.id === "DURABLE_AGENT_EXECUTION_UNVERIFIED") return {
owner: "workers",
error: completion.error
};
this.mastra?.getLogger()?.warn("Evented durable observer disconnected; workers retain settlement authority", {
runId,
error: completion.error
});
}
return { owner: "workers" };
}
resolveShouldPersistSnapshot(_predicate) {
return defaultShouldPersistSnapshot;
}
warnOnRiskyPersistencePolicy(predicate, guardrailLogger) {
if (predicate) guardrailLogger?.warn(`EventedAgent '${this.id}': ignoring the shouldPersistSnapshot option. The evented engine requires the full snapshot set (pending|paused|suspended|running) — the initial 'running' write creates the base row that suspend-merges and multi-worker coordination build on.`);
}
};
// src/agent/durable/evented-agent.ts
/**
* EventedAgent extends DurableAgent to use fire-and-forget execution.
*
* This agent type uses the built-in evented workflow engine, which is useful when:
* - You don't need an external execution engine (like Inngest)
* - You want fire-and-forget execution with pubsub streaming
* - You need resumable streams with event caching
* - You need runs to survive process death: an active run can be picked up by
* a fresh process over the same storage via `recover(runId)` /
* `recoverActiveRuns()` (running step state is persisted before execution)
*
* The key difference from DurableAgent is the execution strategy:
* - DurableAgent: Runs workflow steps in-process via createRun + start.
* - EventedAgent: Steps execute via events on `mastra.pubsub`, so any worker
* sharing that bus can process them. The agent's stream follows
* `mastra.pubsub`, so streaming, suspend/resume, and finish events work even
* when the agent was constructed with its own pubsub. Execution is tracked
* in the background so resume waits for suspension persistence.
*
* Register the EventedAgent on a `Mastra` instance (with storage) to get
* evented execution — the evented engine needs the host's pubsub, storage,
* and event workers. Without a host, the agent falls back to the default
* in-process engine (with a warning), preserving the released behavior of a
* standalone evented agent. Recovery entry points (`recover`,
* `listActiveRuns`, `recoverActiveRuns`) still require a host and throw
* directly without one.
*
* @example
* ```typescript
* import { Mastra } from '@mastra/core';
* import { Agent } from '@mastra/core/agent';
* import { EventedAgent } from '@mastra/core/agent/durable';
*
* const agent = new Agent({
* id: 'my-agent',
* instructions: 'You are a helpful assistant',
* model: openai('gpt-4'),
* });
*
* const eventedAgent = new EventedAgent({ agent });
*
* // Register on a Mastra host to get evented execution (a hostless agent
* // falls back to the default in-process engine).
* const mastra = new Mastra({
* agents: { myAgent: eventedAgent },
* storage: new LibSQLStore({ url: 'file:mastra.db' }),
* });
*
* const { output, runId, cleanup } = await eventedAgent.stream('Hello!');
* const text = await output.text;
* cleanup();
*
* // After a crash/restart, a fresh process over the same storage can resume:
* // await eventedAgent.recoverActiveRuns();
* ```
*/
var EventedAgent = class extends DurableAgent {
/**
* Create a new EventedAgent that wraps an existing Agent
*/
constructor(config) {
super(config);
}
/**
* EventedAgent runs the durable agentic loop on the evented execution
* engine (pubsub + WorkflowEventProcessor) instead of the default
* in-process engine.
* @internal
*/
get workflowEngine() {
return "evented";
}
createExecutionEngine(mastra) {
return new EventedExecutionEngine(this.id, mastra);
}
get suspendPersistedOnReturn() {
return false;
}
/**
* Execute the durable workflow using the evented engine.
*
* The caller tracks this promise in the background without blocking stream(),
* then cleans up snapshots on a non-suspended terminal status.
*
* @param runId - The unique run ID
* @param workflowInput - The serialized workflow input
* @internal
*/
async executeWorkflow(runId, workflowInput) {
const entry = require_run_registry.getRunRegistryEntry(runId, this.getMastraInstance());
const executionFence = entry?.executionFence;
const pubsub = this.getMastraInstance()?.pubsub ?? this.getPubSub();
const { sharedExecution, usesRunPubSub } = this.executionEngine.prepareExecution(pubsub, executionFence, this.workflowEngine, this.logger, this.guardrailLogger);
if (entry) entry.eventedExecution = sharedExecution;
try {
const workflow = this.getWorkflow();
await this.executionEngine.ensureEngineWorkersStarted(this.workflowEngine, this.logger);
const memoryInfo = workflowInput.messageListState?.memoryInfo;
const threadId = workflowInput.state?.threadId ?? memoryInfo?.threadId;
if (sharedExecution && pubsub && entry?.requestContext && executionFence && threadId) {
await require_run_registry.agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, workflowInput.state?.resourceId ?? memoryInfo?.resourceId, executionFence.generation, executionFence.executionId);
require_run_registry.setExecutionClaim(entry.requestContext, runId, {
...executionFence.claim,
threadId,
resourceId: workflowInput.state?.resourceId ?? memoryInfo?.resourceId
});
}
const run = await this.executionEngine.createRun(workflow, {
runId,
resourceId: workflowInput.state?.resourceId ?? memoryInfo?.resourceId,
...usesRunPubSub ? { pubsub: this.fenceRunPubSub(executionFence, entry?.abortController) } : {}
});
await this.executionEngine.startRun(run, workflowInput, entry?.requestContext, require_observability.createObservabilityContext({ currentSpan: entry?.agentSpan })).then((result) => this.executionEngine.finishExecution(runId, executionFence, sharedExecution, { result }), (error) => this.executionEngine.finishExecution(runId, executionFence, sharedExecution, { error })).then((outcome) => {
if (outcome.owner === "agent") return this.settleExecution(runId, executionFence, outcome);
if (outcome.error) return this.emitError(runId, outcome.error, executionFence?.generation).catch((publishError) => this.logger.warn(`Failed to publish error event for run ${runId}`, {
runId,
error: publishError
}));
});
} catch (error) {
await this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") });
}
}
};
/**
* Check if an object is an EventedAgent class instance
*/
function isEventedAgentClass(obj) {
return obj instanceof EventedAgent;
}
// src/agent/durable/create-evented-agent.ts
/**
* Create an EventedAgent that wraps an existing Agent.
*
* This factory function creates an EventedAgent instance with fire-and-forget
* execution via the built-in evented workflow engine. Runs survive process
* death: over the same storage, a fresh process can resume in-flight runs via
* `recover(runId)` / `recoverActiveRuns()`.
*
* @param options - Configuration options
* @returns An EventedAgent instance (register it on a `Mastra` host before use)
*
* @example
* ```typescript
* const agent = new Agent({
* id: 'my-agent',
* instructions: 'You are helpful',
* model: openai('gpt-4'),
* });
*
* const eventedAgent = createEventedAgent({ agent });
*
* const mastra = new Mastra({
* agents: { myAgent: eventedAgent },
* });
* ```
*/
function createEventedAgent(options) {
const { agent, pubsub, cache, maxSteps, shouldCache, shouldPersistSnapshot, storageVersion } = options;
return new EventedAgent({
agent,
pubsub,
cache,
maxSteps,
shouldCache,
shouldPersistSnapshot,
storageVersion
});
}
/**
* Check if an object is an EventedAgent
*/
function isEventedAgent(obj) {
return obj instanceof EventedAgent;
}
// src/agent/durable/workflows/deprecated-tool-execution.ts
/**
* Execute tool calls durably with optional hooks for observability and streaming.
*
* @deprecated Superseded by the shared loop cores; will be removed in v2.
* The durable agent workflows no longer call this helper.
*
* @param ctx - Tool execution context with tool calls, resolved tools, and optional hooks
* @returns Array of tool call outputs with results or errors
*/
async function executeDurableToolCalls(ctx) {
const toolResults = [];
for (const toolCall of ctx.toolCalls) {
if (toolCall.providerExecuted && toolCall.output !== void 0) {
toolResults.push({
...toolCall,
result: toolCall.output
});
continue;
}
const tool = ctx.tools[toolCall.toolName];
if (!tool) {
const error = {
name: "ToolNotFoundError",
message: `Tool ${toolCall.toolName} not found`
};
await ctx.onToolError?.(toolCall, error);
toolResults.push({
...toolCall,
error
});
continue;
}
await ctx.onToolStart?.(toolCall);
try {
if (tool.execute) {
const result = await tool.execute(toolCall.args, {
toolCallId: toolCall.toolCallId,
messages: [],
workspace: ctx.workspace,
requestContext: ctx.requestContext
});
await ctx.onToolResult?.(toolCall, result);
toolResults.push({
...toolCall,
result
});
} else {
await ctx.onToolResult?.(toolCall, void 0);
toolResults.push({
...toolCall,
result: void 0
});
}
} catch (error) {
const toolError = {
name: "ToolExecutionError",
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : void 0
};
await ctx.onToolError?.(toolCall, toolError);
toolResults.push({
...toolCall,
error: toolError
});
}
}
return toolResults;
}
exports.AGENT_CONTROL_TOPIC = require_run_registry.AGENT_CONTROL_TOPIC;
exports.AGENT_STREAM_TOPIC = require_run_registry.AGENT_STREAM_TOPIC;
exports.AgentControlEventTypes = require_run_registry.AgentControlEventTypes;
exports.AgentStreamBus = require_run_registry.AgentStreamBus;
exports.AgentStreamEventTypes = require_run_registry.AgentStreamEventTypes;
exports.DURABLE_STOP_WHEN_ERROR_ID = require_run_registry.DURABLE_STOP_WHEN_ERROR_ID;
exports.DurableAgent = DurableAgent;
exports.DurableAgentDefaults = require_run_registry.DurableAgentDefaults;
exports.DurableStepIds = require_run_registry.DurableStepIds;
exports.EventedAgent = EventedAgent;
exports.ExtendedRunRegistry = require_run_registry.ExtendedRunRegistry;
exports.RUN_DEADLINE_KEY = RUN_DEADLINE_KEY;
exports.RunRegistry = require_run_registry.RunRegistry;
exports.__resetExecutionFencesForTests = require_run_registry.__resetExecutionFencesForTests;
exports.accumulatedUsageSchema = accumulatedUsageSchema;
exports.agentLoopTermination = require_observability.agentLoopTermination;
exports.agentThreadStreamRuntime = require_run_registry.agentThreadStreamRuntime;
exports.applyReservedMemoryContextKeys = applyReservedMemoryContextKeys;
exports.baseDurableAgenticInputSchema = baseDurableAgenticInputSchema;
exports.baseIterationStateSchema = baseIterationStateSchema;
exports.buildStepRecord = buildStepRecord;
exports.calculateAccumulatedUsage = calculateAccumulatedUsage;
exports.createBaseIterationStateUpdate = createBaseIterationStateUpdate;
exports.createDurableAgent = createDurableAgent;
exports.createDurableAgentStream = require_run_registry.createDurableAgentStream;
exports.createDurableAgenticWorkflow = createDurableAgenticWorkflow;
exports.createDurableBackgroundTaskCheckStep = createDurableBackgroundTaskCheckStep;
exports.createDurableGoalStep = createDurableGoalStep;
exports.createDurableIsTaskCompleteStep = createDurableIsTaskCompleteStep;
exports.createDurableLLMExecutionStep = createDurableLLMExecutionStep;
exports.createDurableLLMMappingStep = createDurableLLMMappingStep;
exports.createDurableToolCallStep = createDurableToolCallStep;
exports.createEventedAgent = createEventedAgent;
exports.createRunAbortController = require_run_registry.createRunAbortController;
exports.createWorkflowInput = createWorkflowInput;
exports.deleteRunRegistryEntry = require_run_registry.deleteRunRegistryEntry;
exports.detachFullStreamOnEnd = require_run_registry.detachFullStreamOnEnd;
exports.diffResponseMessages = require_run_registry.diffResponseMessages;
exports.durableAgenticOutputSchema = durableAgenticOutputSchema;
exports.emitAbortEvent = require_run_registry.emitAbortEvent;
exports.emitChunkEvent = require_run_registry.emitChunkEvent;
exports.emitErrorEvent = require_run_registry.emitErrorEvent;
exports.emitFinishEvent = require_run_registry.emitFinishEvent;
exports.emitStepFinishEvent = require_run_registry.emitStepFinishEvent;
exports.emitStepStartEvent = require_run_registry.emitStepStartEvent;
exports.emitSuspendedEvent = require_run_registry.emitSuspendedEvent;
exports.endRunSpansWithError = require_run_registry.endRunSpansWithError;
exports.ensureRemoteAbortListener = ensureRemoteAbortListener;
exports.executeDurableAgentScorers = executeDurableAgentScorers;
exports.executeDurableToolCalls = executeDurableToolCalls;
exports.executionFailureTermination = require_observability.executionFailureTermination;
exports.getRunRegistryEntry = require_run_registry.getRunRegistryEntry;
exports.getRunStreamSlot = require_run_registry.getRunStreamSlot;
exports.getScopeStreamSlot = require_run_registry.getScopeStreamSlot;
exports.globalRunRegistry = require_run_registry.globalRunRegistry;
exports.isDurableAgent = isDurableAgent;
exports.isEventedAgent = isEventedAgent;
exports.isEventedAgentClass = isEventedAgentClass;
exports.isLocalDurableAgent = isLocalDurableAgent;
exports.loadRunStoredMessages = loadRunStoredMessages;
exports.modelConfigSchema = modelConfigSchema;
exports.modelListEntrySchema = modelListEntrySchema;
exports.normalizeResumeGenerateArgs = normalizeResumeGenerateArgs;
exports.persistDurableRunInput = persistDurableRunInput;
exports.prepareForDurableExecution = prepareForDurableExecution;
exports.pruneAgentLoopSnapshot = require_run_registry.pruneAgentLoopSnapshot;
exports.publishAbortRequest = require_run_registry.publishAbortRequest;
exports.readRunDeadline = readRunDeadline;
exports.rebuildRunToolsFromMastra = rebuildRunToolsFromMastra;
exports.requestAcknowledgedAbort = require_run_registry.requestAcknowledgedAbort;
exports.resolveDurableToolCallConcurrency = resolveDurableToolCallConcurrency;
exports.resolveInternalState = resolveInternalState;
exports.resolveModel = resolveModel;
exports.resolveRuntimeDependencies = resolveRuntimeDependencies;
exports.resolveTool = resolveTool;
exports.runDurableFinishSideEffects = runDurableFinishSideEffects;
exports.runDurableStreamUntilIdle = runDurableStreamUntilIdle;
exports.runResumeDurableStreamUntilIdle = runResumeDurableStreamUntilIdle;
exports.serializeDurableOptions = serializeDurableOptions;
exports.serializeDurableState = serializeDurableState;
exports.serializeModelConfig = serializeModelConfig;
exports.serializeToolsMetadata = serializeToolsMetadata;
exports.setRunRegistryEntry = require_run_registry.setRunRegistryEntry;
exports.subscribeToAbortRequests = require_run_registry.subscribeToAbortRequests;
exports.takeRunScorerInstances = require_run_registry.takeRunScorerInstances;
exports.toolRequiresApproval = toolRequiresApproval;
exports.untilIdleHandlesBackgroundTask = require_run_registry.untilIdleHandlesBackgroundTask;
exports.validateModelTimeoutSettings = require_run_registry.validateModelTimeoutSettings;
//# sourceMappingURL=index.cjs.map