import type { ToolsInput } from '@mastra/core/agent'; import type { MessageListInput } from '@mastra/core/agent/message-list'; import type { GenerateReturn } from '@mastra/core/llm'; import { RequestContext } from '@mastra/core/request-context'; import type { FullOutput } from '@mastra/core/stream'; import type { JSONSchema7 } from 'json-schema'; import type { Body, PathParams, RouteResponse } from '../route-types.generated.js'; import type { ZodSchema, GenerateLegacyParams, GetAgentBrowserSessionResponse, GetAgentResponse, GetToolResponse, ClientOptions, AgentVersionIdentifier, StreamLegacyParams, UpdateModelParams, UpdateModelInModelListParams, ReorderModelListParams, NetworkStreamParams, StreamParamsBaseWithoutMessages, CloneAgentParams, StoredAgentResponse, StructuredOutputOptions, AgentVersionResponse, ListAgentVersionsParams, ListAgentVersionsResponse, SendAgentMessageParams, SendAgentSignalParams, QueueAgentMessageParams, QueueAgentSignalParams, SubscribeAgentThreadParams, AbortAgentThreadParams, CancelQueuedAgentMessagesParams, CancelQueuedAgentMessagesResponse, ListAgentSuspendedRunsParams, ListAgentSuspendedRunsResponse, GetAgentPlanResponse, ProcessAgentThreadStreamOptions, CreateCodeAgentVersionParams, ActivateAgentVersionResponse, CompareVersionsResponse, DeleteAgentVersionResponse, RestoreAgentVersionResponse, ClientToolsResolver } from '../types.js'; import type { JSONValue } from '../utils/ai-sdk-v4/index.js'; import { processDataStream } from '../utils/ai-sdk-v4/index.js'; import { processMastraNetworkStream, processMastraStream } from '../utils/process-mastra-stream.js'; import { BaseResource } from './base.js'; type AgentId = PathParams<'GET /agents/:agentId'>['agentId']; type ToolId = PathParams<'GET /agents/:agentId/tools/:toolId'>['toolId']; type ToolCallGenerateResponse = RouteResponse<'POST /agents/:agentId/approve-tool-call-generate'> & FullOutput; type ResumeStreamParams = StreamParamsBaseWithoutMessages & { messages?: MessageListInput; runId: string; toolCallId?: string; structuredOutput?: StructuredOutputOptions; }; type RecoverParams = { runId: string; requestContext?: Record; versions?: { agents?: Record; defaultStatus?: 'draft' | 'published'; }; }; export declare class AgentVoice extends BaseResource { private agentId; private version?; constructor(options: ClientOptions, agentId: AgentId, version?: AgentVersionIdentifier | undefined); private getQueryString; /** * Convert text to speech using the agent's voice provider * @param text - Text to convert to speech * @param options - Optional provider-specific options for speech generation * @returns Promise containing the audio data */ speak(text: string, options?: { speaker?: string; [key: string]: any; }): Promise; /** * Convert speech to text using the agent's voice provider * @param audio - Audio data to transcribe * @param options - Optional provider-specific options * @returns Promise containing the transcribed text */ listen(audio: Blob, options?: Record): Promise>; /** * Get available speakers for the agent's voice provider * @param requestContext - Optional request context to pass as query parameter * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing list of available speakers */ getSpeakers(requestContext?: RequestContext | Record): Promise>; /** * Get the listener configuration for the agent's voice provider * @param requestContext - Optional request context to pass as query parameter * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing a check if the agent has listening capabilities */ getListener(requestContext?: RequestContext | Record): Promise & { enabled: boolean; }>; } export declare class Agent extends BaseResource { private agentId; private version?; private routeOverrides?; readonly voice: AgentVoice; constructor(options: ClientOptions, agentId: AgentId, version?: AgentVersionIdentifier | undefined, routeOverrides?: { stream?: string; } | undefined); private getQueryString; private getSignalRuntimeRunKey; /** * Records that `runId` is being resumed by a request that can execute these client tools, so the * stream that is still open from before the suspension skips them. Released when the last stream * of the run closes, which is after this request returns. */ private holdResumingClientTools; /** Drops the held tool names when the last stream of the run closes. */ private trackOpenStream; private getSignalRuntimeThreadKey; private setSignalRuntimeOptions; private getSignalRuntimeOptions; private deleteSignalRuntimeOptions; private deleteLatestSignalRuntimeOptions; private prepareSignalRouteBody; private requestSignalRoute; /** * Retrieves details about the agent * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing agent details including model and instructions */ details(requestContext?: RequestContext | Record): Promise; /** * Reads a markdown plan submitted by this agent through the core submit_plan tool. * The server only serves paths under `.mastracode/plans/` and only when the * agent exposes that capability. */ readPlan(path: string, requestContext?: RequestContext | Record): Promise; /** * Probe the agent's browser session state before opening a screencast WebSocket. * * Returns `{ hasSession, screencastAvailable }`. Use this to avoid opening a WS * that would either fail (screencast packages not installed) or sit idle (no * active browser session yet). See {@link GetAgentBrowserSessionResponse}. * * @param threadId - Optional thread ID for thread-scoped browser sessions */ browserSession(threadId?: string): Promise; /** * Close the agent's browser session. * * For thread-scoped browsers, pass `threadId` to close only that thread's * session. Omit it to close the shared session (or all sessions for the agent * depending on the toolset's scope). * * @param threadId - Optional thread ID for thread-scoped browser sessions * * @remarks This is a browser-stream adapter compatibility endpoint, not a * `SERVER_ROUTES` route. Its historical deployer implementation returns * `{ success: true }`; no generated contract exists while the adapter owns it. * The public `boolean` result remains broad for backwards compatibility. */ closeBrowser(threadId?: string): Promise<{ success: boolean; }>; enhanceInstructions(instructions: string, comment: string): Promise>; sendMessage(params: SendAgentMessageParams): Promise>; queueMessage(params: QueueAgentMessageParams): Promise>; sendSignal(params: SendAgentSignalParams): Promise>; queueSignal(params: QueueAgentSignalParams): Promise>; subscribeToThread(params: SubscribeAgentThreadParams & { withRunStatus?: WITH_RUN_STATUS; }): Promise) => Promise; abort: (options?: Pick) => Promise; unsubscribe: () => void; }>; /** Stops execution of a run, including runs without a memory thread. */ abortRun(runId: string, options?: { signal?: AbortSignal; }): Promise>; abortThread(params: AbortAgentThreadParams, options?: { signal?: AbortSignal; }): Promise>; /** Cancels pending thread signals and propagates requested IDs through shared PubSub. */ cancelQueuedMessages(params: CancelQueuedAgentMessagesParams): Promise; /** * Clones this agent to a new stored agent in the database * @param params - Clone parameters including optional newId, newName, metadata, authorId, and requestContext * @returns Promise containing the created stored agent */ clone(params?: CloneAgentParams): Promise; /** * Lists all override versions for this code agent * @param params - Optional pagination and sorting parameters * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing paginated list of versions */ listVersions(params?: ListAgentVersionsParams, requestContext?: RequestContext | Record): Promise; /** * Creates a new override version snapshot for this code agent * @param params - Optional override fields and change message for the version * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing the created version */ createVersion(params?: CreateCodeAgentVersionParams, requestContext?: RequestContext | Record): Promise; /** * Retrieves a specific override version by its ID * @param versionId - The UUID of the version to retrieve * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing the version details */ getVersion(versionId: string, requestContext?: RequestContext | Record): Promise; /** * Activates a specific override version for this code agent * @param versionId - The UUID of the version to activate * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing the activated version details */ activateVersion(versionId: string, requestContext?: RequestContext | Record): Promise; /** * Restores a version by creating a new override version with the same configuration * @param versionId - The UUID of the version to restore * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing the newly created version */ restoreVersion(versionId: string, requestContext?: RequestContext | Record): Promise; /** * Deletes a specific override version * @param versionId - The UUID of the version to delete * @param requestContext - Optional request context to pass as query parameter * @returns Promise that resolves with deletion response */ deleteVersion(versionId: string, requestContext?: RequestContext | Record): Promise; /** * Compares two override versions and returns their differences * @param fromId - The UUID of the source version * @param toId - The UUID of the target version * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing the comparison results */ compareVersions(fromId: string, toId: string, requestContext?: RequestContext | Record): Promise; /** * Generates a response from the agent * @param params - Generation parameters including prompt * @returns Promise containing the generated response */ generateLegacy(params: GenerateLegacyParams & { output?: never; experimental_output?: never; }): Promise>; generateLegacy(params: GenerateLegacyParams & { output: Output; experimental_output?: never; }): Promise>; generateLegacy(params: GenerateLegacyParams & { output?: never; experimental_output: StructuredOutput; }): Promise>; generate(messages: MessageListInput, options: StreamParamsBaseWithoutMessages & { structuredOutput: StructuredOutputOptions; }): Promise>; generate(messages: MessageListInput, options?: StreamParamsBaseWithoutMessages): Promise>; private processChatResponse; /** * Streams a response from the agent * @param params - Stream parameters including prompt * @returns Promise containing the enhanced Response object with processDataStream method */ streamLegacy(params: StreamLegacyParams): Promise[0], 'stream'>) => Promise; }>; private processChatResponse_vNext; /** * Creates the consumer-facing stream for the streaming methods. Cancelling the * returned stream or the client-wide signal detaches the HTTP observer and * stops any client-tool continuations. Per-call execution cancellation is * handled separately by processStreamResponse. */ private createCancellableStream; processStreamResponse(processedParams: any, controller: ReadableStreamDefaultController, route?: string, signal?: AbortSignal): Promise; network(messages: MessageListInput, params: Omit, 'messages'>): Promise[0]['onChunk']; }) => Promise; }>; approveNetworkToolCall(params: { runId: string; model?: string; requestContext?: RequestContext | Record; }): Promise[0]['onChunk']; }) => Promise; }>; declineNetworkToolCall(params: { runId: string; model?: string; /** Optional explanation surfaced in place of the default decline message. */ reason?: string; requestContext?: RequestContext | Record; }): Promise[0]['onChunk']; }) => Promise; }>; stream(messages: MessageListInput, streamOptions: StreamParamsBaseWithoutMessages & { structuredOutput: StructuredOutputOptions; }): Promise[0]['onChunk']; }) => Promise; }>; stream(messages: MessageListInput, streamOptions: StreamParamsBaseWithoutMessages & { structuredOutput?: StructuredOutputOptions; }): Promise[0]['onChunk']; }) => Promise; }>; stream(messages: MessageListInput, streamOptions?: StreamParamsBaseWithoutMessages): Promise[0]['onChunk']; }) => Promise; }>; /** * @deprecated Use `stream(messages, { untilIdle: true })` instead. */ streamUntilIdle(messages: MessageListInput, streamOptions: StreamParamsBaseWithoutMessages & { structuredOutput: StructuredOutputOptions; maxIdleMs?: number; }): Promise[0]['onChunk']; }) => Promise; }>; streamUntilIdle(messages: MessageListInput, streamOptions: StreamParamsBaseWithoutMessages & { structuredOutput?: StructuredOutputOptions; maxIdleMs?: number; }): Promise[0]['onChunk']; }) => Promise; }>; streamUntilIdle(messages: MessageListInput, streamOptions?: StreamParamsBaseWithoutMessages & { maxIdleMs?: number; }): Promise[0]['onChunk']; }) => Promise; }>; /** * Lists suspended runs for this agent from storage — runs waiting on a * tool-call approval or on a tool that suspended. Backed by storage, so it * works after a server restart and across server instances. Pass the * returned runId to approveToolCall(), declineToolCall(), or resumeStream(). * @param params - Optional filters (threadId, resourceId, fromDate, toDate) and pagination (perPage, page) * @param requestContext - Optional request context * @returns Promise containing the matching runs and the total count before pagination */ listSuspendedRuns(params?: ListAgentSuspendedRunsParams, requestContext?: RequestContext | Record): Promise; approveToolCall(params: { runId: string; toolCallId: string; model?: string; /** Aborts the underlying request and any client-tool continuations. */ abortSignal?: AbortSignal; requestContext?: RequestContext | Record; /** Client tools the model may call after the approval decision. */ clientTools?: ToolsInput; clientToolsResolver?: ClientToolsResolver; /** * Memory thread/resource of the suspended run. Client-tool continuations go to `/stream`, * so pass the same memory as the original call to keep them on the thread. */ memory?: StreamParamsBaseWithoutMessages['memory']; }): Promise[0]['onChunk']; }) => Promise; }>; sendToolApproval(params: Omit, 'requestContext' | 'messages' | 'streamOptions'> & { requestContext?: RequestContext | Record; messages?: MessageListInput; streamOptions?: StreamParamsBaseWithoutMessages; }): Promise>; declineToolCall(params: { runId: string; toolCallId: string; model?: string; /** Aborts the underlying request and any client-tool continuations. */ abortSignal?: AbortSignal; /** Optional explanation surfaced to the model in place of the default decline message. */ reason?: string; requestContext?: RequestContext | Record; /** Client tools the model may call after the approval decision. */ clientTools?: ToolsInput; clientToolsResolver?: ClientToolsResolver; /** * Memory thread/resource of the suspended run. Client-tool continuations go to `/stream`, * so pass the same memory as the original call to keep them on the thread. */ memory?: StreamParamsBaseWithoutMessages['memory']; }): Promise[0]['onChunk']; }) => Promise; }>; /** * Observe (reconnect to) an existing agent stream. * Use this to resume receiving events after a disconnection. * * @param params.runId - The run ID to observe * @param params.offset - Run-log position to resume from. Chunks from `observe()`, and from `stream()` on * durable and evented agents, carry an `index`; pass the `index + 1` of the last chunk that has one. Chunks without an `index` * (`abort` and structured-output `object` chunks) are skipped when choosing the offset. If omitted, * replays the chunks still cached for the run, or only live chunks if the server's transport can't replay. * @returns Promise containing a streaming Response * * @example * ```typescript * const agent = client.getAgent('my-agent'); * let offset = 0; * const trackOffset = async (chunk: { index?: number }) => { * if (chunk.index === undefined) return; * offset = chunk.index + 1; * }; * * const stream = await agent.stream(messages, { runId: 'run-123' }); * await stream.processDataStream({ onChunk: trackOffset }); * * // After a dropped connection, resume where the last indexed chunk left off * const response = await agent.observe({ runId: 'run-123', offset }); * await response.processDataStream({ onChunk: trackOffset }); * ``` */ observe(params: { runId: string; offset?: number; }): Promise[0]['onChunk']; }) => Promise; }>; /** * Resumes a suspended agent stream with custom resume data. * Used to continue execution after a suspension point (e.g., workflow suspend within an agent). */ resumeStream(resumeData: JSONValue, options: ResumeStreamParams): Promise[0]['onChunk']; }) => Promise; }>; /** * Re-drives an orphaned RUNNING durable-agent run after a process restart. * * Only supported when the target agent is a durable agent (createDurableAgent). * The server rebuilds the runtime state from the persisted snapshot, replays * past chunks, and continues the loop to completion. * * Responds with 409 when the run is not orphaned: another execution still * owns it (retry once its lease lapses), it is already being recovered, or it * is suspended (use `resumeStream` instead). To follow a live run, use `observe`. */ recover(params: RecoverParams): Promise[0]['onChunk']; }) => Promise; }>; /** * @deprecated Use `resumeStream(resumeData, { untilIdle: true, ... })` instead. * * Resumes a suspended agent stream until idle with custom resume data. * Used to continue execution after a suspension point (e.g., workflow suspend within an agent). */ resumeStreamUntilIdle(resumeData: JSONValue, options: ResumeStreamParams & { maxIdleMs?: number; }): Promise[0]['onChunk']; }) => Promise; }>; /** * Approves a pending tool call and returns the complete response (non-streaming). * Used when `requireToolApproval` is enabled with generate() to allow the agent to proceed. */ approveToolCallGenerate(params: Omit, 'requestContext' | 'clientTools'> & { requestContext?: RequestContext | Record; /** Client tools the model may call after the approval decision. */ clientTools?: ToolsInput; clientToolsResolver?: ClientToolsResolver; /** * Memory of the original call. When the model calls a client tool after the decision, the * continuation is saved to this thread instead of running stateless. */ memory?: StreamParamsBaseWithoutMessages['memory']; }): Promise; /** * Declines a pending tool call and returns the complete response (non-streaming). * Used when `requireToolApproval` is enabled with generate() to prevent tool execution. */ declineToolCallGenerate(params: Omit, 'requestContext' | 'clientTools'> & { requestContext?: RequestContext | Record; /** Client tools the model may call after the approval decision. */ clientTools?: ToolsInput; clientToolsResolver?: ClientToolsResolver; /** * Memory of the original call. When the model calls a client tool after the decision, the * continuation is saved to this thread instead of running stateless. */ memory?: StreamParamsBaseWithoutMessages['memory']; }): Promise; /** * Runs executable client tools the model called after an approval decision and continues on * /generate, like generate() does. With memory the continuation sends only the new messages to the * thread. Without memory it re-sends the conversation up to the last user turn, because the resume * routes keep the earlier history server-side and drop it once the run finishes. */ private continueResumedGenerate; /** * Processes the stream response and handles tool calls */ private processStreamResponseLegacy; /** * Gets details about a specific tool available to the agent * @param toolId - ID of the tool to retrieve * @param requestContext - Optional request context to pass as query parameter * @returns Promise containing tool details */ getTool(toolId: ToolId, requestContext?: RequestContext | Record): Promise; /** * Executes a tool for the agent * @param toolId - ID of the tool to execute * @param params - Parameters required for tool execution * @returns Promise containing the tool execution results */ executeTool(toolId: PathParams<'POST /agents/:agentId/tools/:toolId/execute'>['toolId'], params: Omit, 'requestContext'> & { requestContext?: RequestContext | Record; }): Promise>; /** * Updates the model for the agent * @param params - Parameters for updating the model * @returns Promise containing the updated model */ updateModel(params: UpdateModelParams): Promise>; /** * Resets the agent's model to the original model that was set during construction * @returns Promise containing a success message */ resetModel(): Promise>; /** * Updates the model for the agent in the model list * @param params - Parameters for updating the model * @returns Promise containing the updated model */ updateModelInModelList({ modelConfigId, ...params }: UpdateModelInModelListParams): Promise>; /** * Reorders the models for the agent * @param params - Parameters for reordering the model list * @returns Promise containing the updated model list */ reorderModelList(params: ReorderModelListParams): Promise>; } export {}; //# sourceMappingURL=agent.d.ts.map