UNPKG

@mastra/core

Version:

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

1,318 lines (1,317 loc) 66.8 kB
import type { Agent } from '../agent/index.js'; import type { DurableAgentLike } from '../agent/types.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 { MastraModelGateway } 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 { DefinitionSource, ObservabilityEntrypoint, ObservabilityExporter, ObservabilityInstance, LoggerContext, MetricsContext } from '../observability/index.js'; import type { Processor } from '../processors/index.js'; import type { MastraServerBase } from '../server/base.js'; import type { Middleware, ServerConfig } 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 { WorkflowSchedulerConfig, WorkflowScheduler } from '../workflows/scheduler/index.js'; import type { AnyWorkspace, RegisteredWorkspace, Workspace } from '../workspace/index.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; /** * 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; /** * 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, MastraModelGateway>; /** * 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?: WorkflowSchedulerConfig; /** * 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; 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()`). Use it * to create, pause, resume, or delete schedules imperatively. */ get scheduler(): WorkflowScheduler | 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; /** * 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>>; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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]; __registerInternalWorkflow(workflow: Workflow): void; __hasInternalWorkflow(id: string): boolean; __getInternalWorkflow(id: string): Workflow; /** * 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 * * @example Finding a workflow by ID * ```typescript * const mastra = new Mastra({ * workflows: { * dataProcessor: createWorkflow({ * name: 'process-data', * triggerSchema: z.object({ input: z.string() }) * }).commit() * } * }); * * // Get the workflow's ID * const workflow = mastra.getWorkflow('dataProcessor'); * const workflowId = workflow.id; * * // Later, retrieve the workflow by ID * const sameWorkflow = mastra.getWorkflowById(workflowId); * console.log(sameWorkflow.name); // "process-data" * ``` */ getWorkflowById<TWorkflowName extends keyof TWorkflows>(id: TWorkflows[TWorkflowName]['id']): TWorkflows[TWorkflowName]; listActiveWorkflowRuns(): Promise<WorkflowRuns>; restartAllActiveWorkflowRuns(): Promise<void>; /** * Returns all registered scorers as a record keyed by their IDs. * * @example Listing all scorers * ```typescript * import { HelpfulnessScorer, AccuracyScorer, RelevanceScorer } from '@mastra/scorers'; * * const mastra = new Mastra({ * scorers: { * helpfulness: new HelpfulnessScorer(), * accuracy: new AccuracyScorer(), * relevance: new RelevanceScorer() * } * }); * * const allScorers = mastra.listScorers(); * console.log(Object.keys(allScorers)); // ['helpfulness', 'accuracy', 'relevance'] * * // Check scorer configurations * for (const [id, scorer] of Object.entries(allScorers)) { * console.log(`Scorer ${id}:`, scorer.id, scorer.name, scorer.description); * } * ``` */ listScorers(): TScorers | undefined; /** * Adds a new scorer to the Mastra instance. * * This method allows dynamic registration of scorers after the Mastra instance * has been created. * * If a scorer with the same key already exists, this method leaves the existing * scorer registered and returns. * * @example * ```typescript * const mastra = new Mastra(); * const newScorer = new MastraScorer({ * id: 'quality-scorer', * name: 'Quality Scorer' * }); * mastra.addScorer(newScorer); // Uses scorer.id as key * // or * mastra.addScorer(newScorer, 'customKey'); // Uses custom key * ``` */ addScorer<S extends MastraScorer<any, any, any, any>>(scorer: S, key?: string, options?: { source?: DefinitionSource; }): void; /** * Retrieves a registered scorer by its key. * * @template TScorerKey - The specific scorer key type from the registered scorers * @throws {MastraError} When the scorer with the specified key is not found * * @example Getting and using a scorer * ```typescript * import { HelpfulnessScorer, AccuracyScorer } from '@mastra/scorers'; * * const mastra = new Mastra({ * scorers: { * helpfulness: new HelpfulnessScorer({ * model: 'openai/gpt-4o', * criteria: 'Rate how helpful this response is' * }), * accuracy: new AccuracyScorer({ * model: 'openai/gpt-5' * }) * } * }); * * // Get a specific scorer * const helpfulnessScorer = mastra.getScorer('helpfulness'); * const score = await helpfulnessScorer.score({ * input: 'How do I reset my password?', * output: 'You can reset your password by clicking the forgot password link.', * expected: 'Detailed password reset instructions' * }); * * console.log('Helpfulness score:', score); * ``` */ getScorer<TScorerKey extends keyof TScorers>(key: TScorerKey): TScorers[TScorerKey]; /** * Retrieves a registered scorer by its name. * * This method searches through all registered scorers to find one with the specified name. * Unlike `getScorer()` which uses the registration key, this method uses the scorer's * internal name property. * * @throws {MastraError} When no scorer is found with the specified name * * @example Finding a scorer by name * ```typescript * import { HelpfulnessScorer } from '@mastra/scorers'; * * const mastra = new Mastra({ * scorers: { * myHelpfulnessScorer: new HelpfulnessScorer({ * name: 'helpfulness-evaluator', * model: 'openai/gpt-5' * }) * } * }); * * // Find scorer by its internal name, not the registration key * const scorer = mastra.getScorerById('helpfulness-evaluator'); * const score = await scorer.score({ * input: 'question', * output: 'answer' * }); * ``` */ getScorerById<TScorerName extends keyof TScorers>(id: TScorers[TScorerName]['id']): TScorers[TScorerName]; /** * Removes a scorer from the Mastra instance by its key or ID. * * @param keyOrId - The scorer key or ID to remove * @returns true if a scorer was removed, false if no scorer was found */ removeScorer(keyOrId: string): boolean; /** * Returns all registered prompt blocks. */ listPromptBlocks(): Record<string, StorageResolvedPromptBlockType>; /** * Registers a prompt block in the Mastra instance's runtime registry. * * @param promptBlock - The resolved prompt block to register * @param key - Optional registration key (defaults to promptBlock.id) */ addPromptBlock(promptBlock: StorageResolvedPromptBlockType, key?: string): void; /** * Retrieves a registered prompt block by its key. * * @throws {MastraError} When the prompt block with the specified key is not found */ getPromptBlock(key: string): StorageResolvedPromptBlockType; /** * Retrieves a registered prompt block by its ID. * * @throws {MastraError} When no prompt block is found with the specified ID */ getPromptBlockById(id: string): StorageResolvedPromptBlockType; /** * Removes a prompt block from the Mastra instance by its key or ID. * * @param keyOrId - The prompt block key or ID to remove * @returns true if a prompt block was removed, false if not found */ removePromptBlock(keyOrId: string): boolean; /** * Retrieves a specific tool by registration key. * * @throws {MastraError} When the specified tool is not found * * @example * ```typescript * const mastra = new Mastra({ * tools: { * calculator: calculatorTool, * weather: weatherTool * } * }); * * const tool = mastra.getTool('calculator'); * ``` */ getTool<TToolName extends keyof TTools>(name: TToolName): TTools[TToolName]; /** * Retrieves a specific tool by its ID. * * @throws {MastraError} When the specified tool is not found * * @example * ```typescript * const mastra = new Mastra({ * tools: { * calculator: calculatorTool * } * }); * * const tool = mastra.getToolById('calculator-tool-id'); * ``` */ getToolById<TToolName extends keyof TTools>(id: TTools[TToolName]['id']): TTools[TToolName]; /** * Lists all configured tools. * * @example * ```typescript * const mastra = new Mastra({ * tools: { * calculator: calculatorTool, * weather: weatherTool * } * }); * * const tools = mastra.listTools(); * Object.entries(tools || {}).forEach(([name, tool]) => { * console.log(`Tool "${name}":`, tool.id); * }); * ``` */ listTools(): TTools | undefined; /** * Adds a new tool to the Mastra instance. * * This method allows dynamic registration of tools after the Mastra instance * has been created. * * @throws {MastraError} When a tool with the same key already exists * * @example * ```typescript * const mastra = new Mastra(); * const newTool = createTool({ * id: 'calculator-tool', * description: 'Performs calculations' * }); * mastra.addTool(newTool); // Uses tool.id as key * // or * mastra.addTool(newTool, 'customKey'); // Uses custom key * ``` */ addTool<T extends ToolAction<any, any, any, any>>(tool: T, key?: string): void; /** * Retrieves a specific processor by registration key. * * @throws {MastraError} When the specified processor is not found * * @example * ```typescript * const mastra = new Mastra({ * processors: { * validator: validatorProcessor, * transformer: transformerProcessor * } * }); * * const processor = mastra.getProcessor('validator'); * ``` */ getProcessor<TProcessorName extends keyof TProcessors>(name: TProcessorName): TProcessors[TProcessorName]; /** * Retrieves a specific processor by its ID. * * @throws {MastraError} When the specified processor is not found * * @example * ```typescript * const mastra = new Mastra({ * processors: { * validator: validatorProcessor * } * }); * * const processor = mastra.getProcessorById('validator-processor-id'); * ``` */ getProcessorById<TProcessorName extends keyof TProcessors>(id: TProcessors[TProcessorName]['id']): TProcessors[TProcessorName]; /** * Lists all configured processors. * * @example * ```typescript * const mastra = new Mastra({ * processors: { * validator: validatorProcessor, * transformer: transformerProcessor * } * }); * * const processors = mastra.listProcessors(); * Object.entries(processors || {}).forEach(([name, processor]) => { * console.log(`Processor "${name}":`, processor.id); * }); * ``` */ listProcessors(): TProcessors | undefined; /** * Adds a new processor to the Mastra instance. * * This method allows dynamic registration of processors after the Mastra instance * has been created. * * @throws {MastraError} When a processor with the same key already exists * * @example * ```typescript * const mastra = new Mastra(); * const newProcessor = { * id: 'text-processor', * processInput: async (messages) => messages * }; * mastra.addProcessor(newProcessor); // Uses processor.id as key * // or * mastra.addProcessor(newProcessor, 'customKey'); // Uses custom key * ``` */ addProcessor<P extends Processor>(processor: P, key?: string): void; /** * Registers a processor configuration with agent context. * This tracks which agents use which processors with what configuration. * * @param processor - The processor instance * @param agentId - The ID of the agent that uses this processor * @param type - Whether this is an input or output processor */ addProcessorConfiguration(processor: Processor, agentId: string, type: 'input' | 'output'): void; /** * Gets all processor configurations for a specific processor ID. * * @param processorId - The ID of the processor * @returns Array of configurations with agent context */ getProcessorConfigurations(processorId: string): Array<{ processor: Processor; agentId: string; type: 'input' | 'output'; }>; /** * Gets all processor configurations. * * @returns Map of processor IDs to their configurations */ listProcessorConfigurations(): Map<string, Array<{ processor: Processor; agentId: string; type: 'input' | 'output'; }>>; /** * Retrieves a registered memory instance by its registration key. * * @throws {MastraError} When the memory instance with the specified key is not found * * @example * ```typescript * const mastra = new Mastra({ * memory: { * chat: new Memory({ storage }) * } * }); * * const chatMemory = mastra.getMemory('chat'); * ``` */ getMemory<TMemoryName extends keyof TMemory>(name: TMemoryName): TMemory[TMemoryName]; /** * Retrieves a registered memory instance by its ID. * * Searches through all registered memory instances and returns the one whose ID matches. * * @throws {MastraError} When no memory instance with the specified ID is found * * @example * ```typescript * const mastra = new Mastra({ * memory: { * chat: new Memory({ id: 'chat-memory', storage }) * } * }); * * const memory = mastra.getMemoryById('chat-memory'); * ``` */ getMemoryById(id: string): MastraMemory; /** * Returns all registered memory instances as a record keyed by their names. * * @example * ```typescript * const mastra = new Mastra({ * memory: { * chat: new Memory({ storage }), * longTerm: new Memory({ storage }) * } * }); * * const allMemory = mastra.listMemory(); * console.log(Object.keys(allMemory)); // ['chat', 'longTerm'] * ``` */ listMemory(): TMemory | undefined; /** * Adds a new memory instance to the Mastra instance. * * This method allows dynamic registration of memory instances after the Mastra instance * has been created. * * @example * ```typescript * const mastra = new Mastra(); * const chatMemory = new Memory({ * id: 'chat-memory', * storage: mastra.getStorage() * }); * mastra.addMemory(chatMemory); // Uses memory.id as key * // or * mastra.addMemory(chatMemory, 'customKey'); // Uses custom key * ``` */ add