UNPKG

@mastra/core

Version:

Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

1,196 lines 53.4 kB
import type { UIMessage } from '../_types/@internal_ai-sdk-v4/dist/index.js'; 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 { 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, AgentInstructions, AgentSignal, AgentSubscribeToThreadOptions, AgentThreadSubscription, PublicStructuredOutputOptions, SendAgentSignalOptions, SendAgentSignalResult, ModelFallbackSettings, ModelWithRetries, ZodSchema } from './types.js'; export type MastraLLM = MastraLLMV1 | MastraLLMVNext; type ModelFallbacks = { id: string; model: DynamicArgument<MastraModelConfig>; maxRetries: number; enabled: boolean; modelSettings?: DynamicArgument<ModelFallbackSettings>; providerOptions?: DynamicArgument<ProviderOptions>; headers?: DynamicArgument<Record<string, string>>; }[]; /** * 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<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TOutput = undefined, TRequestContext extends Record<string, any> | unknown = unknown> extends MastraBase implements SubAgent<TAgentId, TRequestContext> { #private; id: TAgentId; name: string; source?: DefinitionSource; model: DynamicArgument<MastraModelConfig | ModelWithRetries[], TRequestContext> | 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<TAgentId, TTools, TOutput, TRequestContext>); getMastraInstance(): Mastra<Record<string, Agent<any, ToolsInput, undefined, unknown>>, Record<string, AnyWorkflow>, Record<string, import("../vector").MastraVector<any>>, Record<string, import("../tts").MastraTTS>, import("../logger").IMastraLogger, Record<string, import("../mcp").MCPServerBase<any>>, Record<string, MastraScorer<any, any, any, any>>, Record<string, import("../tools").ToolAction<any, any, any, any, any, any, unknown>>, Record<string, Processor<any, unknown>>, Record<string, MastraMemory>, Record<string, import("../channels").ChannelProvider>> | 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<string, SubAgent> | 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<string, SubAgent<string, TRequestContext>> | Promise<Record<string, SubAgent<string, TRequestContext>>>; /** * 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<InputProcessorOrWorkflow[]>; /** * Returns the output processors for this agent, resolving function-based processors if necessary. */ listOutputProcessors(requestContext?: RequestContext): Promise<OutputProcessorOrWorkflow[]>; /** * Returns the error processors for this agent, resolving function-based processors if necessary. */ listErrorProcessors(requestContext?: RequestContext): Promise<ErrorProcessorOrWorkflow[]>; /** * 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<TId extends string = string>(processorId: TId, requestContext?: RequestContext): Promise<Processor<TId> | 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<InputProcessorOrWorkflow[]>; /** * 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<OutputProcessorOrWorkflow[]>; /** * 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<ProcessorWorkflow[]>; /** * 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<MastraMemory | undefined>; /** * 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<AnyWorkspace | undefined>; get voice(): MastraVoice<unknown, unknown, unknown, ToolsInput, import("../voice").VoiceEventMap, unknown>; /** * 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<TRequestContext> | 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<Record<string, AnyWorkflow>>; listScorers({ requestContext, }?: { requestContext?: RequestContext; }): Promise<MastraScorers>; /** * Gets the voice instance for this agent with tools and instructions configured. * The voice instance enables text-to-speech and speech-to-text capabilities. * * @example * ```typescript * const voice = await agent.getVoice(); * const audioStream = await voice.speak('Hello world'); * ``` */ getVoice({ requestContext }?: { requestContext?: RequestContext; }): Promise<MastraVoice<unknown, unknown, unknown, ToolsInput, import("../voice").VoiceEventMap, unknown>>; /** * 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<AgentInstructions>; /** * 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<string, unknown> | undefined | Promise<Record<string, unknown> | 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<AgentGenerateOptions>; /** * 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<AgentStreamOptions>; /** * 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<TOutput> | Promise<AgentExecutionOptions<TOutput>>; /** * 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<NetworkOptions>; /** * 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<TTools>; /** * 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<MastraModelConfig, TRequestContext>; }): MastraLLM | Promise<MastraLLM>; /** * 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<MastraModelConfig | ModelWithRetries[], TRequestContext> | ModelFallbacks; }): MastraLanguageModel | MastraLegacyLanguageModel | Promise<MastraLanguageModel | MastraLegacyLanguageModel>; /** * 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<Array<AgentModelManagerConfig> | null>; /** * Updates the agent's instructions. * @internal */ __updateInstructions(newInstructions: DynamicArgument<AgentInstructions, any>): void; /** * Updates the agent's model configuration. * @internal */ __updateModel({ model }: { model: DynamicArgument<MastraModelConfig, TRequestContext> | 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 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<import("../llm").SystemMessage, TRequestContext>; model: DynamicArgument<MastraModelConfig | ModelWithRetries[], TRequestContext> | ModelFallbacks; tools: DynamicArgument<TTools, TRequestContext>; workspace: DynamicArgument<AnyWorkspace | undefined, TRequestContext>; }; reorderModels(modelIds: string[]): void; updateModelInModelList({ id, model, enabled, maxRetries, }: { id: string; model?: DynamicArgument<MastraModelConfig>; 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<TTools, any>): 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<TAgentId, TTools, TOutput, TRequestContext>; /** * 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<MastraModelConfig, TRequestContext>; instructions?: DynamicArgument<string>; } & Partial<ObservabilityContext>): Promise<string | undefined>; getMostRecentUserMessage(messages: Array<UIMessage | UIMessageWithMetadata>): UIMessage | UIMessageWithMetadata | undefined; genTitle(userMessage: string | MessageInput | undefined, requestContext: RequestContext, observabilityContext: ObservabilityContext, model?: DynamicArgument<MastraModelConfig, TRequestContext>, instructions?: DynamicArgument<string>, uiMessages?: Array<{ role: string; content?: string; parts?: Array<{ type: string; [key: string]: any; }>; }>): Promise<string | undefined>; __setMemory(memory: DynamicArgument<MastraMemory, TRequestContext>): void; __setPubSub(pubsub: PubSub): void; __setWorkspace(workspace: DynamicArgument<AnyWorkspace | undefined, TRequestContext>): 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<Record<string, CoreTool>>; /** * 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<undefined>): Promise<MastraAgentNetworkStream<undefined>>; network<OUTPUT extends {}>(messages: MessageListInput, options?: MultiPrimitiveExecutionOptions<OUTPUT>): Promise<MastraAgentNetworkStream<OUTPUT>>; /** * 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<MultiPrimitiveExecutionOptions, 'runId'> & { runId: string; }): Promise<MastraAgentNetworkStream<undefined>>; /** * 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<MultiPrimitiveExecutionOptions, 'runId'> & { runId: string; }): Promise<MastraAgentNetworkStream<undefined>>; /** * 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<MultiPrimitiveExecutionOptions, 'runId'> & { runId: string; }): Promise<MastraAgentNetworkStream<undefined>>; generate<OUTPUT extends StandardSchemaWithJSON<any, any>, T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>>(messages: MessageListInput, options: AgentExecutionOptionsBase<T> & { structuredOutput: PublicStructuredOutputOptions<T>; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<FullOutput<T>>; generate<OUTPUT extends {}>(messages: MessageListInput, options: AgentExecutionOptionsBase<OUTPUT> & { structuredOutput: PublicStructuredOutputOptions<OUTPUT>; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<FullOutput<OUTPUT>>; generate(messages: MessageListInput, options: AgentExecutionOptionsBase<unknown> & { structuredOutput?: never; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<FullOutput<TOutput>>; generate<OUTPUT = TOutput>(messages: MessageListInput): Promise<FullOutput<OUTPUT>>; /** * @experimental Agent signals are experimental and may change in a future release. */ subscribeToThread<OUTPUT = TOutput>(options: AgentSubscribeToThreadOptions): Promise<AgentThreadSubscription<OUTPUT>>; abortThreadStream(options: AgentSubscribeToThreadOptions): boolean; abortRunStream(runId: string): boolean; /** * @experimental Agent signals are experimental and may change in a future release. */ sendSignal<OUTPUT = TOutput>(signal: AgentSignal, target: SendAgentSignalOptions<OUTPUT>): SendAgentSignalResult; stream<OUTPUT extends StandardSchemaWithJSON<any, any>, T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>>(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase<T> & { structuredOutput: PublicStructuredOutputOptions<T>; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<T>>; stream<OUTPUT extends {}>(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase<OUTPUT> & { structuredOutput: PublicStructuredOutputOptions<OUTPUT>; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<OUTPUT>>; stream(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase<unknown> & { structuredOutput?: never; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<TOutput>>; stream(messages: MessageListInput): Promise<MastraModelOutput<TOutput>>; /** * 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<OUTPUT extends StandardSchemaWithJSON<any, any>, T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>>(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase<T> & { structuredOutput: PublicStructuredOutputOptions<T>; maxIdleMs?: number; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<T>>; streamUntilIdle<OUTPUT extends {}>(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase<OUTPUT> & { structuredOutput: PublicStructuredOutputOptions<OUTPUT>; maxIdleMs?: number; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<OUTPUT>>; streamUntilIdle(messages: MessageListInput, streamOptions: AgentExecutionOptionsBase<unknown> & { structuredOutput?: never; maxIdleMs?: number; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<TOutput>>; streamUntilIdle(messages: MessageListInput): Promise<MastraModelOutput<TOutput>>; /** * 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<OUTPUT extends StandardSchemaWithJSON<any, any>, T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>>(resumeData: any, streamOptions: AgentExecutionOptionsBase<T> & { structuredOutput: PublicStructuredOutputOptions<T>; toolCallId?: string; /** Close the outer stream after this many ms of idleness. Default: 5 minutes. */ maxIdleMs?: number; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<T>>; resumeStreamUntilIdle<OUTPUT extends {}>(resumeData: any, streamOptions: AgentExecutionOptionsBase<OUTPUT> & { structuredOutput: PublicStructuredOutputOptions<OUTPUT>; toolCallId?: string; maxIdleMs?: number; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<OUTPUT>>; resumeStreamUntilIdle(resumeData: any, streamOptions: AgentExecutionOptionsBase<unknown> & { structuredOutput?: never; toolCallId?: string; maxIdleMs?: number; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<TOutput>>; /** * 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<OUTPUT extends StandardSchemaWithJSON<any, any>, T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>>(resumeData: any, streamOptions: AgentExecutionOptionsBase<T> & { structuredOutput: PublicStructuredOutputOptions<T>; toolCallId?: string; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<T>>; resumeStream<OUTPUT extends {}>(resumeData: any, streamOptions: AgentExecutionOptionsBase<OUTPUT> & { structuredOutput: PublicStructuredOutputOptions<OUTPUT>; toolCallId?: string; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<OUTPUT>>; resumeStream(resumeData: any, streamOptions: AgentExecutionOptionsBase<unknown> & { structuredOutput?: never; toolCallId?: string; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<MastraModelOutput<TOutput>>; /** * 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<OUTPUT extends StandardSchemaWithJSON<any, any>, T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>>(resumeData: any, options: AgentExecutionOptionsBase<T> & { structuredOutput: PublicStructuredOutputOptions<T>; toolCallId?: string; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<FullOutput<T>>; resumeGenerate<OUTPUT extends {}>(resumeData: any, options: AgentExecutionOptionsBase<OUTPUT> & { structuredOutput: PublicStructuredOutputOptions<OUTPUT>; toolCallId?: string; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<FullOutput<OUTPUT>>; resumeGenerate(resumeData: any, options: AgentExecutionOptionsBase<unknown> & { structuredOutput?: never; toolCallId?: string; } & { model?: DynamicArgument<MastraModelConfig>; }): Promise<FullOutput<TOutput>>; /** * 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<OUTPUT = undefined>(options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string; }): Promise<MastraModelOutput<OUTPUT>>; /** * 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<OUTPUT = undefined>(options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string; }): Promise<MastraModelOutput<OUTPUT>>; /** * 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<OUTPUT = undefined>(options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string; }): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['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<OUTPUT = undefined>(options: AgentExecutionOptions<OUTPUT> & { runId: string; toolCallId?: string; }): Promise<Awaited<ReturnType<MastraModelOutput<OUTPUT>['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<undefined, undefined> & { output?: never; experimental_output?: never; model?: DynamicArgument<MastraMo