import type { AgentControllerThinkingLevel, AgentControllerThread, AgentControllerWireEvent, MastraDBMessage } from '@mastra/core/agent-controller'; /** Acknowledgement for approval/suspension commands; `ok` is true only when a pending target claimed it. */ export type AgentControllerCommandRejection = 'not_pending' | 'stale_tool_call' | 'aborting' | 'no_pending_suspension'; export interface AgentControllerCommandAck { ok: boolean; /** Set when `ok` is false. */ reason?: AgentControllerCommandRejection; } export type { MastraDBMessage, MastraMessageContentV2, MastraMessagePart } from '@mastra/core/agent-controller'; import type { RequestContext } from '@mastra/core/request-context'; import type { StorageListMessagesOutput } from '@mastra/core/storage'; import type { QueryParams, RouteResponse } from '../route-types.generated.js'; import type { AgentControllerActiveRun, AgentControllerAvailableModel, AgentControllerGoalRecord, AgentControllerModeInfo, AgentControllerSessionState, AgentControllerThreadInfo, AgentControllerWorkspaceStatus, ClientOptions, CreateAgentControllerSessionResponse, CreateAgentControllerThreadResponse, PermissionPolicy, PermissionRules, SendNotificationInput, SendNotificationResult, ToolCategory } from '../types.js'; import { BaseResource } from './base.js'; type AgentControllerModernListMessagesOptions = Omit, 'limit'> & { limit?: never; }; type AgentControllerLegacyPagedListMessagesOptions = { /** @deprecated Use `perPage` instead. May only be combined with `page`. */ limit: number; page?: number; perPage?: never; orderBy?: never; filter?: never; include?: never; }; /** Pagination, ordering, filtering, and include options for an Agent Controller thread's messages. */ export type AgentControllerListMessagesOptions = AgentControllerModernListMessagesOptions | AgentControllerLegacyPagedListMessagesOptions; /** A page of hydrated Agent Controller thread messages. */ export type AgentControllerListMessagesResult = StorageListMessagesOutput; /** * Notifications reach a session as agent signals carried on messages, not as * controller events. These two arms predate that and no controller emits them. */ type NotificationEvent = { type: 'notification'; notificationId?: string; message: string; source?: string; kind?: string; priority?: string; status?: string; attributes?: Record; metadata?: Record; } | { type: 'notification_summary'; message: string; pending: number; bySource: Record; byPriority: Record; notificationIds: string[]; }; /** The timestamps the SDK gives back as `Date`s. {@link hydrateKnownEvent} is typed against this, so the two cannot drift. */ type Hydrated = T extends { type: 'thread_created'; } ? Omit & { thread: AgentControllerThread; } : T extends { type: 'message_start'; } ? Omit & { message: MastraDBMessage; } : T; /** * AgentController events the SDK types explicitly: the wire union `@mastra/core` * derives from the controller's own events, with timestamps hydrated. This is a * discriminated union, so narrowing on `event.type` gives the right payload. */ export type KnownAgentControllerEvent = Hydrated | NotificationEvent; /** Any other agent controller event the SDK doesn't model explicitly. */ export interface OtherAgentControllerEvent { type: string; [key: string]: unknown; } /** * An agent controller event. Comparing `event.type` to a literal does NOT * narrow this union — {@link OtherAgentControllerEvent} types `type` as * `string`, which matches every literal. Narrow with * {@link isKnownAgentControllerEvent} first, then switch on `type`. */ export type AgentControllerEvent = KnownAgentControllerEvent | OtherAgentControllerEvent; /** Narrows to the explicitly typed events; see {@link AgentControllerEvent}. */ export declare function isKnownAgentControllerEvent(event: AgentControllerEvent): event is KnownAgentControllerEvent; /** * Resume payload for the built-in `submit_plan` suspension. * * The tool suspends with only the plan file `path`; hosts read that file to render * the approval. `path`/`title`/`plan` let the host back-fill what it rendered so the * persisted tool result (`submittedPlan`) replays the plan durably in history even * after the plan file changes or disappears. */ export interface PlanResume { action: 'approved' | 'rejected'; feedback?: string; path?: string; title?: string; plan?: string; } /** * Options accepted by session methods that trigger or resume agent execution. * The `requestContext` is merged into the server-derived request context for * that run (server-controlled keys win), so it reaches dynamic instructions, * tools, and workspace resolution — mirroring `agent.generate()`. */ export interface AgentControllerRequestOptions { requestContext?: RequestContext | Record; } /** Options for subscribing to an agent controller session's event stream. */ export interface SubscribeAgentControllerSessionOptions { /** * Set to false to omit `display_state_changed` snapshots, including the initial one. The stream then opens * with the session's current state as events: `message_start` for the message being streamed, and the latest * `om_status`. Defaults to true. */ displayState?: boolean; /** Called for each event received over the stream. */ onEvent: (event: AgentControllerEvent) => void; /** * Called when the stream errors or ends and no (further) reconnect will be * attempted — the subscription is dead after this fires. */ onError?: (error: unknown) => void; /** * Called each time the stream is re-established after a drop (reconnect * only). The server does NOT replay events missed while disconnected, so * stateful consumers MUST re-sync from here (e.g. `session.state()`) or * they will silently lose the gap. */ onReconnect?: () => void; /** * Automatically re-establish the stream after an established stream drops * (clean close or transport error). Does not apply to the initial * connection — `subscribe()` rejects if it can't connect. Retries back off * exponentially from `delayMs` (default 1s) up to `maxDelayMs` (default * 30s); `maxRetries` (default Infinity) bounds the attempts per outage — * the counter resets once a connection is re-established. When retries are * exhausted, `onError` fires. */ reconnect?: boolean | { maxRetries?: number; delayMs?: number; maxDelayMs?: number; }; /** * Treat the stream as dropped after this many milliseconds without * receiving any bytes. Server heartbeats (every 25s) count, so a healthy * idle stream never trips it; a half-open connection (laptop sleep, proxy * or NAT timeout) does. Also bounds opening the stream: the initial * `subscribe()` rejects, and a reconnect attempt counts as failed, when no * response arrives in time. A timeout is handled like any other drop — * `reconnect` / `onReconnect` if enabled, otherwise `onError`. * Default 60000; `0` disables. */ idleTimeoutMs?: number; } export interface AgentControllerSubscription { /** Stop reading and release the underlying stream. */ unsubscribe: () => void; } /** * A session addressed by its `sessionId` within one agent controller. Sessions * are get-or-create on the server, so re-creating the same sessionId resumes * the existing conversation rather than forking it. Many sessions can work on * one `resourceId` (whose threads and memory they use); each has its own run * loop, thread binding, and mode/model/state. */ export declare class AgentControllerSession extends BaseResource { private readonly controllerId; private readonly sessionId; constructor(options: ClientOptions, controllerId: string, sessionId: string); private base; /** * Create or resume this session. `resourceId` names whose threads and memory * the session works on. Without it the server resumes the session on the * resource it already has (the live session's, or the resource of the thread * with the session's id), falling back to the sessionId. Pass `tags` to scope * initial thread selection — a thread is a resume candidate only when its * metadata matches every tag. Pass `threadId` to bind the session to one * exact thread, creating it with that id when it does not exist. */ create(options?: { resourceId?: string; tags?: Record; threadId?: string; }): Promise; /** * Subscribe to this session's event stream (SSE). The assistant's reply to a * message arrives here as `message_*` events, not on the sendMessage call. * * The returned promise resolves once the stream is actually established and * rejects when it cannot be. A rejected subscribe leaves nothing running — * `reconnect` governs only re-establishment after an established stream * drops, so callers that want connect-time retry can loop around * `subscribe()` themselves and keep cancellation control. */ subscribe(options: SubscribeAgentControllerSessionOptions): Promise; /** * Send a user message. The reply streams over `subscribe()`. * Pass a structured message to attach files (e.g. pasted images) as base64-encoded data: * `sendMessage({ content: 'What is in this image?', files })`. * Pass `options.requestContext` to merge custom context into the run's request context. */ sendMessage(message: string | { content: string; files?: Array<{ data: string; mediaType: string; filename?: string; }>; }, options?: AgentControllerRequestOptions): Promise; /** Abort the in-flight run for this session. */ abort(): Promise; /** * Approve or decline a pending tool call (`tool_approval_required`). Resolves * `{ ok: false, reason }` when no pending approval claimed the decision. */ approveTool(toolCallId: string, approved: boolean, options?: AgentControllerRequestOptions & { /** Also grant the tool's category to the call's thread ("always allow"). */ alwaysAllowCategory?: boolean; }): Promise; /** * Resume a suspended interactive tool (`tool_suspended`). The resume shape * depends on the tool: a string (or string[]) for `ask_user`, "Yes"/"No" for * `request_access`, and a {@link PlanResume} for `submit_plan`. */ respondToToolSuspension(toolCallId: string, resumeData: string | string[] | PlanResume, options?: AgentControllerRequestOptions): Promise; /** * Aborts the in-flight run, then sends the message as a new turn. * Pass a structured message to attach files, as with `sendMessage`. */ steer(message: string | { content: string; files?: Array<{ data: string; mediaType: string; filename?: string; }>; }, options?: AgentControllerRequestOptions): Promise; /** Get the current mode, model, and thread (for initial UI hydration). */ state(options?: { threadId?: string; }): Promise; /** Merge key-value pairs into the session state. Existing keys not in the payload are preserved. */ setState(updates: Record): Promise; /** Switch the active mode (e.g. `build`, `plan`). */ switchMode(modeId: string): Promise; /** * Switch the session model and persist it to the active thread. When * `thinkingLevel` is provided it is applied and persisted with the model. */ switchModel(modelId: string, { thinkingLevel }?: { thinkingLevel?: AgentControllerThinkingLevel; }): Promise; /** * List the session's threads, newest first. Pass `limit` to cap the count * (e.g. for a sidebar) and `tags` to scope to threads matching every tag — * necessary when one resourceId is shared across git worktrees of the same * repo (e.g. `{ tags: { projectPath } }` so each worktree sees only its own * threads). Passing a bare number is shorthand for `{ limit }`. */ listThreads(options?: number | { limit?: number; tags?: Record; }): Promise; /** Switch the session to an existing thread (rebinds stream + state). */ switchThread(threadId: string): Promise; /** Create a new thread (unbinds previous, binds the new one). */ createThread(title?: string): Promise; /** Delete a thread. If it's the active thread the session unbinds. */ deleteThread(threadId: string): Promise; /** Rename a thread. */ renameThread(threadId: string, title: string): Promise; /** Clone a thread (and its messages). The session binds to the clone. */ cloneThread(options?: { sourceThreadId?: string; title?: string; }): Promise; /** List messages for a specific thread, preserving the legacy array-returning limit overload. */ listMessages(threadId: string, limit?: number): Promise; listMessages(threadId: string, options: AgentControllerListMessagesOptions): Promise; /** * Queue a follow-up message. If the session is idle it sends immediately; * if a run is active it queues for after completion. * Pass a structured message to attach files, as with `sendMessage`. */ followUp(message: string | { content: string; files?: Array<{ data: string; mediaType: string; filename?: string; }>; }, options?: AgentControllerRequestOptions): Promise; /** Get the observational memory record for this session's thread. */ getOMRecord(): Promise['record']>; /** Change the session's resource identity. */ setResourceId(newResourceId: string): Promise; /** Get known resource IDs for this session. */ getResourceIds(): Promise['resourceIds']>; /** Get the current goal for this session's thread. */ getGoal(): Promise; /** Set a new goal objective. The agent's in-loop judge evaluates progress after each turn. */ setGoal(objective: string, options?: { judgeModelId?: string; maxRuns?: number; }): Promise; /** Update goal options (judge model, max runs, status). */ updateGoal(options: { judgeModelId?: string; maxRuns?: number; status?: 'active' | 'paused' | 'done'; }): Promise; /** Clear the current goal. */ clearGoal(): Promise; /** Get the current permission rules (per-category and per-tool policies). */ getPermissions(): Promise; /** Set the approval policy for a tool category. */ setPermissionForCategory(category: ToolCategory, policy: PermissionPolicy): Promise; /** Set the approval policy for a specific tool. */ setPermissionForTool(toolName: string, policy: PermissionPolicy): Promise; /** * Send a notification signal to this session. The agent's delivery policy * determines whether the notification wakes an idle thread, is summarised, * or is persisted for later. */ sendNotification(input: SendNotificationInput): Promise; } /** An agent controller hosted on the connected Mastra instance. */ export declare class AgentController extends BaseResource { private readonly controllerId; constructor(options: ClientOptions, controllerId: string); private basePath; /** List the modes configured on this agent controller (e.g. build, plan). */ listModes(): Promise; /** List available models on this agent controller (with auth status and use counts). */ listModels(): Promise; /** List the runs in flight on this controller, across all resources. */ listActiveRuns(): Promise; /** Get workspace status for this agent controller. */ workspaceStatus(): Promise; /** * Address the session with this `sessionId`. Sessions created without an * explicit id are addressed by their `resourceId`. */ session(sessionId: string): AgentControllerSession; } /** Pull the plain text out of an assistant message's nested content parts. */ export declare function agentControllerMessageText(message: MastraDBMessage): string; //# sourceMappingURL=agent-controller.d.ts.map