import type { UIMessage } from '../_types/@internal_ai-sdk-v4/dist/index.d.ts'; import type { StandardSchemaWithJSON } from '@mastra/schema-compat/schema'; import type { JSONSchema7 } from 'json-schema'; import type { MastraPrimitives } from '../action/index.js'; import type { AgentBackgroundConfig } from '../background-tasks/index.js'; import { MastraBase } from '../base.js'; import type { MastraBrowser } from '../browser/browser.js'; import { AgentChannels } from '../channels/agent-channels.js'; import type { MastraScorers, MastraScorer } from '../evals/index.js'; import type { PubSub } from '../events/pubsub.js'; import { MastraLLMV1 } from '../llm/model/index.js'; import type { GenerateObjectResult, GenerateTextResult, StreamObjectResult, StreamTextResult } from '../llm/model/base.types.js'; import { MastraLLMVNext } from '../llm/model/model.loop.js'; import type { ProviderOptions } from '../llm/model/provider-options.js'; import type { MastraLanguageModel, MastraLegacyLanguageModel, MastraModelConfig } from '../llm/model/shared.types.js'; import type { Mastra } from '../mastra/index.js'; import type { MastraMemory } from '../memory/memory.js'; import type { MemoryConfig } from '../memory/types.js'; import type { SendNotificationSignalInput } from '../notifications/types.js'; import type { DefinitionSource, TracingProperties, ObservabilityContext } from '../observability/index.js'; import type { ErrorProcessorOrWorkflow, InputProcessorOrWorkflow, OutputProcessorOrWorkflow, ProcessorWorkflow, Processor } from '../processors/index.js'; import { RequestContext } from '../request-context/index.js'; import type { InferStandardSchemaOutput } from '../schema/index.js'; import type { MastraAgentNetworkStream } from '../stream/index.js'; import type { FullOutput, MastraModelOutput } from '../stream/base/output.js'; import type { CoreTool } from '../tools/types.js'; import type { DynamicArgument } from '../types/index.js'; import type { MastraVoice } from '../voice/index.js'; import type { AnyWorkflow } from '../workflows/workflow.js'; import type { AnyWorkspace } from '../workspace/index.js'; import type { AgentExecutionOptions, AgentExecutionOptionsBase, MultiPrimitiveExecutionOptions, NetworkOptions } from './agent.types.js'; import type { MessageInput, MessageListInput, UIMessageWithMetadata } from './message-list/index.js'; import type { SubAgent } from './subagent.js'; import type { AgentConfig, AgentGenerateOptions, AgentStreamOptions, ToolsetsInput, ToolsInput, AgentModelManagerConfig, AgentEditorConfig, AgentInstructions, AgentMessageInput, AgentSignal, AgentStateSignalInput, AgentSubscribeToThreadOptions, AgentThreadSubscription, PublicStructuredOutputOptions, QueueAgentMessageOptions, QueueAgentMessageResult, SendAgentMessageOptions, SendAgentMessageResult, SendAgentNotificationSignalOptions, SendAgentNotificationSignalResult, SendAgentSignalOptions, SendAgentSignalResult, SendAgentStateSignalOptions, SendAgentStateSignalResult, ModelFallbackSettings, ModelWithRetries, ZodSchema } from './types.js'; export type MastraLLM = MastraLLMV1 | MastraLLMVNext; type ModelFallbacks = { id: string; model: DynamicArgument; maxRetries: number; enabled: boolean; modelSettings?: DynamicArgument; providerOptions?: DynamicArgument; headers?: DynamicArgument>; }[]; /** * The Agent class is the foundation for creating AI agents in Mastra. It provides methods for generating responses, * streaming interactions, managing memory, and handling voice capabilities. * * @example * ```typescript * import { Agent } from '@mastra/core/agent'; * import { Memory } from '@mastra/memory'; * * const agent = new Agent({ * id: 'my-agent', * name: 'My Agent', * instructions: 'You are a helpful assistant', * model: 'openai/gpt-5', * tools: { * calculator: calculatorTool, * }, * memory: new Memory(), * }); * ``` */ export declare class Agent | unknown = unknown, TEditor extends AgentEditorConfig | undefined = AgentEditorConfig | undefined> extends MastraBase implements SubAgent { #private; id: TAgentId; name: string; source?: DefinitionSource; model: DynamicArgument | ModelFallbacks; maxRetries?: number; private _agentNetworkAppend; /** * Creates a new Agent instance with the specified configuration. * * @example * ```typescript * import { Agent } from '@mastra/core/agent'; * import { Memory } from '@mastra/memory'; * * const agent = new Agent({ * id: 'weatherAgent', * name: 'Weather Agent', * instructions: 'You help users with weather information', * model: 'openai/gpt-5', * tools: { getWeather }, * memory: new Memory(), * maxRetries: 2, * }); * ``` */ constructor(config: AgentConfig); getMastraInstance(): Mastra>, Record, Record>, Record, import("../_types/@internal_core/dist/logger/index.d.ts").IMastraLogger, Record>, Record>, Record>, Record>, Record, Record> | undefined; getPubSub(): PubSub | undefined; hasOwnPubSub(): boolean; /** * Returns the background tasks configuration for this agent. */ getBackgroundTasksConfig(): AgentBackgroundConfig | undefined; /** * Returns the statically-configured sub-agents without executing dynamic * resolvers. Used by Mastra at registration time to detect whether background * tasks should be auto-enabled. Returns undefined when sub-agents are * configured via a function (those get resolved per-request). * @internal */ __getStaticAgents(): Record | undefined; /** * True when this agent has any sub-agent registry configured — either a * static record with entries OR a dynamic (function-based) resolver. * Used by Mastra at registration time to decide whether to auto-enable * background tasks; we can't know what a function resolver will return * at request time, so we enable defensively. * @internal */ __hasSubAgentsConfigured(): boolean; /** * Disables background task dispatch for this agent. Every tool call will run * synchronously in the agentic loop, regardless of the agent's or tools' * background configuration. * * Useful when this agent is invoked as a sub-agent and the parent has wrapped * the entire sub-agent invocation as a background task — you don't want the * sub-agent's own tools to also dispatch separate background tasks inside it. */ disableBackgroundTasks(): void; /** * Re-enables background task dispatch after it has been disabled. */ enableBackgroundTasks(): void; /** * Inspects a sub-agent (a child agent invoked as a tool) and derives a * ToolBackgroundConfig if any of its tools are background-eligible OR if the * sub-agent itself has a background tasks config that enables tools. * * Returns undefined when no background dispatch is warranted, so the parent * runs the sub-agent synchronously. * * @internal */ private deriveSubAgentBackgroundConfig; /** * Returns the AgentChannels instance that manages all channel adapters. * Returns null if no channels are configured. */ getChannels(): AgentChannels | null; /** * Sets the AgentChannels instance for this agent. * Used by ChannelProvider implementations to inject the channels they create. * @internal */ setChannels(agentChannels: AgentChannels): void; /** * Returns the browser instance for this agent, if configured. * Browser tools are automatically added at execution time via `convertTools()`. * This getter is primarily used by server-side code to access browser features * like screencast streaming and input injection. */ get browser(): MastraBrowser | undefined; /** * Sets or updates the browser instance for this agent. * This allows hot-swapping browser configuration without recreating the agent. * Browser tools will be automatically updated on the next execution. * * @param browser - The new browser instance, or undefined to disable browser tools */ setBrowser(browser: MastraBrowser | undefined): void; /** * Returns true if this agent was configured with its own browser instance. * Used by Harness to avoid overwriting agent-level browser configuration. */ hasOwnBrowser(): boolean; /** * Gets the skills processors to add to input processors when workspace has skills. * @internal */ private getSkillsProcessors; /** * Gets the workspace-instructions processors to add when the workspace has a * filesystem or sandbox (i.e. something to describe). * @internal */ private getWorkspaceInstructionsProcessors; /** * Returns the agents configured for this agent, resolving function-based agents if necessary. * Used in multi-agent collaboration scenarios where this agent can delegate to other agents. * * @example * ```typescript * const agents = await agent.listAgents(); * console.log(Object.keys(agents)); // ['agent1', 'agent2'] * ``` */ listAgents({ requestContext }?: { requestContext?: RequestContext; }): Record> | Promise>>; /** * Creates and returns a ProcessorRunner with resolved input/output processors. * @internal */ private getProcessorRunner; /** * Combines multiple processors into a single workflow. * Each processor becomes a step in the workflow, chained together. * If there's only one item and it's already a workflow, returns it as-is. * @internal */ private combineProcessorsIntoWorkflow; /** * Resolves and returns output processors from agent configuration. * All processors are combined into a single workflow for consistency. * @internal */ private listResolvedOutputProcessors; /** * Resolves input processors from agent configuration in execution order. * @internal */ private resolveInputProcessors; /** * Resolves and returns input processors from agent configuration. * All processors are combined into a single workflow for consistency. * @internal */ private listResolvedInputProcessors; /** * Resolves and returns input processors for the provider-boundary LLM request hook. * These processors stay uncombined because processLLMRequest runs after conversion to model prompt format. * @internal */ private listResolvedLLMRequestProcessors; /** * Returns the input processors for this agent, resolving function-based processors if necessary. */ listInputProcessors(requestContext?: RequestContext): Promise; /** * Returns the output processors for this agent, resolving function-based processors if necessary. */ listOutputProcessors(requestContext?: RequestContext): Promise; /** * Returns the error processors for this agent, resolving function-based processors if necessary. */ listErrorProcessors(requestContext?: RequestContext): Promise; /** * Resolves a processor by its ID from both input and output processors. * This method resolves dynamic processor functions and includes memory-derived processors. * Returns the processor if found, null otherwise. * * @example * ```typescript * const omProcessor = await agent.resolveProcessorById('observational-memory'); * if (omProcessor) { * // Observational memory is configured * } * ``` */ resolveProcessorById(processorId: TId, requestContext?: RequestContext): Promise | null>; /** * Returns only the user-configured input processors, excluding memory-derived processors. * Useful for scenarios where memory processors should not be applied (e.g., network routing agents). * * Unlike `listInputProcessors()` which includes both memory and configured processors, * this method returns only what was explicitly configured via the `inputProcessors` option. */ listConfiguredInputProcessors(requestContext?: RequestContext): Promise; /** * Returns only the user-configured output processors, excluding memory-derived processors. * Useful for scenarios where memory processors should not be applied (e.g., network routing agents). * * Unlike `listOutputProcessors()` which includes both memory and configured processors, * this method returns only what was explicitly configured via the `outputProcessors` option. */ listConfiguredOutputProcessors(requestContext?: RequestContext): Promise; /** * Returns the IDs of the raw configured input, output, and error processors, * without combining them into workflows. Used by the editor to clone * agent processor configuration to storage. */ getConfiguredProcessorIds(requestContext?: RequestContext): Promise<{ inputProcessorIds: string[]; outputProcessorIds: string[]; errorProcessorIds: string[]; }>; /** * Returns configured processor workflows for registration with Mastra. * This excludes memory-derived processors to avoid triggering memory factory functions. * @internal */ getConfiguredProcessorWorkflows(): Promise; /** * Returns whether this agent has its own memory configured. * * @example * ```typescript * if (agent.hasOwnMemory()) { * const memory = await agent.getMemory(); * } * ``` */ hasOwnMemory(): boolean; /** * Gets the memory instance for this agent, resolving function-based memory if necessary. * The memory system enables conversation persistence, semantic recall, and working memory. * * @example * ```typescript * const memory = await agent.getMemory(); * if (memory) { * // Memory is configured * } * ``` */ getMemory({ requestContext }?: { requestContext?: RequestContext; }): Promise; /** * Checks if this agent has its own workspace configured. * * @example * ```typescript * if (agent.hasOwnWorkspace()) { * const workspace = await agent.getWorkspace(); * } * ``` */ hasOwnWorkspace(): boolean; /** * Gets the workspace instance for this agent, resolving function-based workspace if necessary. * The workspace provides filesystem and sandbox capabilities for file operations and code execution. * * @example * ```typescript * const workspace = await agent.getWorkspace(); * if (workspace) { * await workspace.writeFile('/data.json', JSON.stringify(data)); * const result = await workspace.executeCode('console.log("Hello")'); * } * ``` */ getWorkspace({ requestContext, }?: { requestContext?: RequestContext; }): Promise; get voice(): MastraVoice; /** * Gets the request context schema for this agent. * Returns the Zod schema used to validate request context values, or undefined if not set. */ get requestContextSchema(): StandardSchemaWithJSON | undefined; /** * Gets the workflows configured for this agent, resolving function-based workflows if necessary. * Workflows are step-based execution flows that can be triggered by the agent. * * @example * ```typescript * const workflows = await agent.listWorkflows(); * const workflow = workflows['myWorkflow']; * ``` */ listWorkflows({ requestContext, }?: { requestContext?: RequestContext; }): Promise>; listScorers({ requestContext, }?: { requestContext?: RequestContext; }): Promise; /** * Gets the voice instance for this agent with tools and instructions configured. * The voice instance enables text-to-speech and speech-to-text capabilities. * * When `voice` is configured as a resolver (`({ requestContext }) => new SomeVoice(...)`), * each call resolves a fresh, session-owned instance. The resolver is responsible for * configuring its own tools/instructions/request context, so this method does not mutate * the resolved instance. The caller owns the lifecycle (e.g. `disconnect()`) of that instance. * * A static `MastraVoice` is shared across calls and is configured with the current * tools/instructions on each call (appropriate for one-shot TTS). * * @example * ```typescript * const voice = await agent.getVoice(); * const audioStream = await voice.speak('Hello world'); * ``` */ getVoice({ requestContext }?: { requestContext?: RequestContext; }): Promise>; /** * Gets the instructions for this agent, resolving function-based instructions if necessary. * Instructions define the agent's behavior and capabilities. * * @example * ```typescript * const instructions = await agent.getInstructions(); * console.log(instructions); // 'You are a helpful assistant' * ``` */ getInstructions({ requestContext }?: { requestContext?: RequestContext; }): AgentInstructions | Promise; private getMcpServerGuidance; /** * Returns the description of the agent. * * @example * ```typescript * const description = agent.getDescription(); * console.log(description); // 'A helpful weather assistant' * ``` */ getDescription(): string; /** * Gets the metadata for this agent, resolving function-based metadata if necessary. * Metadata is a classification bag for clients and is never read by the agent runtime. * * @example * ```typescript * const metadata = await agent.getMetadata(); * console.log(metadata?.type); // 'support' * ``` */ getMetadata({ requestContext }?: { requestContext?: RequestContext; }): Record | undefined | Promise | undefined>; /** * Gets the legacy handler instance, initializing it lazily if needed. * @internal */ private getLegacyHandler; /** * Gets the default generate options for the legacy generate method. * These options are used as defaults when calling `generateLegacy()` without explicit options. * * @example * ```typescript * const options = await agent.getDefaultGenerateOptionsLegacy(); * console.log(options.maxSteps); // 5 * ``` */ getDefaultGenerateOptionsLegacy({ requestContext, }?: { requestContext?: RequestContext; }): AgentGenerateOptions | Promise; /** * Gets the default stream options for the legacy stream method. * These options are used as defaults when calling `streamLegacy()` without explicit options. * * @example * ```typescript * const options = await agent.getDefaultStreamOptionsLegacy(); * console.log(options.temperature); // 0.7 * ``` */ getDefaultStreamOptionsLegacy({ requestContext, }?: { requestContext?: RequestContext; }): AgentStreamOptions | Promise; /** * Gets the default options for this agent, resolving function-based options if necessary. * These options are used as defaults when calling `stream()` or `generate()` without explicit options. * * @example * ```typescript * const options = await agent.getDefaultStreamOptions(); * console.log(options.maxSteps); // 5 * ``` */ getDefaultOptions({ requestContext }?: { requestContext?: RequestContext; }): AgentExecutionOptions | Promise>; /** * Gets the default NetworkOptions for this agent, resolving function-based options if necessary. * These options are used as defaults when calling `network()` without explicit options. * * @returns NetworkOptions containing maxSteps, completion (CompletionConfig), and other network settings * * @example * ```typescript * const options = await agent.getDefaultNetworkOptions(); * console.log(options.maxSteps); // 20 * console.log(options.completion?.scorers); // [testsScorer, buildScorer] * ``` */ getDefaultNetworkOptions({ requestContext }?: { requestContext?: RequestContext; }): NetworkOptions | Promise; /** * Gets the tools configured for this agent, resolving function-based tools if necessary. * Tools extend the agent's capabilities, allowing it to perform specific actions or access external systems. * * Note: Browser tools are NOT included here. They are added at execution time via `convertTools()`. * * @example * ```typescript * const tools = await agent.listTools(); * console.log(Object.keys(tools)); // ['calculator', 'weather', ...] * ``` */ listTools({ requestContext }?: { requestContext?: RequestContext; }): TTools | Promise; /** * Gets or creates an LLM instance based on the provided or configured model. * The LLM wraps the language model with additional capabilities like error handling. * * @example * ```typescript * const llm = await agent.getLLM(); * // Use with custom model * const customLlm = await agent.getLLM({ model: 'openai/gpt-5' }); * ``` */ getLLM({ requestContext, model, }?: { requestContext?: RequestContext; model?: DynamicArgument; }): MastraLLM | Promise; /** * Resolves a model configuration to a LanguageModel instance * @param modelConfig The model configuration (magic string, config object, or LanguageModel) * @returns A LanguageModel instance * @internal */ private resolveModelConfig; /** * Type guard to check if an array is already normalized to ModelFallbacks. * Used to optimize and avoid double normalization. * @internal */ private isModelFallbacks; /** * Normalizes model arrays into the internal fallback shape. * @internal */ private normalizeModelFallbacks; /** * Builds a single normalized fallback entry from a user-supplied `ModelWithRetries`. * Shared by the constructor and `normalizeModelFallbacks` to keep the mapping in one place. * @internal */ private static toFallbackEntry; /** * Ensures a model can participate in prepared multi-model execution. * @internal */ private assertSupportsPreparedModels; /** * Resolves model configuration that may be a dynamic function returning a single model or array of models. * Supports DynamicArgument for both MastraModelConfig and ModelWithRetries[]. * Normalizes fallback arrays while preserving single-model semantics. * * @internal */ private resolveModelSelection; /** * Gets the model instance, resolving it if it's a function or model configuration. * When the agent has multiple models configured, returns the first enabled model. * * @example * ```typescript * const model = await agent.getModel(); * // Get with custom model config * const customModel = await agent.getModel({ * modelConfig: 'openai/gpt-5' * }); * ``` */ getModel({ requestContext, modelConfig, }?: { requestContext?: RequestContext; modelConfig?: DynamicArgument | ModelFallbacks; }): MastraLanguageModel | MastraLegacyLanguageModel | Promise; /** * Gets the list of configured models if the agent has multiple models, otherwise returns null. * Used for model fallback and load balancing scenarios. * * @example * ```typescript * const models = await agent.getModelList(); * if (models) { * console.log(models.map(m => m.id)); * } * ``` */ getModelList(requestContext?: RequestContext): Promise | null>; /** * Updates the agent's instructions. * @internal */ __updateInstructions(newInstructions: DynamicArgument): void; /** * Updates the agent's model configuration. * @internal */ __updateModel({ model }: { model: DynamicArgument | ModelFallbacks; }): void; /** * Resets the agent's model to the original model set during construction. * Clones arrays to prevent reordering mutations from affecting the original snapshot. * @internal */ __resetToOriginalModel(): void; /** * Returns the editor ownership config for this agent. * @internal */ __getEditorConfig(): AgentEditorConfig | undefined; /** * Returns a snapshot of the raw field values that may be overridden by stored config. * Used by the editor to save/restore code defaults externally. * @internal */ __getOverridableFields(): { instructions: DynamicArgument; model: DynamicArgument | ModelFallbacks; tools: DynamicArgument; workspace: DynamicArgument; }; reorderModels(modelIds: string[]): void; updateModelInModelList({ id, model, enabled, maxRetries, }: { id: string; model?: DynamicArgument; enabled?: boolean; maxRetries?: number; }): void; /** * Registers logger primitives with the agent. * @internal */ __registerPrimitives(p: MastraPrimitives): void; /** * Registers the Mastra instance with the agent. * @internal */ __registerMastra(mastra: Mastra): void; /** * Set the concrete tools for the agent * @param tools * @internal */ __setTools(tools: DynamicArgument): void; /** * Create a lightweight clone of this agent that can be independently mutated * without affecting the original instance. Used by the editor to apply * version overrides without mutating the singleton agent. * @internal */ __fork(): Agent; /** * Extract plain text lines from a single message's parts array. * Modeled after observational memory's formatObserverMessage — switches on * part type, emits role-prefixed text, and drops all metadata. */ private formatMessagePartsForTitle; /** * Format an array of UI messages into plain text for title generation. * Like observational memory's formatMessagesForObserver — loops over messages, * formats each one's parts with role context, and joins the results. */ formatMessagesForTitle(messages: Array<{ role: string; content?: string; parts?: Array<{ type: string; [key: string]: any; }>; }>): string; generateTitleFromUserMessage({ message, messages, requestContext, model, instructions, ...rest }: { message?: string | MessageInput; messages?: Array<{ role: string; content?: string; parts?: Array<{ type: string; [key: string]: any; }>; }>; requestContext?: RequestContext; model?: DynamicArgument; instructions?: DynamicArgument; } & Partial): Promise; getMostRecentUserMessage(messages: Array): UIMessage | UIMessageWithMetadata | undefined; genTitle(userMessage: string | MessageInput | undefined, requestContext: RequestContext, observabilityContext: ObservabilityContext, model?: DynamicArgument, instructions?: DynamicArgument, uiMessages?: Array<{ role: string; content?: string; parts?: Array<{ type: string; [key: string]: any; }>; }>): Promise; __setMemory(memory: DynamicArgument): void; __setPubSub(pubsub: PubSub): void; __setWorkspace(workspace: DynamicArgument): void; /** * Retrieves and converts memory tools to CoreTool format. * @internal */ private listMemoryTools; /** * Lists workspace tools if a workspace is configured. * @internal */ private listWorkspaceTools; /** * Returns tools provided by the agent's channels (e.g. discord_send_message). * @internal */ private listChannelTools; /** * Returns skill tools (skill, skill_search, skill_read) when the workspace * has skills configured. These are added at the Agent level (like workspace * tools) rather than inside a processor, so they persist across turns and * survive serialization across tool-approval pauses. * @internal */ private listSkillTools; /** * Lists browser tools if a browser is configured. * @internal */ private listBrowserTools; /** * Returns tools that input processors loaded into their own state. * These tools need to be available before a resumed approval call enters toolCallStep. * Otherwise the resumed workflow bypasses processInputStep and loses dynamic executors. * @internal */ private listInputProcessorLoadedTools; /** * Executes input processors on the message list before LLM processing. * @internal */ private __runInputProcessors; /** * Runs processInputStep phase on input processors. * Used by legacy path to execute per-step input processing (e.g., Observational Memory) * that would otherwise only run in the v5 agentic loop. * @internal */ private __runProcessInputStep; /** * Executes output processors on the message list after LLM processing. * @internal */ private __runOutputProcessors; /** * Fetches remembered messages from memory for the current thread. * @internal */ private getMemoryMessages; /** * Retrieves and converts assigned tools to CoreTool format. * @internal */ private listAssignedTools; /** * Retrieves and converts toolset tools to CoreTool format. * @internal */ private listToolsets; /** * Retrieves and converts client-side tools to CoreTool format. * @internal */ private listClientTools; /** * Strips tool parts from messages. * * When a supervisor delegates to a sub-agent, the parent's conversation * history may include tool_call parts for its own delegation tools * (agent-* and workflow-*) and other tools. The sub-agent doesn't have these tools, * so sending references to them causes model providers to reject or * mishandle the request. * * This function removes those parts while preserving all other * conversation context (user messages, assistant text, etc.). * @internal */ private stripParentToolParts; /** * Retrieves and converts agent tools to CoreTool format. * @internal */ private listAgentTools; /** * Retrieves and converts workflow tools to CoreTool format. * @internal */ private listWorkflowTools; /** * Get tools for execution. * * This method assembles all tools from various sources (assigned tools, memory tools, * toolsets, client tools, agent tools, workflow tools) into a unified CoreTool dictionary. * * This is useful for durable execution where tools need to be reconstructed from * serialized state rather than stored in a registry. * * @param options - Options for tool assembly * @returns A record of tool names to CoreTool instances */ getToolsForExecution(options: { toolsets?: ToolsetsInput; clientTools?: ToolsInput; threadId?: string; resourceId?: string; runId?: string; requestContext?: RequestContext; memoryConfig?: MemoryConfig; autoResumeSuspendedTools?: boolean; }): Promise>; /** * Assembles all tools from various sources into a unified CoreTool dictionary. * @internal */ private convertTools; /** * Formats and validates tool names to comply with naming restrictions. * @internal */ private formatTools; /** * Resolves scorer name references to actual scorer instances from Mastra. * @internal */ private resolveOverrideScorerReferences; /** * Resolves and prepares model configurations for the LLM. * @internal */ private prepareModels; /** @internal */ private resolveFallbackDynamic; /** * Executes a network loop where multiple agents can collaborate to handle messages. * The routing agent delegates tasks to appropriate sub-agents based on the conversation. * * @experimental * * @example * ```typescript * const result = await agent.network('Find the weather in Tokyo and plan an activity', { * memory: { * thread: 'user-123', * resource: 'my-app' * }, * maxSteps: 10 * }); * * for await (const chunk of result.stream) { * console.log(chunk); * } * ``` */ network(messages: MessageListInput, options?: MultiPrimitiveExecutionOptions): Promise>; network(messages: MessageListInput, options?: MultiPrimitiveExecutionOptions): Promise>; /** * Resumes a suspended network loop where multiple agents can collaborate to handle messages. * The routing agent delegates tasks to appropriate sub-agents based on the conversation. * * @experimental * * @example * ```typescript * const result = await agent.resumeNetwork({ approved: true }, { * runId: 'previous-run-id', * memory: { * thread: 'user-123', * resource: 'my-app' * }, * maxSteps: 10 * }); * * for await (const chunk of result.stream) { * console.log(chunk); * } * ``` */ resumeNetwork(resumeData: any, options: Omit & { runId: string; }): Promise>; /** * Approves a pending network tool call and resumes execution. * Used when `tool.requireApproval` is enabled to allow the agent to proceed with a tool call. * * @example * ```typescript * const stream = await agent.approveNetworkToolCall({ * runId: 'pending-run-id' * }); * * for await (const chunk of stream) { * console.log(chunk); * } * ``` */ approveNetworkToolCall(options: Omit & { runId: string; }): Promise>; /** * Declines a pending network tool call and resumes execution. * Used when `tool.requireApproval` is enabled to allow the agent to proceed with a tool call. * * @example * ```typescript * const stream = await agent.declineNetworkToolCall({ * runId: 'pending-run-id' * }); * * for await (const chunk of stream) { * console.log(chunk); * } * ``` */ declineNetworkToolCall(options: Omit & { runId: string; }): Promise>; generate, T extends InferStandardSchemaOutput = InferStandardSchemaOutput>(messages: MessageListInput, options: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; } & { model?: DynamicArgument; }): Promise>; generate(messages: MessageListInput, options: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; } & { model?: DynamicArgument; }): Promise>; generate(messages: MessageListInput, options: AgentExecutionOptionsBase & { structuredOutput?: never; } & { model?: DynamicArgument; }): Promise>; generate(messages: MessageListInput): Promise>; /** * @experimental Agent signals are experimental and may change in a future release. */ subscribeToThread(options: AgentSubscribeToThreadOptions): Promise>; getActiveThreadRunId(options: AgentSubscribeToThreadOptions): string | undefined; abortThreadStream(options: AgentSubscribeToThreadOptions): boolean; abortRunStream(runId: string): boolean; /** * @experimental Agent message APIs are experimental and may change in a future release. */ sendMessage(message: AgentMessageInput, target: SendAgentMessageOptions): SendAgentMessageResult; /** * @experimental Agent message APIs are experimental and may change in a future release. */ queueMessage(message: AgentMessageInput, target: QueueAgentMessageOptions): QueueAgentMessageResult; /** * @experimental Agent state signal APIs are experimental and may change in a future release. */ sendStateSignal(state: AgentStateSignalInput, target: SendAgentStateSignalOptions): Promise; /** * @experimental Agent notification signal APIs are experimental and may change in a future release. */ sendNotificationSignal(notification: SendNotificationSignalInput, target: SendAgentNotificationSignalOptions): Promise; /** * @experimental Agent signals are experimental and may change in a future release. */ sendSignal(signal: AgentSignal, target: SendAgentSignalOptions): SendAgentSignalResult; stream, T extends InferStandardSchemaOutput = InferStandardSchemaOutput>(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; } & { model?: DynamicArgument; }): Promise>; stream(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; } & { model?: DynamicArgument; }): Promise>; stream(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase & { structuredOutput?: never; } & { model?: DynamicArgument; }): Promise>; stream(messages: MessageListInput): Promise>; /** * @deprecated Use `stream(messages, { untilIdle: true })` instead. * * Streams the agent's response and keeps the stream open until all * background tasks dispatched during this turn (and any triggered by * follow-up turns) complete. When a background task finishes, its tool * result is injected into memory by the tool-call-step's `onResult` hook, * and this method re-enters the agentic loop via `agent.stream([], ...)` * so the LLM can process the result immediately — without waiting for a * new user message. * * Invariants: * - Only one inner LLM stream runs at a time (a completion arriving * mid-turn is queued and processed after the current turn ends). * - When there are no running background tasks and no queued completions, * the outer stream closes. * - If the agent has no memory configured, this falls through to a plain * `stream()` call since continuation requires memory. * * Return shape: `streamUntilIdle` returns a `MastraModelOutput` that looks * like the one from `stream()` — *only* `fullStream` spans the initial * turn **and** any auto-continuations. Aggregate properties (`text`, * `toolCalls`, `toolResults`, `finishReason`, `messageList`, * `getFullOutput()`) still resolve against the **first turn's** internal * buffer. If you need an aggregate view across continuations, consume * `fullStream` yourself and accumulate — or follow up with `agent.generate` * once the stream closes. * * @example * ```typescript * const stream = await agent.streamUntilIdle('Research solana for me', { * memory: { thread: 't1', resource: 'u1' }, * }); * * for await (const chunk of stream.fullStream) { * // chunks from the initial turn AND any continuation turns * // triggered by background task completions flow through here * } * ``` */ streamUntilIdle, T extends InferStandardSchemaOutput = InferStandardSchemaOutput>(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; maxIdleMs?: number; } & { model?: DynamicArgument; }): Promise>; streamUntilIdle(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; maxIdleMs?: number; } & { model?: DynamicArgument; }): Promise>; streamUntilIdle(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase & { structuredOutput?: never; maxIdleMs?: number; } & { model?: DynamicArgument; }): Promise>; streamUntilIdle(messages: MessageListInput): Promise>; /** * @deprecated Use `resumeStream(resumeData, { untilIdle: true, ... })` instead. * * Resume-flavored counterpart to {@link streamUntilIdle}. Resumes a * previously suspended stream identified by `streamOptions.runId`, then * keeps the outer stream open across any continuations that background * task completions trigger — same idle-loop semantics as `streamUntilIdle`. * * Use this when (a) the suspended run produced a background task whose * completion should drive a follow-up turn, or (b) a tool dispatched as a * background task from inside the resume itself needs the outer stream to * stay open until it finishes. * * @example * ```typescript * const stream = await agent.resumeStreamUntilIdle( * { approved: true }, * { runId: 'previous-run-id', memory: { thread: 't1', resource: 'u1' } }, * ); * * for await (const chunk of stream.fullStream) { * // chunks from the resumed turn AND any continuation turns * } * ``` */ resumeStreamUntilIdle, T extends InferStandardSchemaOutput = InferStandardSchemaOutput>(resumeData: any, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; toolCallId?: string; /** Close the outer stream after this many ms of idleness. Default: 5 minutes. */ maxIdleMs?: number; } & { model?: DynamicArgument; }): Promise>; resumeStreamUntilIdle(resumeData: any, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; toolCallId?: string; maxIdleMs?: number; } & { model?: DynamicArgument; }): Promise>; resumeStreamUntilIdle(resumeData: any, streamOptions: AgentExecutionOptionsBase & { structuredOutput?: never; toolCallId?: string; maxIdleMs?: number; } & { model?: DynamicArgument; }): Promise>; /** * Resumes a previously suspended stream execution. * Used to continue execution after a suspension point (e.g., tool approval, workflow suspend). * * @example * ```typescript * // Resume after suspension * const stream = await agent.resumeStream( * { approved: true }, * { runId: 'previous-run-id' } * ); * ``` */ resumeStream, T extends InferStandardSchemaOutput = InferStandardSchemaOutput>(resumeData: any, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; toolCallId?: string; } & { model?: DynamicArgument; }): Promise>; resumeStream(resumeData: any, streamOptions: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; toolCallId?: string; } & { model?: DynamicArgument; }): Promise>; resumeStream(resumeData: any, streamOptions: AgentExecutionOptionsBase & { structuredOutput?: never; toolCallId?: string; } & { model?: DynamicArgument; }): Promise>; /** * Resumes a previously suspended generate execution. * Used to continue execution after a suspension point (e.g., tool approval, workflow suspend). * * @example * ```typescript * // Resume after suspension * const stream = await agent.resumeGenerate( * { approved: true }, * { runId: 'previous-run-id' } * ); * ``` */ resumeGenerate, T extends InferStandardSchemaOutput = InferStandardSchemaOutput>(resumeData: any, options: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; toolCallId?: string; } & { model?: DynamicArgument; }): Promise>; resumeGenerate(resumeData: any, options: AgentExecutionOptionsBase & { structuredOutput: PublicStructuredOutputOptions; toolCallId?: string; } & { model?: DynamicArgument; }): Promise>; resumeGenerate(resumeData: any, options: AgentExecutionOptionsBase & { structuredOutput?: never; toolCallId?: string; } & { model?: DynamicArgument; }): Promise>; /** * Approves a pending tool call and resumes execution. * Used when `requireToolApproval` is enabled to allow the agent to proceed with a tool call. * * @example * ```typescript * const stream = await agent.approveToolCall({ * runId: 'pending-run-id' * }); * * for await (const chunk of stream) { * console.log(chunk); * } * ``` */ approveToolCall(options: AgentExecutionOptions & { runId: string; toolCallId?: string; }): Promise>; sendToolApproval(options: AgentExecutionOptions & { threadId: string; resourceId: string; toolCallId?: string; approved: boolean; messages?: MessageListInput; streamOptions?: AgentExecutionOptions; }): Promise<{ accepted: true; runId: string; toolCallId?: string; }>; /** * Declines a pending tool call and resumes execution. * Used when `requireToolApproval` is enabled to prevent the agent from executing a tool call. * * @example * ```typescript * const stream = await agent.declineToolCall({ * runId: 'pending-run-id' * }); * * for await (const chunk of stream) { * console.log(chunk); * } * ``` */ declineToolCall(options: AgentExecutionOptions & { runId: string; toolCallId?: string; }): Promise>; /** * Approves a pending tool call and returns the complete result (non-streaming). * Used when `requireToolApproval` is enabled with generate() to allow the agent to proceed. * * @example * ```typescript * const output = await agent.generate('Find user', { requireToolApproval: true }); * if (output.finishReason === 'suspended') { * const result = await agent.approveToolCallGenerate({ * runId: output.runId, * toolCallId: output.suspendPayload.toolCallId * }); * console.log(result.text); * } * ``` */ approveToolCallGenerate(options: AgentExecutionOptions & { runId: string; toolCallId?: string; }): Promise['getFullOutput']>>>; /** * Declines a pending tool call and returns the complete result (non-streaming). * Used when `requireToolApproval` is enabled with generate() to prevent tool execution. * * @example * ```typescript * const output = await agent.generate('Find user', { requireToolApproval: true }); * if (output.finishReason === 'suspended') { * const result = await agent.declineToolCallGenerate({ * runId: output.runId, * toolCallId: output.suspendPayload.toolCallId * }); * console.log(result.text); * } * ``` */ declineToolCallGenerate(options: AgentExecutionOptions & { runId: string; toolCallId?: string; }): Promise['getFullOutput']>>>; /** * Legacy implementation of generate method using AI SDK v4 models. * Use this method if you need to continue using AI SDK v4 models. * * @example * ```typescript * const result = await agent.generateLegacy('What is 2+2?'); * console.log(result.text); * ``` */ generateLegacy(messages: MessageListInput, args?: AgentGenerateOptions & { output?: never; experimental_output?: never; model?: DynamicArgument; }): Promise>; generateLegacy(messages: MessageListInput, args?: AgentGenerateOptions & { output?: OUTPUT; experimental_output?: never; model?: DynamicArgument; }): Promise>; generateLegacy(messages: MessageListInput, args?: AgentGenerateOptions & { output?: never; experimental_output?: EXPERIMENTAL_OUTPUT; model?: DynamicArgument; }): Promise>; /** * Legacy implementation of stream method using AI SDK v4 models. * Use this method if you need to continue using AI SDK v4 models. * * @example * ```typescript * const result = await agent.streamLegacy('Tell me a story'); * for await (const chunk of result.textStream) { * process.stdout.write(chunk); * } * ``` */ streamLegacy(messages: MessageListInput, args?: AgentStreamOptions & { output?: never; experimental_output?: never; model?: DynamicArgument; }): Promise>; streamLegacy(messages: MessageListInput, args?: AgentStreamOptions & { output?: OUTPUT; experimental_output?: never; model?: DynamicArgument; }): Promise & TracingProperties>; streamLegacy(messages: MessageListInput, args?: AgentStreamOptions & { output?: never; experimental_output?: EXPERIMENTAL_OUTPUT; model?: DynamicArgument; }): Promise & { partialObjectStream: StreamTextResult['experimental_partialOutputStream']; }>; /** * Resolves the configuration for title generation. * @internal */ resolveTitleGenerationConfig(generateTitleConfig: boolean | { model?: DynamicArgument; instructions?: DynamicArgument; minMessages?: number; } | undefined): { shouldGenerate: boolean; model?: DynamicArgument; instructions?: DynamicArgument; minMessages?: number; }; /** * Resolves title generation instructions, handling both static strings and dynamic functions * @internal */ resolveTitleInstructions(requestContext: RequestContext, instructions?: DynamicArgument): Promise; } export {}; //# sourceMappingURL=agent.d.ts.map