UNPKG

@mastra/core

Version:
1,216 lines (1,214 loc) 83.9 kB
import type { Agent } from '../agent/index.js'; import type { DurableAgentLike } from '../agent/types.js'; import type { AgentController } from '../agent-controller/index.js'; import { BackgroundTaskManager } from '../background-tasks/index.js'; import type { BackgroundTaskManagerConfig } from '../background-tasks/types.js'; import type { BundlerConfig } from '../bundler/types.js'; import type { MastraServerCache } from '../cache/index.js'; import { AgentChannels } from '../channels/index.js'; import type { ChannelProvider } from '../channels/index.js'; import { DatasetsManager } from '../datasets/manager.js'; import type { MastraDeployer } from '../deployer/index.js'; import type { IMastraEditor } from '../editor/index.js'; import type { MastraScorer } from '../evals/index.js'; import type { PubSub } from '../events/pubsub.js'; import type { Event } from '../events/types.js'; import type { Harness } from '../harness/index.js'; import type { MastraModelGatewayInterface } from '../llm/model/gateways/index.js'; import { LogLevel } from '../logger/index.js'; import type { IMastraLogger } from '../logger/index.js'; import type { MCPServerBase } from '../mcp/index.js'; import type { MastraMemory } from '../memory/index.js'; import type { NotificationDispatchConfig } from '../notifications/workflow.js'; import type { DefinitionSource, ObservabilityEntrypoint, ObservabilityExporter, ObservabilityInstance, LoggerContext, MetricsContext, TracingContext } from '../observability/index.js'; import type { Processor } from '../processors/index.js'; import { Schedules } from '../schedules/schedules.js'; import type { SchedulesConfig, ScheduleHooks } from '../schedules/types.js'; import type { MastraServerBase } from '../server/base.js'; import type { Middleware, ServerConfig, StudioConfig } from '../server/types.js'; import type { MastraCompositeStore, WorkflowRuns } from '../storage/index.js'; import type { SchedulesStorage } from '../storage/domains/schedules/base.js'; import type { StorageResolvedPromptBlockType } from '../storage/types.js'; import type { ToolLoopAgentLike } from '../tool-loop-agent/index.js'; import type { ToolAction, ToolPayloadTransformPolicy } from '../tools/index.js'; import type { MastraTTS } from '../tts/index.js'; import type { MastraIdGenerator, IdGeneratorContext } from '../types/index.js'; import type { MastraVector } from '../vector/index.js'; import type { MastraWorker } from '../worker/index.js'; import type { AnyWorkflow, Workflow } from '../workflows/index.js'; import type { SchedulerConfig, Scheduler } from '../workflows/scheduler/index.js'; import type { AnyWorkspace, RegisteredWorkspace, Workspace } from '../workspace/index.js'; import type { RunScope } from './run-scope.js'; import type { VersionOverrides, VersionSelector } from './types.js'; /** * Configuration interface for initializing a Mastra instance. * * The Config interface defines all the optional components that can be registered * with a Mastra instance, including agents, workflows, storage, logging, and more. * * @template TAgents - Record of agent instances keyed by their names * @template TWorkflows - Record of workflow instances * @template TVectors - Record of vector store instances * @template TTTS - Record of text-to-speech instances * @template TLogger - Logger implementation type * @template TVNextNetworks - Record of agent network instances * @template TMCPServers - Record of MCP server instances * @template TScorers - Record of scorer instances * * @example * ```typescript * const mastra = new Mastra({ * agents: { * weatherAgent: new Agent({ * id: 'weather-agent', * name: 'Weather Agent', * instructions: 'You help with weather information', * model: 'openai/gpt-5' * }) * }, * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }), * logger: new PinoLogger({ name: 'MyApp' }) * }); * ``` */ export interface Config<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>, TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>, TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>, TLogger extends IMastraLogger = IMastraLogger, TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>, TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>, TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<string, ToolAction<any, any, any, any, any, any>>, TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>, TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>, TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>> { /** * Agents are autonomous systems that can make decisions and take actions. * Accepts Mastra Agent instances, AI SDK v6 ToolLoopAgent instances, * and durable agent wrappers (e.g., InngestAgent from createInngestAgent). * ToolLoopAgent and durable agents are automatically handled during registration. */ agents?: { [K in keyof TAgents]: TAgents[K] | ToolLoopAgentLike | DurableAgentLike; }; /** * Storage provider for persisting data, conversation history, and workflow state. * Required for agent memory and workflow persistence. */ storage?: MastraCompositeStore; /** * Vector stores for semantic search and retrieval-augmented generation (RAG). * Used for storing and querying embeddings. */ vectors?: TVectors; /** * Logger implementation for application logging and debugging. * Set to `false` to disable logging entirely. * @default `INFO` level in development, `WARN` in production. */ logger?: TLogger | false; /** * Workflows provide type-safe, composable task execution with built-in error handling. */ workflows?: TWorkflows; /** * AgentControllers to host on this Mastra instance, keyed by id. Each * registered AgentController uses this Mastra (its storage, agents, gateways, * and observability) instead of building its own internal one, and is * reachable via {@link Mastra.getAgentController} / * {@link Mastra.listAgentControllers}. This is how a server exposes multiple * AgentControllers' sessions over HTTP. */ agentControllers?: Record<string, AgentController<any>>; /** * Harnesses to host on this Mastra instance, keyed by id. * * @deprecated Use {@link MastraConfig.agentControllers} instead. `harnesses` * is retained as a backwards-compatible alias and will be removed in a future * major. Entries from both keys are merged, with `agentControllers` taking * precedence on key collisions. */ harnesses?: Record<string, Harness<any>>; /** * Text-to-speech providers for voice synthesis capabilities. */ tts?: TTTS; /** * Observability entrypoint for tracking model interactions and tracing. * Pass an instance of the Observability class from @mastra/observability. * * @example * ```typescript * import { Observability, MastraStorageExporter, MastraPlatformExporter } from '@mastra/observability'; * * new Mastra({ * observability: new Observability({ * configs: { * default: { * serviceName: 'mastra', * exporters: [new MastraStorageExporter(), new MastraPlatformExporter()], * }, * }, * }) * }) * ``` * * `Observability` auto-applies a `SensitiveDataFilter` span output processor * to every configured instance. Set `sensitiveDataFilter: false` on the * registry config to opt out, or pass a `SensitiveDataFilterOptions` object * to customize it. */ observability?: ObservabilityEntrypoint; /** * Custom ID generator function for creating unique identifiers. * Receives optional context about what type of ID is being generated * and where it's being requested from. * @default `crypto.randomUUID()` */ idGenerator?: MastraIdGenerator; /** * Deployment provider for publishing applications to cloud platforms. */ deployer?: MastraDeployer; /** * Server configuration for HTTP endpoints and middleware. */ server?: ServerConfig; /** * Studio-specific authentication and authorization configuration. * * When configured, Studio uses separate auth from the server (API) auth, * allowing different providers for internal team members vs external customers. * * - `server.auth` handles API authentication (external customers) * - `studio.auth` handles Studio authentication (internal team) * * **Dual auth is opt-in:** If `studio.auth` is not configured, Studio requests * fall back to `server.auth` for backward compatibility. To enable strict * separation between Studio and API auth, configure both `studio.auth` and * `server.auth`. * * @example * ```typescript * const mastra = new Mastra({ * server: { * auth: new MastraAuthWorkos({ ... }), // External customers * }, * studio: { * auth: new MastraAuthOkta({ ... }), // Internal team * rbac: new StaticRBACProvider({ * roles: DEFAULT_ROLES, * getUserRoles: (user) => [user.role], * }), * }, * }); * ``` */ studio?: StudioConfig; /** * MCP servers provide tools and resources that agents can use. */ mcpServers?: TMCPServers; /** * Bundler configuration for packaging and deployment. */ bundler?: BundlerConfig; /** * Pub/sub system for event-driven communication between components. * @default EventEmitterPubSub */ pubsub?: PubSub; /** * Server cache for storing stream events and other temporary data. * Used by durable agents for resumable streams - clients can disconnect * and reconnect without missing events. * * When provided, durable agents created without their own cache will * inherit this cache instance. * * @default InMemoryServerCache */ cache?: MastraServerCache; /** * Scorers help assess the quality of agent responses and workflow outputs. */ scorers?: TScorers; /** * Tools are reusable functions that agents can use to interact with external systems. */ tools?: TTools; /** * Processors transform inputs and outputs for agents and workflows. */ processors?: TProcessors; /** * Memory instances that can be referenced by stored agents. * Keys are used to look up memory instances when resolving stored agent configurations. */ memory?: TMemory; /** * Global workspace for file storage, skills, and code execution. * Agents inherit this workspace unless they have their own configured. * Skills are accessed via workspace.skills when skills is configured. */ workspace?: AnyWorkspace; /** * Custom model router gateways for accessing LLM providers. * Gateways handle provider-specific authentication, URL construction, and model resolution. */ gateways?: Record<string, MastraModelGatewayInterface>; /** * Event handlers for custom application events. * Maps event topics to handler functions for event-driven architectures. */ events?: { [topic: string]: (event: Event, cb?: () => Promise<void>) => Promise<void> | ((event: Event, cb?: () => Promise<void>) => Promise<void>)[]; }; /** * Editor instance for handling agent instantiation and configuration. * The editor handles complex instantiation logic including memory resolution. */ editor?: IMastraEditor; /** * Global version overrides for primitives. * When set, sub-agent delegation (and future primitive resolution) will * resolve the specified version instead of the code-defined default. * * @example * ```typescript * new Mastra({ * versions: { * agents: { * 'researcher-agent': { versionId: '123' }, * 'writer-agent': { status: 'published' }, * }, * }, * }); * ``` */ versions?: VersionOverrides; /** * Background task configuration for running tool calls asynchronously. * When configured, agents can dispatch tool executions to run in the background * while the conversation continues. */ backgroundTasks?: BackgroundTaskManagerConfig; /** * Scheduler configuration for cron-driven workflow triggers. * * The scheduler is auto-enabled when any registered workflow declares a * `schedule` config or when `scheduler.enabled` is true. It requires a * storage adapter implementing the `schedules` domain (e.g. `@mastra/libsql`). */ scheduler?: SchedulerConfig; /** * Notification runtime configuration. Notification dispatch is scheduled automatically by default. */ notifications?: { dispatch?: NotificationDispatchConfig; }; /** * Schedules runtime configuration. A single lifecycle-hook bundle runs for * every agent-schedule fire and is invoked by the agent-schedule worker * around schedule-driven agent runs; hooks branch per agent via the * `agentId` on each context. Configuring hooks here (rather than on the * Agent) lets both code-defined and stored agents share the same hook * surface, since stored agents cannot define functions in their serialized * config. */ schedules?: SchedulesConfig<Mastra>; /** * Platform channels for messaging integrations (Slack, Discord, etc.). * Routes are automatically registered and agents can reference channel configs. * * @example * ```typescript * import { SlackProvider } from '@mastra/slack'; * * new Mastra({ * channels: { * slack: new SlackProvider({ * configToken: process.env.SLACK_APP_CONFIG_TOKEN, * refreshToken: process.env.SLACK_APP_CONFIG_REFRESH_TOKEN, * }), * }, * }); * ``` */ channels?: TChannels; /** * Deployment environment name (e.g. `'production'`, `'staging'`, `'development'`). * When set, the value is automatically attached to all observability signals * so they can be filtered by environment without passing * `tracingOptions.metadata.environment` on every call. * * If unset, falls back to `process.env.NODE_ENV`. If neither is set the field * is left undefined rather than guessed. * * Per-call `tracingOptions.metadata.environment` always takes precedence. * * @example * ```typescript * new Mastra({ * environment: 'production', * observability: new Observability({ ... }), * }) * ``` */ environment?: string; /** * Optional central transform policy for tool payloads before they are * serialized into display streams or user-visible transcripts. */ transform?: ToolPayloadTransformPolicy; /** * Configure which workers run in this Mastra instance. * * - `undefined` (default): Auto-creates default workers (existing behavior) * - `false`: Disables all event processing — useful when running standalone workers separately * - `MastraWorker[]`: Use exactly these workers */ workers?: MastraWorker[] | false; } /** * The central orchestrator for Mastra applications, managing agents, workflows, storage, logging, observability, and more. * * The `Mastra` class serves as the main entry point and registry for all components in a Mastra application. * It coordinates the interaction between agents, workflows, storage systems, and other services. * @template TAgents - Record of agent instances keyed by their names * @template TWorkflows - Record of modern workflow instances * @template TVectors - Record of vector store instances for semantic search and RAG * @template TTTS - Record of text-to-speech provider instances * @template TLogger - Logger implementation type for application logging * @template TVNextNetworks - Record of next-generation agent network instances * @template TMCPServers - Record of Model Context Protocol server instances * @template TScorers - Record of evaluation scorer instances for measuring AI performance * * @example * ```typescript * const mastra = new Mastra({ * agents: { * weatherAgent: new Agent({ * id: 'weather-agent', * name: 'Weather Agent', * instructions: 'You provide weather information', * model: 'openai/gpt-5', * tools: [getWeatherTool] * }) * }, * workflows: { dataWorkflow }, * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }), * logger: new PinoLogger({ name: 'MyApp' }) * }); * ``` */ export declare class Mastra<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>, TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>, TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>, TLogger extends IMastraLogger = IMastraLogger, TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>, TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>, TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<string, ToolAction<any, any, any, any, any, any>>, TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>, TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>, TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>> { #private; static readonly INTERNAL_WORKFLOW_TTL_MS: number; get pubsub(): PubSub; get agentThreadStreamRuntime(): import("../agent/thread-stream-runtime").AgentThreadStreamRuntime; get workers(): readonly MastraWorker[]; getWorker<T extends MastraWorker>(name: string): T | undefined; get backgroundTaskManager(): BackgroundTaskManager | undefined; /** * Returns the workflow scheduler owned by the SchedulerWorker, * or undefined if the scheduler is not enabled / not yet started. * * The scheduler is created when `startWorkers()` initializes the * SchedulerWorker (guarded by `#shouldEnableScheduler()`). * * This is runtime plumbing (the cron tick loop). To create, list, pause, * resume, or delete schedules use `mastra.schedules` instead. * * @internal */ get scheduler(): Scheduler | undefined; get datasets(): DatasetsManager; /** * Gets the currently configured ID generator function. * * @example * ```typescript * const mastra = new Mastra({ * idGenerator: context => * context?.idType === 'message' && context.threadId * ? `msg-${context.threadId}-${Date.now()}` * : `custom-${Date.now()}` * }); * const generator = mastra.getIdGenerator(); * console.log(generator?.({ idType: 'message', threadId: 'thread-123' })); // \"msg-thread-123-1234567890\" * ``` */ getIdGenerator(): MastraIdGenerator | undefined; /** * Gets the currently configured editor instance. * The editor is responsible for handling agent instantiation and configuration. * * @example * ```typescript * const mastra = new Mastra({ * editor: new MastraEditor({ logger }) * }); * const editor = mastra.getEditor(); * ``` */ getEditor(): IMastraEditor | undefined; /** * Gets a registered channel provider by its key. * * @example * ```typescript * import { SlackProvider } from '@mastra/slack'; * const slack = mastra.getChannelProvider<SlackProvider>('slack'); * ``` */ getChannelProvider<T extends ChannelProvider = ChannelProvider>(key: string): T | undefined; /** * Gets all registered channel providers. */ getChannelProviders(): Record<string, ChannelProvider> | undefined; /** * Shorthand getter for platform channels. * Usage: `mastra.channels.slack.connect(agentId)` */ get channels(): TChannels; /** * Canonical entrypoint for schedules — recurring agent or workflow runs * persisted as schedule rows discriminated by `target.type` (`'agent'` or * `'workflow'`). Use to create, list, update, pause/resume, manually fire, * or inspect trigger history for schedules across any agent or workflow. * * Lazily constructed. Operates against `getStorage()?.getStore('schedules')`. * * @example * ```ts * const schedule = await mastra.schedules.create({ * agentId: 'pinger', * name: 'morning-checkin', * cron: '0 9 * * *', * prompt: 'good morning, anything to report?', * threadId: 't1', * resourceId: 'u1', * }); * await mastra.schedules.list({ agentId: 'pinger' }); * ``` */ get schedules(): Schedules; /** * Returns the schedule lifecycle hook bundle configured via * `new Mastra({ schedules: { ... } })`, if any. A single bundle runs for * every agent-schedule fire; hooks branch per agent via the `agentId` on * each context. Internal: consumed by the {@link AgentScheduleWorker} to * invoke `prepare`, `onFinish`, `onError`, and `onAbort` around * schedule-driven runs. * * @internal */ __getScheduleHooks(): ScheduleHooks<Mastra> | undefined; /** * Returns the global version overrides configured on this Mastra instance. * These are used as defaults when resolving sub-agent versions during delegation. */ getVersionOverrides(): VersionOverrides | undefined; /** * Returns the deployment environment name configured on this Mastra instance, * falling back to `process.env.NODE_ENV` when unset, or `undefined` if neither * is provided. * * Observability automatically reads this and attaches it to all signals so * consumers can filter by environment without passing * `tracingOptions.metadata.environment` on each call. */ getEnvironment(): string | undefined; getToolPayloadTransform(): ToolPayloadTransformPolicy | undefined; /** * Gets the stored agents cache * @internal */ getStoredAgentCache(): Map<string, Agent<string, import("../agent").ToolsInput, undefined, unknown, import("../agent").AgentEditorConfig | undefined>>; /** * Gets the stored scorers cache * @internal */ getStoredScorerCache(): Map<string, MastraScorer<any, any, any, any>>; /** * Generates a unique identifier using the configured generator or defaults to `crypto.randomUUID()`. * * This method is used internally by Mastra for creating unique IDs for various entities * like workflow runs, agent conversations, and other resources that need unique identification. * * @param context - Optional context information about what type of ID is being generated * and where it's being requested from. This allows custom ID generators * to create deterministic IDs based on context. * * @throws {MastraError} When the custom ID generator returns an empty string * * @example * ```typescript * const mastra = new Mastra(); * const id = mastra.generateId(); * console.log(id); // "550e8400-e29b-41d4-a716-446655440000" * * // With context for deterministic IDs * const messageId = mastra.generateId({ * idType: 'message', * source: 'agent', * threadId: 'thread-123' * }); * ``` */ generateId(context?: IdGeneratorContext): string; /** * Sets a custom ID generator function for creating unique identifiers. * * The ID generator function will be used by `generateId()` instead of the default * `crypto.randomUUID()`. This is useful for creating application-specific ID formats * or integrating with existing ID generation systems. The function receives * optional context about what is requesting the ID. * * @example * ```typescript * const mastra = new Mastra(); * mastra.setIdGenerator(context => * context?.idType === 'run' && context.entityId * ? `run-${context.entityId}-${Date.now()}` * : `custom-${Date.now()}` * ); * const id = mastra.generateId({ idType: 'run', entityId: 'agent-123' }); * console.log(id); // "run-agent-123-1234567890" * ``` */ setIdGenerator(idGenerator: MastraIdGenerator): void; /** * Sets the server configuration for this Mastra instance. * * @param server - The server configuration object * * @example * ```typescript * mastra.setServer({ ...mastra.getServer(), auth: new MastraAuthWorkos() }); * ``` */ setServer(server: ServerConfig): void; /** * Sets the studio configuration for this Mastra instance. * * The studio configuration controls authentication and authorization for Studio UI, * separate from the server configuration. This enables dual auth patterns where * Studio users (e.g., internal team) use different auth than API consumers. * * @param studio - The studio configuration object * * @example * ```typescript * // Set studio auth separately from server auth * mastra.setStudio({ * auth: new MastraAuthStudio(), * rbac: new MastraRBACStudio({ roleMapping: { admin: ['*'] } }), * }); * ``` */ setStudio(studio: StudioConfig): void; /** * Registers an exporter on the default observability instance. * * If the current observability is a no-op (user didn't configure any), it is * first replaced with the provided entrypoint and the instance is registered * as default. If a real observability entrypoint already exists, the exporter * is added directly to the existing default instance. * * @param exporter - The exporter to register (e.g. a MastraPlatformExporter) * @param instance - An ObservabilityInstance pre-configured with the exporter, used as default when bootstrapping * @param entrypoint - A real ObservabilityEntrypoint to bootstrap if the current one is a no-op */ registerExporter(exporter: ObservabilityExporter, instance: ObservabilityInstance, entrypoint: ObservabilityEntrypoint): void; /** * Creates a new Mastra instance with the provided configuration. * * The constructor initializes all the components specified in the config, sets up * internal systems like logging and observability, and registers components with each other. * * @example * ```typescript * const mastra = new Mastra({ * agents: { * assistant: new Agent({ * id: 'assistant', * name: 'Assistant', * instructions: 'You are a helpful assistant', * model: 'openai/gpt-5' * }) * }, * storage: new PostgresStore({ * connectionString: process.env.DATABASE_URL * }), * logger: new PinoLogger({ name: 'MyApp' }), * observability: new Observability({ * configs: { default: { serviceName: 'mastra', exporters: [new MastraStorageExporter()] } }, * }), * }); * ``` */ constructor(config?: Config<TAgents, TWorkflows, TVectors, TTTS, TLogger, TMCPServers, TScorers, TTools, TProcessors, TMemory, TChannels>); /** * Sync code-declared schedule configs to the database. Called by * SchedulerWorker during init and by addWorkflow() for late registrations. * * @internal — public so SchedulerWorker can call it, not part of the user API. */ registerDeclarativeSchedules(schedulesStore: SchedulesStorage): Promise<void>; /** * Retrieves a registered agent by its name. * * @template TAgentName - The specific agent name type from the registered agents * @throws {MastraError} When the agent with the specified name is not found * * @example * ```typescript * const mastra = new Mastra({ * agents: { * weatherAgent: new Agent({ * id: 'weather-agent', * name: 'weather-agent', * instructions: 'You provide weather information', * model: 'openai/gpt-5' * }) * } * }); * const agent = mastra.getAgent('weatherAgent'); * const response = await agent.generate('What is the weather?'); * ``` */ getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName]; getAgent<TAgentName extends keyof TAgents>(name: TAgentName, version: { versionId: string; } | { status?: 'draft' | 'published'; }): Promise<TAgents[TAgentName]>; /** * Returns the `AgentChannels` instances for all registered agents. * Keys are agent IDs. */ getChannels(): Record<string, AgentChannels>; /** * Retrieves a registered agent by its unique ID. * * This method searches for an agent using its internal ID property. If no agent * is found with the given ID, it also attempts to find an agent using the ID as * a name. * * @throws {MastraError} When no agent is found with the specified ID * * @example * ```typescript * const mastra = new Mastra({ * agents: { * assistant: new Agent({ * id: 'assistant', * name: 'assistant', * instructions: 'You are a helpful assistant', * model: 'openai/gpt-5' * }) * } * }); * * const assistant = mastra.getAgent('assistant'); * const sameAgent = mastra.getAgentById(assistant.id); * ``` */ getAgentById<TAgentName extends keyof TAgents>(id: TAgents[TAgentName]['id']): TAgents[TAgentName]; getAgentById<TAgentName extends keyof TAgents>(id: TAgents[TAgentName]['id'], version: { versionId: string; } | { status?: 'draft' | 'published'; }): Promise<TAgents[TAgentName]>; /** * Resolve a versioned variant of an agent by applying stored overrides from the editor. * * Requires the editor package to be configured — throws * `MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP` if it is not. * * @param agent - The code-defined agent to resolve a version for. * @param version - Selects a version by ID or publication status. * @returns A forked agent instance with the stored overrides applied. */ resolveVersionedAgent<TAgent extends Agent>(agent: TAgent, version: VersionSelector | { status?: 'draft' | 'published'; }): Promise<TAgent>; /** * Returns all registered agents as a record keyed by their names. * * This method provides access to the complete registry of agents, allowing you to * iterate over them, check what agents are available, or perform bulk operations. * * @example * ```typescript * const mastra = new Mastra({ * agents: { * weatherAgent: new Agent({ id: 'weather-agent', name: 'weather', model: 'openai/gpt-4o' }), * supportAgent: new Agent({ id: 'support-agent', name: 'support', model: 'openai/gpt-4o' }) * } * }); * * const allAgents = mastra.listAgents(); * console.log(Object.keys(allAgents)); // ['weatherAgent', 'supportAgent'] * ``` */ listAgents(): TAgents; /** * Get an AgentController hosted on this Mastra instance by its registration * key (the key it was registered under in `new Mastra({ agentControllers })`). * Returns `undefined` when none is registered under that key. Server route * handlers use this to create and drive sessions over HTTP. * * @example * ```typescript * const code = new AgentController({ id: 'code-controller', modes }); * const mastra = new Mastra({ agentControllers: { code } }); * * mastra.getAgentController('code'); // → the AgentController (by key) * ``` */ getAgentController(key: string): AgentController<any> | undefined; /** * Get an AgentController hosted on this Mastra instance by its unique `id` * (the `id` passed to the `AgentController` constructor). Falls back to a * registration-key lookup when none matches by id, mirroring * {@link getAgentById}. Returns `undefined` when none is found. * * @example * ```typescript * const code = new AgentController({ id: 'code-controller', modes }); * const mastra = new Mastra({ agentControllers: { code } }); * * mastra.getAgentControllerById('code-controller'); // → by id * ``` */ getAgentControllerById(id: string): AgentController<any> | undefined; /** * List all AgentControllers hosted on this Mastra instance, keyed by their * registration key. */ listAgentControllers(): Record<string, AgentController<any>>; /** * Get a Harness hosted on this Mastra instance by its registration key. * * @deprecated Use {@link Mastra.getAgentController} instead. */ getHarness(key: string): Harness<any> | undefined; /** * Get a Harness hosted on this Mastra instance by its unique `id`. * * @deprecated Use {@link Mastra.getAgentControllerById} instead. */ getHarnessById(id: string): Harness<any> | undefined; /** * List all Harnesses hosted on this Mastra instance, keyed by their * registration key. * * @deprecated Use {@link Mastra.listAgentControllers} instead. */ listHarnesses(): Record<string, Harness<any>>; /** * Adds a new agent to the Mastra instance. * * This method allows dynamic registration of agents after the Mastra instance * has been created. The agent will be initialized with the current logger. * * @throws {MastraError} When an agent with the same key already exists * * @example * ```typescript * const mastra = new Mastra(); * const newAgent = new Agent({ * id: 'chat-agent', * name: 'Chat Assistant', * model: 'openai/gpt-4o' * }); * mastra.addAgent(newAgent); // Uses agent.id as key * // or * mastra.addAgent(newAgent, 'customKey'); // Uses custom key * * // Durable agents (e.g., InngestAgent) are also supported: * const durableAgent = createInngestAgent({ agent: newAgent, inngest }); * mastra.addAgent(durableAgent); // Auto-registers required workflows * ``` */ addAgent<A extends Agent | ToolLoopAgentLike | DurableAgentLike>(agent: A, key?: string, options?: { source?: DefinitionSource; }): void; /** * Registers a map of file-system routed agents (discovered from * `agents/<name>/` directories) into this Mastra instance. * * Code-registered agents win on name collisions: if an agent with the same * key already exists, the file-system agent is skipped and a warning is * logged. Otherwise each agent is added via {@link addAgent} with * `source: 'fs'`. * * Intended to be called by the bundler/dev generated entry, not by user code. * * @internal */ __registerFsAgents(fsAgents: Record<string, Agent | ToolLoopAgentLike | DurableAgentLike>): void; /** * Registers a map of file-system routed workflows (discovered from * `workflows/*.ts` files) into this Mastra instance. * * Code-registered workflows win on name collisions: if a workflow with the * same key already exists, the file-system workflow is skipped and a warning * is logged. Otherwise each workflow is added via {@link addWorkflow} with * its key. * * Intended to be called by the bundler/dev generated entry, not by user code. * * @internal */ __registerFsWorkflows(fsWorkflows: Record<string, AnyWorkflow>): void; /** * Registers a file-system routed storage instance (discovered from * `storage.ts`) into this Mastra instance. * * Code-registered storage wins: if the user already passed `storage` to the * `new Mastra({storage})` constructor, the file-system storage is skipped * and a warning is logged. Otherwise the fs-provided storage replaces the * default InMemoryStore via {@link setStorage}. * * Intended to be called by the bundler/dev generated entry, not by user code. * * @internal */ __registerFsStorage(fsStorage: MastraCompositeStore): void; /** * Registers a file-system routed observability instance (discovered from * `observability.ts`) into this Mastra instance. * * Code-registered observability wins: if the user already passed * `observability` to the `new Mastra({observability})` constructor, the * file-system instance is skipped with a warning. * * @internal */ __registerFsObservability(fsObservability: ObservabilityEntrypoint): void; /** * Registers a file-system routed server config (discovered from * `server.ts`) into this Mastra instance. * * Code-registered server config wins on collision. * * @internal */ __registerFsServer(fsServer: ServerConfig): void; /** * Registers a file-system routed studio config (discovered from * `studio.ts`) into this Mastra instance. * * Code-registered studio config wins on collision. * * @internal */ __registerFsStudio(fsStudio: StudioConfig): void; /** * Removes an agent from the Mastra instance by its key or ID. * Used when stored agents are updated/deleted to allow fresh data to be loaded. * * @param keyOrId - The agent key or ID to remove * @returns true if an agent was removed, false if no agent was found * * @example * ```typescript * // Remove by key * mastra.removeAgent('myAgent'); * * // Remove by ID * mastra.removeAgent('agent-123'); * ``` */ removeAgent(keyOrId: string): boolean; /** * Retrieves a registered vector store by its name. * * @template TVectorName - The specific vector store name type from the registered vectors * @throws {MastraError} When the vector store with the specified name is not found * * @example Using a vector store for semantic search * ```typescript * import { PineconeVector } from '@mastra/pinecone'; * import { OpenAIEmbedder } from '@mastra/embedders'; * * const mastra = new Mastra({ * vectors: { * knowledge: new PineconeVector({ * apiKey: process.env.PINECONE_API_KEY, * indexName: 'knowledge-base', * embedder: new OpenAIEmbedder({ * apiKey: process.env.OPENAI_API_KEY, * model: 'text-embedding-3-small' * }) * }), * products: new PineconeVector({ * apiKey: process.env.PINECONE_API_KEY, * indexName: 'product-catalog' * }) * } * }); * * // Get a vector store and perform semantic search * const knowledgeBase = mastra.getVector('knowledge'); * const results = await knowledgeBase.query({ * query: 'How to reset password?', * topK: 5 * }); * * console.log('Relevant documents:', results); * ``` */ getVector<TVectorName extends keyof TVectors>(name: TVectorName): TVectors[TVectorName]; /** * Retrieves a specific vector store instance by its ID. * * This method searches for a vector store by its internal ID property. * If not found by ID, it falls back to searching by registration key. * * @throws {MastraError} When the specified vector store is not found * * @example * ```typescript * const mastra = new Mastra({ * vectors: { * embeddings: chromaVector * } * }); * * const vectorStore = mastra.getVectorById('chroma-123'); * ``` */ getVectorById<TVectorName extends keyof TVectors>(id: TVectors[TVectorName]['id']): TVectors[TVectorName]; /** * Returns all registered vector stores as a record keyed by their names. * * @example Listing all vector stores * ```typescript * const mastra = new Mastra({ * vectors: { * documents: new PineconeVector({ indexName: 'docs' }), * images: new PineconeVector({ indexName: 'images' }), * products: new ChromaVector({ collectionName: 'products' }) * } * }); * * const allVectors = mastra.getVectors(); * console.log(Object.keys(allVectors)); // ['documents', 'images', 'products'] * * // Check vector store types and configurations * for (const [name, vectorStore] of Object.entries(allVectors)) { * console.log(`Vector store ${name}:`, vectorStore.constructor.name); * } * ``` */ listVectors(): TVectors | undefined; /** * Adds a new vector store to the Mastra instance. * * This method allows dynamic registration of vector stores after the Mastra instance * has been created. The vector store will be initialized with the current logger. * * @throws {MastraError} When a vector store with the same key already exists * * @example * ```typescript * const mastra = new Mastra(); * const newVector = new ChromaVector({ id: 'chroma-embeddings' }); * mastra.addVector(newVector); // Uses vector.id as key * // or * mastra.addVector(newVector, 'customKey'); // Uses custom key * ``` */ addVector<V extends MastraVector>(vector: V, key?: string): void; /** * @deprecated Use listVectors() instead */ getVectors(): TVectors | undefined; /** * Gets the currently configured deployment provider. * * @example * ```typescript * const mastra = new Mastra({ * deployer: new VercelDeployer({ * token: process.env.VERCEL_TOKEN, * projectId: process.env.VERCEL_PROJECT_ID * }) * }); * * const deployer = mastra.getDeployer(); * if (deployer) { * await deployer.deploy({ * name: 'my-mastra-app', * environment: 'production' * }); * } * ``` */ getDeployer(): MastraDeployer | undefined; /** * Gets the global workspace instance. * Workspace provides file storage, skills, and code execution capabilities. * Agents inherit this workspace unless they have their own configured. * * @example * ```typescript * const workspace = mastra.getWorkspace(); * if (workspace?.skills) { * const skills = await workspace.skills.list(); * } * ``` */ getWorkspace(): Workspace | undefined; /** * Retrieves a registered workspace by its ID. * * @throws {MastraError} When the workspace with the specified ID is not found * * @example * ```typescript * const workspace = mastra.getWorkspaceById('workspace-123'); * const files = await workspace.filesystem.readdir('/'); * ``` */ getWorkspaceById(id: string): Workspace; /** * Returns all registered workspaces as a record keyed by their IDs. * * @example * ```typescript * const workspaces = mastra.listWorkspaces(); * for (const [id, entry] of Object.entries(workspaces)) { * console.log(`Workspace ${id}: ${entry.workspace.name} (source: ${entry.source})`); * } * ``` */ listWorkspaces(): Record<string, RegisteredWorkspace>; /** * Adds a new workspace to the Mastra instance. * * This method allows dynamic registration of workspaces after the Mastra instance * has been created. Workspaces are keyed by their ID. * * @example * ```typescript * const workspace = new Workspace({ * id: 'project-workspace', * name: 'Project Workspace', * filesystem: new LocalFilesystem({ rootPath: './workspace' }) * }); * mastra.addWorkspace(workspace); * ``` */ addWorkspace(workspace: AnyWorkspace, key?: string, metadata?: { source?: 'mastra' | 'agent'; agentId?: string; agentName?: string; }): void; /** * Removes a registered workspace by its ID. * * When `destroy` is true, the workspace is destroyed before it is removed from * the registry. If destruction fails, the workspace remains registered and the * error is rethrown. * * @example * ```typescript * await mastra.removeWorkspace('workspace-123', { destroy: true }); * ``` */ removeWorkspace(id: string, options?: { destroy?: boolean; }): Promise<boolean>; /** * Retrieves a registered workflow by its ID. * * @template TWorkflowId - The specific workflow ID type from the registered workflows * @throws {MastraError} When the workflow with the specified ID is not found * * @example Getting and executing a workflow * ```typescript * import { createWorkflow, createStep } from '@mastra/core/workflows'; * import { z } from 'zod/v4'; * * const processDataWorkflow = createWorkflow({ * name: 'process-data', * triggerSchema: z.object({ input: z.string() }) * }) * .then(validateStep) * .then(transformStep) * .then(saveStep) * .commit(); * * const mastra = new Mastra({ * workflows: { * dataProcessor: processDataWorkflow * } * }); * ``` */ getWorkflow<TWorkflowId extends keyof TWorkflows>(id: TWorkflowId, { serialized }?: { serialized?: boolean; }): TWorkflows[TWorkflowId]; /** * Register a workflow under an internal-only registry. * * - Without `runId`: stored at the bare `${id}` slot. Used by single-instance * internal workflows (background tasks, score-traces) that are looked up * without a runId. * - With `runId`: stored *only* at `${id}:${runId}`. Concurrent or nested * invocations that share a workflow id (e.g. a parent and a sub-agent both * registering their `agentic-loop`) each get their own closure-bound * instance keyed by run, and the bare `${id}` slot is never overwritten by * a run-scoped registration — so a run-scoped lookup can never resolve a * *different* run's instance via an id scan. */ __registerInternalWorkflow(workflow: AnyWorkflow, runId?: string): void; /** * Remove a runId-scoped registration. The unscoped `${id}` entry is left intact * so single-instance callers (background tasks, score-traces) continue to resolve. * * Decrements the refcount for the runScope tied to this runId; when the * count hits zero the scope is dropped along with every reference it held. */ __unregisterInternalWorkflow(id: string, runId: string): void; /** * Get the existing runScope for a runId without creating one. * Returns undefined when no internal workflow has been registered against * the runId — callers should treat this as the run not yet being bootstrapped. */ __getRunScope(runId: string): RunScope | undefined; /** * Idempotently allocate a runScope for a runId. Used by call sites (like * `loop()`) that need to populate the scope *before* the internal workflow * registration lands. The scope is held until the matching internal-workflow * registration is released or the TTL sweep evicts it. * * Bumps the refcount so the scope cannot be freed before the caller is done * with it; callers MUST pair this with `__releaseRunScope(runId)`. */ __createRunScope(runId: string): RunScope; /** * Decrement the runScope refcount; drops the scope when the count reaches * zero. Public so callers that called `__createRunScope` directly (e.g., * `loop()` hydration) can release their hold without unregistering a * workflow. */ __releaseRunScope(runId: string): void; __hasInternalWorkflow(id: string, runId?: string): boolean; __getInternalWorkflow(id: string, runId?: string): AnyWorkflow; /** * @internal Records the tracing context for an evented workflow run so the * event processor can nest step spans under the run's parent span. The * `currentSpan` is non-serializable, so it is held here rather than passed * through the engine's pubsub events. */ __registerRunTracingContext(runId: string, tracingContext: TracingContext): void; /** @internal Returns the tracing context recorded for an evented workflow run. */ __getRunTracingContext(runId: string): TracingContext | undefined; /** @internal Clears the tracing context once an evented workflow run finishes. */ __unregisterRunTracingContext(runId: string): void; /** * Retrieves a registered workflow by its unique ID. * * This method searches for a workflow using its internal ID property. If no workflow * is found with the given ID, it also attempts to find a workflow using the ID as * a name. * * @throws {MastraError} When no workflow is found with the specified ID *