@mastra/core
Version:
2,742 lines • 110 kB
TypeScript
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/index.js';
import type { MastraServerCache } from '../cache/index.js';
import { AgentChannels } from '../channels/index.js';
import type { ChannelProvider, ChannelsResolver } from '../channels/index.js';
import type { Classifier } from '../classifier/index.js';
import { DatasetsManager } from '../datasets/manager.js';
import type { IDeployer } 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 { Knowledge } from '../knowledge/index.js';
import type { MastraModelGatewayInterface } from '../llm/model/gateways/index.js';
import { LogLevel } from '../logger/index.js';
import type { IMastraLogger, LoggerAdapterOptions } 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 type { AgentScheduleHandler } from '../schedules/define.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, ServerConfigInput, 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, WorkerStopOptions } from '../worker/index.js';
import type { AnyWorkflow, Workflow } from '../workflows/index.js';
import type { WorkflowBuilderDefinitionInput } from '../workflows/builder/index.js';
import type { DynamicWorkflowGraph } from '../workflows/dynamic/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>, TClassifiers extends Record<string, Classifier<any>> = Record<string, Classifier<any>>, TKnowledge extends Record<string, Knowledge> = Record<string, Knowledge>> {
/**
* 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;
/**
* How the configured logger integrates with Mastra observability.
*
* - `correlation` — inject `trace_id`/`span_id` into the logger's native
* records (stdout, transports) when a span is active. Requires a logger
* that supports adapters (e.g. `ConsoleLogger`, `PinoLogger`). Default: true.
* - `export` — export log records to Mastra observability storage/exporters.
* Set to false to keep trace-correlated stdout without shipping logs.
* Default: true.
*/
loggerOptions?: Partial<LoggerAdapterOptions>;
/**
* 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?: IDeployer;
/**
* Server configuration for HTTP endpoints and middleware.
*/
server?: ServerConfigInput;
/**
* 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;
/**
* Classifiers return typed fixed-option decisions from evaluation models.
* Registered classifiers can be retrieved with getClassifier() or getClassifierById().
*/
classifiers?: TClassifiers;
/**
* 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;
/**
* Knowledge instances registered by stable application key.
*/
knowledge?: TKnowledge;
/**
* 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) => Promise<void> | void) | ((event: Event) => Promise<void> | 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, when schedule rows exist in storage, when a schedule is
* created at runtime (in this process or — via the shared pubsub — in
* another), or when `scheduler.enabled` is true. Apps that never schedule
* anything never poll storage. 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.
*
* Accepts either a static provider record or a {@link ChannelsResolver} —
* a callable that returns the current provider map. With a resolver, routes
* for every possible channel are mounted up front (via
* `resolver.getRoutes()`) and the live provider set is re-resolved at
* runtime, so channels added or removed in an external system of record
* (e.g. the Mastra platform) take effect without redeploying.
*
* @example
* ```typescript
* import { SlackProvider } from '@mastra/slack';
*
* // Static record
* new Mastra({
* channels: {
* slack: new SlackProvider({
* configToken: process.env.SLACK_APP_CONFIG_TOKEN,
* refreshToken: process.env.SLACK_APP_CONFIG_REFRESH_TOKEN,
* }),
* },
* });
*
* // Live resolver (platform-managed connections)
* import { channels } from '@mastra/connect';
*
* new Mastra({
* channels: await channels({ projectId }),
* });
* ```
*/
channels?: TChannels | ChannelsResolver<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, resolves to `'development'` for `mastra dev` runs (detected via
* `MASTRA_DEV`), then falls back to `process.env.NODE_ENV`. If none of these
* are 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[]`: Additional workers merged with the auto-created
* defaults. A custom worker replaces a default with the same `name`;
* duplicate names within the array throw. Use `false` to run no workers.
*/
workers?: MastraWorker[] | false;
/**
* Boot-time recovery behavior for orphaned agent/workflow runs.
*
* `workflows` controls whether the server calls
* {@link Mastra.restartAllActiveWorkflowRuns} on boot and whether
* `startWorkers()` starts the workflow recovery loop. Set it to `'off'` to
* skip both (no storage queries), for example when several replicas share
* one database and you recover runs another way. `workflowConcurrency` caps
* how many runs recovery restarts at once, `workflowGraceMs` sets how long a
* default-engine run must have stopped before it does, and
* `workflowScanIntervalMs` how often the loop looks.
*
* `durableAgents` controls whether the deployer will automatically call
* {@link Mastra.recoverAllDurableAgents} for every registered `DurableAgent`
* when the server starts (concurrently with `restartAllActiveWorkflowRuns`).
*
* - `'off'` (default): the deployer never auto-recovers durable agent runs.
* Operators can still call `mastra.recoverAllDurableAgents()` or
* `agent.recoverActiveRuns()` by hand.
* - `'auto'`: the deployer will invoke `recoverAllDurableAgents()` on boot,
* re-driving every RUNNING durable agent run discovered in storage.
*
* Opt-in only. Auto-recovery re-runs the agentic loop from the last persisted
* snapshot, so it re-issues LLM calls (real cost) and re-executes tool calls
* (must be idempotent). In multi-instance deploys a run another replica
* still drives is skipped, and recovered once that replica's claim lapses.
*
* @default { workflows: 'auto', workflowConcurrency: 5, workflowGraceMs: 2000, workflowScanIntervalMs: 60000, durableAgents: 'off' }
*/
recovery?: MastraRecoveryConfig;
/**
* Marks this instance as an internally-owned ephemeral Mastra — e.g. the
* fallback instance a standalone `Agent` lazily creates so its
* prepare-stream workflow has a pubsub-equipped Mastra to run on.
*
* Ephemeral instances skip module-level scorer-hook registration: they have
* no agent/scorer/editor registries for the hook to resolve against, so the
* hook could never persist a score — but the module-level emitter would
* retain the instance (and everything it references) for the lifetime of
* the process, leaking one Mastra graph per discarded standalone Agent
* (#19404).
*
* @internal Not part of the public API — do not set this on application
* Mastra instances; it silently disables scorer persistence.
*/
__ephemeral?: boolean;
}
/**
* Boot-time recovery configuration. See {@link Mastra['recoveryConfig']}.
*/
export interface MastraRecoveryConfig {
/**
* Restart RUNNING/WAITING workflow runs found in storage on server boot,
* and run the workflow recovery loop on instances that call `startWorkers()`.
* @default 'auto'
*/
workflows?: 'auto' | 'off';
/**
* Maximum number of workflow runs restarted at the same time by
* {@link Mastra.restartAllActiveWorkflowRuns} and the recovery loop. Use
* `Infinity` for no limit. A restarted run holds its slot until it finishes.
* @default 5
*/
workflowConcurrency?: number;
/**
* How long a RUNNING/WAITING default-engine run must show no sign of life
* before recovery restarts it: no instance holds the run's lease, and neither
* the run nor that lease changed for this long. A run skipped as live or in
* its grace period is looked at again by the recovery loop's next pass.
*
* Evented runs don't use it. On a pubsub whose broker redelivers unacked
* messages (see `PubSub.redeliversUnacked`) the broker recovers them; on any
* other pubsub they are restarted at once.
* @default 2000
*/
workflowGraceMs?: number;
/**
* How often the workflow recovery loop looks for default-engine runs whose
* instance stopped. Each wait is up to a fifth shorter or longer, so
* instances that booted together don't look at once, and is shortened when
* a run the last pass saw comes out of its grace period sooner. Capped at
* 2^31 - 1 ms. One instance at a time runs the passes; see
* {@link Mastra.startWorkers}.
* @default 60000
*/
workflowScanIntervalMs?: number;
/**
* Auto-recover orphaned RUNNING durable agent runs on server boot.
* @default 'off'
*/
durableAgents?: 'auto' | 'off';
}
export interface WorkersConfigSection {
enabled: boolean;
[key: string]: unknown;
}
export interface WorkersConfig {
version: 1;
orchestration: WorkersConfigSection;
scheduler: WorkersConfigSection;
backgroundTasks: WorkersConfigSection;
custom: string[];
}
/**
* Registers and coordinates agents, workflows, storage, and other Mastra services.
*
* @example
* `yourAgent` is an agent you have already configured.
* ```typescript
* import { Mastra } from '@mastra/core/mastra';
*
* const mastra = new Mastra({
* agents: { assistant: yourAgent },
* });
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Mastra documentation](https://mastra.ai/reference/core/mastra-class)
* if packaged docs are unavailable.
*/
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>, TClassifiers extends Record<string, Classifier<any>> = Record<string, Classifier<any>>, TKnowledge extends Record<string, Knowledge> = Record<string, Knowledge>> {
#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;
/** Returns a serializable snapshot of this instance's active worker configuration. */
getWorkerConfig(): WorkersConfig;
get backgroundTaskManager(): BackgroundTaskManager | undefined;
/**
* Returns the workflow scheduler owned by the SchedulerWorker,
* or undefined if the scheduler is not enabled / not yet started.
*
* It is created when worker startup detects scheduling work, or lazily when
* a schedule is created after boot.
*
* 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.
*
* When channels were configured with a {@link ChannelsResolver}, this
* returns the latest resolved snapshot (possibly `undefined` before the
* first resolution completes). Use {@link resolveChannels} to get the
* current provider map.
*/
getChannelProviders(): Record<string, ChannelProvider> | undefined;
/**
* Resolves the current channel provider map.
*
* For a static `channels` record this returns it directly. For a
* {@link ChannelsResolver} it invokes the resolver (the resolver owns
* freshness via its own cache/TTL), attaches and initializes any providers
* not seen before, and updates the synchronous snapshot served by
* {@link getChannelProviders} / {@link channels}.
*
* Server handlers that act on channels (webhooks, connect/disconnect,
* listings) should await this instead of reading the snapshot so
* connections added after boot are picked up.
*/
resolveChannels(): Promise<Record<string, ChannelProvider>>;
/**
* 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.
* When unset, resolves to `'development'` for `mastra dev` runs (detected via
* `MASTRA_DEV`), then falls back to `process.env.NODE_ENV`, or `undefined` if
* none are 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, any, 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: ServerConfigInput): 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, TClassifiers, TKnowledge>);
/**
* Resolve the handler for a handler-mode file-based schedule. Handlers are
* functions and therefore cannot be persisted on the JSON schedule row, so
* the agent-schedule worker looks them up in-process by row id at fire time.
*
* @internal — public so the agent-schedule worker can call it.
*/
__getFsAgentScheduleHandler(scheduleId: string): AgentScheduleHandler<Mastra> | undefined;
/**
* 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 and
* agent controllers. Keys are agent / agent controller registration keys.
* A controller's channels — also attached to its mode agents — are
* reported once, under the controller's key.
*/
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.
*
* Looking up a specific `versionId` requires the editor package to be
* configured — throws `MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP` if
* it is not. A `status` selector is a default rather than a request for a
* specific stored version (the server stamps one on every agent request), so
* without the editor there are no stored versions and the code-defined agent
* is returned as-is.
*
* @param agent - The code-defined agent to resolve a version for.
* @param version - Selects a version by ID or publication status.
* @returns The code-defined agent for a status selector without an editor, otherwise 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.
* Re-registering the same instance under the same key is a no-op. Rehydrating
* a stored agent under an existing stored-agent key also leaves the original
* registration unchanged.
*
* @throws {MastraError} When a different agent with the same key already exists,
* except when both registrations have source 'stored'
*
* @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 logger (discovered from `logger.ts`) into
* this Mastra instance.
*
* Code-registered loggers win: if the user already passed `logger` to the
* `new Mastra({logger})` constructor (including `logger: false`), the
* file-system logger is skipped and a warning is logged. Otherwise the
* fs-provided logger replaces the default ConsoleLogger via {@link setLogger}.
*
* Intended to be called by the bundler/dev generated entry, not by user code.
*
* @internal
*/
__registerFsLogger(fsLogger: TLogger): 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(): IDeployer | 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;
agentSource?: DefinitionSource;
}): 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];
/**
* Track an in-flight evented workflow run owned by this instance so
* {@link shutdown} can let it settle before tearing down pubsub. Returns a
* release function the caller must invoke once the run has settled.
*
* @internal
*/
__trackEventedRun(execution: Promise<unknown>): () => void;
/**
* 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.
*
* Pass `{ distributed: true }` (unscoped only) when every process registers
* the workflow identically, so any process's workers can execute its runs.
* Its events then travel through the shared pubsub instead of being kept
* local to the publishing process.
*/
__registerInternalWorkflow(workflow: AnyWorkflow, runId?: string, options?: {
distributed?: boolean;
}): 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;
/**
* Whether this process consumes workflow-execution events itself, i.e.
* whether a `workflow.start` published here would be handled here.
*
* True when a local OrchestrationWorker is pulling the `workflows` topic,
* or when a push-only pubsub has `handleWorkflowEvent` wired directly
* (`#wirePushWorkflowSubscription`).
*
* The scheduler uses this to keep a scheduled fire on the instance that
* claimed it (#19169). Scheduler and execution workers start through
* separate paths (`#startSchedulingWorkers` / `#startExecutionWorkers`),
* so a scheduler-only process is a supported topology and must keep
* publishing to the shared topic instead of stranding the fire locally.
*
* @internal
*/
__hasLocalWorkflowExecution(): boolean;
__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
*
* @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];
/**
* Every RUNNING/WAITING run of the workflows recovery restarts, with full snapshots, read in one
* call per workflow and status. `restartAllActiveWorkflowRuns()` lists summaries instead.
*/
listActiveWorkflowRuns(): Promise<WorkflowRuns>;
/**
* Restarts the RUNNING/WAITING runs of the registered workflows that no process runs any more,
* `recovery.workflowConcurrency` at a time (default 5).
*
* A default-engine run counts as stopped once no instance holds its run lease and
* `recovery.workflowGraceMs` passed since it or its lease last changed. A run still live or in
* its grace period is left to the recovery loop (see {@link Mastra.startWorkers}); this call
* doesn't look at it again. Without run fencing in the store, every active default-engine run is
* restarted.
*
* An evented run on a pubsub whose broker redelivers unacked messages
* (`PubSub.redeliversUnacked`) is left to the broker and never read, except a scheduled run
* whose events stay in the process. Every other evented run is restarted at once, by this call
* only: the recovery loop never restarts evented runs.
*
* Resolves once every restart its pass queued finished. Runs an earlier pass already queued are
* skipped and not awaited. A call made while a default-engine pass is still handing out restarts
* joins it. Failures are logged per run and never reject. Once `shutdown()` starts, no further
* runs are restarted.
*/
restartAllActiveWorkflowRuns(): Promise<void>;
/**
* The resolved boot-time recovery configuration for this Mastra instance.
* See {@link Config.recovery}.
*/
get recoveryConfig(): MastraRecoveryConfig;
/**
* True once `shutdown()` has started. Durable agents use it to checkpoint
* in-flight runs so they can be recovered after the process exits.
* @internal
*/
get __shuttingDown(): boolean;
/**
* Re-drive every orphaned RUNNING durable-agent run across every registered
* `DurableAgent`. Delegates to `DurableAgent.recoverActiveRuns()` on each
* agent that supports it (default-engine durable agents only — Inngest and
* other externally-executed durable wrappers run their own recovery).
*
* Intended to be called once on server boot, concurrently with
* `restartAllActiveWorkflowRuns()`. The deployer wires this up automatically
* when `recovery.durableAgents` is set to `'auto'` in the Mastra config; you
* can also call it directly if you need finer control (e.g. running it in a
* cron, or gating it behind a leader election).
*
* Runs another instance still drives are skipped, not taken over, and
* counted in `skipped`. Each is re-checked once that instance's claim could
* have lapsed, so a run whose instance crashed is recovered without another
* call. `shutdown()` cancels pending re-checks.
*
* Requires persistent storage — with an in-memory store there is nothing to
* recover after a process restart, so this is a no-op and returns zeroed
* counts.
*/
recoverAllDurableAgents(): Promise<{
agents: number;
recovered: number;
succeeded: number;
failed: number;
skipped: number;
}>;
/** @internal Bound waiting, not execution; shutdown must still drain the original attempt. */
__awaitDurableRecoveryAttempt<T>(promise: Promise<T>, description: string): Promise<{
value: T;
} | undefined>;
/**
* 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 classifiers keyed by their registration key.
*/
listClassifiers(): TClassifiers | undefined;
/**
* Adds a classifier to the Mastra instance.
*
* If a classifier with the same key already exists, this method leaves the existing
* classifier registered and returns.
*
* @example
* ```typescript
* const mastra = new Mastra();
* mastra.addClassifier(new Classifier({ id: 'safety', model })); // Uses classifier.id as key
* mastra.addClassifier(new Classifier({ id: 'safety', model }), 'customKey');
* ```
*/
addClassifier<C extends Classifier<any>>(classifier: C, key?: string): void;
/**
* Retrieves a registered classifier by its registration key.
*
* @throws {MastraError} When the classifier with the specified key is not found
*/
getClassifier<TClassifierKey extends keyof TClassifiers>(key: TClassifierKey): TClassifiers[TClassifierKey];
/**
* Retrieves a registered classifier by its `id`, falling back to the registration key.
*
* @throws {MastraError} When no classifier is found with the specified id
*/
getClassifierById<TClassifierKey extends keyof TClassifiers>(id: TClassifiers[TClassifierKey]['id']): TClassifiers[TClassifierKey];
/**
* Removes a classifier from the Mastra instance by its key or id.
*
* @returns true if a classifier was removed, false if no classifier was found
*/
removeClassifier(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.
*
* If a tool with the same key already exists, this method leaves the existing
* tool registered and returns without an error. The new tool is not added.
*
* @throws {MastraError} When the tool is undefined
*
* @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;
/**
* Removes a tool from the Mastra instance by its registration key.
*
* Also unregisters the tool's static executor from the background task
* manager, if one was registered.
*
* @returns `true` if a tool was removed, `false` if no tool was registered under the key
*
* @example
* ```typescript
* mastra.removeTool('calculator-tool');
* ```
*/
removeTool(key: string): boolean;
/**
* 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
* @param source - Where the agent is defined. Configurations of stored agents stay marked as stored, so they can
* be told apart from code agents' configurations after the stored agent is gone.
*/
addProcessorConfiguration(processor: Processor, agentId: string, type: 'input' | 'output', source?: DefinitionSource): 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';
source?: DefinitionSource;
}>;
/**
* Gets all processor configurations.
*
* @returns Map of processor IDs to their configurations
*/
listProcessorConfigurations(): Map<string, Array<{
processor: Processor;
agentId: string;
type: 'input' | 'output';
source?: DefinitionSource;
}>>;
/** Retrieves a registered Knowledge instance by its application key. */
getKnowledge<TKnowledgeKey extends keyof TKnowledge>(key: TKnowledgeKey): TKnowledge[TKnowledgeKey];
/** Returns all registered Knowledge instances keyed by application key. */
listKnowledge(): TKnowledge;
/** Registers a Knowledge instance without initializing its storage. */
addKnowledge<K extends Knowledge>(knowledge: K, key?: string): void;
/**
* 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
* ```
*/
addMemory<M extends MastraMemory>(memory: M, key?: string): void;
/**
* Returns all registered workflows as a record keyed by their IDs.
*
* @example Listing all workflows
* ```typescript
* const mastra = new Mastra({
* workflows: {
* dataProcessor: createWorkflow({...}).commit(),
* emailSender: createWorkflow({...}).commit(),
* reportGenerator: createWorkflow({...}).commit()
* }
* });
*
* const allWorkflows = mastra.listWorkflows();
* console.log(Object.keys(allWorkflows)); // ['dataProcessor', 'emailSender', 'reportGenerator']
*
* // Execute all workflows with sample data
* for (const [id, workflow] of Object.entries(allWorkflows)) {
* console.log(`Workflow ${id}:`, workflow.name);
* // const result = await workflow.execute(sampleData);
* }
* ```
*/
listWorkflows(props?: {
serialized?: boolean;
}): Record<string, Workflow>;
/**
* Removes a workflow from the Mastra instance by its key or ID.
* Used when dynamic workflows are updated/deleted so subsequent saves can
* re-register the same id cleanly.
*
* Note: this only clears the live in-process registration. In-flight runs
* are unaffected (they capture stepFlow at start time). Static workflow
* scorers stay registered (matching removeAgent/removeTool behavior).
*
* @param keyOrId - The workflow key or ID to remove
* @returns true if a workflow was removed, false if no workflow was found
*
* @example
* ```typescript
* // Remove by key
* mastra.removeWorkflow('myWorkflow');
*
* // Remove by ID
* mastra.removeWorkflow('workflow-123');
* ```
*/
removeWorkflow(keyOrId: string): boolean;
/**
* Returns how a workflow was registered — `'code'` for statically declared
* or `addWorkflow()`-added workflows, `'dynamic'` for anything added via
* `addDynamicWorkflow()` (either at boot or through the HTTP/SDK surface).
* Returns `undefined` if no workflow is registered under that key/id.
*
* Reads `workflow.origin`, which is set to `'dynamic'` by `rehydrateWorkflow`
* at construction time and defaults to `'code'` otherwise. Used by the HTTP
* layer to surface a visual distinction (e.g. a "Dynamic" badge in Studio).
*/
getWorkflowOrigin(keyOrId: string): 'code' | 'dynamic' | undefined;
/**
* Adds a new workflow to the Mastra instance.
*
* This method allows dynamic registration of workflows after the Mastra instance
* has been created. The workflow will be initialized with Mastra and primitives.
*
* @throws {MastraError} When a workflow with the same key already exists
*
* @example
* ```typescript
* const mastra = new Mastra();
* const newWorkflow = createWorkflow({
* id: 'data-pipeline',
* name: 'Data Pipeline'
* }).commit();
* mastra.addWorkflow(newWorkflow); // Uses workflow.id as key
* // or
* mastra.addWorkflow(newWorkflow, 'customKey'); // Uses custom key
* ```
*/
addWorkflow(workflow: AnyWorkflow, key?: string): void;
/**
* Persist a static workflow definition to storage and live-register it on
* this Mastra instance so it becomes immediately runnable. The same path is
* used by `loadDynamicWorkflows()` at boot to re-materialize previously saved
* workflows.
*
* @example
* ```typescript
* await mastra.addDynamicWorkflow({
* id: 'cli-weather-v1',
* inputSchema: { type: 'object', properties: { location: { type: 'string' } }, required: ['location'] },
* outputSchema: { type: 'object', properties: { report: { type: 'string' } }, required: ['report'] },
* graph: [...],
* });
*
* const run = await mastra.getWorkflow('cli-weather-v1').createRun();
* await run.start({ inputData: { location: 'Helsinki' } });
* ```
*/
addDynamicWorkflow(def: DynamicWorkflowGraph | WorkflowBuilderDefinitionInput): Promise<void>;
/**
* Persist and live-register a set of dynamic workflow definitions that depend
* on each other — typically a root workflow plus the helper workflows it
* nests, none of which exist yet.
*
* The bundle is validated as a unit: references resolve against this
* instance's registries UNION the bundle's own ids, so a root may nest a
* helper being introduced in the same call. Members are then hydrated in
* dependency order, since hydration resolves nested workflows through the
* live registry.
*
* Failure semantics — a rejected bundle registers nothing:
* - Duplicate ids, invalid members, and dependency cycles are all detected
* before anything is mutated.
* - If hydration or persistence fails partway, the in-memory registry is
* restored to its prior state.
* - Storage writes happen last. A storage-level failure mid-bundle is the
* one residual window where rows can be partially written; the registry is
* still rolled back, and the orphaned rows are inert until the next boot.
*
* `addDynamicWorkflow()` is the single-member case.
*
* @example
* ```typescript
* await mastra.addDynamicWorkflows([
* { id: 'lookup-first-customer', ... }, // helper — order is derived, not assumed
* { id: 'parallel-customer-lookup', ... }, // root, nests the helper above
* ]);
* ```
*/
addDynamicWorkflows(defs: readonly (DynamicWorkflowGraph | WorkflowBuilderDefinitionInput)[]): Promise<void>;
/**
* Signal that a schedule has been registered imperatively at runtime
* (e.g. `mastra.schedules.create()` after `startWorkers()`). Flips the
* scheduler-requested flag and, if workers are already running,
* lazily injects + starts both the scheduler and agent-schedule workers.
*
* @internal
*/
__ensureScheduleRuntimeReady(): Promise<void>;
/**
* Publish a best-effort cross-process wake after the schedule row is durable.
* This also runs in producer-only (`workers: false`) processes.
*
* @internal
*/
__publishSchedulerWake(scheduleId: string): Promise<void>;
/**
* Signal that a deferred notification exists and the dispatcher schedule is
* needed. Lazily upserts the dispatcher schedule row (imperative, non-`wf_`
* id so declarative orphan-cleanup leaves it alone) and requests the
* scheduler — mirroring `__ensureScheduleRuntimeReady()`. This also supports
* processes that publish notifications without running workers locally.
*
* The row is read on every call rather than memoized: the dispatcher deletes
* it once nothing is pending (`__releaseNotificationDispatchIfIdle()`),
* possibly from another process, and the next deferral must re-arm it.
*
* @internal
*/
__ensureNotificationDispatchReady(): Promise<void>;
/**
* Called by the dispatcher after each pass. When no deferred notification is
* pending, deletes the dispatcher schedule row so its cron stops firing and
* an idle app stops polling storage. The next deferral re-creates it.
*
* @internal
*/
__releaseNotificationDispatchIfIdle(): Promise<void>;
private registerStaticWorkflowScorers;
/**
* Sets the storage provider for the Mastra instance.
*
* @example
* ```typescript
* const mastra = new Mastra();
*
* // Set PostgreSQL storage
* mastra.setStorage(new PostgresStore({
* connectionString: process.env.DATABASE_URL
* }));
*
* // Now agents can use memory with the storage
* const agent = new Agent({
* id: 'assistant',
* name: 'assistant',
* memory: new Memory({ storage: mastra.getStorage() })
* });
* ```
*/
setStorage(storage: MastraCompositeStore): void;
setLogger({ logger }: {
logger: TLogger;
}): void;
/**
* Gets all registered text-to-speech (TTS) providers.
*
* @example
* ```typescript
* const mastra = new Mastra({
* tts: {
* openai: new OpenAITTS({
* apiKey: process.env.OPENAI_API_KEY,
* voice: 'alloy'
* })
* }
* });
*
* const ttsProviders = mastra.getTTS();
* const openaiTTS = ttsProviders?.openai;
* if (openaiTTS) {
* const audioBuffer = await openaiTTS.synthesize('Hello, world!');
* }
* ```
*/
getTTS(): TTTS | undefined;
/**
* Gets the currently configured logger instance.
*
* @example
* ```typescript
* const mastra = new Mastra({
* logger: new PinoLogger({
* name: 'MyApp',
* level: 'info'
* })
* });
*
* const logger = mastra.getLogger();
* logger.info('Application started');
* logger.error('An error occurred', { error: 'details' });
* ```
*/
getLogger(): TLogger;
/**
* Gets the currently configured storage provider.
*
* @example
* ```typescript
* const mastra = new Mastra({
* storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./data.db' })
* });
*
* // Use the storage in agent memory
* const agent = new Agent({
* id: 'assistant',
* name: 'assistant',
* memory: new Memory({
* storage: mastra.getStorage()
* })
* });
* ```
*/
getStorage(): MastraCompositeStore | undefined;
get observability(): ObservabilityEntrypoint;
/**
* Structured logging API for observability.
* Logs emitted via this API will not have trace correlation when used outside a span.
* Use for startup logs, background jobs, or other non-traced scenarios.
*
* Note: For the infrastructure logger (IMastraLogger), use getLogger() instead.
*/
get loggerVNext(): LoggerContext;
/**
* Direct metrics API for use outside trace context.
* Metrics emitted via this API will not have auto correlation or cost context from spans.
* Use for background jobs, startup metrics, or other non-traced scenarios.
*/
get metrics(): MetricsContext;
getServerMiddleware(): {
handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;
path: string;
}[];
getServerCache(): MastraServerCache;
setServerMiddleware(serverMiddleware: Middleware | Middleware[]): void;
getServer(): ServerConfig | undefined;
/**
* Gets the Studio-specific authentication and authorization configuration.
*
* @returns The studio config, or undefined if not configured
*
* @example
* ```typescript
* const studioConfig = mastra.getStudio();
* if (studioConfig?.auth) {
* // Studio has separate auth configured
* }
* ```
*/
getStudio(): StudioConfig | undefined;
/**
* Sets the server adapter for this Mastra instance.
*
* The server adapter provides access to the underlying server app (e.g., Hono, Express)
* and allows users to call routes directly via `app.fetch()` instead of making HTTP requests.
*
* This is typically called by `createHonoServer` or similar factory functions during
* server initialization.
*
* @param adapter - The server adapter instance (e.g., MastraServer from @mastra/hono or @mastra/express)
*
* @example
* ```typescript
* const app = new Hono();
* const adapter = new MastraServer({ app, mastra });
* mastra.setMastraServer(adapter);
* ```
*/
setMastraServer(adapter: MastraServerBase): void;
/**
* Gets the server adapter for this Mastra instance.
*
* @returns The server adapter, or undefined if not set
*
* @example
* ```typescript
* const adapter = mastra.getMastraServer();
* if (adapter) {
* const app = adapter.getApp<Hono>();
* }
* ```
*/
getMastraServer(): MastraServerBase | undefined;
/**
* Gets the server app from the server adapter.
*
* This is a convenience method that calls `getMastraServer()?.getApp<T>()`.
* Use this to access the underlying server framework's app instance (e.g., Hono, Express)
* for direct operations like calling routes via `app.fetch()`.
*
* @template T - The expected type of the app (e.g., Hono, Express Application)
* @returns The server app, or undefined if no adapter is set
*
* @example
* ```typescript
* // After createHonoServer() is called:
* const app = mastra.getServerApp<Hono>();
*
* // Call routes directly without HTTP overhead
* const response = await app?.fetch(new Request('http://localhost/health'));
* const data = await response?.json();
* ```
*/
getServerApp<T = unknown>(): T | undefined;
getBundlerConfig(): BundlerConfig | undefined;
listLogsByRunId({ runId, transportId, fromDate, toDate, logLevel, filters, page, perPage, }: {
runId: string;
transportId: string;
fromDate?: Date;
toDate?: Date;
logLevel?: LogLevel;
filters?: Record<string, any>;
page?: number;
perPage?: number;
}): Promise<{
logs: import("../_types/@internal_core@0.1.4/dist/logger/index.js").BaseLogMessage[];
total: number;
page: number;
perPage: number;
hasMore: boolean;
}>;
listLogs(transportId: string, params?: {
fromDate?: Date;
toDate?: Date;
logLevel?: LogLevel;
filters?: Record<string, any>;
page?: number;
perPage?: number;
}): Promise<{
logs: import("../_types/@internal_core@0.1.4/dist/logger/index.js").BaseLogMessage[];
total: number;
page: number;
perPage: number;
hasMore: boolean;
}>;
/**
* Gets all registered Model Context Protocol (MCP) server instances.
*
* @example
* ```typescript
* const mastra = new Mastra({
* mcpServers: {
* filesystem: new FileSystemMCPServer({
* rootPath: '/app/data'
* })
* }
* });
*
* const mcpServers = mastra.getMCPServers();
* if (mcpServers) {
* const fsServer = mcpServers.filesystem;
* const tools = await fsServer.listTools();
* }
* ```
*/
listMCPServers(): Record<string, MCPServerBase> | undefined;
/**
* Adds a new MCP server to the Mastra instance.
*
* This method allows dynamic registration of MCP servers after the Mastra instance
* has been created. The server will be initialized with ID, Mastra instance, and logger.
*
* @throws {MastraError} When an MCP server with the same key already exists
*
* @example
* ```typescript
* const mastra = new Mastra();
* const newServer = new FileSystemMCPServer({
* rootPath: '/data'
* });
* mastra.addMCPServer(newServer); // Uses server.id as key
* // or
* mastra.addMCPServer(newServer, 'customKey'); // Uses custom key
* ```
*/
addMCPServer<M extends MCPServerBase>(server: M, key?: string): void;
/**
* Retrieves a specific MCP server instance by registration key.
*
* @throws {MastraError} When the specified MCP server is not found
*
* @example
* ```typescript
* const mastra = new Mastra({
* mcpServers: {
* filesystem: new FileSystemMCPServer({...})
* }
* });
*
* const fsServer = mastra.getMCPServer('filesystem');
* const tools = await fsServer.listTools();
* ```
*/
getMCPServer<TMCPServerName extends keyof TMCPServers>(name: TMCPServerName): TMCPServers[TMCPServerName] | undefined;
/**
* Retrieves a specific Model Context Protocol (MCP) server instance by its logical ID.
*
* This method searches for an MCP server using its logical ID. If a version is specified,
* it returns the exact version match. If no version is provided, it returns the server
* with the most recent release date.
*
* @example
* ```typescript
* const mastra = new Mastra({
* mcpServers: {
* filesystem: new FileSystemMCPServer({
* id: 'fs-server',
* version: '1.0.0',
* rootPath: '/app/data'
* })
* }
* });
*
* const fsServer = mastra.getMCPServerById('fs-server');
* if (fsServer) {
* const tools = await fsServer.listTools();
* }
* ```
*/
getMCPServerById<TMCPServerName extends keyof TMCPServers>(serverId: TMCPServers[TMCPServerName]['id'], version?: string): TMCPServers[TMCPServerName] | undefined;
addTopicListener(topic: string, listener: (event: any) => Promise<void>): Promise<void>;
removeTopicListener(topic: string, listener: (event: any) => Promise<void>): Promise<void>;
/**
* Process a single workflow event. Shared entry point used by:
* - pull-mode workers (OrchestrationWorker)
* - in-process push pubsubs (EventEmitterPubSub) wired during startWorkers()
* - HTTP push delivered to `POST /api/workers/events`
*
* Returns `{ ok: true }` on success; the caller should ack/return 2xx.
* Returns `{ ok: false, retry: true }` on transient failure; the caller
* should nack/return 5xx so the broker retries.
*/
handleWorkflowEvent(event: Event): Promise<{
ok: true;
} | {
ok: false;
retry: boolean;
}>;
/**
* Initialize and start workers. If `name` is provided, starts only
* that worker. Otherwise starts all registered workers and subscribes
* user-defined event listeners.
*
* When the orchestration worker is among them, this also starts the
* workflow recovery loop (unless `recovery.workflows` is `'off'`): every
* `recovery.workflowScanIntervalMs` it restarts default-engine runs whose
* instance stopped, by the rule of {@link Mastra.restartAllActiveWorkflowRuns}.
* Instances sharing a store elect one leader through a run lease; the others'
* ticks only try to take that role, which they get once the leader's
* `stopWorkers()` releases it or its lease lapses. The leader's loop looks
* only at the workflows it registers, and the runs it restarts execute on
* it. The loop never restarts evented runs, and doesn't run on a store
* without run fencing.
*/
startWorkers(name?: string): Promise<void>;
/**
* Ensure the execution-side machinery — the `orchestration` and
* `backgroundTasks` workers, plus the push-mode workflow subscription —
* is running. Called lazily by {@link BackgroundTaskManager} when a task
* is dispatched or resumed, so background tasks execute in "library mode"
* where nothing ever calls `startWorkers()` (no server, no `mastra dev`;
* see #19339).
*
* Deliberately narrower than `startWorkers()`: it never injects or starts
* the scheduler/agent-schedule workers and never subscribes user event
* listeners — dispatching a background task must not boot cron machinery
* as a side effect.
*
* Honors the same opt-outs as the rest of the worker lifecycle:
* `workers: false` / `MASTRA_WORKERS=false` (standalone-worker topologies
* run their own worker processes, so this instance must not start local
* ones) and the `MASTRA_WORKERS` name filter.
*
* The fast path is its own `#executionWorkersStarted` flag, NOT
* `#workersStarted` — the latter is set by any `startWorkers(name)` call,
* including partial named starts (e.g. `startWorkers('backgroundTasks')`)
* that never start the orchestration worker or push wiring, which would
* leave dispatched tasks stuck again. The pass itself is idempotent
* (per-worker `isRunning` checks, idempotent push wiring), so running it
* once after a full `startWorkers()` boot is a cheap no-op.
*
* @internal
*/
__ensureExecutionWorkersStarted(): Promise<void>;
/**
* Stop all running workers and unsubscribe event listeners.
*
* Workflow events already being processed are given up to
* `options.drainTimeout` milliseconds (default 5000) to finish before the
* pubsub is flushed.
*/
stopWorkers(options?: WorkerStopOptions): Promise<void>;
/**
* Release the module-level hooks this instance registered in its constructor.
* The scorer hook is added to a shared emitter that never drops handlers on
* its own, so short-lived internal/ephemeral Mastras must call this on teardown
* or their handler keeps firing (and failing to resolve the scorer) on every
* scorer run for the rest of the process. Idempotent.
* @internal
*/
__unregisterHooks(): void;
/**
* @deprecated Use {@link Mastra.startWorkers} instead. Will be removed in a
* future release.
*/
startEventEngine(name?: string): Promise<void>;
/**
* @deprecated Use {@link Mastra.stopWorkers} instead. Will be removed in a
* future release.
*/
stopEventEngine(): Promise<void>;
/**
* Retrieves a registered gateway by its key.
*
* @throws {MastraError} When the gateway with the specified key is not found
*
* @example
* ```typescript
* const mastra = new Mastra({
* gateways: {
* myGateway: new CustomGateway()
* }
* });
*
* const gateway = mastra.getGateway('myGateway');
* ```
*/
getGateway(key: string): MastraModelGatewayInterface;
/**
* Retrieves a registered gateway by its ID.
*
* Searches through all registered gateways and returns the one whose ID matches.
* If a gateway doesn't have an explicit ID, its name is used as the ID.
*
* @throws {MastraError} When no gateway with the specified ID is found
*
* @example
* ```typescript
* class CustomGateway extends MastraModelGateway {
* readonly id = 'custom-gateway-v1';
* readonly name = 'Custom Gateway';
* // ...
* }
*
* const mastra = new Mastra({
* gateways: {
* myGateway: new CustomGateway()
* }
* });
*
* const gateway = mastra.getGatewayById('custom-gateway-v1');
* ```
*/
getGatewayById(id: string): MastraModelGatewayInterface;
/**
* Returns all registered gateways as a record keyed by their registration keys.
*
* Gateways can be plain objects that satisfy `MastraModelGatewayInterface` or
* classes that extend `MastraModelGateway`.
*
* @example
* ```typescript
* import { createOpenAICompatible } from '@ai-sdk/openai-compatible-v6';
* import { MastraModelGateway, type MastraModelGatewayInterface } from '@mastra/core/llm';
*
* const plainGateway: MastraModelGatewayInterface = {
* id: 'plain-gateway',
* name: 'Plain Gateway',
* async fetchProviders() { return {}; },
* buildUrl() { return undefined; },
* async getApiKey() { return ''; },
* resolveLanguageModel(args) { return createOpenAICompatible({ name: args.providerId, apiKey: args.apiKey }).chatModel(args.modelId); },
* };
*
* class ClassGateway extends MastraModelGateway {
* readonly id = 'class-gateway';
* readonly name = 'Class Gateway';
* // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.
* }
*
* const mastra = new Mastra({
* gateways: {
* plain: plainGateway,
* class: new ClassGateway(),
* },
* });
*
* const allGateways = mastra.listGateways();
* console.log(Object.keys(allGateways ?? {})); // ['plain', 'class']
* ```
*/
listGateways(): Record<string, MastraModelGatewayInterface> | undefined;
/**
* Adds a new gateway to the Mastra instance.
*
* This method allows dynamic registration of gateways after the Mastra instance
* has been created. Gateways enable access to LLM providers through custom
* authentication and routing logic.
*
* If no key is provided, the gateway's ID will be used as the key.
*
* @example Plain object gateway
* ```typescript
* import type { MastraModelGatewayInterface } from '@mastra/core/llm';
*
* const customGateway: MastraModelGatewayInterface = {
* id: 'custom-gateway-v1',
* name: 'Custom Gateway',
* async fetchProviders() {
* return {
* myProvider: {
* name: 'My Provider',
* models: ['model-1', 'model-2'],
* apiKeyEnvVar: 'MY_API_KEY',
* gateway: 'custom-gateway-v1',
* },
* };
* },
* buildUrl() {
* return 'https://api.myprovider.com/v1';
* },
* async getApiKey() {
* return process.env.MY_API_KEY || '';
* },
* async resolveLanguageModel({ modelId, providerId, apiKey }) {
* const provider = createOpenAICompatible({
* name: providerId,
* apiKey,
* baseURL: this.buildUrl(),
* supportsStructuredOutputs: true,
* });
* return provider.chatModel(modelId);
* },
* };
*
* const mastra = new Mastra();
* mastra.addGateway(customGateway);
* ```
*
* @example Convenience base class
* ```typescript
* import { MastraModelGateway } from '@mastra/core/llm';
*
* class CustomGateway extends MastraModelGateway {
* readonly id = 'custom-gateway-v1';
* readonly name = 'Custom Gateway';
*
* // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.
* }
*
* mastra.addGateway(new CustomGateway(), 'customKey');
* ```
*/
addGateway(gateway: MastraModelGatewayInterface, key?: string): void;
/**
* Gracefully shuts down the Mastra instance and cleans up all resources.
*
* This method performs a clean shutdown of all Mastra components, including:
* - tracing registry and all tracing instances
* - Event engine and pub/sub system
* - registered workspaces (sandbox processes, filesystem handles, LSP, browser)
* - All registered components and their resources
*
* It's important to call this method when your application is shutting down
* to ensure proper cleanup and prevent resource leaks.
*
* @example
* ```typescript
* const mastra = new Mastra({
* agents: { myAgent },
* workflows: { myWorkflow }
* });
*
* // Graceful shutdown on SIGINT
* process.on('SIGINT', async () => {
* await mastra.shutdown();
* process.exit(0);
* });
* ```
*
* In-flight evented workflow runs (including durable agent runs) started
* through this instance are given up to `drainTimeout` milliseconds
* (default 5000) to reach a terminal or suspended state before workers and
* pubsub subscriptions are torn down. Runs that do not settle within the
* window are abandoned with a warning. Durable agent runs using the default
* snapshot policy persist a `running` checkpoint at each step boundary they
* reach during the drain. An abandoned durable agent run then stops without
* writing and is released. It can be recovered only if a checkpoint was
* persisted.
*
* Agent thread runs this instance still holds are then handed back. A run
* still executing is aborted so it starts no further steps, and other
* processes watching its thread see it end; its partial response is not
* saved. A run parked on a tool approval or suspension stays parked and
* resumable. Either way the thread lease is released right away instead of
* at expiry, so another process can use the thread immediately. Release is
* best-effort: if an aborted run doesn't stop in time (for example, a tool
* call that ignores the abort), or the lease backend doesn't answer or
* fails the release, the lease is kept until it expires. Handing runs back can take up to about 1.5 seconds past
* `drainTimeout`.
*/
shutdown(options?: {
drainTimeout?: number;
}): Promise<void>;
get serverCache(): MastraServerCache;
}
//# sourceMappingURL=index.d.ts.map