UNPKG

@mastra/core

Version:
1,185 lines 66.9 kB
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, TracingPolicy } 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 { GoalObjectiveRecord } from '../storage/domains/thread-state/base.js'; import type { MastraAgentNetworkStream } from '../stream/index.js'; import type { FullOutput, MastraModelOutput } from '../stream/base/output.js'; import type { CoreTool, ToolHooks, ToolPayloadTransformPolicy } from '../tools/types.js'; import type { DynamicArgument } from '../types/index.js'; import type { MastraVoice } from '../voice/index.js'; import type { OutputWriter, WorkflowRunStatus } from '../workflows/types.js'; import type { AnyWorkflow } from '../workflows/workflow.js'; import type { AnyWorkspace } from '../workspace/index.js'; import type { Skill, SkillMetadata } from '../workspace/skills/types.js'; import type { AgentExecutionOptions, AgentExecutionOptionsBase, MultiPrimitiveExecutionOptions, NetworkOptions, DelegationConfig } from './agent.types.js'; import type { MessageInput, MessageListInput, UIMessageWithMetadata } from './message-list/index.js'; import type { CreatedAgentSignal } from './signals.js'; import type { SubAgent } from './subagent.js'; import type { AgentConfig, AgentGenerateOptions, GoalConfig, AgentStreamOptions, ToolsetsInput, ToolsInput, AgentModelManagerConfig, AgentEditorConfig, AgentInstructions, AgentMessageInput, AgentMethodType, AgentSignal, AgentStateSignalInput, AgentSubscribeToThreadOptions, AgentThreadSubscription, PublicStructuredOutputOptions, QueueAgentMessageOptions, QueueAgentMessageResult, SendAgentMessageOptions, SendAgentMessageResult, SendAgentNotificationSignalOptions, SendAgentNotificationSignalResult, SendAgentSignalOptions, SendAgentSignalResult, SendAgentStateSignalOptions, SendAgentStateSignalResult, SendAgentStreamResumeOptions, SendAgentStreamResumeResult, 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>>; }[]; /** * A suspended tool call inside a suspended agent run — either waiting on a * tool-call approval (`requireApproval` / `requireToolApproval`) or on resume * data for a tool that called `suspend()`. */ export interface AgentRunToolCall { toolCallId?: string; toolName?: string; /** Arguments the model supplied for the tool call (approval suspensions only). */ args?: unknown; /** True when the run is waiting on a tool-call approval. */ requiresApproval: boolean; /** The tool-defined suspend payload when the tool itself called `suspend()`. */ suspendPayload?: unknown; } /** * Statuses of agent runs discoverable via {@link Agent.listSuspendedRuns}. * * Agent run snapshots are only persisted while a run is waiting on input and * are deleted when the run reaches a terminal state, so `'suspended'` is the * only status discoverable from storage today. */ export type AgentRunStatus = Extract<WorkflowRunStatus, 'suspended'>; /** * Filters for {@link Agent.listSuspendedRuns}. Mirrors the `listWorkflowRuns` * filter contract, plus the agent-level `threadId` filter. */ export interface AgentListSuspendedRunsOptions { /** Only return runs that belong to this memory thread. */ threadId?: string; /** Only return runs that belong to this memory resource. */ resourceId?: string; /** Only return runs created at or after this date. */ fromDate?: Date; /** Only return runs created at or before this date. */ toDate?: Date; /** * Number of items per page. Pagination is applied when both `perPage` and * `page` are provided; otherwise all matching runs are returned. */ perPage?: number; /** Zero-indexed page number. */ page?: number; } /** * An agent run discovered from workflow snapshot storage. */ export interface AgentRun { /** Run ID accepted by `resumeStream()`, `approveToolCall()`, and `declineToolCall()`. */ runId: string; status: AgentRunStatus; threadId?: string; resourceId?: string; /** When the run's snapshot was last persisted (i.e. when it suspended). */ suspendedAt: Date; /** Suspended tool calls awaiting approval or resume data. */ toolCalls: AgentRunToolCall[]; } export interface AgentListSuspendedRunsResult { runs: AgentRun[]; /** Total number of matching runs, before pagination. */ total: number; } /** * 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, TEditor extends AgentEditorConfig | undefined = AgentEditorConfig | undefined> 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, TEditor>); getMastraInstance(): Mastra<Record<string, Agent<any, ToolsInput, undefined, unknown, AgentEditorConfig | undefined>>, Record<string, AnyWorkflow>, Record<string, import("../vector").MastraVector<any>>, Record<string, import("../tts").MastraTTS>, import("../_types/@internal_core/dist/logger/index.d.ts").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 agent-level tool payload transform policy, if any. * Used by durable execution to mirror the non-durable layer's * per-call → agent → mastra merge order. */ getToolPayloadTransform(): ToolPayloadTransformPolicy | undefined; /** * Returns the agent's native goal configuration, if any. Read by the loop's * goal step to resolve effective settings (judge model, max runs, prompt). * @internal */ __getGoalConfig(): GoalConfig | undefined; /** * Returns a closure that drains pending signals for a given run from the * shared `AgentThreadStreamRuntime`. Used by `prepareForDurableExecution` to * store the drain function on the in-process `RunRegistryEntry`. * @internal */ __getDrainPendingSignals(): (runId: string, scope?: 'pending' | 'pre-run') => CreatedAgentSignal[]; /** * Returns the uncombined input processors suitable for `processLLMRequest`. * Combined (workflow-wrapped) processors skip `processLLMRequest`; this * method returns them individually so the `ProcessorRunner` can invoke * each processor's `processLLMRequest` method. * @internal — used by `DurableAgent` preparation to populate the registry. */ __listLLMRequestProcessors(requestContext?: RequestContext): Promise<InputProcessorOrWorkflow[]>; /** * Set the durable objective for a thread. The objective is judged in the * execution loop until complete or the run budget is exhausted. Requires a * memory-backed thread and a Mastra storage instance; no-ops otherwise. * * Only the optional fields explicitly provided are persisted into the * objective record; unset fields fall back to the agent's `goal` config at * evaluation time. A judge model (here or in `goal.judge`) is required for the * goal to do anything. * * @experimental Agent goals are experimental and may change in a future release. */ setObjective(objective: string, options: { threadId: string; resourceId?: string; judgeModelId?: string; maxRuns?: number; prompt?: string; id?: string; }): Promise<GoalObjectiveRecord | undefined>; /** * Read the current objective record for a thread, or `undefined` when none is * set (or the agent has no storage). */ getObjective(options: { threadId: string; }): Promise<GoalObjectiveRecord | undefined>; /** * Drop the objective for a thread. */ clearObjective(options: { threadId: string; }): Promise<void>; /** * Partially update the options of the active objective. Only provided fields * are persisted into the record (so the precedence over agent config is * remembered in thread state). No-ops when no objective is set. */ updateObjectiveOptions(options: { threadId: string; judgeModelId?: string; maxRuns?: number; prompt?: string; status?: GoalObjectiveRecord['status']; }): Promise<GoalObjectiveRecord | 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 AgentController to avoid overwriting agent-level browser configuration. */ hasOwnBrowser(): boolean; /** * Resolves the combined WorkspaceSkills from agent-level skills and/or workspace skills. * Agent-level skills win on name conflicts when both are present. * @internal */ private resolveSkills; /** * Gets the skills processors to add to input processors when skills are configured. * Supports both agent-level skills and workspace 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>; /** * Programmatically invoke a skill by name. * * Loads the full skill instructions and returns them, or returns the skill * object directly. This is the programmatic equivalent of the `skill` tool * that the LLM calls — useful in workflows and custom pipelines. * * @param skillName - Name or path of the skill to invoke * @param options - Optional request context for dynamic skill resolution * @returns The full Skill object with instructions, or null if not found * * @example * ```typescript * // In a workflow step * const skill = await agent.getSkill('code-review'); * if (skill) { * console.log(skill.instructions); // Full skill instructions * console.log(skill.references); // Available reference files * } * ``` */ getSkill(skillName: string, options?: { requestContext?: RequestContext; }): Promise<Skill | null>; /** * List all skills available to this agent (from both agent-level and workspace). * * @param options - Optional request context for dynamic skill resolution * @returns Array of skill metadata (name, description, path) * * @example * ```typescript * const skills = await agent.listSkills(); * for (const skill of skills) { * console.log(`${skill.name}: ${skill.description}`); * } * ``` */ listSkills(options?: { requestContext?: RequestContext; }): Promise<SkillMetadata[]>; get voice(): MastraVoice<unknown, unknown, unknown, import("../_types/@internal_voice/dist/index.d.ts").ToolsInput, import("../_types/@internal_voice/dist/index.d.ts").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. * * 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<MastraVoice<unknown, unknown, unknown, import("../_types/@internal_voice/dist/index.d.ts").ToolsInput, import("../_types/@internal_voice/dist/index.d.ts").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>; private getMcpServerGuidance; /** * Returns the description of the agent. * * @example * ```typescript * const description = agent.getDescription(); * console.log(description); // 'A helpful weather assistant' * ``` */ getDescription(): string; /** * Returns the tracing policy configured at agent construction time. * * Exposed so out-of-process consumers (e.g. the durable agent runner) can * forward the same policy onto AGENT_RUN spans without reaching into private * fields. */ getTracingPolicy(): TracingPolicy | undefined; /** * 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 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<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; private getSubAgentToolSchemas; /** * 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; outputWriter?: OutputWriter; memoryConfig?: MemoryConfig; autoResumeSuspendedTools?: boolean; hooks?: ToolHooks; delegation?: DelegationConfig; methodType?: AgentMethodType; }): Promise<Record<string, CoreTool>>; /** * Assembles all tools from various sources into a unified CoreTool dictionary. * @internal */ private convertTools; /** * Returns the agent's statically-configured tool hooks, if any. * * @internal Used by dataset experiments to compose item-level tool mocks with * the user's configured `beforeToolCall`/`afterToolCall` hooks. Run-level hooks * override these via {@link resolveToolHooks}, so callers that need to preserve * the configured hooks must read and compose them explicitly. */ getConfiguredToolHooks(): ToolHooks | undefined; private resolveToolHooks; private wrapToolsWithHooks; private wrapToolWithHooks; /** * 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>>; getActiveThreadRunId(options: AgentSubscribeToThreadOptions): string | undefined; /** * Lists suspended agent runs from workflow snapshot storage — runs waiting on * a tool-call approval (`requireApproval` / `requireToolApproval`) or on a * tool that called `suspend()`. * * Unlike {@link getActiveThreadRunId}, which only knows about runs started by the * current process, this is backed by storage: it works after a server restart and * across multiple server instances. Pass the returned `runId` to `resumeStream()`, * `approveToolCall()`, or `declineToolCall()`. * * Results are scoped to runs started by this agent: snapshots persist the owning * agent's id, and runs whose snapshots carry a different id are skipped. Filter by * `threadId`/`resourceId` to scope results to a conversation. * * @example * ```typescript * const { runs } = await agent.listSuspendedRuns({ threadId, resourceId }); * if (runs[0]) { * await agent.approveToolCall({ runId: runs[0].runId }); * } * ``` */ listSuspendedRuns(options?: AgentListSuspendedRunsOptions): Promise<AgentListSuspendedRunsResult>; abortThreadStream(options: AgentSubscribeToThreadOptions): boolean; abortRunStream(runId: string): boolean; /** * @experimental Agent message APIs are experimental and may change in a future release. */ sendMessage<OUTPUT = TOutput>(message: AgentMessageInput, target: SendAgentMessageOptions<OUTPUT>): SendAgentMessageResult<OUTPUT>; /** * @experimental Agent message APIs are experimental and may change in a future release. */ queueMessage<OUTPUT = TOutput>(message: AgentMessageInput, target: QueueAgentMessageOptions<OUTPUT>): QueueAgentMessageResult<OUTPUT>; /** * @experimental Agent state signal APIs are experimental and may change in a future release. */ sendStateSignal<OUTPUT = TOutput>(state: AgentStateSignalInput, target: SendAgentStateSignalOptions<OUTPUT>): Promise<SendAgentStateSignalResult<OUTPUT>>; /** * @experimental Agent notification signal APIs are experimental and may change in a future rele