UNPKG

@mastra/core

Version:
503 lines • 25.1 kB
import { Agent } from '../agent/index.js'; import type { ActiveThreadRun } from '../agent/thread-stream-runtime.js'; import type { MastraFGAPermissionInput } from '../auth/ee/index.js'; import type { MastraBrowser } from '../browser/browser.js'; import { AgentControllerChannels } from '../channels/agent-controller-channels.js'; import type { MastraModelConfig } from '../llm/model/shared.types.js'; import { Mastra } from '../mastra/index.js'; import type { StorageThreadType } from '../memory/types.js'; import { RequestContext } from '../request-context/index.js'; import type { ObservationalMemoryRecord, StorageListMessagesInput, StorageListMessagesOutput } from '../storage/types.js'; import type { DynamicArgument } from '../types/index.js'; import type { Workspace } from '../workspace/workspace.js'; import { Session } from './session.js'; import type { AvailableModel, IntervalHandler, AgentControllerConfig, AgentControllerMode, AgentControllerSessionCreatedListener, AgentControllerSessionCreatedOptions, AgentControllerSessionDeletedListener, AgentControllerThread, ModelAuthStatus, ToolCategory } from './types.js'; /** * Returns Anthropic `providerOptions` that enable a server-side fallback to * {@link FABLE_FALLBACK_MODEL} when the active model is `claude-fable-5`, and * `undefined` otherwise. * * fable-5 can have a turn blocked server-side by its safety classifiers. With * a fallback configured, Anthropic transparently retries the blocked turn on * the fallback model and returns that model's answer instead of refusing. If * the whole chain refuses, the run still ends on a `content-filter` finish * reason, which is handled as a terminal error. * * The match is suffix-based so it covers `anthropic/claude-fable-5`, a bare * `claude-fable-5`, and any pack/provider-prefixed form. */ export declare function buildFableFallbackProviderOptions(modelId: string): { anthropic: { fallbacks: { model: string; }[]; }; } | undefined; /** * The AgentController orchestrates multiple agent modes, shared state, memory, and storage. * It's the core abstraction that a TUI (or other UI) controls. * * @example * ```ts * const controller = new AgentController({ * id: "my-coding-agent", * storage: new LibSQLStore({ url: "file:./data.db" }), * stateSchema: z.object({ * currentModelId: z.string().optional(), * }), * modes: [ * { id: "plan", name: "Plan", default: true, agent: planAgent }, * { id: "build", name: "Build", agent: buildAgent }, * ], * }) * * controller.subscribe((event) => { * if (event.type === "message_update") appendText(event.id, event.event.delta) * }) * * await controller.init() * await controller.sendMessage({ content: "Hello!" }) * ``` */ export declare class AgentController<TState = {}> { #private; readonly id: string; private config; private initPromise; private browser; private workspace; private intervalTimers; constructor(config: AgentControllerConfig<TState>); /** * Subscribe to process-local notifications for newly materialized sessions. * Cached `createSession()` calls do not notify listeners again. * * Async listeners are fire-and-forget by default. Pass `blocking: true` to * make `createSession()` await the listener before resolving — for setup that * must land before the caller can start a run (e.g. seeding session state * from storage). Blocking listeners run sequentially in registration order, * before fire-and-forget listeners are notified. Failures are isolated and * logged, never thrown — session creation stays best-effort with respect to * listener setup. A blocking listener must not call `createSession()` for * the same session id it is initializing: that lookup awaits the * in-flight creation that is awaiting the listener, which deadlocks. */ onSessionCreated(listener: AgentControllerSessionCreatedListener<TState>, options?: AgentControllerSessionCreatedOptions): () => void; /** * Subscribe to process-local notifications after live sessions are torn * down. Fires even when teardown cleanup fails — the session is * deregistered either way. */ onSessionDeleted(listener: AgentControllerSessionDeletedListener<TState>): () => void; /** * Create a new, fully-wired {@link Session} and bring it online: it starts in * the default mode with the seeded model, is connected to the AgentController's shared * machinery (agent, storage/lock, config catalog), and normally has a current * thread (the most recent matching thread, or a freshly created one). When * `createInitialThread` is false and no thread matches, the returned session * has no current thread; the first operation that needs one (sending a * message, {@link SessionThread.ensureId}) creates it. * * The AgentController owns no session of its own — every consumer creates its own * session and drives all work through it (`session.sendMessage`, * `session.mode.switch`, `session.thread.*`, `session.subscribe`, ...). In a * server / multiplayer setting, each request / thread / user gets its own * session, isolated from every other: independent event bus, mode, model, * state, and current thread. * * Call {@link init} once before creating sessions so shared storage and * workspace are ready. * * @param id - Stable session identifier (mirrors `SessionRecord.id`). Sessions are looked up by this id * ({@link getSession}); several sessions may share one resourceId. Defaults to the resolved `resourceId`. * @param ownerId - Stable session owner (mirrors `SessionRecord.ownerId`). Defaults to the controller `id`. * @param resourceId - Memory resource to bind this session to. Defaults to the controller `resourceId` or `id`. * @param createInitialThread - Create a thread when no existing thread matches. Defaults to true. * @param resumeOnly - Only return a live session or recover one from a stored thread; never start a new conversation. */ createSession({ resourceId, ownerId, id, tags, threadId, createInitialThread, resumeOnly, workspace, browser, requestContext, }?: { resourceId?: string; id?: string; ownerId?: string; /** * Arbitrary string tags that scope this session. Each tag is seeded into the * session's state and used to filter initial thread selection: a thread is a * resume candidate only when its metadata matches every provided tag. This * lets worktrees sharing a resourceId each resume their own thread (via a * `projectPath` tag) and leaves room for future scoping dimensions without * changing the API. Falls back to `initialState` when omitted. */ tags?: Record<string, string>; /** Exact thread id to bind during session creation. Existing threads are resumed; missing threads are created with this id. */ threadId?: string; /** Create a thread when no existing thread matches. Set false to defer creation until first use, so unused sessions leave no empty thread behind. */ createInitialThread?: boolean; /** * Return the live session, or rebuild a lost one (e.g. after a restart) bound to the most recent stored * thread in its scope. Never creates a thread: throws {@link SessionNotStartedError} when there is no * live session and no stored thread to recover, so writes cannot start a conversation on a thread the * caller never asked for. */ resumeOnly?: boolean; workspace?: Workspace; browser?: MastraBrowser; requestContext?: RequestContext; }): Promise<Session<TState>>; /** * Resolve a live session by its session id (the `id` passed to * {@link createSession}, which defaults to the resourceId). Returns * `undefined` when no live session has that id. Used by notification * delivery to run woken signals as the session that owns the target thread, * rather than an arbitrary session. */ getSession(sessionId: string, requestContext?: RequestContext): Promise<Session<TState> | undefined>; /** * Tear down the live session with this session id. * This only removes runtime state; persisted threads and messages remain. * Returns `false` when no live session is registered. */ deleteSession({ sessionId }: { sessionId: string; }): Promise<boolean>; /** * Access the Mastra instance backing this AgentController. * * Returns the parent Mastra when this AgentController is registered on one (see * {@link __registerMastra}); otherwise the internal Mastra created during * `init()` when storage is configured. * * Useful for scorer registration, observability access, and eval tooling. */ getMastra(): Mastra | undefined; /** @internal */ requireAgentControllerFGA({ permission, requestContext, resourceId, sessionId, }: { permission: MastraFGAPermissionInput; requestContext?: RequestContext; resourceId?: string; sessionId?: string; }): Promise<void>; /** * Whether a workspace is configured on this AgentController (static instance, dynamic * factory, or config object). Sessions without an explicit workspace override * fall back to this. */ hasWorkspace(): boolean; /** * Whether the AgentController-level static workspace has been explicitly initialized. * Dynamic factory workspaces have no controller-level readiness state. */ isWorkspaceReady(): boolean; /** * The AgentController-level workspace, if it is a static instance. Dynamic factory * workspaces are not resolved here — use {@link resolveWorkspace} to resolve * a factory against a session's request context. */ getWorkspace(): Workspace | undefined; /** * The workspace this session runs against, for code paths outside the request * flow (e.g. slash commands). Sessions resolve their workspace once at * creation — dynamic factories included — so this returns that instance * rather than re-resolving, and only falls back to the factory for a session * created without one. */ resolveWorkspace({ session, requestContext, }: { session: Session<TState>; requestContext?: RequestContext; }): Promise<Workspace | undefined>; /** * Register this AgentController on a parent Mastra. Called by Mastra during * construction when a harness is passed in its config. Once registered, the * AgentController uses the parent Mastra (its storage, agents, gateways, and * observability) instead of building its own internal one during `init()`. * * @internal */ __registerMastra(mastra: Mastra): void; /** * Sets or updates the harness-level browser and propagates it to mode agents. */ setBrowser(browser: MastraBrowser | undefined): void; /** * Initialize the harness by loading storage and propagating runtime services. * Workspaces initialize lazily when used. Must be called before using the harness. Idempotent: repeated calls * return the same in-flight/completed initialization instead of rebuilding * the internal Mastra instance (which would orphan registered agents). */ init(): Promise<void>; /** * Initialize only what read-only queries need: the storage layer (either a * fresh internal Mastra wrapping the configured storage, or the inherited * parent Mastra's storage). Skips workspace/sandbox provisioning entirely. * * Idempotent and safe to call from every read query; the underlying * MastraCompositeStore init dedupes. */ initStorage(): Promise<void>; private runStorageInit; private runInit; private getMemoryStorage; /** * The shared-host storage gateway the Session's thread domain reads/writes * through. The Session owns the thread-domain logic; this adapter maps raw * storage rows to AgentController types and uses the active session only when * resolving configured memory for a clone. */ private createThreadDataStore; /** Persist a thread row to memory storage (gateway primitive for the Session thread domain). */ private persistThreadRow; /** * Delete a thread from controller storage and, when memory is resolved per * caller, from the caller's memory as well so a clone's messages are not * left behind there (gateway primitive for the Session thread domain). */ private deleteThreadRow; /** Clone a thread (and messages) via the host's memory (gateway primitive for the Session thread domain). */ private cloneThreadRow; private readThreadMetadataValue; private writeThreadMetadataValues; private writeThreadMetadataValue; private removeThreadMetadataValue; /** * Read a single thread by id directly from storage, without constructing a * {@link Session}. Read-only server endpoints use this so a GET request for a * thread doesn't spin up a workspace/sandbox as a side effect of session * creation. Returns `null` when the thread doesn't exist or no storage is * configured. */ queryThreadById({ threadId }: { threadId: string; }): Promise<AgentControllerThread | null>; /** * Switch the model of a resource's stored thread without creating a session. * A live session bound to that thread switches immediately; otherwise the * selection is persisted and applies when a session next loads the thread. * Returns whether the switch reached a live session. */ setThreadModel({ resourceId, threadId, modelId, }: { resourceId: string; threadId: string; modelId: string; }): Promise<{ live: boolean; }>; /** * List threads directly from storage, without constructing a {@link Session}. * Read-only server endpoints use this so a GET on `/threads` doesn't spin up * a workspace/sandbox as a side effect of session creation. */ queryThreads({ resourceId, includeForkedSubagents, metadata, limit, matchesScope, }: { resourceId?: string; includeForkedSubagents?: boolean; metadata?: Record<string, unknown>; /** Return only the newest `limit` threads by `updatedAt`, read page by page instead of all at once. */ limit?: number; matchesScope?: (thread: StorageThreadType) => boolean; }): Promise<AgentControllerThread[]>; /** * List messages for a thread directly from storage, without constructing a * {@link Session}. The session thread-data adapter and read-only server * endpoints use this shared path so message reads never provision a * workspace/sandbox. */ queryThreadMessages({ threadId, resourceId, perPage, page, orderBy, include, filter, }: Omit<StorageListMessagesInput, 'threadId'> & { threadId: string; }): Promise<StorageListMessagesOutput>; private queryFirstUserMessages; /** * Name a thread from where its conversation went, with the model and * instructions `generateTitle` gives the first-turn namer — so a title asked * for by hand reads like one the thread would have been given on its own. * * Runs without constructing a {@link Session}: naming reads a window of recent * messages and writes the thread row, so asking for a title never spins up a * workspace or sandbox. A live session named by `sessionId` lends its agent, request * context and event stream; otherwise the default mode answers — and with no * session state to read, a `generateTitle.model` that resolves from it falls * back to its own default, which is why hosts that store the choice elsewhere * pass `model`. Resolves to the new title, or `undefined` when the model * returns nothing and the current title stands. */ generateThreadTitle({ threadId, sessionId, model, requestContext: callerContext, }: { threadId: string; /** Live session to borrow the agent and request context from. */ sessionId?: string; /** Overrides the memory-configured title model — for hosts that resolve it themselves. */ model?: DynamicArgument<MastraModelConfig>; /** The caller's context — carries the identity model resolution bills to. */ requestContext?: RequestContext; }): Promise<string | undefined>; listModes(): AgentControllerMode[]; getDefaultMode(): AgentControllerMode; private propagateRuntimeServicesToAgent; /** * Chat channels configured on this controller (from `config.channels`), * or null when the controller has no channels. */ getChannels(): AgentControllerChannels | null; /** * Sets the AgentControllerChannels instance for this controller and * propagates it onto every backing agent so their runs render back through * the controller's adapters. Used by ChannelProvider implementations (e.g. * SlackProvider) to inject channels they create for dynamic installations. * Mirrors {@link setBrowser}: the instance is attached to the shared backing * agent plus any per-mode agents via `Agent.setChannels`, and lazily-built * mode agents pick it up on their first run via * `propagateRuntimeServicesToAgent`. * * Replacing an existing instance is expected on provider reconnect (the * provider rebuilds channels as a superset merge rather than mutating the * live instance), so it logs at debug level only. Note the replaced * instance's in-memory `autoApproveResourceIds` tracking is discarded with * it — harmless, since it is refreshed on every inbound message. * @internal */ setChannels(channels: AgentControllerChannels): void; /** The distinct agents backing this controller: the shared one plus any deprecated per-mode agent. */ private backingAgents; private getAgentForMode; /** * Resolve the combined instructions for the current mode: harness-level * instructions + mode-specific instructions. Passed at call time via * `buildAgentMessageStreamOptions` so the agent's own instructions are * never mutated. */ private resolveCurrentModeInstructions; /** * Convert AgentInstructions (string | string[] | system message objects) to * a plain string for combining with mode instructions. */ private instructionsToString; /** * Get the agent for the current mode. */ /** * Resolve the Agent backing the current mode, with runtime services (storage, * pubsub, telemetry) propagated. Public so consumers like MastraCode's * GoalManager can drive the agent's native objective methods * (`setObjective`/`getObjective`/`clearObjective`/`updateObjectiveOptions`), * which read/write the durable `threadState` `'goal'` slot. */ getCurrentAgent(session: Session<TState>): Agent; listActiveThreadRuns(): ActiveThreadRun[]; /** * Check if the current model's provider has authentication configured. * Delegates to the {@link GatewayManager} auth chain (the same resolution * the model router uses at run time). Returns `hasAuth: true` only when no * model is selected; gateway-chain failures return `hasAuth: false` so the * auth-status endpoint stays stable instead of erroring. */ getCurrentModelAuthStatus(session: Session<TState>): Promise<ModelAuthStatus>; /** * Get available models from the configured gateways with use counts applied. * * Remote catalogs (models.dev, Netlify) are served from their last good * download and refreshed in the background once it is a few minutes old; * calls wait for one only until it has downloaded once. * Configured gateways and auth are checked again after a few seconds, or on * the next call after {@link invalidateAvailableModelsCache}. */ listAvailableModels(): Promise<AvailableModel[]>; /** * Make the next {@link listAvailableModels} call check configured gateways and * auth again, and download remote catalogs again in the background. Call it * after credentials or custom providers change. */ invalidateAvailableModelsCache(): void; /** * Point the session at a different memory resourceId. The resourceId itself * lives on the session (`session.identity`); the AgentController orchestrates the * surrounding teardown — dropping the current thread subscription and clearing * the active thread — since those are AgentController-owned. * * The session stays registered under its session id, so {@link getSession} * keeps resolving it. A session that is being deleted is left alone. */ setResourceId(session: Session<TState>, { resourceId }: { resourceId: string; }): Promise<void>; getKnownResourceIds(session: Session<TState>): Promise<string[]>; /** * Load observational memory progress for the current thread. * Reconstructs status from the durable OM record, then emits an `om_status` event for the UI. */ loadOMProgress(session: Session<TState>, isCurrent?: () => boolean): Promise<void>; getObservationalMemoryRecord(session: Session<TState>): Promise<ObservationalMemoryRecord | null>; getToolCategory({ toolName }: { toolName: string; }): ToolCategory | null; /** * Resolve the `activeTools` allowlist for the current mode's run. * * Returns `undefined` when the mode has no `availableTools` configured * (no restriction — all tools visible). When the mode declares * `availableTools`, returns that list filtered to remove tools whose * permission category is denied. * * Per-tool `deny` is already handled by `buildToolsets` (denied tools are * deleted from the toolsets), so those tools won't exist at execution time * regardless of whether they appear in the allowlist. * * The returned list uses the same exposed tool names the execution pipeline * checks against (e.g. `view`, `write_file`, `ask_user`), which matches the * names workspace tools are renamed to via `TOOL_NAME_OVERRIDES`. * * Pass the run's `requestContext` to filter with the rules of the run's own * thread rather than the thread the session currently holds. */ private resolveModeActiveTools; private buildAgentMessageStreamOptions; private formatToolProgressOutput; /** * Options that every harness-driven agent run must carry — the initial stream * AND every `resumeStream`. Centralized so the two paths can't drift: a * missing `maxSteps` on resume silently caps the resumed run at the agent's * small default and ends it mid-task (see {@link HARNESS_MAX_STEPS}). */ private buildSharedRunOptions; /** * Persist a system-reminder message for a thread (host-owned storage). Throws * when no storage is configured — the Session guards the no-thread case before * calling. Returns the saved {@link MastraDBMessage}. */ private saveSystemReminder; /** * Resolve the mode the session transitions to when a plan is approved: the * source mode's `transitionsTo`, else the configured default mode. The mode * catalog is AgentController config, so this is host-owned. Returns `undefined` when * no default mode is configured. */ private resolveTransitionModeId; private convertToControllerMessage; private getSubagentDisplayName; /** * Build the toolsets object that includes built-in harness tools (ask_user, submit_plan, * and optionally subagent) plus any user-configured tools. * Used by sendMessage, handleToolApprove, and handleToolDecline. */ private buildToolsets; /** * Build request context for agent execution. * Tools can access controller state via requestContext.get('controller'). */ private buildRequestContext; /** * Resolve memory from config — handles both static instances and dynamic factory functions. * Pass the caller's context so a dynamic factory sees the caller's user. */ private resolveMemory; /** * Execution-side usage recorder for one run. Stream subscribers only project * usage for display; the run that spends the tokens folds each step into its * thread's persisted total exactly once. */ private createUsageRecorder; private startIntervals; registerInterval(handler: IntervalHandler): void; removeInterval({ id }: { id: string; }): Promise<void>; stopIntervals(): Promise<void>; destroy(): Promise<void>; private generateId; } //# sourceMappingURL=agent-controller.d.ts.map