@mastra/core
Version:
2,095 lines • 99.3 kB
TypeScript
import type { Agent } from '../agent/index.js';
import type { MastraDBMessage, MastraProviderMetadata } from '../agent/message-list/state/types.js';
import type { AgentSignalAttributes, AgentSignalContents, AgentSignalInput, MessageAuthor } from '../agent/signals.js';
import type { AgentSignalActiveBehavior, AgentSignalIdleBehavior, AgentThreadSubscription, MastraBrowser, SendAgentNotificationSignalOptions, SendAgentNotificationSignalResult, SendAgentSignalAccepted, ToolsetsInput } from '../agent/types.js';
import type { MastraModelGatewayInterface } from '../llm/model/gateways/index.js';
import type { MastraModelConfig } from '../llm/model/shared.types.js';
import type { RunScope } from '../mastra/run-scope.js';
import type { MastraMemory } from '../memory/memory.js';
import type { SendNotificationSignalInput } from '../notifications/index.js';
import type { TracingContext, TracingOptions } from '../observability/index.js';
import { RequestContext } from '../request-context/index.js';
import type { PublicSchema } from '../schema/index.js';
import type { StorageListMessagesOutput } from '../storage/types.js';
import { Workspace } from '../workspace/index.js';
import { SessionRunEngine } from './session-run-engine.js';
import type { TaskItemSnapshot } from './tools.js';
import type { AgentControllerDisplayState, AgentControllerEvent, AgentControllerEventListener, AgentControllerMode, AgentControllerOMConfig, AgentControllerRequestState, AgentControllerRequestStateUpdater, AgentControllerThinkingLevel, AgentControllerThread, ModelUseCountTracker, OMModel, PermissionPolicy, PermissionRules, TokenUsage, ToolCategory } from './types.js';
export declare const SUSPENDED_RUN_AGENT_KEY: import("../mastra/run-scope").RunScopeKey<Agent<string, import("../agent").ToolsInput, undefined, any, import("../agent").AgentEditorConfig | undefined>>;
export declare const SOURCE_APPROVAL_CALLS_KEY: import("../mastra/run-scope").RunScopeKey<Set<string>>;
export declare const THREAD_OWNER_ID_RUN_SCOPE_KEY: import("../mastra/run-scope").RunScopeKey<string>;
export declare const THREAD_OWNER_ID_CONTEXT_KEY = "mastra__agentControllerThreadOwnerId";
/**
* The mode a run was started (or explicitly transitioned) in. Stored as a raw
* request-context value so the suspend snapshot persists it, and a resume can
* apply that mode's tool allowlist even after the session switched modes.
*/
export declare const RUN_MODE_ID_CONTEXT_KEY = "mastra__agentControllerRunModeId";
/**
* Memory the suspended run persisted its messages under, resolved with the
* run's own RequestContext while the stream was live. Abort settlement cannot
* rebuild that context later (dynamic `memory: ({ requestContext }) => …`
* configs would resolve differently against an empty context), so the resolved
* instance is retained beside the owning agent for the life of the run scope.
*/
export declare const SUSPENDED_RUN_MEMORY_KEY: import("../mastra/run-scope").RunScopeKey<MastraMemory>;
/**
* Minimal persistence surface the Session uses to read and write per-thread
* settings (mode id, per-mode model id, …). The AgentController backs this with thread
* metadata; when no storage is configured it is absent and the Session keeps
* its state purely in memory.
*/
export interface ThreadSettingsStore {
/** Read all settings for a specific thread. */
getAllOn(threadId: string): Promise<Record<string, unknown>>;
/** Read a setting for the active thread, or undefined when unset/unavailable. */
get(key: string): Promise<unknown>;
/** Return the active thread id, or undefined when no thread is bound. */
getThreadId(): string | undefined;
/** Persist a setting for the active thread (no-op when storage is unavailable). */
set(key: string, value: unknown): Promise<void>;
/** Persist a setting to a specific thread. */
setOn(threadId: string, key: string, value: unknown): Promise<void>;
/** Persist a model selection and its preferences in one metadata write. */
setModelOn(threadId: string, settings: Record<string, unknown>): Promise<void>;
}
/** Process-local listener awaited before a terminal agent event is emitted. */
export type SessionBeforeAgentEndListener = (event: Extract<AgentControllerEvent, {
type: 'agent_end';
}>) => void | Promise<void>;
/** Options for {@link Session.sendNotificationSignal}. */
export type SessionSendNotificationSignalOptions = {
ifActive?: SendAgentNotificationSignalOptions['ifActive'];
ifIdle?: SendAgentNotificationSignalOptions['ifIdle'];
tracingContext?: TracingContext;
tracingOptions?: TracingOptions;
requestContext?: RequestContext;
/**
* Scopes for the run the notification starts. A run's scopes are fixed when it starts:
* a notification naming other scopes than the active run's starts its own run after it.
*/
scopes?: string[];
};
/**
* Reason attached to tool prompts retracted because the user aborted the run.
* Shared by the parked-suspension retraction and the gated-approval decline so
* both render the same "the user interrupted this" explanation.
*/
export declare const ABORTED_BY_USER_REASON = "Aborted by the user";
/** Version marker for thread metadata using the single-model persistence format. */
export declare const MODEL_PERSISTENCE_VERSION: 2;
export declare const MODEL_PERSISTENCE_VERSION_KEY: 'modelPersistenceVersion';
export declare function runModelPersistenceOperation<T>(threadId: string | undefined, operation: () => Promise<T>): Promise<T>;
/**
* Resolve and migrate a thread's persisted model selection.
*
* Threads created before single-model sessions have a create-time `currentModelId`
* plus the actual last selection in `modeModelId_<mode>`. Without the version
* marker, the active mode's legacy value wins. Migration copies that selection
* to `currentModelId`, stamps the marker, then removes all obsolete mode keys.
*/
export declare function migratePersistedModelSelection({ metadata, getMetadata, modeId, onResolved, set, threadId, validModeIds, }: {
metadata?: Record<string, unknown>;
getMetadata?: () => Promise<Record<string, unknown>>;
modeId: string;
onResolved?: (modelId: string, metadata: Record<string, unknown>) => void | Promise<void>;
set: (key: string, value: unknown) => Promise<void>;
threadId?: string;
validModeIds?: readonly string[];
}): Promise<string | undefined>;
/**
* Internal thread-metadata keys used by `Session.loadMetadata()` to persist
* runtime bookkeeping (selected model/mode, observer/reflector config, token
* usage). These share the flat thread `metadata` bag with user-provided
* session scoping tags, so they must never be treated as tags: they are
* skipped when stamping tags onto a thread and excluded when reading tags
* back out of thread metadata.
*/
declare const RESERVED_THREAD_METADATA_KEYS: readonly ["currentModelId", "modelPersistenceVersion", "currentModeId", "observerModelId", "reflectorModelId", "observerModelSelection", "reflectorModelSelection", "observationThreshold", "reflectionThreshold", "tokenUsage", "ownerId", "createdBy", "thinkingLevel", "notifications", "permissionRules"];
/** Packages that cannot import the list as a value pin their copy to it with `satisfies Record<ReservedThreadMetadataKey, true>`. */
export type ReservedThreadMetadataKey = (typeof RESERVED_THREAD_METADATA_KEYS)[number];
export declare function isReservedThreadMetadataKey(key: string): boolean;
/**
* Identifies an in-memory session host. A session is not a durable conversation:
* it is the process-local handle for `{ id, resourceId, tags, active threadId }`.
* Conversation settings and run state belong to the active thread and are
* re-derived whenever the host creates or switches threads.
*
* `defaultResourceId` is the resourceId the host started with; switching to a
* different resource (e.g. impersonation, or browsing another user's threads)
* updates the current resourceId while the default is retained so the host can
* return to its original resource.
*
* `id` and `ownerId` are stable host identity fields. They are not persisted by
* AgentController and do not describe ownership of any particular thread. The
* active thread binding lives on {@link SessionThread}.
*/
export declare class SessionIdentity {
#private;
constructor({ resourceId, id, ownerId }: {
resourceId: string;
id: string;
ownerId: string;
});
/** The resourceId the session currently reads/writes under. */
getResourceId(): string;
/** The resourceId the session started with. */
getDefaultResourceId(): string;
/** The stable session identifier for this session. */
getId(): string;
/**
* The stable identity of this process-local session host.
* Use `AgentControllerRequestContext.threadOwnerId` for thread ownership and billing attribution.
*/
getOwnerId(): string;
/** Point the session at a different resourceId (the default is unchanged). */
setResourceId({ resourceId }: {
resourceId: string;
}): void;
}
/**
* The shared-host storage surface the Session's thread domain leverages to read
* and write threads. The AgentController backs this with its memory storage (mapping raw
* storage rows to {@link AgentControllerThread}/{@link MastraDBMessage}); when no storage
* is configured the handle is absent and the data methods degrade gracefully
* (empty lists, undefined settings, no-op writes).
*
* This is a gateway to shared infrastructure — not a callback into AgentController
* orchestration. The Session owns the thread-domain logic; the host owns the DB.
*/
export interface ThreadDataStore {
/** List threads for a resource (or all resources), already mapped + filtered of forked subagents unless asked. */
listThreads(input: {
resourceId?: string;
includeForkedSubagents?: boolean;
metadata?: Record<string, unknown>;
}): Promise<AgentControllerThread[]>;
/** Fetch a single thread by id, or null when it doesn't exist. */
getById(input: {
threadId: string;
}): Promise<AgentControllerThread | null>;
/** List messages for a thread, newest-`limit` (returned oldest-first) or all. */
listMessages(input: {
threadId: string;
limit?: number;
}): Promise<StorageListMessagesOutput>;
/** The first user message for each given thread id. */
firstUserMessages(input: {
threadIds: string[];
}): Promise<Map<string, MastraDBMessage>>;
/** Read a value from a thread's metadata. */
getMetadata(input: {
threadId: string;
key: string;
}): Promise<unknown>;
/** Write a value into a thread's metadata. */
setMetadata(input: {
threadId: string;
key: string;
value: unknown;
}): Promise<void>;
/** Delete a value from a thread's metadata. */
deleteMetadata(input: {
threadId: string;
key: string;
}): Promise<void>;
/** Whether the host has thread storage configured. When false, lifecycle persistence is a no-op. */
hasStorage(): boolean;
/** Persist a new or updated thread row. No-op when storage is unavailable. */
saveThread(input: {
thread: AgentControllerThread;
}): Promise<void>;
/**
* Delete a thread by id from controller storage and, when memory is resolved
* per caller, from that caller's memory too. No-op when storage is unavailable.
*/
deleteThread(input: {
threadId: string;
requestContext?: RequestContext;
}): Promise<void>;
/** Clone a thread (and its messages) via the host's memory, returning the new thread. */
cloneThread(input: {
sourceThreadId: string;
resourceId: string;
title?: string;
metadata?: Record<string, unknown>;
/** The caller's context, so a dynamic memory resolves for the caller's user. */
requestContext?: RequestContext;
}): Promise<AgentControllerThread>;
/** Acquire the host thread lock for a thread id. No-op when no lock is configured. */
acquireLock(threadId: string): Promise<void>;
/** Release the host thread lock for a thread id. No-op when no lock is configured. */
releaseLock(threadId: string): Promise<void>;
/** The host's configured mode ids, used to validate a thread's persisted mode on restore. */
getModeIds(): string[];
}
/** Options every controller execution carries, including its usage recorder. */
export type SharedRunOptions = Record<string, unknown> & {
onStepFinish?: (step: {
usage?: unknown;
}) => Promise<void>;
};
/**
* The AgentController-owned machinery a Session leverages to drive an agent run. In the
* multi-user host one AgentController serves many sessions; the run loop, run state, and
* thread stream are per-session (they cannot be shared) and so belong on the
* Session. But *how* a run is produced — which agent answers, the config-backed
* run/stream options, the toolset, the request context, the tool-approval
* policy, usage persistence, id generation — is shared infrastructure the
* AgentController owns. The AgentController injects this machinery into each Session it
* constructs (via {@link Session.setMachinery}); the Session calls into it but
* never reaches back into the AgentController or another session.
*
* This is the formalized DI boundary: the Session receives exactly the
* capabilities it is allowed to use, nothing more.
*/
export interface SessionMachinery {
/** Resolve the agent that should answer for the session's current mode/model. */
getAgent(): Agent;
getAgents?(): Iterable<Agent>;
/** Get the ephemeral state associated with an active or suspended run. */
getRunScope(runId: string): RunScope | undefined;
/**
* Release a suspended run that was aborted instead of resumed: drop its
* run-scoped workflow registration and delete its snapshot rows, so it is no
* longer listed as suspended.
*/
releaseSuspendedRun(runId: string): Promise<void>;
/** Open a fresh subscription to a thread's agent event stream. */
subscribeToThread(input: {
agent?: Agent;
resourceId: string;
threadId: string;
requestContext?: RequestContext;
}): Promise<AgentThreadSubscription<any, true>>;
/** Build the per-call stream options (instructions, memory, toolsets, abort signal, tracing). */
buildStreamOptions(input: {
requestContext?: RequestContext;
tracingContext?: TracingContext;
tracingOptions?: TracingOptions;
untilIdle?: boolean | {
maxIdleMs?: number;
};
/** Queue preparation owns this signal instead of mutating the active Session run. */
abortSignal?: AbortSignal;
/**
* Thread the run should read and write, when it is not the session's current
* one — a claimed thread being woken by a peer, for instance. Memory and
* request-context thread bindings follow this value.
*/
threadId?: string;
}): Promise<Record<string, unknown>>;
/** The run budget every initial stream and resume must carry (maxSteps, provider fallbacks, …). */
buildSharedRunOptions(requestContext?: RequestContext): SharedRunOptions;
/**
* The `activeTools` allowlist of `modeId` (the session's current mode when
* omitted or unknown), or `undefined` when the mode does not restrict tools.
* Resumes pass the suspended run's mode so the continuation sees the same
* tools as the initial stream, and the run's request context so tools denied
* on the run's own thread are filtered out.
*/
resolveModeActiveTools(modeId?: string, requestContext?: RequestContext): string[] | undefined;
onSessionDeleted?(listener: () => void): () => void;
/** Resolve the toolset (built-in controller tools + user/subagent tools) for a run. */
buildToolsets(requestContext: RequestContext): Promise<ToolsetsInput>;
/** Resolve the effective request context for a run, layering controller defaults. */
buildRequestContext(requestContext?: RequestContext, scope?: {
abortSignal?: AbortSignal;
resourceId?: string;
threadId?: string;
threadOwnerId?: string;
modeId?: string;
runId?: string;
execution?: boolean;
}): Promise<RequestContext>;
/** Authorize an actor-driven operation before it changes session state. */
authorizeExecute?(requestContext?: RequestContext): Promise<void>;
/** Generate a new id (thread ids, message ids) using the host's id strategy. */
generateId(): string;
/**
* Resolve the mode the session transitions to when a plan is approved: the
* supplied mode's `transitionsTo`, else the host's default mode. Returns
* `undefined` when the host has no default mode. The mode catalog is AgentController
* config, so this is genuinely host-owned.
*/
resolveTransitionModeId(modeId: string): string | undefined;
/**
* Persist a system-reminder message to a thread, returning the saved message
* (or `null` when no storage is configured). Pure host-owned persistence
* (storage handle + id strategy).
*/
saveSystemReminder(input: {
threadId: string;
resourceId: string;
message: string;
reminderType: string;
role: 'user' | 'assistant' | 'system';
metadata?: Record<string, unknown>;
}): Promise<MastraDBMessage | null>;
}
export declare class SessionThread {
#private;
constructor(getResourceId: () => string);
/**
* Attach the shared-host storage gateway the thread domain reads/writes
* through and the owning session whose subsystems lifecycle transitions
* orchestrate. The AgentController calls this once during wiring; without a store the
* data methods degrade gracefully.
*/
connect(store: ThreadDataStore | undefined, session: Session): void;
/** The active thread id, or null when the session is not bound to a thread. */
getId(): string | null;
/** Whether the session is currently bound to a thread. */
isSet(): boolean;
/** The active thread id, throwing when the session is not bound to a thread. */
requireId(): string;
/**
* The active thread id, creating and binding a new thread when the session
* is unbound. Concurrent callers share one creation.
*/
ensureId({ requestContext }?: {
requestContext?: RequestContext;
}): Promise<string>;
/**
* Bind the session directly to a thread and reset its live projection.
*
* Prefer {@link create}, {@link clone}, or {@link switch}; direct binding is
* rejected while a serialized lifecycle transition is pending.
*/
set({ threadId }: {
threadId: string;
}): number;
/**
* Clear the session's thread binding and reset its live projection.
*
* Prefer lifecycle methods; direct clearing is rejected while a serialized
* lifecycle transition is pending.
*/
clear(): void;
/** Serialize teardown with thread lifecycle work, then clear the binding and release its lock. */
clearAndReleaseLock(): Promise<void>;
/** Serialize a resource transition with thread lifecycle work. */
setResourceId({ resourceId }: {
resourceId: string;
}): Promise<void>;
/** List this session's threads (its own resource by default, or all resources). */
list(options?: {
allResources?: boolean;
includeForkedSubagents?: boolean;
metadata?: Record<string, unknown>;
}): Promise<AgentControllerThread[]>;
/** Fetch a single thread by id, or null when it doesn't exist / no storage. */
getById({ threadId }: {
threadId: string;
}): Promise<AgentControllerThread | null>;
/** Clone a detected cross-resource project thread into this session's resource. */
cloneToCurrentResource(options: {
threadId: string;
expectedResourceId: string;
expectedProjectPath: string;
requestContext?: RequestContext;
}): Promise<AgentControllerThread>;
/** List messages for a thread (newest-`limit`, returned oldest-first), or all. */
listMessages({ threadId, limit }: {
threadId: string;
limit?: number;
}): Promise<MastraDBMessage[]>;
/** List messages for the session's active thread (empty when not bound). */
listActiveMessages({ limit }?: {
limit?: number;
}): Promise<MastraDBMessage[]>;
/** The first user message for a single thread, or null. */
firstUserMessage({ threadId }: {
threadId: string;
}): Promise<MastraDBMessage | null>;
/** The first user message for each given thread id. */
firstUserMessages({ threadIds }: {
threadIds: string[];
}): Promise<Map<string, MastraDBMessage>>;
/** Read a setting (metadata value) for the active thread. */
getSetting({ key }: {
key: string;
}): Promise<unknown>;
/** Read a setting from a specific thread, regardless of the current binding. */
getSettingOn({ threadId, key }: {
threadId: string;
key: string;
}): Promise<unknown>;
/** Persist a setting (metadata value) for the active thread. */
setSetting({ key, value }: {
key: string;
value: unknown;
}): Promise<void>;
/** Persist a setting to a specific thread, regardless of the current binding. */
setSettingOn({ threadId, key, value }: {
threadId: string;
key: string;
value: unknown;
}): Promise<void>;
/** Delete a setting (metadata value) for the active thread. */
deleteSetting({ key }: {
key: string;
}): Promise<void>;
/**
* Read a thread's durable owner. Owner-less legacy threads lazily inherit this
* session host's identity without writing a backfill.
*/
getOwner({ threadId }?: {
threadId?: string | null;
}): Promise<string | undefined>;
/**
* Transfer a thread to a new owner. Defaults to the active thread; pass
* `threadId` to transfer another thread of this resource without switching to it.
*
* Transfers are serialized within this process. Hosts needing strict durable
* compare-and-set semantics should commit that change in their own store before
* mirroring it here.
*/
transferOwnership({ toOwnerId, threadId: requestedThreadId, }: {
toOwnerId: string;
threadId?: string;
}): Promise<void>;
/** Tear down the current agent subscription and reset the run tracker. */
cleanupSubscription(): void;
/**
* Ensure the session is subscribed to the given agent/thread stream, opening a
* fresh subscription (and driving its run loop) when the binding changed.
*/
ensureSubscription(threadId: string, agent?: Agent<string, import("../agent").ToolsInput, undefined, any, import("../agent").AgentEditorConfig | undefined>, requestContext?: RequestContext, resourceId?: string, shouldAttach?: () => boolean): Promise<void>;
/** Ensure a subscription for the session's active thread (no-op when unbound). */
ensureCurrentSubscription(requestContext?: RequestContext): Promise<void>;
/**
* Detach this host from the current thread without changing durable run state.
* Pending suspension and approval prompts are removed from the host projection
* and can be rebuilt when a session binds the thread again. A parked tool
* approval is not declined: its run stays suspended and can still be answered,
* for example with `respondToPersistedToolApproval`.
*/
detachFromCurrent(): void;
/** Create a new thread, bind the session to it, and rebind the agent stream. */
create(options?: {
title?: string;
id?: string;
requestContext?: RequestContext;
}): Promise<AgentControllerThread>;
/**
* Rename the session's active thread. No-op when unbound or storageless.
*
* Renames pin the title by default (`metadata.titlePinned`) so Observational
* Memory's title extractor cannot overwrite a user's manual rename. Pass
* `pin: false` for programmatic title writes that should keep auto-naming.
*/
rename({ title, pin }: {
title: string;
pin?: boolean;
}): Promise<void>;
/** Clone a thread (and its messages), bind the session to the clone, and rebind the stream. */
clone(options?: {
sourceThreadId?: string;
title?: string;
resourceId?: string;
requestContext?: RequestContext;
}): Promise<AgentControllerThread>;
/** Switch the session to an existing thread, hydrating its persisted settings and rebinding the stream. */
switch(options: {
threadId: string;
emitEvent?: boolean;
requestContext?: RequestContext;
}): Promise<void>;
/** Delete a thread; when it's the active thread, clear the binding and tear down the run. */
delete(options: {
threadId: string;
requestContext?: RequestContext;
}): Promise<void>;
/**
* Hydrate the session's per-thread settings from the active thread's metadata:
* token usage, the persisted mode (restored first), the selected model, and
* observer/reflector model ids + thresholds. Best-effort: on any failure the
* token tally is reset and the rest is left at defaults.
*/
loadMetadata({ preserveTokenUsageOnFailure, }?: {
preserveTokenUsageOnFailure?: boolean;
}): Promise<void>;
}
/**
* Owns the session's live subscription to the active thread's agent event
* stream. A subscription is created per `(agent, resource, thread)` and reused
* while that triple is unchanged (tracked by {@link key}); switching threads or
* agents tears the old one down and opens a new one.
*
* The Session owns the subscription *handle* and its dedup key plus the
* mechanical lifecycle (reuse check, teardown, identity check, run-id read).
* The AgentController still owns *how* a subscription is produced (calling the agent)
* and *how* its stream is consumed, passing the resolved handle in via
* {@link attach}.
*/
export declare class SessionStream {
#private;
private readonly getSessionRun;
constructor(getSessionRun: () => {
sessionId: string;
runId: string | null;
});
/**
* Track the run loop consuming `subscription`. If it rejects while no other
* subscription has replaced it, consumer-failure waiters receive the error, so
* callers awaiting a run on this stream don't wait on a loop that is gone.
*/
trackConsumer(subscription: AgentThreadSubscription<any, true>, consumer: Promise<void>): void;
/** Rejects with the live run loop's error if it fails; resolves when `signal` cancels the wait. */
waitForConsumerFailure(signal: AbortSignal): Promise<void>;
waitForTeardown(signal: AbortSignal): Promise<void>;
/** Build the dedup key identifying a subscription to `threadId` for `agent`. */
static keyFor({ agent, resourceId, threadId }: {
agent: Agent;
resourceId: string;
threadId: string;
}): string;
/** Whether the open subscription already targets `key` (so it can be reused). */
matches({ key }: {
key: string;
}): boolean;
/** Adopt `subscription` as the live one, recording its owning agent and dedup `key`. */
attach({ subscription, agent, key, resourceId, threadId, }: {
subscription: AgentThreadSubscription<any, true>;
agent?: Agent;
key: string;
resourceId: string;
threadId: string;
}): void;
/** Record that `runId` was aborted on `subscription`, so its trailing chunks are dropped. */
markAbortedRun({ subscription, runId, }: {
subscription: AgentThreadSubscription<any, true>;
runId: string | null;
}): void;
/** The run id `subscription` is dropping chunks for, or null. */
abortedRunId({ subscription }: {
subscription: AgentThreadSubscription<any, true>;
}): string | null;
/**
* Stop dropping chunks for the aborted run (only if it is `runId`, when given).
* Returns a callback that restores the filter while the same subscription is
* still live and no other run has replaced it, or undefined if nothing was cleared.
*/
clearAbortedRun({ runId }?: {
runId?: string;
}): (() => void) | undefined;
/** Agent that owns `subscription`, when it is the live subscription. */
getAgent({ subscription }: {
subscription: AgentThreadSubscription<any, true>;
}): Agent | null;
/** Durable binding owned by `subscription`, when it is the live subscription. */
getBinding({ subscription }: {
subscription: AgentThreadSubscription<any, true>;
}): {
resourceId: string;
threadId: string;
} | null;
/** Whether a subscription is currently open. */
isOpen(): boolean;
/** Whether `subscription` is the one currently adopted (identity check). */
isCurrent({ subscription }: {
subscription: AgentThreadSubscription<any, true>;
}): boolean;
/** The run id the live subscription reports as active, or null when none/idle. */
activeRunId(): string | null;
/** Whether the live subscription currently has a run in flight. */
isActive(): boolean;
/**
* Abort the live subscription's in-flight run, if any. Swallows errors.
* `localOnly` keeps an abort caused by a thread lifecycle transition (detach,
* switch) from asking a remote thread owner to stop its run.
*/
abort(options?: {
localOnly?: boolean;
}): void;
/** Detach the live subscription without aborting (e.g. on stream error). */
detach(): void;
/** Tear down this binding, cancelling only an execution initiated by this session. */
cleanup(): void;
}
/** Immutable identity of a tool call parked awaiting a resume. */
export interface SuspensionAddress {
/** The thread the suspended invocation was persisted under. */
threadId: string;
/** The memory resource the suspended invocation was persisted under. */
resourceId: string;
/** The run id to resume when this tool call is answered. */
runId: string;
/** The suspended tool call id. */
toolCallId: string;
}
/** A tool call parked awaiting a resume, keyed in {@link SessionSuspensions}. */
export interface PendingSuspension extends SuspensionAddress {
/** The suspended tool's name (e.g. `ask_user`, `submit_plan`). */
toolName: string;
}
export declare function getSuspensionAddressKey({ resourceId, threadId, runId, toolCallId }: SuspensionAddress): string;
/**
* Owns the session's parked tool suspensions: tool calls paused via the native
* tool-suspension primitive (e.g. `ask_user` / `request_access` / `submit_plan`)
* that are awaiting a resume, keyed by `(threadId, runId, toolCallId)`. Each entry
* records the run id to resume and the tool name. A Map lets several
* tools — e.g. parallel `ask_user` calls in one step — stay suspended and be
* resumed independently.
*
* This is the resume *data* the AgentController reads to drive a resume. The richer
* per-suspension UI snapshot lives on the AgentController display state; the Session
* owns only what's needed to resume.
*/
export declare class SessionSuspensions {
#private;
constructor(getActiveBinding?: () => {
resourceId: string;
threadId: string | null;
});
/**
* Park `toolCallId` as awaiting a resume on `runId` for `toolName`, recording
* the thread/resource the suspended invocation was persisted under. When the
* same tool call is replayed for the same run (e.g. a resumed stream re-emits
* the suspension), the original thread/resource binding is preserved so later
* settlement still targets where the invocation was first persisted.
*/
register({ toolCallId, runId, toolName, threadId, resourceId, }: {
toolCallId: string;
runId: string;
toolName: string;
threadId: string;
resourceId: string;
}): void;
/** Resolve one active-thread suspension, rejecting ambiguous partial addresses. */
resolve({ toolCallId, runId }?: {
toolCallId?: string;
runId?: string;
}): PendingSuspension | undefined;
/** Read a suspension by exact address, or by an unambiguous active-thread selector. */
get(address: SuspensionAddress | {
toolCallId: string;
runId?: string;
}): PendingSuspension | undefined;
/** Whether an exact or unambiguous suspension is currently parked. */
has(address: SuspensionAddress | {
toolCallId: string;
runId?: string;
}): boolean;
/** Drop exactly one parked suspension; ambiguous partial addresses are ignored. */
delete(address: SuspensionAddress | {
toolCallId: string;
runId?: string;
}): void;
/**
* Drop every suspension parked on `runId`, returning the dropped toolCallIds.
* Used when a run reaches a terminal failure after emitting `tool_suspended`
* (e.g. persisting the suspended snapshot failed): those suspensions can never
* be resumed, so keeping them parked would leave the user with prompts whose
* answers fail with a misleading "could not find a suspended run" error.
* Suspensions parked on other runs are left intact.
*/
deleteForRun({ resourceId, threadId, runId, }: {
resourceId: string;
threadId: string;
runId: string;
}): PendingSuspension[];
/** Discard the in-memory suspension mirror for a deleted thread. */
deleteForThread({ threadId }: {
threadId: string;
}): void;
/**
* Drop every suspension parked on the active thread, returning the dropped
* entries with their original thread/resource binding. Suspensions for other
* threads remain available when the host switches back.
*/
clear(): Array<{
toolCallId: string;
} & PendingSuspension>;
/** Whether the active thread has tool calls parked awaiting a resume. */
hasPending(): boolean;
/**
* Resolve which active-thread suspension to act on. A partial address only
* succeeds when it identifies exactly one parked suspension.
*/
resolveAddress({ toolCallId, runId }?: {
toolCallId?: string;
runId?: string;
}): SuspensionAddress | undefined;
/** @deprecated Use {@link resolveAddress} to retain the complete suspension identity. */
resolveToolCallId(toolCallId?: string): string | undefined;
}
/** A message queued to send once the active run finishes, held in {@link SessionFollowUps}. */
export interface FollowUp {
/** The message text to send. */
content: string;
/** Optional request context to apply when the queued message is sent. */
requestContext?: RequestContext;
}
/**
* Owns the session's follow-up queue: messages a user submits while a run is in
* progress, held FIFO until the active run finishes and the queue is drained.
*
* This owns the queue *data* (enqueue/dequeue/requeue/clear/count). The AgentController
* still drives draining — sending each message and emitting `follow_up_queued`
* as the count changes — and keeps the display-state mirror (`queuedFollowUps`).
*/
export declare class SessionFollowUps {
#private;
/** Number of messages currently queued. */
count(): number;
/** Whether the queue is empty. */
isEmpty(): boolean;
/** Append a follow-up to the back of the queue. */
enqueue(followUp: FollowUp): void;
/** Remove and return the next follow-up, or undefined when empty. */
dequeue(): FollowUp | undefined;
/** Put a follow-up back at the front (e.g. when draining it failed). */
requeue(followUp: FollowUp): void;
/** Drop all queued follow-ups (e.g. on steer or thread switch). */
clear(): void;
}
/** The decision a user returns to resolve a parked tool-approval gate. */
export interface ApprovalDecision {
/** Whether to run the gated tool or reject it. */
decision: 'approve' | 'decline';
/** Optional request context to apply when the gated tool resumes. */
requestContext?: RequestContext;
/** Optional context explaining why a tool approval was declined. */
declineContext?: {
reason?: string;
message?: string;
};
}
/**
* How a parked approval gate was released: a user (or abort) decision, or
* `detached` when the host let go of the thread without deciding, leaving the
* run parked in storage.
*/
type ApprovalGateResolution = ApprovalDecision | {
decision: 'detached';
};
/**
* Whether a tool approval/suspension response was claimed by a pending target.
* `accepted: true` only means the command was taken, not that the resumed tool
* later succeeded.
*/
export type SessionCommandResult = {
accepted: true;
} | {
accepted: false;
reason: 'not_pending' | 'stale_tool_call' | 'aborting' | 'no_pending_suspension';
};
/**
* A user's response to a parked approval. `always_allow_category` approves the
* tool and additionally grants its category for the rest of the session.
*/
export interface ApprovalResponse {
decision: 'approve' | 'decline' | 'always_allow_category';
requestContext?: RequestContext;
declineContext?: {
reason?: string;
message?: string;
};
}
/**
* Narrows which parked gate(s) an operation applies to. A field the filter
* *names* is a constraint, so `{ threadId: undefined }` selects the gates the
* producer left untagged rather than every gate — a caller with no thread
* binding must not release a detached thread's gate. Omitted fields constrain
* nothing.
*/
interface ApprovalGateFilter {
toolCallId?: string;
threadId?: string;
runId?: string;
}
/**
* Owns the session's interactive tool-approval gates: when a tool requires user
* approval, the run parks on a promise here until the UI responds approve or
* decline.
*
* Gates retain the tool call and thread/run that opened them. Bare call-ID
* responses are rejected when more than one owner has that ID. More than one gate can be parked at once — a background/sub-agent run on a
* detached thread arms its own gate while the foreground run arms another — so
* arming never overwrites or strands an existing gate, and a response can only
* release the gate it names. Thread-scoped callers (abort, a user-message
* interjection) release only their own thread's gate, so one thread can never
* mutate another thread's approval authority.
*
* The Session owns the gate mechanics (arm / respond / cancel); the
* AgentController still maps a decision to its effects (running vs declining the
* tool, and any "always allow" grant), since those touch config-derived tool
* categories.
*/
export declare class SessionApproval {
#private;
/**
* Park an approval for `toolCallId` and return a promise that resolves once
* {@link respond} or {@link cancel} releases it. The caller awaits this while
* the run is suspended on the gate. Re-arming the same call returns the
* already-parked promise rather than replacing its resolver, so a duplicate
* arm can never strand the first waiter.
*/
arm({ toolName, toolCallId, threadId, runId, }: {
toolName: string;
toolCallId: string;
threadId?: string;
runId?: string;
}): Promise<ApprovalGateResolution>;
/**
* Whether a gate is parked. With no filter this is true when *any* gate is
* parked; with a filter it is true only when a gate matches every supplied
* field, so callers can ask "is my thread/run parked?" without seeing another
* thread's gate.
*/
isArmed(filter?: ApprovalGateFilter): boolean;
/** The parked gates' tool and owner, without their resolvers. */
list(): Array<{
toolCallId: string;
toolName: string;
threadId?: string;
runId?: string;
}>;
/** Ids of the parked gates that match `filter` (or every gate when omitted). */
getToolCallIds(filter?: ApprovalGateFilter): string[];
/**
* Apply a user's {@link ApprovalResponse} to the gate named by `toolCallId`.
* A no-op for an id that is not parked, so a missing *or* stale id can never
* resolve a different pending gate. `always_allow_category` runs
* `onAlwaysAllow` with the gated tool name and the gate's thread (so the
* caller can grant the tool's category to the thread that owns the gate — a
* lookup that needs AgentController config) and then approves;
* `approve`/`decline` resolve as-is.
*/
respond({ decision, toolCallId, threadId, runId, requestContext, declineContext, onAlwaysAllow, }: ApprovalResponse & {
toolCallId: string;
/** Narrow to one owner when the same call id is parked on several threads or runs. */
threadId?: string;
runId?: string;
onAlwaysAllow?: (toolName: string, threadId?: string) => void;
}): SessionCommandResult;
/**
* Release parked gate(s) without a user decision — on abort, or when a user
* message interrupts a run. Each is resolved as a `decline` so the gated tool
* is rejected (not run) and the run can finalize. `filter` narrows the release
* to a specific call, thread, or run (so aborting one thread cannot decline
* another's gate): naming `threadId`/`runId` with an undefined value — a
* caller with no thread binding — releases only the untagged gates rather than
* every gate. With no filter every gate is released. Returns the ids that were
* released.
*/
cancel(options?: ApprovalGateFilter & {
declineContext?: {
reason?: string;
message?: string;
};
requestContext?: RequestContext;
}): string[];
/**
* Release parked gate(s) without a decision, for a host detaching from the
* thread. Each waiter resolves as `detached`, so the gated call is neither
* run nor declined: the run stays parked in storage and can be answered after
* a session binds the thread again. `filter` narrows the release exactly as
* for {@link cancel}. Returns the ids that were released.
*/
detach(filter?: ApprovalGateFilter): string[];
}
/**
* Owns the session's transient run identity and abort control: the id of the
* run currently streaming on the active thread, its trace id, a monotonic
* operation counter bumped each time a new operation starts, and the
* AbortController/abort-requested flag governing cancellation. All of this is
* per-run scratch state — it is never persisted and resets between runs.
*
* The live agent subscription itself lives on {@link SessionStream}
* (`session.stream`); this holds the last run id observed on a chunk so callers
* have a stable value once the subscription has settled.
*/
export declare class SessionRun {
#private;
waitForTeardown(signal: AbortSignal): Promise<void>;
/** Generation of the latest abort request; pass to {@link waitForAbortRequest} as `after`. */
getAbortGeneration(): number;
/**
* Resolves once an abort is requested for the current run (immediately if
* one already was), or when `signal` cancels the wait. With `after`, only an
* abort requested after that generation counts.
*/
waitForAbortRequest(signal: AbortSignal, { after }?: {
after?: number;
}): Promise<void>;
/** The current run id (null when idle). */
getRunId(): string | null;
/** Set the current run id. */
setRunId({ runId }: {
runId: string | null;
}): void;
/** The current trace id (null when unset). */
getTraceId(): string | null;
/** Set the current trace id. */
setTraceId({ traceId }: {
traceId: string | null;
}): void;
/**
* Clear all run state (run id, trace id, abort controller + requested flag)
* when a run ends or is reset. Does not touch the operation counter.
*/
reset(): void;
/**
* Generation of the session's thread binding. Bumped whenever the binding is
* torn down (detach, switch, `/new`, ...), so async work started for one run
* can tell that the session has since moved on to another.
*/
bindingGeneration(): number;
/** Mark the current binding as superseded; see {@link bindingGeneration}. */
supersedeBinding(): void;
/** Bump and return the operation counter at the start of a new operation. */
nextOperation(): number;
/**
* Lazily create (if needed) and return the AbortController for the current
* run. Callers pass its `.signal` into the underlying stream.
*/
ensureAbortController(): AbortController;
/**
* How many times the run has been armed via {@link ensureAbortController}.
* Lets a caller tell whether anyone else joined the run it armed.
*/
armCount(): number;
/** Signal for the current run's AbortController, or undefined when none is armed. */
getAbortSignal(): AbortSignal | undefined;
/**
* Whether a run is currently in progress. A run is armed with an
* AbortController for its duration, so the presence of one is what "running"
* means; this is the semantic accessor callers should use.
*/
isRunning(): boolean;
/**
* Whether an AbortController is currently armed. Equivalent to
* {@link isRunning} today; kept for callers that assert on the controller's
* lifecycle specifically (e.g. that it was cleared after an abort).
*/
hasAbortController(): boolean;
/** Clear the abort-requested flag at the start of a fresh run. */
clearAbortRequested(): void;
/** Whether an abort has been requested for the current run. */
isAbortRequested(): boolean;
/**
* Request an abort: mark the run as aborting and fire the AbortController (if
* armed), then drop the controller. Leaves the requested flag set so the
* run-end path can resolve its reason as 'aborted'; {@link reset} clears it.
*
* `deferSignal` marks the run as aborting without firing the controller. Used
* when the abort interrupts a parked tool-approval gate: the gated call still
* has to be declined through the (still live) agent run so the denial is
* persisted, and firing the signal first would tear that run down underneath
* the decline. The engine fires the signal itself once the decline lands.
*/
requestAbort({ deferSignal }?: {
deferSignal?: boolean;
}): void;
}
/**
* Owns the session's currently-selected model. Source of truth for which model
* is active and responsible for persisting that one selection per thread.
*/
type ThinkingLevelSwitch = (level: unknown, commit: (() => Promise<void>) | undefined, isActive: () => boolean, applyModel: () => void) => Promise<boolean>;
export declare class SessionModel {
#private;
constructor(store: () => ThreadSettingsStore | undefined, bus: SessionBus, setThinkingLevel: ThinkingLevelSwitch, getThinkingLevel: () => AgentControllerThinkingLevel | undefined);
/** Attach mode accessors and the optional model-use tracker. */
setResolver(options: {
getCurrentModeId: () => string;
getModeIds: () => string[];
trackModelUse?: ModelUseCountTracker;
}): void;
/** The currently-selected model id ('' when none selected yet). */
get(): string;
/** Whether a model is currently selected. */
hasSelection(): boolean;
/**
* A short display name for the selected model: the last segment of the model
* id (e.g. `__GATEWAY_ANTHROPIC_MODEL_SONNET__` -> `claude-sonnet-4-6`). Returns
* `'unknown'` when no model is selected.
*/
displayName(): string;
/** Set the in-memory selected model id (no persistence). */
set({ modelId }: {
modelId: string;
}): void;
/** @internal Record the host-configured model used when resetting or creating threads. */
setDefault({ modelId }: {
modelId: string;
}): void;
/** Restore the host-configured model before hydrating another thread. */
reset(): void;
/** @internal The host-configured model used to seed a new thread. */
getDefault(): string;
/**
* Re-sync the in-memory model and thinking level from the persisted thread.
*
* Unmarked legacy metadata is migrated before the selection is applied. Only
* emits `model_changed` when either value changes the in-memory selection.
*/
syncFromPersisted(): Promise<void>;
/**
* Switch to a different model at runtime.
*
* Persists the selection for the thread, reports it to the model-use tracker,
* and emits `model_changed` with the current thinking level. When
* `thinkingLevel` is provided it is applied and persisted with the model
* (through the session-state preference, which also survives restarts).
* Rejects if a thread change cancels the switch before any selection is committed.
*/
switch(modelId: string, { thinkingLevel }?: {
thinkingLevel?: AgentControllerThinkingLevel;
}): Promise<void>;
}
/**
* Owns the session's currently-selected mode and the logic for switching modes.
* The AgentController still owns the mode *definitions* (`config.modes`); this
* owns "which mode is active" and persists that selection without changing the
* session's model.
*/
export declare class SessionMode {
#private;
constructor(store: () => ThreadSettingsStore | undefined, bus: SessionBus);
/**
* Attach the resolver that maps a mode id to its definition. The AgentController owns
* the mode catalog (`config.modes`) and injects this once.
*/
setResolver(resolve: (modeId: string) => AgentControllerMode | null): void;
/** The currently-selected mode id. */
get(): string;
/**
* Resolve the currently-selected mode id to its full definition against the
* host's mode catalog. Throws if the selected mode id isn't in the catalog.
*/
resolve(): AgentControllerMode;
/** Set the currently-selected mode id (on default resolution or hydration). */
set({ modeId }: {
modeId: string;
}): void;
/** @internal Record the host-configured mode used when resetting or creating threads. */
setDefault({ modeId }: {
modeId: string;
}): void;
/** Restore the host-configured mode before hydrating another thread. */
reset(): void;
/** @internal The host-configured mode id used to seed a new thread. */
getDefault(): string;
/** @internal Resolve a mode without changing the live selection. */
resolveId(modeId: string): AgentControllerMode;
/** Switch to a different mode without changing the session's selected model. */
switch({ modeId }: {
modeId: string;
}): Promise<void>;
}
/** Per-role wiring + state/config keys a {@link SessionOMRole} reads and writes. */
interface SessionOMRoleConfig {
/** The event `role` and `om_model_changed` discriminator for this role. */
role: 'observer' | 'reflector';
/** Session-state / thread-settings key holding this role's model id. */
modelIdKey: 'observerModelId' | 'reflectorModelId';
/** Session-state / thread-settings key holding this role's selection intent. */
selectionKey: 'observerModelSelection' | 'reflectorModelSelection';
/** Session-state key holding this role's threshold. */
thresholdKey: 'observationThreshold' | 'reflectionThreshold';
/** Resolve this role's default model id from `omConfig`. */
defaultModelId: (omConfig: AgentControllerOMConfig | undefined) => string | undefined;
/** Resolve this role's default threshold from `omConfig`. */
defaultThreshold: (omConfig: AgentControllerOMConfig | undefined) => number | undefined;
}
/**
* One observational-memory role (observer or reflector): its model id, resolved
* model instance, threshold, and model switch. Reads return the session-state
* value when set, falling back to the AgentController's `omConfig` defaults. The shared
* wiring is injected by {@link SessionOM.setResolver}.
*/
declare class SessionOMRole {
#private;
constructor(config: SessionOMRoleConfig, bus: SessionBus);
/** @internal Injected by {@link SessionOM.setResolver}. */
setWiring(wiring: {
getState: () => Record<string, unknown>;
getCurrentModelId: () => string | undefined;
setState: (updates: Record<string, unknown>, event?: AgentControllerEvent) => Promise<void>;
omConfig?: AgentControllerOMConfig;
gateways?: MastraModelGatewayInterface[];
}): void;
/** This role's configured model. `auto` follows the active main model. */
model(): OMModel | undefined;
/** This role's effective concrete model id. */
modelId(): string | undefined;
/** This role's threshold from session state, falling back to `omConfig`. */
threshold(): number | undefined;
/**
* Resolve this role's effective model id to a model instance via the
* configured gateways, or undefined when unset.
*/
resolvedModel(): MastraModelConfig | undefined;
/** Switch this role's model, persist it, and emit the effective concrete model. */
switchModel({ modelId }: {
modelId: OMModel;
}): Promise<void>;
}
/**
* Owns the session's observational-memory model selection, grouped by role:
* {@link SessionOM.observer} and {@link SessionOM.reflector}. The AgentController owns
* `omConfig` and the model resolver, so it injects them — plus the session-state
* read/write and thread-settings persistence — once via {@link setResolver},
* which fans the wiring out to both roles.
*/
declare class SessionOM {
readonly observer: SessionOMRole;
readonly reflector: SessionOMRole;
constructor(bus: SessionBus);
/**
* Attach the session-state read/write, thread-settings persistence, and the
* AgentController-owned `omConfig` defaults plus model resolver. The AgentController injects
* these once; the wiring is shared by both roles.
*/
setResolver(options: {
getState: () => Record<string, unknown>;
getCurrentModelId: () => string | undefined;
setState: (updates: Record<string, unknown>, event?: AgentControllerEvent) => Promise<void>;
omConfig?: AgentControllerOMConfig;
gateways?: MastraModelGatewayInterface[];
}): void;
}
/** The permission rules held in a session state snapshot, or empty rules when none are set. */
export declare function readPermissionRules(state: Readonly<Record<string, unknown>> | undefined): PermissionRules;
/**
* Owns the session's tool-permission rules: the per-category and per-tool
* approval policies persisted in session state under `permissionRules`. The
* AgentController injects the session-state read/write once via {@link setResolver}.
*
* These are the persisted rules consulted during tool-approval resolution; they
* are distinct from the in-memory "allow for this session" grants on the
* Session.
*/
declare class SessionPermissions {
#private;
/** Attach the session-state read/write. The AgentController injects these once. */
setResolver(options: {
getState: () => Record<string, unknown>;
setState: (updates: Record<string, unknown>) => Promise<void>;
/** Runs after a rule change is persisted, so parked approvals follow the new policy. */
onChange?: () => Promise<void>;
}): void;
/** The current permission rules, or empty rules when none are set. */
getRules(): PermissionRules;
/** Set the approval policy for a tool category. Resolves once persisted. */
setForCategory({ category, policy }: {
category: ToolCategory;
policy: PermissionPolicy;
}): Promise<void>;
/** Set the approval policy for an individual tool. Resolves once persisted. */
setForTool({ toolName, policy }: {
toolName: string;
policy: PermissionPolicy;
}): Promise<void>;
}
/**
* The subagent model selection. Reads prefer the per-`agentType` value and fall
* back to the global subagent model; writes persist to thread settings and emit
* a `subagent_model_changed` event. Wiring is injected by
* {@link SessionSubagents.setResolver}.
*/
declare class SessionSubagentModel {
#private;
constructor(bus: SessionBus);
/** @internal Injected by {@link SessionSubagents.setResolver}. */
setWiring(wiring: {
getState: () => Record<string, unknown>;
setState: (updates: Record<string, unknown>, event: AgentControllerEvent) => Promise<void>;
}): void;
/**
* The subagent model id, preferring the `agentType`-specific value when one is
* given, then the global subagent model, or `null` when neither is set.
*/
get({ agentType }?: {
agentType?: string;
}): string | null;
/**
* Set the subagent model id (per-`agentType` when given, otherwise global).
* Persists to thread settings and emits `subagent_model_changed`.
*/
set({ modelId, agentType }: {
modelId: string;
agentType?: string;
}): Promise<void>;
}
/**
* The session's subagent configuration. Currently exposes the subagent model
* selection under {@link SessionSubagents.model}; grouped under `subagents` to
* leave room for additional subagent settings. The AgentController injects the
* session-state read/write, thread-settings persistence, and event emitter once
* via {@link setResolver}.
*/
declare class SessionSubagents {
readonly model: SessionSubagentModel;
constructor(bus: SessionBus);
/**
* Attach the session-state read/write and thread-settings persistence. The
* AgentController injects these once.
*/
setResolver(options: {
getState: () => Record<string, unknown>;
setState: (updates: Record<string, unknown>, event: AgentControllerEvent) => Promise<void>;
}): void;
}
type SessionStateUpdater<TState, TResult> = AgentControllerRequestStateUpdater<TState, TResult>;
interface SessionStateOptions<TState> {
initialState?: Partial<TState>;
stateSchema?: PublicSchema<TState, any>;
}
/**
* Owns the live AgentController state for a single Session.
*
* Reads return shallow snapshots, writes are serialized through a promise queue,
* and validated updates emit the same `state_changed` event the AgentController used to
* emit when it owned state directly.
*/
type PersistSettingFn = (args: {
key: string;
value: unknown;
}) => Promise<void>;
/** @internal State implementation shared with controller execution-context wiring. */
export type { SessionState };
declare class SessionState<TState = unknown> {
#private;
private readonly getSelection;
constructor({ initialState, stateSchema }: SessionStateOptions<TState>, bus: SessionBus, capturePersistSetting?: () => PersistSettingFn | undefined, getBinding?: () => {
resourceId: string;
threadId: string | null;
}, getSelection?: () => {
modeId: string;
modelId: string;
});
get(): Readonly<TState>;
captureSelection(): void;
/** Internal source handle. Run-held handles follow runScope reachability; temporary owners may release explicitly. */
retain(input?: {
resourceId: string;
threadId: string;
preferences: Record<string, unknown>;
selection: {
modeId: string;
modelId: string;
};
persistSetting: PersistSettingFn;
}, retain?: boolean): {
resourceId: string;
threadId: string | null;
isActive: () => boolean;
selection: () => {
modeId: string;
modelId: string;
};
setSelection: (selection: {
modeId: string;
modelId: string;
}) => void;
emit: (event: AgentControllerEvent) => void;
get: () => Readonly<TState>;
set: (updates: Partial<TState>) => Promise<void>;
update: <TResult>(updater: SessionStateUpdater<TState, TResult>) => Promise<TResult>;
release: () => void;
};
private getSchemaDefaults;
private apply;
rebind(keys: readonly string[]): void;
/** Hydration must not overwrite successful writes held by a warm source view. */
hydrate(updates: Partial<TState>, shouldApply: () => boolean): Promise<boolean>;
set(updates: Partial<TState>): Promise<void>;
/** Validate a model preference before applying its model and optionally committing metadata. */
setWithCommit(updates: Partial<TState>, commit: (() => Promise<void>) | undefined, shouldApply: () => boolean, onApply: () => void): Promise<boolean>;
/** Apply an update only while a caller-owned identity still matches. */
setIf(updates: Partial<TState>, shouldApply: () => boolean): Promise<boolean>;
update<TResult>(updater: SessionStateUpdater<TState, TResult>): Promise<TResult>;
}
/**
* A AgentController session owns the per-conversation runtime state that today lives
* flattened on the {@link AgentController} instance. This class is the seam we extract
* that state into, one concern at a time, so the AgentController can eventually own a
* `Session` rather than the state itself.
*
* Currently owns:
* - the live AgentController state (`session.state`): schema-validated snapshots and
* serialized updates that emit `state_changed`.
* - session-scoped permission grants — the "allow for this session" approvals a
* user makes when a tool or tool category is gated behind the permission check.
* - the live token-usage counter for the active thread. The Session holds the
* in-memory running tally; the AgentController remains responsible for persisting it
* to (and hydrating it from) thread metadata, because usage is thread-scoped.
* - the currently-selected mode (`session.mode`) and model (`session.model`).
* The Session is the source of truth for which mode/model is active and owns
* the mode-switch sequence and per-mode model memory. The AgentController still owns
* the mode *definitions* (`config.modes`).
* - transient run identity and abort control (`session.run`): the current run
* id, trace id, monotonic operation counter, and the AbortController/
* abort-requested flag. This is per-run scratch state and is never persisted.
* - the live agent thread subscription (`session.stream`): the open
* subscription to the active thread's event stream and its dedup key. The
* AgentController still produces the subscription (calling the agent) and consumes its
* stream; the Session owns the handle and its lifecycle.
* - the parked tool suspensions (`session.suspensions`): tool calls paused via
* the native tool-suspension primitive awaiting a resume, keyed by toolCallId.
* The Session owns the resume data; the AgentController keeps the richer per-suspension
* UI snapshot on its display state.
* - follow-up queue observation: a subscription to the Agent-owned FIFO for
* the active resource/thread. The Agent runtime schedules messages; the
* Session renders its current shared `queuedFollowUps` count. * - the interactive tool-approval gate (`session.approval`): when a tool needs
* user approval, the run parks on a promise here until the UI responds. The
* Session owns the gate; the AgentController maps the decision to its effects (run vs
* decline, any "always allow" grant), which touch config-derived categories.
*
* It also exposes a couple of accessors that compose `run` and `stream`:
* {@link getCurrentRunId} (the active run id, preferring the live subscription)
* and {@link abortRun} (abort the live run and mark it aborting).
*
* Mode/model persistence is thread-scoped, so the Session writes through a
* {@link ThreadSettingsStore} the AgentController backs with thread metadata; when no
* storage is configured the store is absent and state stays in memory.
*/
/**
* Owns the session's canonical display state — the projection a UI renders from
* instead of folding raw events itself. The Session holds the snapshot and the
* reducer ({@link apply}) that keeps it in sync with every AgentController event; the
* AgentController still owns the event bus and dispatches `display_state_changed` to
* listeners after applying.
*
* The reducer needs a few read-only host/session facts it doesn't own: the live
* token-usage tally, a subagent display-name lookup (AgentController config), and the
* active thread id (to decide whether a `thread_deleted` clears the view). Those
* are injected at construction so the reducer stays self-contained.
*/
export declare class SessionDisplayState {
#private;
private readonly deps;
constructor(deps: {
/** The session's live token-usage tally, mirrored into the view on usage/thread events. */
getTokenUsage: () => TokenUsage;
/** Resolve a subagent's display name from AgentController config, or undefined when unnamed. */
getSubagentDisplayName: (agentType: string) => string | undefined;
/** The active thread id, used to gate `thread_deleted` resets. */
getThreadId: () => string | null;
/** Clear the session's follow-up queue when thread-scoped display state resets. */
clearFollowUps: () => void;
/** The run the session is tracking, still set while its `agent_end` is applied. */
getRunId: () => string | null;
});
/**
* A read-only snapshot of the canonical display state. UIs should render from
* this instead of building state up from raw events.
*/
get(): Readonly<AgentControllerDisplayState>;
/**
* Drop the display mirror of every parked tool suspension. Used on abort,
* which abandons the run's parked suspensions; the caller dispatches
* `display_state_changed`.
*/
clearPendingSuspensions(): void;
/**
* Clear the modified-files tally without touching the rest of the snapshot.
* Used after a clone, which starts the cloned thread with a clean working set
* while the surrounding UI reset handles tasks/tools explicitly.
*/
clearModifiedFiles(): void;
/**
* Drop the display mirror of exactly one parked tool suspension once it has
* resumed, preserving a sibling that reused the same tool-call id.
*/
deletePendingSuspension(address: SuspensionAddress): void;
/**
* Restore task display state after a UI replays persisted task-tool history.
* Updates the snapshot without emitting a live `task_updated` event, since no
* task tool just ran. The caller dispatches `display_state_changed`.
*/
restoreTasks(tasks: TaskItemSnapshot[]): void;
/**
* Reset display fields scoped to a thread. Called on thread switch/creation.
* Also clears the session's follow-up queue (mirrored by `queuedFollowUps`).
*/
resetThread(): void;
/**
* Drop the pending-approval display entries for the given tool calls. Called
* when a gate is answered (approve/decline) or released (abort / interjection)
* so the UI stops rendering approvals that can no longer be resolved.
*/
clearPendingApprovals(toolCallIds: readonly string[]): void;
/**
* Apply a display-state update based on an incoming event. The centralized
* state machine that keeps {@link AgentControllerDisplayState} in sync with every
* event the AgentController emits.
*/
apply(event: AgentControllerEvent): void;
}
export declare class SessionBus {
#private;
/** Attach the display-state reducer the bus folds events into. Set once by the Session. */
setDisplayState(displayState: SessionDisplayState): void;
subscribe(listener: AgentControllerEventListener): () => void;
/** Whether anything is currently listening. Lets emitters skip snapshot work nobody reads. */
hasListeners(): boolean;
/** See {@link Session.initialStateEvents}. */
initialStateEvents(): AgentControllerEvent[];
emit(event: AgentControllerEvent): void;
}
/**
* A process-local host for `{ id, resourceId, tags, active threadId }`.
* It is not the durable conversation record: mode, model, persisted state,
* token usage, pending runs, and display projections are re-derived from the
* active thread whenever one is created or selected. Custom `TState` fields
* that are not reserved thread settings are host-level configuration.
*/
export declare class Session<TState = unknown> {
#private;
/** The session's currently-selected model (source of truth). */
readonly model: SessionModel;
/** The session's currently-selected mode. */
readonly mode: SessionMode;
/** The session's observational-memory model selection (observer/reflector). */
readonly om: SessionOM;
/** The session's persisted tool-permission rules (per-category / per-tool). */
readonly permissions: SessionPermissions;
/** The session's subagent configuration (currently the subagent model). */
readonly subagents: SessionSubagents;
/** Transient run identity (run id, trace id, operation counter) for the active run. */
readonly run: SessionRun;
/** Live subscription to the active thread's agent event stream. */
readonly stream: SessionStream;
/** Rebuildable resume mirror for suspensions on the active thread. */
readonly suspensions: SessionSuspensions;
/** The interactive tool-approval gate the current run parks on. */
readonly approval: SessionApproval;
/** The session's identity: the memory resourceId it reads/writes under. */
readonly identity: SessionIdentity;
/** The session's thread domain: current binding + reads scoped to it. */
readonly thread: SessionThread;
/** The canonical display state a UI renders, plus the reducer that maintains it. */
readonly displayState: SessionDisplayState;
/** The session-owned AgentController state domain. */
readonly state: AgentControllerRequestState<TState> & Pick<SessionState<TState>, 'setIf'>;
browser?: MastraBrowser;
constructor({ resourceId, state, id, ownerId, tags, workspace, browser, }: {
resourceId: string;
state?: SessionStateOptions<TState>;
id: string;
ownerId: string;
tags?: Record<string, string>;
workspace?: Workspace;
browser?: MastraBrowser;
});
/**
* This session's scoping tags (e.g. `{ projectPath }`), stamped onto every
* thread it creates. Returns a copy; empty when the session is unscoped.
*/
getTags(): Record<string, string>;
/** @internal Restore host defaults before hydrating another thread's selection. */
resetThreadSelection(): void;
/** @internal Reset state fields whose durable source is the active thread. */
resetThreadDerivedState(): void;
/**
* The scope this session's threads carry: what `thread.create()` stamps and
* what thread selection filters on. Both must read it here — computing it on
* each side is what let selection drift off the controller-global state while
* creation stamped the session's own.
*/
getThreadScope(): Record<string, string>;
/**
* The workspace resolved for this session, or `undefined` when the session
* runs without one. A workspace is optional: sessions that only need threads,
* state, and agent runs (chat-style usage) do not have to configure
* filesystem or sandbox access.
*
* Dynamic workspace factories are evaluated independently when each session
* is created. Use this accessor for operations that must stay bound to the
* session's workspace rather than resolving through controller-global state.
*/
getWorkspace(): Workspace | undefined;
/**
* Subscribe to this session's events. Returns an unsubscribe function.
* Listeners are scoped to this session: a session never delivers its events
* to another session's subscribers.
*/
subscribe(listener: AgentControllerEventListener): () => void;
/**
* The session's current state as events, for a subscriber that joins without
* `display_state_changed` snapshots: the message being streamed, as
* `message_start` so later `message_update` deltas apply to it, the active
* thread's latest `om_status`, and its token total as a `usage_update` with
* no step usage. Never emitted on the bus: deliver them to the joining
* subscriber only, right before {@link subscribe} in the same synchronous
* block, so no live event lands between.
*/
initialStateEvents(): AgentControllerEvent[];
/** Subscribe to work that must complete before the terminal agent event is exposed. */
onBeforeAgentEnd(listener: SessionBeforeAgentEndListener): () => void;
/** Await terminal hooks, then emit the terminal event to subscribers. */
finishAgentRun(reason: NonNullable<Extract<AgentControllerEvent, {
type: 'agent_end';
}>['reason']>, { abortReason }?: {
abortReason?: string;
}): Promise<void>;
/** Await the terminal event for a specific accepted agent run. */
private waitForAcceptedRunCompletion;
/**
* Emit an event on this session. Delegates to this session's bus, which folds
* the event into the canonical display state, dispatches to this session's
* listeners, then fans out a synthetic `display_state_changed`.
*/
emit(event: AgentControllerEvent): void;
/**
* Whether this session has any event subscribers. Emitters use this to skip
* building per-event snapshots that nothing would read.
*/
hasListeners(): boolean;
/**
* Attach the thread-settings store the Session persists mode/model through.
* The AgentController calls this once storage is available; without it, mode/model
* state lives purely in memory.
*/
setStore(store: ThreadSettingsStore | undefined): void;
/**
* Attach the tool→category resolver used when a user picks "always allow
* category". The category map is AgentController config, so the AgentController injects this
* once; without it, an "always_allow_category" decision simply approves.
*/
setCategoryResolver(resolveCategory: (toolName: string) => ToolCategory | null): void;
/**
* Attach the subagent display-name resolver the display-state reducer uses to
* label active subagents. The subagent catalog is AgentController config, so the
* AgentController injects this once; without it, subagents render without a name.
*/
setSubagentNameResolver(resolveSubagentName: (agentType: string) => string | undefined): void;
/**
* Attach the AgentController-owned run machinery this session leverages to drive agent
* runs (resolve the agent, build run/stream options + toolsets + request
* context, persist usage, generate ids). The AgentController injects this once when it
* constructs the session. The run loop, run state, and thread stream live on
* the session; this is the narrow set of shared capabilities it reaches back
* into the host for — see {@link SessionMachinery}.
*/
setMachinery(machinery: SessionMachinery): void;
/**
* The AgentController-owned run machinery injected via {@link setMachinery}, throwing
* when accessed before wiring (a run can never be driven without it).
*/
get machinery(): SessionMachinery;
/** The per-session run engine, throwing when accessed before machinery is wired. */
get runEngine(): SessionRunEngine;
/**
* Consume an agent stream response, folding chunks into this session's display
* messages and usage and driving tool approval. Delegates to the per-session
* run engine. Production runs go through `processSubscribedThreadStream`;
* only tests call this directly.
*/
processStream(response: {
fullStream: AsyncIterable<any>;
}, requestContext?: RequestContext): Promise<{
message: MastraDBMessage;
suspended?: boolean;
} | undefined>;
/**
* Drive the run loop for a subscribed thread stream: process each run's chunks
* and finalize it. Delegates to the per-session run engine.
*/
processSubscribedThreadStream(subscription: AgentThreadSubscription<any, true>): Promise<void>;
/**
* The id of the run currently active on this session: the live subscription's
* active run id when it is streaming, falling back to the last run id the run
* tracker observed. Null when the session is idle.
*/
getCurrentRunId(): string | null;
/**
* Abort the session's active run: drop any parked tool suspensions, abort the
* live subscription's in-flight run, and mark the run as aborting so the
* run-end path resolves its reason as 'aborted'.
*
* Dropping the parked suspensions matters because a run sitting in a tool
* `suspend()` (e.g. `ask_user` / `request_access`) is not actively streaming,
* so aborting the controller alone would leave it orphaned. The AgentController still
* clears its own display-state mirror of those suspensions separately.
*
* Releasing a parked tool-approval gate matters for the same reason: a run
* awaiting `approval.arm()` is not streaming, so we resolve it as a decline so
* the gated tool is rejected and the run can finalize rather than hang.
*/
abortRun(options?: {
localOnly?: boolean;
keepParked?: boolean;
}): void;
/**
* Take the origin captured when a gated abort was armed. The run engine
* claims it as soon as the gate releases, so a later abort of another run
* cannot overwrite the origin this run's teardown is checked against.
*/
takeDeferredAbortOrigin(): {
bindingGeneration: number;
localOnly: boolean;
} | undefined;
/**
* Fire the deferred abort teardown for a run that was aborted while parked on
* a tool-approval gate: abort the live subscription and the run's controller.
* Called by the run engine once the gated call's decline has been driven
* through the agent, so the denial is persisted before the run is torn down.
* When `origin` is present, the teardown is skipped if the session's binding
* was torn down since, because a successor run may now own the stream and
* run state. (The abort-requested flag is not a usable guard: the denial's
* own resumed run resets it before settlement resolves.)
*/
completeDeferredAbort(origin?: {
bindingGeneration: number;
localOnly: boolean;
}): void;
/**
* Abort the session's active run and clear the display-state mirror of any
* parked tool suspensions. {@link abortRun} drops the parked suspensions (so a
* run sitting in a tool suspend() like ask_user / request_access isn't left
* orphaned), aborts the live subscription, and marks the run as aborting; this
* additionally clears the display-state mirror of those suspensions and
* notifies subscribers so stale suspension UI doesn't linger.
*/
abort(options?: {
localOnly?: boolean;
keepParked?: boolean;
}): void;
/**
* Resolve the effective approval policy for a tool: explicit per-tool deny
* wins, then session-wide yolo, then an explicit per-tool policy, then a
* grant, then the tool's category grant/policy, falling back to "ask". Pure
* session state plus the injected category resolver.
*
* `scope` names the thread whose rules and grants apply. Pass a thread id to
* read that thread's grants against the session's current rules, or a run's
* request context to use the rules of the thread that run belongs to, which
* may not be the thread the session currently holds. Grants are checked
* against that thread (default: the current thread) plus the session-wide
* bucket, so a grant made from one thread's approval prompt is not inherited
* by every other thread in the session.
*/
resolveToolApproval(toolName: string, scope?: string | RequestContext): PermissionPolicy;
/**
* @internal The thread and session state a run sees. Rules are thread-scoped
* state, so a run on a thread the session no longer holds reads its own
* thread's view from its request context. A run on the current thread reads
* the live state, which also covers a view whose source was released while
* the run was parked.
*/
__getRunState(requestContext: RequestContext | undefined): {
threadId: string | undefined;
state: Record<string, unknown>;
};
/**
* Respond to the parked tool-approval gate named by `toolCallId` with the
* user's decision. The id is required: a response can only release the gate it
* names, so a stale or id-less response can never resolve a different pending
* gate. A no-op when that gate is not parked, or when the run is aborting and
* the gate belongs to the aborting thread.
* "always_allow_category" grants the gated tool's category to the thread that
* owns the gate (resolved via the injected {@link setCategoryResolver}) and then
* approves; "approve"/"decline" release the run as-is.
*/
respondToToolApproval({ decision, toolCallId, requestContext, declineContext, }: {
decision: 'approve' | 'decline' | 'always_allow_category';
toolCallId: string;
requestContext?: RequestContext;
declineContext?: {
reason?: string;
message?: string;
};
}): SessionCommandResult;
/**
* Whether a suspended run on the current thread is waiting on an approval for
* `toolCallId`. Lets callers reject stale answers before scheduling the resume.
*/
hasPersistedToolApproval(toolCallId: string): Promise<boolean>;
/**
* Answer an approval that is stored with a suspended run but not parked on this
* session's gate, e.g. a card rebuilt from thread history after a restart.
* Resolves the run that owns `toolCallId` and resumes it by run id. Throws when
* no suspended run on the current thread is waiting on that tool call.
*/
respondToPersistedToolApproval({ toolCallId, approved, alwaysAllowCategory, requestContext, }: {
toolCallId: string;
approved: boolean;
/** Also grant the tool's category to the run's thread, like a parked "always allow". */
alwaysAllowCategory?: boolean;
requestContext?: RequestContext;
}): Promise<void>;
/** Resume calls released by a policy re-check under the context of the request that opened this session. */
setParkedApprovalsRequestContext(requestContext: RequestContext | undefined): void;
applyToolPolicyToParkedApprovals(): Promise<void>;
/**
* Build the agent message input for a user turn, attaching any files as
* additional message parts (text files inlined as fenced code, binary files
* as `file` parts). Returns the plain string when there are no files.
*/
private createMessageInput;
/**
* Resolve once this session's stream is fully idle.
*
* After `abort()` is called the run's status can still be `'running'` for a
* few microtasks while the underlying model stream finalizes. Callers that
* need to send a fresh signal after an abort (e.g. plan approval → mode
* switch → trigger reminder) should await this before calling `sendSignal`
* to avoid the new signal being queued onto the dying run, which would then
* be drained with the previous run's already-aborted abortSignal.
*/
private waitForStreamIdle;
/** Persist a signal to an explicit conversation without changing this session's current thread. */
sendSignalToThread(input: AgentSignalInput, target: {
resourceId: string;
threadId: string;
}, options?: {
requestContext?: RequestContext;
}): {
id: string;
type: AgentSignalInput['type'];
accepted: Promise<{
accepted: true;
}>;
};
/**
* Send a signal to this session's current agent/thread. Creates a thread when
* the session is not yet bound. When a run is already active the signal is
* dispatched onto it; otherwise the signal carries fresh stream options that
* start a new run.
*/
sendSignal(input: AgentSignalInput | {
content: AgentSignalContents;
ifActive?: {
behavior?: AgentSignalActiveBehavior;
attributes?: AgentSignalAttributes;
};
ifIdle?: {
behavior?: AgentSignalIdleBehavior;
attributes?: AgentSignalAttributes;
};
tracingContext?: TracingContext;
tracingOptions?: TracingOptions;
requestContext?: RequestContext;
untilIdle?: boolean | {
maxIdleMs?: number;
};
author?: MessageAuthor;
/**
* Scopes for this message. A run's scopes are fixed when it starts, so a message
* whose scopes differ from the active run's does not join it (`scope-mismatch`).
*/
scopes?: string[];
/**
* Provider options attached to the resulting prompt turn. Surfaces as
* `providerOptions` on the `UserModelMessage` sent to the model and as
* `content.providerMetadata` on the persisted DB message (see
* {@link AgentSignalInput.providerOptions}).
*/
providerOptions?: MastraProviderMetadata;
}, options?: {
ifActive?: {
behavior?: AgentSignalActiveBehavior;
attributes?: AgentSignalAttributes;
};
ifIdle?: {
behavior?: AgentSignalIdleBehavior;
attributes?: AgentSignalAttributes;
};
tracingContext?: TracingContext;
tracingOptions?: TracingOptions;
requestContext?: RequestContext;
untilIdle?: boolean | {
maxIdleMs?: number;
};
/**
* When true, the returned `accepted` promise awaits the agent's real
* acceptance decision (`wake`/`deliver`/…) and propagates routing or
* stream-setup failures as rejections instead of resolving on the next
* tick. Callers that need delivery guarantees (e.g. the Factory rule
* dispatcher) use this so a failed wake is retried rather than silently
* treated as sent.
*/
requireDelivery?: boolean;
}): {
id: string;
type: AgentSignalInput['type'];
accepted: Promise<{
accepted: true;
runId?: string;
action?: SendAgentSignalAccepted['action'];
/** Why the thread refused it, when `action` is `blocked`. */
reason?: 'thread-blocked' | 'scope-mismatch';
}>;
};
/**
* Send a notification signal to this session's current agent/thread.
*/
sendNotificationSignal(input: SendNotificationSignalInput, options?: SessionSendNotificationSignalOptions): Promise<SendAgentNotificationSignalResult>;
private prepareMessageTarget;
/**
* Send a message to this session's current agent and await the run. Streams
* the response and emits events.
*
* `scopes` are the scopes the message's run holds. A run's scopes are fixed when it
* starts: a message whose scopes match the active run's joins it, and one whose scopes
* differ waits for that run to end and then starts its own run on the same thread.
* Messages carrying scopes start in the order they were sent.
*/
sendMessage({ content, files, tracingContext, tracingOptions, requestContext: requestContextInput, untilIdle, author, scopes, }: {
content: string;
files?: Array<{
data: string;
mediaType: string;
filename?: string;
}>;
tracingContext?: TracingContext;
tracingOptions?: TracingOptions;
requestContext?: RequestContext;
untilIdle?: boolean | {
maxIdleMs?: number;
};
author?: MessageAuthor;
scopes?: string[];
}): Promise<void>;
/**
* Queue a message for the next run, or send it immediately when this session
* is idle. Queue ordering and retry behavior are owned by the Agent runtime.
*/
queueMessage({ content, files, tracingContext, tracingOptions, requestContext: requestContextInput, author, scopes, }: {
content: string;
files?: Array<{
data: string;
mediaType: string;
filename?: string;
}>;
tracingContext?: TracingContext;
tracingOptions?: TracingOptions;
requestContext?: RequestContext;
author?: MessageAuthor;
/** Scopes for the run the queued message starts. */
scopes?: string[];
}): Promise<void>;
/**
* Queue a typed signal for the next run, or send it immediately when this
* session is idle. Shares the Agent runtime queue used by `queueMessage()`.
* Unlike `queueMessage()`, no author is inferred from the request context:
* set `signal.author` when the signal is human-authored.
*/
queueSignal(signal: AgentSignalInput, { tracingContext, tracingOptions, requestContext: requestContextInput, scopes, }?: {
tracingContext?: TracingContext;
tracingOptions?: TracingOptions;
requestContext?: RequestContext;
/** Scopes for the run the queued signal starts. */
scopes?: string[];
}): Promise<void>;
/** Abort the current run and send steering input without clearing queued follow-ups. */
steer({ content, files, requestContext, author, scopes, }: {
content: string;
files?: Array<{
data: string;
mediaType: string;
filename?: string;
}>;
requestContext?: RequestContext;
author?: MessageAuthor;
/** Scopes for the run the steering message starts; see `sendMessage`. */
scopes?: string[];
}): Promise<void>;
ensureFollowUpBinding(agent: Agent, resourceId: string, threadId: string): {
agent: Agent;
resourceId: string;
threadId: string;
unsubscribe?: () => void;
} | undefined;
/** Queue a follow-up through the Agent runtime, or send it immediately while idle. */
followUp({ content, files, requestContext, }: {
content: string;
files?: Array<{
data: string;
mediaType: string;
filename?: string;
}>;
requestContext?: RequestContext;
}): Promise<void>;
cleanupFollowUpBinding(): void;
/**
* Persist a system-reminder message to this session's current thread. Returns
* the saved message, or `null` when the session has no thread or no storage.
*/
saveSystemReminderMessage({ message, reminderType, role, metadata, }: {
message: string;
reminderType: string;
role?: 'user' | 'assistant' | 'system';
metadata?: Record<string, unknown>;
}): Promise<MastraDBMessage | null>;
/** @internal Capture the trusted owner snapshot while processing a run's stream. */
__captureRunThreadOwnerId(runId: string, requestContext: RequestContext): void;
/**
* The mode the suspended run executed in, read from its persisted request
* context, so a mode switch during the suspension does not change the tools
* the continuation sees. Runs suspended before the mode was recorded fall back
* to the mode of the run's source thread as `requestContext` resolves it.
*/
private isConfiguredMode;
private resolveSuspendedRunModeId;
private resolveSuspendedThreadOwnerId;
private resolveSuspensionAgent;
/**
* Claim the right to answer `toolCallId` so concurrent requests cannot both be
* acknowledged for the same pending target. Synchronous, so a caller that
* claims and then starts the response without awaiting in between is atomic.
* Pair with {@link releaseToolResponse} once the response settles.
*/
claimToolResponse(toolCallId: string): boolean;
/** Release a claim taken with {@link claimToolResponse}. */
releaseToolResponse(toolCallId: string): void;
/**
* Register a suspension that lives only in storage, so {@link claimToolSuspension}
* can find it. A run parked by a process that has since gone away stays
* suspended in storage, but this session never saw it park. Only an exact
* `toolCallId` on the active thread is looked up, and only when exactly one
* stored, non-approval suspension matches. The scan is bounded so an unknown
* id can't make a reply read every stored run on the thread.
*/
restoreStoredToolSuspension(toolCallId?: string, runId?: string): Promise<void>;
/**
* Claim the parked suspension a {@link respondToToolSuspension} call would
* resume. Returns the resolved tool call id, or a rejection when nothing is
* pending or another response already claimed it.
*/
claimToolSuspension(toolCallId?: string, runId?: string): {
accepted: true;
toolCallId: string;
address: SuspensionAddress;
claimKey: string;
} | Extract<SessionCommandResult, {
accepted: false;
}>;
/**
* Respond to a pending tool suspension. Provides resume data so the suspended
* tool can continue. `toolCallId` selects which suspended tool to resume —
* required when more than one is suspended concurrently; when omitted it
* resolves to the sole pending suspension. `submit_plan` resumes are routed
* through the plan-approval path (approval switches to the default mode).
*/
respondToToolSuspension({ resumeData, toolCallId, runId, address: inputAddress, requestContext, }: {
resumeData: any;
toolCallId?: string;
runId?: string;
address?: SuspensionAddress;
requestContext?: RequestContext;
}): Promise<void>;
/**
* Respond to a suspended `submit_plan` tool call. Rejections resume the plan
* tool with feedback. Approvals switch to the transition mode when needed,
* then resume the same suspended tool so the approved tool result is persisted
* and the model continues naturally in the target mode.
*/
private handlePlanApprovalResume;
/**
* Approve a parked tool call: drive the agent to execute it. Throws when there
* is no active run.
*
* `runId`/`threadId`/`resourceId` resolve the call against the run that
* parked it rather than the session's current thread/run/resource. The run
* engine passes its stream state's own binding because the session can switch
* thread (or be re-scoped to another resource) while a run is still in
* flight, and the agent locates the suspended run by `threadId`/`resourceId`
* — resolving with the newly-bound identity would throw or land on the wrong
* thread.
*
* The owning agent is read from the run scope first (the
* {@link SUSPENDED_RUN_AGENT_KEY} invariant the resume path uses), then
* `agent` for callers that hold no run scope, then the session's current
* agent. `abortSignal` pins the run's own signal, because a successor run
* replaces the session's abort controller.
*/
approveToolCall(input: {
toolCallId?: string;
requestContext?: RequestContext;
runId?: string;
threadId?: string;
resourceId?: string;
agent?: Agent;
abortSignal?: AbortSignal;
}, onDispatch?: () => void): Promise<void>;
/**
* Decline a parked tool call: drive the agent to reject it. Throws when there
* is no active run.
*
* `runId`/`threadId`/`resourceId` follow the same contract as
* {@link approveToolCall}: the run engine resolves declined calls against the
* run that parked them, so a thread switch mid-run cannot redirect the
* decline to another thread.
*/
declineToolCall(input: {
toolCallId?: string;
requestContext?: RequestContext;
declineContext?: {
reason?: string;
message?: string;
};
runId?: string;
threadId?: string;
resourceId?: string;
agent?: Agent;
abortSignal?: AbortSignal;
}, onDispatch?: () => void): Promise<void>;
private createSubscribedResumeBoundaryWaiter;
private observeSourceResume;
/**
* Resume a suspended tool call through the active thread subscription.
* Re-supplies the shared run budget so the resumed run doesn't stop mid-task
* on the agent's small default maxSteps.
*
* The continuation keeps the run's approval policy. The resumed call itself
* is not gated again: the loop only gates calls that have not run yet or that
* were parked for approval, so an `ask_user` answer reaches the model as-is
* while later calls in the run still go through approval.
*/
resumeToolCall(input: {
resumeData: any;
address: SuspensionAddress;
requestContext?: RequestContext;
resolveOnToolEnd?: boolean;
/** The mode the continuation runs in; defaults to the suspended run's mode. */
modeId?: string;
}): Promise<void>;
/**
* Grant a tool category "allow". Scoped to `threadId` when given; a call that
* names no thread grants session-wide (every thread).
*/
grantCategory(category: ToolCategory, threadId?: string): void;
/**
* Grant an individual tool "allow". Scoped to `threadId` when given; a call
* that names no thread grants session-wide (every thread).
*/
grantTool(toolName: string, threadId?: string): void;
/**
* Whether the given tool category has been granted session-wide or for
* `threadId` (default: the current thread).
*/
hasCategoryGrant(category: ToolCategory, threadId?: string): boolean;
/**
* Whether the given tool has been granted session-wide or for `threadId`
* (default: the current thread).
*/
hasToolGrant(toolName: string, threadId?: string): boolean;
/**
* Snapshot of the grants that apply to `threadId` (default: the current
* thread): session-wide grants plus that thread's own.
*/
getGrants(threadId?: string): {
categories: ToolCategory[];
tools: string[];
};
/** A copy of the running token-usage tally for the active thread. */
getTokenUsage(): TokenUsage;
/**
* Replace the running tally, e.g. when hydrating from persisted thread
* metadata on thread switch.
*/
setTokenUsage(usage: TokenUsage): void;
/** Reset the running tally to zero, e.g. on a new/empty thread. */
resetTokenUsage(): void;
/** Fold a single step's usage into the running tally. */
addUsage(stepUsage: TokenUsage): void;
}
//# sourceMappingURL=session.d.ts.map