@mastra/core
Version:
1,273 lines • 64.1 kB
TypeScript
import type { MastraServerCache } from '../../cache/base.js';
import type { PubSub } from '../../events/pubsub.js';
import type { MastraModelConfig } from '../../llm/model/shared.types.js';
import type { IMastraLogger } from '../../logger/index.js';
import type { Mastra } from '../../mastra/index.js';
import { RequestContext } from '../../request-context/index.js';
import type { DeclaredAgentSchedule } from '../../schedules/define.js';
import type { FullOutput, MastraModelOutput } from '../../stream/base/output.js';
import type { ChunkType, MastraOnFinishCallback, MastraStreamTransformOptions } from '../../stream/types.js';
import type { DynamicArgument } from '../../types/index.js';
import type { ShouldPersistSnapshotFn, WorkflowRunStatus } from '../../workflows/types.js';
import { Agent } from '../agent.js';
import type { AgentExecutionOptions } from '../agent.types.js';
import type { MessageListInput } from '../message-list/index.js';
import type { AgentStreamBus } from '../streams/bus.js';
import type { AgentRunRecord } from '../streams/run-records.js';
import type { AgentStreamsConfig } from '../streams/types.js';
import type { AgentAbortThreadOptions, AgentDurableOption, AgentModelManagerConfig, ToolsInput } from '../types.js';
import { DurableExecutionEngine } from './execution-engine.js';
import { ExecutionFence } from './execution-fence.js';
import { ExtendedRunRegistry } from './run-registry.js';
import type { AgentAbortEventData, AgentStreamEvent, DurableAgentStepFinishResult, AgentSuspendedEventData, DurableAgenticWorkflowInput, RunRegistryEntry } from './types.js';
import type { createDurableAgenticWorkflow } from './workflows/index.js';
/**
* 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.
*/
export declare function applyReservedMemoryContextKeys<T extends {
requestContext?: RequestContext;
memory?: any;
}>(options: T | undefined): T | undefined;
/**
* Options for DurableAgent.stream()
*/
export interface DurableAgentStreamOptions<OUTPUT = undefined> {
/** Signal chunks to hide from this caller's stream. Does not affect generated results. */
hideSignals?: AgentExecutionOptions<OUTPUT>['hideSignals'];
/** Custom instructions that override the agent's default instructions for this execution */
instructions?: AgentExecutionOptions<OUTPUT>['instructions'];
/** Additional context messages to provide to the agent */
context?: AgentExecutionOptions<OUTPUT>['context'];
/** Memory configuration for conversation persistence and retrieval */
memory?: AgentExecutionOptions<OUTPUT>['memory'];
/** Scopes this run acts with. See `AgentExecutionOptions.scopes`. */
scopes?: string[];
/** Unique identifier for this execution run */
runId?: string;
/** Request Context containing dynamic configuration and state */
requestContext?: AgentExecutionOptions<OUTPUT>['requestContext'];
/** Maximum number of steps to run */
maxSteps?: number;
/**
* Model to run for this call instead of the agent's model.
*
* A model instance can't be persisted, so `recover()` in another process falls back to the
* agent's own model and logs a warning.
*/
model?: DynamicArgument<MastraModelConfig>;
/**
* Conditions for stopping execution (e.g., step count, token limit).
*
* The predicate is non-serializable, so it's parked on the in-process run
* registry and evaluated by the durable loop on every iteration. Cross-process
* durable engines (e.g. Inngest after a worker restart) cannot recover the
* closure and degrade to `maxSteps` only.
*/
stopWhen?: AgentExecutionOptions<OUTPUT>['stopWhen'];
/** Additional tool sets that can be used for this execution */
toolsets?: AgentExecutionOptions<OUTPUT>['toolsets'];
/** Client-side tools available during execution */
clientTools?: AgentExecutionOptions<OUTPUT>['clientTools'];
/** Tool selection strategy */
toolChoice?: AgentExecutionOptions<OUTPUT>['toolChoice'];
/** Tool names enabled for this execution */
activeTools?: AgentExecutionOptions<OUTPUT>['activeTools'];
/** Model-specific settings like temperature */
modelSettings?: AgentExecutionOptions<OUTPUT>['modelSettings'];
/** Provider-specific options forwarded to the model (serialized into the durable workflow input) */
providerOptions?: AgentExecutionOptions<OUTPUT>['providerOptions'];
/** Require approval for tool calls. Boolean (gate all / none) or a per-call function policy. */
requireToolApproval?: AgentExecutionOptions<OUTPUT>['requireToolApproval'];
/** Automatically resume suspended tools */
autoResumeSuspendedTools?: boolean;
/** Maximum number of tool calls to execute concurrently, or an object with `limit`/`strategy` */
toolCallConcurrency?: AgentExecutionOptions<OUTPUT>['toolCallConcurrency'];
/** Whether to include raw chunks in the stream output */
includeRawChunks?: boolean;
/** Experimental transforms applied whenever `fullStream` is consumed. */
experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;
/** Maximum processor retries */
maxProcessorRetries?: number;
/** Structured output configuration */
structuredOutput?: AgentExecutionOptions<OUTPUT>['structuredOutput'];
/** Whether to return detailed scoring data in the response */
returnScorerData?: boolean;
/** Version overrides for sub-agent delegation */
versions?: AgentExecutionOptions<OUTPUT>['versions'];
/** Callback when chunk is received */
onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;
/** Callback when step finishes */
onStepFinish?: (result: DurableAgentStepFinishResult) => void | Promise<void>;
/** Callback when execution finishes — receives rich step data (text, steps, toolResults) */
onFinish?: MastraOnFinishCallback<OUTPUT>;
/** Callback on error */
onError?: ({ error }: {
error: Error | string;
}) => void | Promise<void>;
/** Callback when workflow suspends (e.g., for tool approval) */
onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;
/** Callback when execution is aborted via abortSignal */
onAbort?: AgentExecutionOptions<OUTPUT>['onAbort'];
/** Callback fired after each agentic-loop iteration */
onIterationComplete?: AgentExecutionOptions<OUTPUT>['onIterationComplete'];
/** Additional system message appended after context but before user messages. */
system?: AgentExecutionOptions<OUTPUT>['system'];
/** When true, background tasks are disabled for this run. */
disableBackgroundTasks?: AgentExecutionOptions<OUTPUT>['disableBackgroundTasks'];
/** Execution-scoped background dispatch policy for delegated agents. */
backgroundTaskPolicy?: AgentExecutionOptions<OUTPUT>['backgroundTaskPolicy'];
/** Tracing options forwarded to the agent/model spans. */
tracingOptions?: AgentExecutionOptions<OUTPUT>['tracingOptions'];
/** Per-call actor signal forwarded to FGA checks and tool execution. */
actor?: AgentExecutionOptions<OUTPUT>['actor'];
/** MCP protocol context forwarded to tools for in-process durable runs. */
mcp?: AgentExecutionOptions<OUTPUT>['mcp'];
/**
* Per-call tool lifecycle hooks. Applied when tools are prepared for this execution.
* Function hooks are not serialized; a cross-process recovery cannot restore them.
*/
hooks?: AgentExecutionOptions<OUTPUT>['hooks'];
/**
* Per-invocation tool payload transform policy. The closure rides on the
* in-process run registry; only the JSON-safe `targets` shadow is serialized
* for cross-process engines.
*/
transform?: AgentExecutionOptions<OUTPUT>['transform'];
/**
* Per-step preparation hook. Closure-only: stored on the in-process run
* registry and invoked as a `PrepareStepProcessor` at the start of every
* iteration. Cross-process resumes lose the hook.
*/
prepareStep?: AgentExecutionOptions<OUTPUT>['prepareStep'];
/**
* Per-call `isTaskComplete` policy. Scorer instances and `onComplete` are
* closure-only and live on the in-process run registry; the JSON-safe
* primitives (`strategy`, `timeout`, `parallel`, `suppressFeedback`,
* `scorerNames`) are serialized for cross-process observability.
*/
isTaskComplete?: AgentExecutionOptions<OUTPUT>['isTaskComplete'];
/**
* Sub-agent delegation hooks (`onDelegationStart`, `onDelegationComplete`,
* `messageFilter`, etc.). The callbacks are forwarded into `convertTools`
* at prepare time and burned into the sub-agent `CoreTool` wrappers on the
* in-process run registry. Cross-process resumes lose the callbacks (only
* `includeSubAgentToolResultsInModelContext` would be JSON-safe), so a
* fresh worker degrades to default delegation behaviour.
*/
delegation?: AgentExecutionOptions<OUTPUT>['delegation'];
/**
* When set, `stream()` delegates to the idle-loop wrapper that keeps the
* outer stream open across background-task continuations — the same
* behaviour as the now-deprecated `streamUntilIdle()`.
*
* Pass `true` for default idle timeout (5 min), or `{ maxIdleMs }` to
* customise.
*
* @example
* ```typescript
* const { output, cleanup } = await durableAgent.stream('Research topic', {
* untilIdle: true,
* memory: { thread: 't1', resource: 'u1' },
* });
* ```
*/
untilIdle?: boolean | {
maxIdleMs?: number;
};
/** When true, the in-loop background task check step skips waiting (streamUntilIdle sets this) */
_skipBgTaskWait?: boolean;
/**
* @internal
* Detach HTTP observers on reader cancellation instead of aborting execution.
*/
_detachObserverOnCancel?: boolean;
/**
* External abort signal. The durable agent always installs its own internal
* `AbortController` for the run; when this signal is provided, its `abort`
* event is forwarded to the internal controller so either source can cancel
* the run.
*
* Cross-process resumes (e.g. Inngest after a worker restart) cannot
* recover the signal — call `resume(runId, ..., { abortSignal })` with a
* fresh signal on each segment if you need abortability post-resume.
*/
abortSignal?: AbortSignal;
/**
* Whether this caller's stream closes when the run suspends (e.g. for tool
* approval). Defaults to `false`: the stream stays open across suspension so
* a later resume can continue streaming on this same reader.
*
* Set to `true` so `fullStream`, `text`, and `getFullOutput()` resolve at the
* suspension boundary (matching non-durable `Agent.stream()`), letting callers
* such as AG-UI or A2A react instead of hanging. Resume the run with
* `resumeStream()`/`resume()` — those always return a fresh stream.
*/
closeOnSuspend?: boolean;
}
type DurableAgentResumeOptions<OUTPUT = undefined> = DurableAgentStreamOptions<OUTPUT> & {
toolCallId?: string;
};
/**
* Result from DurableAgent.stream()
*/
export interface DurableAgentStreamResult<OUTPUT = undefined> {
/** The streaming output */
output: MastraModelOutput<OUTPUT>;
/** The full stream - delegates to output.fullStream for server compatibility */
readonly fullStream: ReadableStream<any>;
/** The unique run ID for this execution */
runId: string;
/** Thread ID if using memory */
threadId?: string;
/** Resource ID if using memory */
resourceId?: string;
/** Cleanup function to call when done (unsubscribes from pubsub) */
cleanup: () => void;
/**
* Abort the run. Flips the internal `AbortController` for this run, which
* surfaces as an `AbortError` inside the durable LLM-execution step and
* is bridged to the user's `onAbort` callback via the run's pubsub topic.
*
* Safe to call after the run has already finished — it's a no-op in that
* case.
*
* Also publishes an abort request over pubsub so the abort reaches the
* process executing the run, which in a load-balanced deployment is usually
* not this one. That process flips its own controller and unwinds normally;
* the workflow run is never hard-cancelled, so the terminal `finish` event
* still reaches stream consumers. Await the returned promise to know the
* request has been dispatched; ignoring it keeps the previous
* fire-and-forget behaviour.
*/
abort: (reason?: unknown) => Promise<void>;
}
/**
* Configuration for DurableAgent - wraps an existing Agent with durable execution
*/
export interface DurableAgentConfig<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TOutput = undefined> extends AgentStreamsConfig {
/**
* The Agent to wrap with durable execution capabilities.
* All agent methods (getModel, listTools, etc.) delegate to this agent.
*/
agent: Agent<TAgentId, TTools, TOutput>;
/**
* Optional ID override. Defaults to agent.id.
*/
id?: TAgentId;
/**
* Optional name override. Defaults to agent.name.
*/
name?: string;
/**
* Maximum steps for the agentic loop.
* Defaults to the workflow default if not specified.
*/
maxSteps?: number;
/**
* Overrides the snapshot-persistence policy for this agent's durable
* workflows. Returning false for a status skips that snapshot write.
*
* The default policy always persists `pending | paused | suspended`
* (required for human-in-the-loop `resume()`), and persists `running`
* when the Mastra instance is configured with
* `recovery: { durableAgents: 'auto' }`, or at each step boundary after
* `mastra.shutdown()` starts (even with recovery off). `running`
* checkpoints exist solely so `listActiveRuns()` / `recover()` /
* `recoverActiveRuns()` can see in-flight runs after a crash or shutdown.
*
* Footguns when providing a custom predicate:
* - Excluding `paused` / `suspended` breaks human-in-the-loop resume.
* - Excluding `running` makes the agent invisible to crash recovery.
* A guardrail warning is logged for both cases (detected by probing the
* predicate with an empty `stepResults`, so predicates that read
* `stepResults` may probe inaccurately — the warning is best-effort).
*
* EventedAgent and InngestAgent own their persistence policy and ignore
* this option with a warning.
*/
shouldPersistSnapshot?: ShouldPersistSnapshotFn;
/**
* How this agent's new runs are stored. `1` rewrites one snapshot per run
* on every write. `2` stores a run header plus per-step entries, and each
* write sends only what changed.
*
* Where the storage adapter doesn't support version 2, new runs are stored
* as version 1 and a warning is logged. Runs keep the version they were
* created with: a run resumed after this option changes continues in its
* stored version.
*
* @default 1
* @experimental
*/
storageVersion?: 1 | 2;
}
/**
* DurableAgent wraps an existing Agent with durable execution capabilities.
*
* Key features:
* 1. Resumable streams - clients can disconnect and reconnect without missing events
* 2. Serializable workflow inputs - works with durable execution engines
* 3. PubSub-based streaming - events flow through pubsub for distribution
*
* DurableAgent extends Agent, delegating most methods to the wrapped agent.
* It overrides stream() to use durable execution with the agentic workflow.
*
* Subclasses (EventedAgent, InngestAgent) override executeWorkflow() to
* customize how the workflow is executed.
*
* @example
* ```typescript
* import { Agent } from '@mastra/core/agent';
* import { DurableAgent } from '@mastra/core/agent/durable';
*
* const agent = new Agent({
* id: 'my-agent',
* instructions: 'You are a helpful assistant',
* model: openai('gpt-4'),
* });
*
* const durableAgent = new DurableAgent({ agent });
*
* const { output, runId, cleanup } = await durableAgent.stream('Hello!');
* const text = await output.text;
* cleanup();
* ```
*/
/**
* Statuses of durable agent runs discoverable via {@link DurableAgent.listActiveRuns}.
*
* `running` is the status reported by the workflow engine while the durable
* agent's agentic loop is actively executing (i.e. between suspend
* boundaries). Persisted `running` snapshots are the recovery source for runs
* orphaned by a process restart.
*/
export type DurableAgentActiveRunStatus = Extract<WorkflowRunStatus, 'running'>;
/**
* Filters for {@link DurableAgent.listActiveRuns}. Mirrors the
* `listWorkflowRuns` filter contract, plus the agent-level `threadId` /
* `resourceId` filters used by the base {@link Agent.listSuspendedRuns}.
*/
export interface DurableAgentListActiveRunsOptions {
/** Only return runs that belong to this memory thread. */
threadId?: string;
/** Only return runs that belong to this memory resource. */
resourceId?: string;
/** Only return runs created at or after this date. */
fromDate?: Date;
/** Only return runs created at or before this date. */
toDate?: Date;
/**
* Number of items per page. Pagination is applied when both `perPage` and
* `page` are provided; otherwise all matching runs are returned.
*/
perPage?: number;
/** Zero-indexed page number. */
page?: number;
}
/**
* A durable agent run currently reported as `running` in workflow snapshot
* storage. These are the runs that a boot-time or operator-initiated
* recovery would re-drive after a process restart.
*/
export interface DurableAgentActiveRun {
/** Run ID accepted by {@link DurableAgent.recoverActiveRuns} and workflow `restart`. */
runId: string;
status: DurableAgentActiveRunStatus;
threadId?: string;
resourceId?: string;
/** When the run's snapshot was last persisted while running. */
updatedAt: Date;
}
export interface DurableAgentListActiveRunsResult {
runs: DurableAgentActiveRun[];
/** Total number of matching runs, before pagination. */
total: number;
}
/**
* Outcome of a single run restart attempted by
* {@link DurableAgent.recoverActiveRuns}. `success` means `run.restart()`
* returned; `failed` means it threw and the error was captured so recovery
* of remaining runs could proceed; `skipped` means the run was not orphaned,
* recovery hit a transient error, its recovery wait timed out, or recovery was interrupted by shutdown.
*/
export interface DurableAgentRecoveredRun {
runId: string;
status: 'success' | 'failed' | 'skipped';
/** Set when `status` is `failed`. */
error?: Error;
/**
* Set when `status` is `skipped`:
* - `run-active`: another execution, possibly in another process, is live.
* Check again at `retryAt`.
* - `run-active-locally`: this process is executing the run.
* - `already-in-progress`: this process is already recovering the run.
* - `transient-error`: recovery hit a transient infrastructure error. Check again at `retryAt`.
* - `recovery-timeout`: the attempt is still pending or its 30-second wait expired. Check again at `retryAt`.
*/
reason?: 'run-active' | 'run-active-locally' | 'already-in-progress' | 'transient-error' | 'recovery-timeout';
/** Epoch ms to check again: claim expiry for `run-active`, or a retry delay for `transient-error` / `recovery-timeout`. */
retryAt?: number;
}
/**
* Filters for {@link DurableAgent.recoverActiveRuns}. Reuses the
* {@link DurableAgentListActiveRunsOptions} discovery filters and adds an
* escape hatch for targeting a specific run ID.
*/
export interface DurableAgentRecoverActiveRunsOptions extends DurableAgentListActiveRunsOptions {
/**
* Recover a specific run by ID. When set, the discovery filters and
* pagination fields are ignored. Useful when the caller already knows the
* run ID from another source (e.g. their own bookkeeping).
*/
runId?: string;
}
export interface DurableAgentRecoverActiveRunsResult {
recovered: DurableAgentRecoveredRun[];
/** Number of runs that restarted successfully. */
succeeded: number;
/** Number of runs whose restart threw. */
failed: number;
}
/**
* Options for {@link DurableAgent.recover}, a single-run streamable recovery
* counterpart to {@link DurableAgent.resume}.
*
* `recover()` rebuilds the run's non-serializable state from the persisted
* workflow snapshot (message list, model, tools, memory, saveQueueManager,
* request context, agent span) and returns a fresh {@link DurableAgentStreamResult}
* whose `fullStream` observes the recovered run through pubsub. Callbacks
* mirror `stream()` / `resume()`.
*/
export interface DurableAgentRecoverOptions<OUTPUT = undefined> {
/** Callback when chunk is received */
onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;
/** Experimental transforms applied whenever `fullStream` is consumed. */
experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;
/** Callback when a step finishes */
onStepFinish?: (result: DurableAgentStepFinishResult) => void | Promise<void>;
/** Callback when the recovered run finishes */
onFinish?: MastraOnFinishCallback<OUTPUT>;
/** Callback when the recovered run errors */
onError?: ({ error }: {
error: Error | string;
}) => void | Promise<void>;
/** Callback when the recovered run is aborted */
onAbort?: (data: AgentAbortEventData) => void | Promise<void>;
/** Callback when the recovered run suspends again */
onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;
/**
* Close the recovered stream once the run suspends (e.g. awaiting tool
* approval) so callers can hand off to `resume()`. Defaults to `false`.
*/
closeOnSuspend?: boolean;
/**
* Optional abort signal for the recovered segment. Forwarded onto a fresh
* internal `AbortController` installed on the run's registry entry, so
* `result.abort()` and the external signal can both cancel the recovered run.
*/
abortSignal?: AbortSignal;
/**
* Take the run over even while another execution is live. The other
* execution loses the run and stops; its writes are rejected when the
* workflows store supports run fencing. Without `force`, `recover()` throws
* `DURABLE_AGENT_RUN_ACTIVE` for a live run.
*/
force?: boolean;
}
export declare class DurableAgent<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TOutput = undefined> extends Agent<TAgentId, TTools, TOutput> {
#private;
/** @internal One execution owner per Agent, initialized without starting a workflow. */
protected get executionEngine(): DurableExecutionEngine;
/** @internal Subclasses supply their default engine without changing workflow fallback policy. */
protected createExecutionEngine(mastra?: Mastra): DurableExecutionEngine;
/**
* User-supplied snapshot-persistence policy
* (see DurableAgentConfig.shouldPersistSnapshot). Protected so subclasses
* that pin their own policy (EventedAgent) can detect and warn when set.
*/
protected readonly userShouldPersistSnapshot: ShouldPersistSnapshotFn | undefined;
/**
* Create a new DurableAgent that wraps an existing Agent
*/
constructor(config: DurableAgentConfig<TAgentId, TTools, TOutput>);
/** @internal Read one request-context value captured in a suspended durable run snapshot. */
__getSuspendedRunRequestContextValue({ runId, key, }: {
runId: string;
key: string;
}): Promise<unknown>;
/**
* Get the resolved cache instance.
* Lazily initialized to allow inheriting from Mastra.
*/
get cache(): MastraServerCache | null;
/**
* Get the PubSub instance.
* Returns CachingPubSub if caching is enabled, otherwise the inner pubsub.
*/
get pubsub(): PubSub;
/** Durable runs always publish on their stream topic. */
hasResumableStreams(): boolean;
__usesSharedRunLog(): boolean;
/** Durable execution uses its lifecycle publisher, not the plain Agent entry point. @internal */
protected __ownsPlainStreamPublisher(): boolean;
/** Kept `false`, the value this getter has always reported for durable agents. */
get durable(): AgentDurableOption | undefined;
/** @internal */
__getStreamBus(): AgentStreamBus;
/**
* Owner of a run this process still tracks (until its auto-cleanup clears
* the replay history), or undefined.
* @internal
*/
__getRunOwner(runId: string): {
resourceId?: string;
threadId?: string;
} | undefined;
__getRunRecord(runId: string): Promise<AgentRunRecord | undefined>;
/**
* 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
*/
__getReplayOwner(runId: string): Promise<{
resourceId?: string;
threadId?: string;
} | undefined>;
/**
* Get the wrapped agent instance.
*/
get agent(): Agent<TAgentId, TTools, TOutput>;
/**
* 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(): DeclaredAgentSchedule[];
/**
* Mirrors {@link getDeclaredSchedules} so attaching schedules to an
* already-wrapped agent lands on the instance the getter reads from.
*/
__setDeclaredSchedules(schedules: DeclaredAgentSchedule[]): void;
/**
* Get the run registry (for testing and advanced usage)
*/
get runRegistry(): ExtendedRunRegistry;
/**
* Get the max steps configured for this agent
*/
get maxSteps(): number | undefined;
/**
* Get the cleanup timeout in milliseconds.
* Returns 0 if auto-cleanup is disabled.
*/
get cleanupTimeoutMs(): number;
__setLogger(logger: IMastraLogger): void;
getModel(options?: any): import("../../_types/@internal_ai-sdk-v4@0.0.98/dist/index.js").LanguageModelV1 | Promise<import("../../_types/@internal_ai-sdk-v4@0.0.98/dist/index.js").LanguageModelV1 | import("..").MastraLanguageModel> | import("..").MastraLanguageModel;
getLLM(options?: any): Promise<import("..").MastraLLM> | import("..").MastraLLM;
getModelList(requestContext?: any): Promise<AgentModelManagerConfig[] | null>;
getInstructions(options?: any): Promise<import("../../llm").SystemMessage> | import("../../llm").SystemMessage;
getDescription(): string;
getMetadata(options?: any): Promise<Record<string, unknown> | undefined> | Record<string, unknown> | undefined;
getTracingPolicy(): import("../../observability").TracingPolicy | undefined;
listTools(options?: any): Promise<TTools>;
getConfiguredToolHooks(): import("../../tools").ToolHooks<unknown, unknown, unknown, Record<string, unknown>> | undefined;
getDefaultOptions(options?: any): Promise<import("../agent.types").PublicAgentExecutionOptions<TOutput>> | import("../agent.types").PublicAgentExecutionOptions<TOutput>;
getDefaultGenerateOptionsLegacy(options?: any): Promise<import("..").AgentGenerateOptions> | import("..").AgentGenerateOptions;
getDefaultStreamOptionsLegacy(options?: any): Promise<import("..").AgentStreamOptions> | import("..").AgentStreamOptions;
getDefaultNetworkOptions(options?: any): Promise<import("..").NetworkOptions> | import("..").NetworkOptions;
getMemory(options?: any): Promise<import("../../memory").MastraMemory | undefined>;
getScopes(options?: any): Promise<string[]>;
hasOwnMemory(): boolean;
getWorkspace(options?: any): Promise<import("../../workspace").AnyWorkspace | undefined>;
hasOwnWorkspace(): boolean;
getVoice(options?: any): Promise<import("../../_types/@internal_voice@0.0.47/dist/index.js").IMastraVoice<unknown, unknown, import("../../_types/@internal_voice@0.0.47/dist/index.js").ToolsInput, import("../../_types/@internal_voice@0.0.47/dist/index.js").VoiceEventMap, unknown>>;
get voice(): import("../../_types/@internal_voice@0.0.47/dist/index.js").IMastraVoice<unknown, unknown, import("../../_types/@internal_voice@0.0.47/dist/index.js").ToolsInput, import("../../_types/@internal_voice@0.0.47/dist/index.js").VoiceEventMap, unknown>;
get requestContextSchema(): import("@mastra/schema-compat").StandardSchemaWithJSON<any> | undefined;
getConfiguredProcessorWorkflows(): Promise<import("../../processors").ProcessorWorkflow[]>;
listInputProcessors(requestContext?: any): Promise<import("../../processors").InputProcessorOrWorkflow[]>;
listOutputProcessors(requestContext?: any): Promise<import("../../processors").OutputProcessorOrWorkflow[]>;
listErrorProcessors(requestContext?: any): Promise<import("../../processors").ErrorProcessorOrWorkflow[]>;
resolveProcessorById<TId extends string = string>(processorId: TId, requestContext?: any): Promise<import("../../processors").Processor<TId, unknown> | null>;
listConfiguredInputProcessors(requestContext?: any): Promise<import("../../processors").InputProcessorOrWorkflow[]>;
listConfiguredOutputProcessors(requestContext?: any): Promise<import("../../processors").OutputProcessorOrWorkflow[]>;
getConfiguredProcessorIds(requestContext?: any): Promise<{
inputProcessorIds: string[];
outputProcessorIds: string[];
errorProcessorIds: string[];
}>;
getConfiguredErrorProcessorIds(requestContext?: any): Promise<string[]>;
__resolveRunErrorProcessors(requestContext: any, overrides?: any): Promise<{
errorProcessors: import("../../processors").ErrorProcessorOrWorkflow[];
hasConfiguredErrorProcessors: boolean;
}>;
__listLLMRequestProcessors(requestContext?: any, errorProcessorOverrides?: any): Promise<import("../../processors").LLMRequestProcessorOrWorkflow[]>;
listAgents(options?: any): Promise<Record<string, import("..").SubAgent<string, any>>> | Record<string, import("..").SubAgent<string, any>>;
__getStaticAgents(): Record<string, import("..").SubAgent<string, any>> | undefined;
__hasSubAgentsConfigured(): boolean;
listWorkflows(options?: any): Promise<Record<string, import("../../workflows").AnyWorkflow>>;
getSkill(skillName: string, options?: any): Promise<import("../../workspace").Skill | null>;
listSkills(options?: any): Promise<import("../../workspace").SkillMetadata[]>;
listScorers(options?: any): Promise<import("../../evals").MastraScorers>;
getBackgroundTasksConfig(): import("../../background-tasks").AgentBackgroundConfig | undefined;
disableBackgroundTasks(): void;
enableBackgroundTasks(): void;
getToolPayloadTransform(): import("../../tools").ToolPayloadTransformPolicy | undefined;
__getGoalConfig(): import("..").GoalConfig | undefined;
get browser(): import("..").MastraBrowser | undefined;
setBrowser(browser: any): void;
hasOwnBrowser(): boolean;
getChannels(): import("../../channels").AgentChannels | null;
setChannels(agentChannels: any): void;
hasOwnPubSub(): boolean;
getPubSub(): PubSub | undefined;
__setMemory(memory: any): void;
__setPubSub(pubsub: any): void;
__setWorkspace(workspace: any): void;
__getEditorConfig(): import("..").AgentEditorConfig | undefined;
__getOverridableFields(): {
instructions: DynamicArgument<import("../../llm").SystemMessage, any>;
model: {
id: string;
model: DynamicArgument<import("../../llm").WidenedMastraModelConfig>;
maxRetries: number;
maxRetriesConfigured: boolean;
enabled: boolean;
modelSettings?: DynamicArgument<import("..").ModelFallbackSettings>;
providerOptions?: DynamicArgument<import("../../llm/model/provider-options").ProviderOptions>;
headers?: DynamicArgument<Record<string, string>>;
}[] | DynamicArgument<import("..").ModelWithRetries[] | MastraModelConfig, any>;
tools: DynamicArgument<TTools, any>;
workspace: DynamicArgument<import("../../workspace").AnyWorkspace | undefined, any>;
};
__updateInstructions(instructions: Parameters<Agent<TAgentId, TTools, TOutput>['__updateInstructions']>[0]): void;
__updateModel(config: Parameters<Agent<TAgentId, TTools, TOutput>['__updateModel']>[0]): void;
__setTools(tools: Parameters<Agent<TAgentId, TTools, TOutput>['__setTools']>[0]): void;
/**
* 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(): Record<string, unknown> | undefined;
__setRawConfig(rawConfig: Record<string, unknown>): void;
/**
* 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(): Agent<TAgentId, TTools, TOutput>;
/**
* Get the run registry for use by subclasses.
* @internal
*/
protected get runRegistryInternal(): ExtendedRunRegistry;
/**
* Which workflow execution engine the durable agentic loop runs on.
* Subclasses override this (EventedAgent → 'evented').
* @internal
*/
protected get workflowEngine(): 'default' | 'evented';
/** Whether new runs opt into journal storage. @internal */
protected get storesRunsInJournal(): boolean;
/**
* 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
*/
protected resolveWorkflowEngine(): 'default' | 'evented';
/**
* 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
*/
protected ensureEngineWorkersStarted(): Promise<void>;
private persistInitialInput;
/**
* 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
*/
protected executeWorkflow(runId: string, workflowInput: DurableAgenticWorkflowInput): Promise<{
status?: string;
} | void>;
/**
* 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).
*/
private withSuspensionAfterPersist;
/**
* 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
*/
protected get suspendPersistedOnReturn(): boolean;
/**
* 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
*/
protected createWorkflow(): ReturnType<typeof createDurableAgenticWorkflow>;
/**
* 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
*/
protected resolveShouldPersistSnapshot(): ShouldPersistSnapshotFn;
protected workflowFailureError(workflowError: unknown, fallbackMessage: string): Error;
protected workflowExecutionError(workflowError: unknown, fallbackMessage: string): Error;
/**
* 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
*/
protected emitError(runId: string, error: Error, generation?: number): Promise<void>;
/**
* 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
*/
protected fenceRunPubSub(executionFence: ExecutionFence | undefined, abortController: AbortController | undefined, pubsub?: PubSub): PubSub;
/**
* 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
*/
protected settleExecution(runId: string, fence: ExecutionFence | undefined, outcome: {
status?: string;
error?: Error;
}): Promise<void>;
/**
* 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: string, resourceId: string, taskId: string): boolean;
abortThreadStream(options: AgentAbortThreadOptions): boolean;
/** @internal Like {@link abortThreadStream}, but reports whether a run on another process was asked to stop. */
__abortThreadStreamAcrossProcesses(options: AgentAbortThreadOptions): Promise<boolean>;
abortRunStream(runId: string): boolean;
protected __abortLocalRun(runId: string): boolean;
/**
* 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.
*/
__abortRunAcknowledged(runId: string): Promise<boolean>;
/**
* 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
*/
protected deleteRunSnapshots(runId: string): Promise<void>;
/**
* Stream a response from the agent using durable execution.
*/
stream(messages: MessageListInput, options?: DurableAgentStreamOptions<TOutput>): Promise<DurableAgentStreamResult<TOutput>>;
/**
* Resume a suspended workflow execution.
*/
resume(runId: string, resumeData: unknown, options?: DurableAgentResumeOptions<TOutput>): Promise<DurableAgentStreamResult<TOutput>>;
/**
* 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();
* ```
*/
recover(runId: string, options?: DurableAgentRecoverOptions<TOutput>): Promise<DurableAgentStreamResult<TOutput>>;
/**
* 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()`.
*/
resumeStream(resumeData: any, streamOptions?: any): Promise<MastraModelOutput<TOutput>>;
/** @deprecated Use `resumeStream(resumeData, { untilIdle: true })` instead. */
resumeStreamUntilIdle(resumeData: any, streamOptions?: any): Promise<MastraModelOutput<TOutput>>;
/**
* Override the inherited `approveToolCall()` to route through the durable
* `resume()` path.
*/
approveToolCall(options: {
runId: string;
toolCallId?: string;
} & Record<string, any>): Promise<MastraModelOutput<any>>;
/**
* Override the inherited `declineToolCall()` to route through the durable
* `resume()` path.
*/
declineToolCall(options: {
runId: string;
toolCallId?: string;
reason?: string;
} & Record<string, any>): Promise<MastraModelOutput<any>>;
approveToolCallGenerate<OUTPUT = undefined>(options: AgentExecutionOptions<OUTPUT> & {
runId: string;
toolCallId?: string;
}): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['getFullOutput']>>>;
declineToolCallGenerate<OUTPUT = undefined>(options: AgentExecutionOptions<OUTPUT> & {
runId: string;
toolCallId?: string;
reason?: string;
}): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['getFullOutput']>>>;
/**
* 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.
*/
generate(messages: MessageListInput, options?: DurableAgentStreamOptions<TOutput>): Promise<FullOutput<TOutput>>;
/**
* Resume a suspended durable run and drain it to a single
* {@link FullOutput}. Mirrors {@link Agent.resumeGenerate} on top of
* {@link DurableAgent.resume}.
*
* Unlike `generate()`, this delegates to `resume()` because resume reads
* its tools from the existing run-registry entry rather than running
* `prepareForDurableExecution` again — there is no `methodType` to thread
* through. The same `EventedAgent` caveat about fire-and-forget snapshot
* persistence noted on `generate()` applies if the resumed turn suspends.
*/
resumeGenerate(resumeData: unknown, options: Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2] & {
runId: string;
}): Promise<FullOutput<TOutput>>;
/** @deprecated Use `resumeGenerate(resumeData, { runId, ...options })`, matching `Agent.resumeGenerate`. */
resumeGenerate(runId: string, resumeData: unknown, options?: Parameters<DurableAgent<TAgentId, TTools, TOutput>['resume']>[2]): Promise<FullOutput<TOutput>>;
/**
* 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 });
* }
* ```
*/
listActiveRuns(options?: DurableAgentListActiveRunsOptions): Promise<DurableAgentListActiveRunsResult>;
/**
* 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 });
* ```
*/
recoverActiveRuns(options?: DurableAgentRecoverActiveRunsOptions): Promise<DurableAgentRecoverActiveRunsResult>;
/**
* 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
*/
__subscribeToRunStream(runId: string, options: {
offset?: number;
onComplete?: () => void;
}, onEvent: (event: AgentStreamEvent) => void): Promise<() => Promise<void>>;
/**
* 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.
*/
observe(runId: string, options?: {
/**
* Inclusive, zero-based PubSub event index. It counts all cached run-topic events, including
* lifecycle events, not chunks. Each chunk carries its event's index as `chunk.index`: to resume
* after a dropped connection, pass the `index + 1` of the last chunk that has an index. Omit it to replay all available cached events. Transports
* without numeric offsets live-tail instead. Skipping earlier text deltas produces partial text
* and may make structured output fail to parse; beyond retained history, an offset also skips
* lower-index live events on numeric-offset transports. See
* https://mastra.ai/reference/agents/durable-agent#observerunid-options.
*/
offset?: number;
idleTimeoutMs?: number;
isAlive?: () => boolean | Promise<boolean>;
onChunk?: (chunk: ChunkType<TOutput>) => void | Promise<void>;
experimentalTransform?: MastraStreamTransformOptions<TOutput>;
onStepFinish?: (result: DurableAgentStepFinishResult) => void | Promise<void>;
onFinish?: MastraOnFinishCallback<TOutput>;
onError?: ({ error }: {
error: Error | string;
}) => void | Promise<void>;
onAbort?: (data: AgentAbortEventData) => void | Promise<void>;
onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;
}): Promise<Omit<DurableAgentStreamResult<TOutput>, 'runId'> & {
runId: string;
detach: () => void;
}>;
/**
* Get the workflow instance for direct execution.
* Lazily creates the workflow and registers Mastra on it (needed for
* getAgentById in execution steps).
*/
getWorkflow(): ReturnType<typeof createDurableAgenticWorkflow>;
/**
* 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
*/
protected warnOnRiskyPersistencePolicy(): void;
/**
* 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
*/
protected get guardrailLogger(): IMastraLogger;
/**
* @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.
*/
streamUntilIdle<OUTPUT = TOutput>(messages: MessageListInput, streamOptions?: DurableAgentStreamOptions<OUTPUT> & {
maxIdleMs?: number;
}): Promise<DurableAgentStreamResult<OUTPUT>>;
/**
* Prepare for durable execution without starting it.
*/
prepare(messages: MessageListInput, options?: AgentExecutionOptions<TOutput>): Promise<{
runId: string;
messageId: string;
workflowInput: DurableAgenticWorkflowInput;
registryEntry: RunRegistryEntry;
threadId: string | undefined;
resourceId: string | undefined;
}>;
/**
* Get the durable workflows required by this agent.
* Called by Mastra during agent registration.
* @internal
*/
getDurableWorkflows(): import("../../workflows").Workflow<import("../../workflows").DefaultEngineType, import("../../workflows").Step<string, unknown, unknown, unknown, unknown, unknown, any, unknown>[], "durable-agentic-loop", unknown, {
__workflowKind: "durable-agent";
runId: string;
agentId: string;
agentName?: string | undefined;
agentVersionId?: string | undefined;
messageListState: any;
toolsMetadata: any[];
modelConfig: {
provider: string;
modelId: string;
specificationVersion?: string | undefined;
settings?: Record<string, any> | undefined;
providerOptions?: Record<string, any> | undefined;
};
modelList?: {
id: string;
config: {
provider: string;
modelId: string;
specificationVersion?: string | undefined;
originalConfig?: string | Record<string, any> | undefined;
settings?: Record<string, any> | undefined;
providerOptions?: Record<string, any> | undefined;
};
maxRetries: number;
enabled: boolean;
}[] | undefined;
scorers?: Record<string, any> | undefined;
options: any;
state: any;
messageId: string;
agentSpanData?: any;
modelSpanData?: any;
stepIndex?: number | undefined;
requestContextEntries?: Record<string, any> | undefined;
inputTripwire?: {
reason: string;
retry?: boolean | undefined;
processorId?: string | undefined;
metadata?: unknown;
} | undefined;
}, {
messageListState: any;
messageId: string;
stepResult: any;
output: {
text?: string | undefined;
usage: any;
steps: any[];
};
state: any;
}, {
messageListState: any;
messageId: string;
stepResult: any;
output: {
text?: string | undefined;
usage: any;
steps: any[];
};
state: any;
}, unknown, 1>[];
/**
* 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: Mastra): void;
/**
* 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: Mastra): void;
}
export {};
//# sourceMappingURL=durable-agent.d.ts.map