{"version":3,"sources":["../src/mastra/index.ts"],"names":["MastraError","agentThreadStreamRuntime","DatasetsManager","randomUUID","NoOpObservability","initContextStorage","InMemoryServerCache","normalizeToolPayloadTransformPolicy","EventEmitterPubSub","OrchestrationWorker","BackgroundTaskWorker","noopLogger","LogLevel","ConsoleLogger","augmentWithInit","DualLogger","defaultGateways","registerHook","createOnScorerHook","BackgroundTaskManager","computeNextFireAt","AgentChannels","isDurableAgentLike","agentKey","agents","isToolLoopAgentLike","toolLoopAgentToMastraAgent","noOpLoggerContext","noOpMetricsContext","WorkflowEventProcessor","SchedulerWorker"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkEA,SAAS,6BAAA,CACP,IAAA,EAWA,KAAA,EACA,GAAA,EACa;AACb,EAAA,MAAM,SAAA,GAAY,IAAA,KAAS,YAAA,GAAe,YAAA,GAAe,IAAA;AACzD,EAAA,MAAM,OAAA,GAAU,cAAc,IAAA,CAAK,WAAA,GAAc,OAAA,CAAQ,GAAA,EAAK,GAAG,CAAC,CAAA,UAAA,CAAA;AAClE,EAAA,OAAO,IAAIA,6BAAA,CAAY;AAAA,IACrB,EAAA,EAAI,OAAA;AAAA,IACJ,MAAA,EAAA,QAAA;AAAA,IACA,QAAA,EAAA,MAAA;AAAA,IACA,IAAA,EAAM,cAAc,SAAS,CAAA,EAAA,EAAK,SAAS,CAAA,IAAA,EAAO,KAAA,KAAU,IAAA,GAAO,MAAA,GAAS,WAAW,CAAA,uHAAA,CAAA;AAAA,IACvF,OAAA,EAAS,EAAE,MAAA,EAAQ,GAAA,EAAK,GAAI,GAAA,IAAO,EAAE,KAAI;AAAG,GAC7C,CAAA;AACH;AASA,SAAS,YAAA,CAAa,GAAmC,CAAA,EAAgC;AACvF,EAAA,IAAI,CAAA,KAAM,GAAG,OAAO,IAAA;AACpB,EAAA,IAAI,CAAC,GAAG,OAAO,KAAA;AACf,EAAA,OAAO,KAAK,SAAA,CAAU,CAAC,CAAA,KAAM,IAAA,CAAK,UAAU,CAAC,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AAA,EA2BA,MAAM,QAAA,GAA0B;AAE9B,IAAA,MAAM,KAAK,WAAA,EAAY;AAEvB,IAAA,MAAM,IAAA,CAAK,eAAe,QAAA,EAAS;AAEnC,IAAA,IAAA,CAAK,OAAA,EAAS,KAAK,2BAA2B,CAAA;AAAA,EAChD;AAAA;AAAA,EAGA,IAAW,WAAA,GAAc;AACvB,IAAA,OAAO,IAAA,CAAK,YAAA;AAAA,EACd;AACF","file":"chunk-FENFWEH5.cjs","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../agent';\nimport { agentThreadStreamRuntime } from '../agent/thread-stream-runtime';\nimport type { DurableAgentLike } from '../agent/types';\nimport { isDurableAgentLike } from '../agent/types';\nimport { BackgroundTaskManager } from '../background-tasks';\nimport type { BackgroundTaskManagerConfig } from '../background-tasks/types';\nimport type { BundlerConfig } from '../bundler/types';\nimport { InMemoryServerCache } from '../cache';\nimport type { MastraServerCache } from '../cache';\nimport { AgentChannels } from '../channels';\nimport type { ChannelProvider } from '../channels';\nimport { DatasetsManager } from '../datasets/manager.js';\nimport type { MastraDeployer } from '../deployer';\nimport type { IMastraEditor } from '../editor';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../error';\nimport type { MastraScorer } from '../evals';\nimport { EventEmitterPubSub } from '../events/event-emitter';\nimport type { PubSub } from '../events/pubsub';\nimport type { Event, EventCallback } from '../events/types';\nimport { AvailableHooks, registerHook } from '../hooks';\nimport type { MastraModelGateway } from '../llm/model/gateways';\nimport { defaultGateways } from '../llm/model/router';\nimport { LogLevel, noopLogger, ConsoleLogger, DualLogger } from '../logger';\nimport type { IMastraLogger } from '../logger';\nimport type { MCPServerBase } from '../mcp';\nimport type { MastraMemory } from '../memory';\nimport type {\n  DefinitionSource,\n  ObservabilityEntrypoint,\n  ObservabilityExporter,\n  ObservabilityInstance,\n  LoggerContext,\n  MetricsContext,\n} from '../observability';\nimport { NoOpObservability, noOpLoggerContext, noOpMetricsContext } from '../observability';\nimport { initContextStorage } from '../observability/context-storage';\nimport type { Processor } from '../processors';\nimport type { MastraServerBase } from '../server/base';\nimport type { ApiRoute, Middleware, ServerConfig } from '../server/types';\nimport type { MastraCompositeStore, WorkflowRuns } from '../storage';\nimport type { Schedule, ScheduleUpdate, SchedulesStorage } from '../storage/domains/schedules/base';\nimport { augmentWithInit } from '../storage/storageWithInit';\nimport type { StorageResolvedPromptBlockType } from '../storage/types';\nimport type { ToolLoopAgentLike } from '../tool-loop-agent';\nimport { isToolLoopAgentLike, toolLoopAgentToMastraAgent } from '../tool-loop-agent';\nimport type { ToolAction, ToolPayloadTransformPolicy } from '../tools';\nimport { normalizeToolPayloadTransformPolicy } from '../tools/payload-transform';\nimport type { MastraTTS } from '../tts';\nimport type { MastraIdGenerator, IdGeneratorContext } from '../types';\nimport type { MastraVector } from '../vector';\nimport { OrchestrationWorker, SchedulerWorker, BackgroundTaskWorker } from '../worker';\nimport type { MastraWorker, WorkerDeps } from '../worker';\nimport type { AnyWorkflow, Workflow } from '../workflows';\nimport { WorkflowEventProcessor } from '../workflows/evented/workflow-event-processor';\nimport { computeNextFireAt } from '../workflows/scheduler';\nimport type { WorkflowScheduleConfig, WorkflowSchedulerConfig, WorkflowScheduler } from '../workflows/scheduler';\nimport type { AnyWorkspace, RegisteredWorkspace, Workspace } from '../workspace';\nimport { createOnScorerHook } from './hooks';\nimport type { VersionOverrides, VersionSelector } from './types';\n\n/**\n * Creates an error for when a null/undefined value is passed to an add* method.\n * This commonly occurs when config is spread ({ ...config }) and the original\n * object had getters or non-enumerable properties.\n */\nfunction createUndefinedPrimitiveError(\n  type:\n    | 'agent'\n    | 'tool'\n    | 'processor'\n    | 'vector'\n    | 'scorer'\n    | 'workflow'\n    | 'mcp-server'\n    | 'gateway'\n    | 'memory'\n    | 'workspace',\n  value: null | undefined,\n  key?: string,\n): MastraError {\n  const typeLabel = type === 'mcp-server' ? 'MCP server' : type;\n  const errorId = `MASTRA_ADD_${type.toUpperCase().replace('-', '_')}_UNDEFINED` as Uppercase<string>;\n  return new MastraError({\n    id: errorId,\n    domain: ErrorDomain.MASTRA,\n    category: ErrorCategory.USER,\n    text: `Cannot add ${typeLabel}: ${typeLabel} is ${value === null ? 'null' : 'undefined'}. This may occur if config was spread ({ ...config }) and the original object had getters or non-enumerable properties.`,\n    details: { status: 400, ...(key && { key }) },\n  });\n}\n\n/**\n * Stable JSON-shape comparison for two `Schedule.target` values. Uses\n * JSON.stringify because targets are plain JSON-serializable objects (the\n * storage layer round-trips them through the same encoding). Covers the\n * `inputData` / `initialState` / `requestContext` payload fields that we\n * want to detect changes on across redeploys.\n */\nfunction targetsEqual(a: Schedule['target'] | undefined, b: Schedule['target']): boolean {\n  if (a === b) return true;\n  if (!a) return false;\n  return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Reads the declarative schedule configs off a workflow. Supports both the\n * new `getScheduleConfigs(): WorkflowScheduleConfig[]` accessor on the evented\n * engine and a legacy `getScheduleConfig(): WorkflowScheduleConfig | undefined`\n * fallback used in tests that inject a fake getter.\n */\nfunction collectWorkflowScheduleConfigs(workflow: unknown): WorkflowScheduleConfig[] {\n  const w = workflow as {\n    getScheduleConfigs?: () => WorkflowScheduleConfig[] | undefined;\n    getScheduleConfig?: () => WorkflowScheduleConfig | WorkflowScheduleConfig[] | undefined;\n  };\n  if (typeof w.getScheduleConfigs === 'function') {\n    return w.getScheduleConfigs() ?? [];\n  }\n  if (typeof w.getScheduleConfig === 'function') {\n    const cfg = w.getScheduleConfig();\n    if (!cfg) return [];\n    return Array.isArray(cfg) ? cfg : [cfg];\n  }\n  return [];\n}\n\n/**\n * Builds the storage row id for a declarative schedule. Workflow and schedule\n * ids are URL-encoded so delimiters in user-supplied ids cannot collide\n * across workflows (e.g. `foo__bar` single vs `foo` array-entry `bar`).\n */\nfunction declarativeScheduleRowId(workflowId: string, scheduleId?: string): string {\n  const encodedWorkflow = encodeURIComponent(workflowId);\n  if (scheduleId === undefined) return `wf_${encodedWorkflow}`;\n  return `wf_${encodedWorkflow}__${encodeURIComponent(scheduleId)}`;\n}\n\n/**\n * Determines whether a stored schedule row id belongs to one of the registered\n * workflows. Returns the owning workflow id when the row id either equals\n * `wf_<encoded(workflowId)>` (single-schedule form) or starts with\n * `wf_<encoded(workflowId)>__` (array form). Returns undefined when no\n * registered workflow owns the row.\n */\nfunction ownerWorkflowIdForRow(rowId: string, byWorkflow: Map<string, Set<string>>): string | undefined {\n  for (const workflowId of byWorkflow.keys()) {\n    const prefix = `wf_${encodeURIComponent(workflowId)}`;\n    if (rowId === prefix || rowId.startsWith(`${prefix}__`)) {\n      return workflowId;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Decodes the owning workflow id directly from a `wf_<encoded>` /\n * `wf_<encoded>__<...>` row id without needing the workflow to be in the\n * current registry. Used to identify rows whose workflow has been deleted\n * from code so we can clean them up on startup.\n */\nfunction ownerWorkflowIdFromRowId(rowId: string): string | undefined {\n  if (!rowId.startsWith('wf_')) return undefined;\n  const rest = rowId.slice('wf_'.length);\n  const sep = rest.indexOf('__');\n  const encoded = sep === -1 ? rest : rest.slice(0, sep);\n  if (!encoded) return undefined;\n  try {\n    return decodeURIComponent(encoded);\n  } catch {\n    return undefined;\n  }\n}\n\n/** See {@link targetsEqual}. Same approach for free-form metadata. */\nfunction metadataEqual(a: Record<string, unknown> | null | undefined, b: Record<string, unknown> | undefined): boolean {\n  const aNorm = a ?? undefined;\n  const bNorm = b ?? undefined;\n  if (aNorm === bNorm) return true;\n  if (!aNorm || !bNorm) return false;\n  return JSON.stringify(aNorm) === JSON.stringify(bNorm);\n}\n\n/**\n * Configuration interface for initializing a Mastra instance.\n *\n * The Config interface defines all the optional components that can be registered\n * with a Mastra instance, including agents, workflows, storage, logging, and more.\n *\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of workflow instances\n * @template TVectors - Record of vector store instances\n * @template TTTS - Record of text-to-speech instances\n * @template TLogger - Logger implementation type\n * @template TVNextNetworks - Record of agent network instances\n * @template TMCPServers - Record of MCP server instances\n * @template TScorers - Record of scorer instances\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n *   agents: {\n *     weatherAgent: new Agent({\n *       id: 'weather-agent',\n *       name: 'Weather Agent',\n *       instructions: 'You help with weather information',\n *       model: 'openai/gpt-5'\n *     })\n *   },\n *   storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n *   logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport interface Config<\n  TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n  TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>,\n  TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n  TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n  TLogger extends IMastraLogger = IMastraLogger,\n  TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n  TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n  TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n    string,\n    ToolAction<any, any, any, any, any, any>\n  >,\n  TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n  TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>,\n  TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>,\n> {\n  /**\n   * Agents are autonomous systems that can make decisions and take actions.\n   * Accepts Mastra Agent instances, AI SDK v6 ToolLoopAgent instances,\n   * and durable agent wrappers (e.g., InngestAgent from createInngestAgent).\n   * ToolLoopAgent and durable agents are automatically handled during registration.\n   */\n  agents?: { [K in keyof TAgents]: TAgents[K] | ToolLoopAgentLike | DurableAgentLike };\n\n  /**\n   * Storage provider for persisting data, conversation history, and workflow state.\n   * Required for agent memory and workflow persistence.\n   */\n  storage?: MastraCompositeStore;\n\n  /**\n   * Vector stores for semantic search and retrieval-augmented generation (RAG).\n   * Used for storing and querying embeddings.\n   */\n  vectors?: TVectors;\n\n  /**\n   * Logger implementation for application logging and debugging.\n   * Set to `false` to disable logging entirely.\n   * @default `INFO` level in development, `WARN` in production.\n   */\n  logger?: TLogger | false;\n\n  /**\n   * Workflows provide type-safe, composable task execution with built-in error handling.\n   */\n  workflows?: TWorkflows;\n\n  /**\n   * Text-to-speech providers for voice synthesis capabilities.\n   */\n  tts?: TTTS;\n\n  /**\n   * Observability entrypoint for tracking model interactions and tracing.\n   * Pass an instance of the Observability class from @mastra/observability.\n   *\n   * @example\n   * ```typescript\n   * import { Observability, MastraStorageExporter, MastraPlatformExporter } from '@mastra/observability';\n   *\n   * new Mastra({\n   *   observability: new Observability({\n   *     configs: {\n   *       default: {\n   *         serviceName: 'mastra',\n   *         exporters: [new MastraStorageExporter(), new MastraPlatformExporter()],\n   *       },\n   *     },\n   *   })\n   * })\n   * ```\n   *\n   * `Observability` auto-applies a `SensitiveDataFilter` span output processor\n   * to every configured instance. Set `sensitiveDataFilter: false` on the\n   * registry config to opt out, or pass a `SensitiveDataFilterOptions` object\n   * to customize it.\n   */\n  observability?: ObservabilityEntrypoint;\n\n  /**\n   * Custom ID generator function for creating unique identifiers.\n   * Receives optional context about what type of ID is being generated\n   * and where it's being requested from.\n   * @default `crypto.randomUUID()`\n   */\n  idGenerator?: MastraIdGenerator;\n\n  /**\n   * Deployment provider for publishing applications to cloud platforms.\n   */\n  deployer?: MastraDeployer;\n\n  /**\n   * Server configuration for HTTP endpoints and middleware.\n   */\n  server?: ServerConfig;\n\n  /**\n   * MCP servers provide tools and resources that agents can use.\n   */\n  mcpServers?: TMCPServers;\n\n  /**\n   * Bundler configuration for packaging and deployment.\n   */\n  bundler?: BundlerConfig;\n\n  /**\n   * Pub/sub system for event-driven communication between components.\n   * @default EventEmitterPubSub\n   */\n  pubsub?: PubSub;\n\n  /**\n   * Server cache for storing stream events and other temporary data.\n   * Used by durable agents for resumable streams - clients can disconnect\n   * and reconnect without missing events.\n   *\n   * When provided, durable agents created without their own cache will\n   * inherit this cache instance.\n   *\n   * @default InMemoryServerCache\n   */\n  cache?: MastraServerCache;\n\n  /**\n   * Scorers help assess the quality of agent responses and workflow outputs.\n   */\n  scorers?: TScorers;\n\n  /**\n   * Tools are reusable functions that agents can use to interact with external systems.\n   */\n  tools?: TTools;\n\n  /**\n   * Processors transform inputs and outputs for agents and workflows.\n   */\n  processors?: TProcessors;\n\n  /**\n   * Memory instances that can be referenced by stored agents.\n   * Keys are used to look up memory instances when resolving stored agent configurations.\n   */\n  memory?: TMemory;\n\n  /**\n   * Global workspace for file storage, skills, and code execution.\n   * Agents inherit this workspace unless they have their own configured.\n   * Skills are accessed via workspace.skills when skills is configured.\n   */\n  workspace?: AnyWorkspace;\n\n  /**\n   * Custom model router gateways for accessing LLM providers.\n   * Gateways handle provider-specific authentication, URL construction, and model resolution.\n   */\n  gateways?: Record<string, MastraModelGateway>;\n\n  /**\n   * Event handlers for custom application events.\n   * Maps event topics to handler functions for event-driven architectures.\n   */\n  events?: {\n    [topic: string]: (\n      event: Event,\n      cb?: () => Promise<void>,\n    ) => Promise<void> | ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n  };\n\n  /**\n   * Editor instance for handling agent instantiation and configuration.\n   * The editor handles complex instantiation logic including memory resolution.\n   */\n  editor?: IMastraEditor;\n\n  /**\n   * Global version overrides for primitives.\n   * When set, sub-agent delegation (and future primitive resolution) will\n   * resolve the specified version instead of the code-defined default.\n   *\n   * @example\n   * ```typescript\n   * new Mastra({\n   *   versions: {\n   *     agents: {\n   *       'researcher-agent': { versionId: '123' },\n   *       'writer-agent': { status: 'published' },\n   *     },\n   *   },\n   * });\n   * ```\n   */\n  versions?: VersionOverrides;\n\n  /**\n   * Background task configuration for running tool calls asynchronously.\n   * When configured, agents can dispatch tool executions to run in the background\n   * while the conversation continues.\n   */\n  backgroundTasks?: BackgroundTaskManagerConfig;\n\n  /**\n   * Scheduler configuration for cron-driven workflow triggers.\n   *\n   * The scheduler is auto-enabled when any registered workflow declares a\n   * `schedule` config or when `scheduler.enabled` is true. It requires a\n   * storage adapter implementing the `schedules` domain (e.g. `@mastra/libsql`).\n   */\n  scheduler?: WorkflowSchedulerConfig;\n\n  /**\n   * Platform channels for messaging integrations (Slack, Discord, etc.).\n   * Routes are automatically registered and agents can reference channel configs.\n   *\n   * @example\n   * ```typescript\n   * import { SlackProvider } from '@mastra/slack';\n   *\n   * new Mastra({\n   *   channels: {\n   *     slack: new SlackProvider({\n   *       configToken: process.env.SLACK_APP_CONFIG_TOKEN,\n   *       refreshToken: process.env.SLACK_APP_CONFIG_REFRESH_TOKEN,\n   *     }),\n   *   },\n   * });\n   * ```\n   */\n  channels?: TChannels;\n\n  /**\n   * Deployment environment name (e.g. `'production'`, `'staging'`, `'development'`).\n   * When set, the value is automatically attached to all observability signals\n   * so they can be filtered by environment without passing\n   * `tracingOptions.metadata.environment` on every call.\n   *\n   * If unset, falls back to `process.env.NODE_ENV`. If neither is set the field\n   * is left undefined rather than guessed.\n   *\n   * Per-call `tracingOptions.metadata.environment` always takes precedence.\n   *\n   * @example\n   * ```typescript\n   * new Mastra({\n   *   environment: 'production',\n   *   observability: new Observability({ ... }),\n   * })\n   * ```\n   */\n  environment?: string;\n  /**\n   * Optional central transform policy for tool payloads before they are\n   * serialized into display streams or user-visible transcripts.\n   */\n  transform?: ToolPayloadTransformPolicy;\n  /**\n   * Configure which workers run in this Mastra instance.\n   *\n   * - `undefined` (default): Auto-creates default workers (existing behavior)\n   * - `false`: Disables all event processing — useful when running standalone workers separately\n   * - `MastraWorker[]`: Use exactly these workers\n   */\n  workers?: MastraWorker[] | false;\n}\n\n/**\n * The central orchestrator for Mastra applications, managing agents, workflows, storage, logging, observability, and more.\n *\n * The `Mastra` class serves as the main entry point and registry for all components in a Mastra application.\n * It coordinates the interaction between agents, workflows, storage systems, and other services.\n\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of modern workflow instances\n * @template TVectors - Record of vector store instances for semantic search and RAG\n * @template TTTS - Record of text-to-speech provider instances\n * @template TLogger - Logger implementation type for application logging\n * @template TVNextNetworks - Record of next-generation agent network instances\n * @template TMCPServers - Record of Model Context Protocol server instances\n * @template TScorers - Record of evaluation scorer instances for measuring AI performance\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n *   agents: {\n *     weatherAgent: new Agent({\n *       id: 'weather-agent',\n *       name: 'Weather Agent',\n *       instructions: 'You provide weather information',\n *       model: 'openai/gpt-5',\n *       tools: [getWeatherTool]\n *     })\n *   },\n *   workflows: { dataWorkflow },\n *   storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n *   logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport class Mastra<\n  TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n  TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>,\n  TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n  TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n  TLogger extends IMastraLogger = IMastraLogger,\n  TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n  TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n  TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n    string,\n    ToolAction<any, any, any, any, any, any>\n  >,\n  TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n  TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>,\n  TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>,\n> {\n  #vectors?: TVectors;\n  #agents: TAgents;\n  #logger: TLogger;\n  #workflows: TWorkflows;\n  #observability: ObservabilityEntrypoint;\n  #tts?: TTTS;\n  #deployer?: MastraDeployer;\n  #serverMiddleware: Array<{\n    handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;\n    path: string;\n  }> = [];\n\n  #storage?: MastraCompositeStore;\n  #scorers?: TScorers;\n  #tools?: TTools;\n  #processors?: TProcessors;\n  #processorConfigurations: Map<string, Array<{ processor: Processor; agentId: string; type: 'input' | 'output' }>> =\n    new Map();\n  #memory?: TMemory;\n  #workspace?: Workspace;\n  #workspaces: Record<string, RegisteredWorkspace> = {};\n  #server?: ServerConfig;\n  #serverAdapter?: MastraServerBase;\n  #mcpServers?: TMCPServers;\n  #bundler?: BundlerConfig;\n  #idGenerator?: MastraIdGenerator;\n  #pubsub: PubSub;\n  #backgroundTaskConfig?: BackgroundTaskManagerConfig;\n  #backgroundTaskManager?: BackgroundTaskManager;\n  #schedulerConfig?: WorkflowSchedulerConfig;\n  /**\n   * Tracks whether any registered workflow has declared a `schedule` config.\n   * Used as a fast short-circuit so users without scheduled workflows pay\n   * zero cost beyond a boolean check.\n   */\n  #hasScheduledWorkflow = false;\n  #gateways?: Record<string, MastraModelGateway>;\n  #channels?: TChannels;\n  #environment?: string;\n  #toolPayloadTransform?: ToolPayloadTransformPolicy;\n  #workers: MastraWorker[] = [];\n  #workerFilter?: Set<string>;\n  // Lazily-constructed processor used by handleWorkflowEvent(). Shared between\n  // pull-mode workers (OrchestrationWorker) and push-mode entry points\n  // (in-process EventEmitter listener, the /api/workers/events HTTP route).\n  #workflowEventProcessor?: WorkflowEventProcessor;\n  // Callback registered against the pubsub when running in push mode so we can\n  // unsubscribe it cleanly during stopWorkers().\n  #pushSubscription?: { topic: string; cb: EventCallback };\n  // Tracks (topic, listener) pairs registered against the pubsub on behalf of\n  // user-defined event listeners during startWorkers(). Used to make\n  // startWorkers()/stopWorkers() idempotent — a second startWorkers() call\n  // must not double-subscribe the same listener.\n  #userEventSubscriptions: Array<{\n    topic: string;\n    cb: (event: Event, ack?: () => Promise<void>) => Promise<void>;\n  }> = [];\n\n  #events: {\n    [topic: string]: ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n  } = {};\n  #internalMastraWorkflows: Record<string, Workflow> = {};\n  // Server cache for temporary persistence and durable agent resumable streams\n  #serverCache: MastraServerCache;\n  // Cache for stored agents to allow in-memory modifications (like model changes) to persist across requests\n  #storedAgentsCache: Map<string, Agent> = new Map();\n  // Cache for stored scorers to allow in-memory modifications to persist across requests\n  #storedScorersCache: Map<string, MastraScorer<any, any, any, any>> = new Map();\n  // Registry for prompt blocks (stored or code-defined)\n  #promptBlocks: Record<string, StorageResolvedPromptBlockType> = {};\n  // Editor instance for handling agent instantiation and configuration\n  #editor?: IMastraEditor;\n  #datasets?: DatasetsManager;\n  // Global version overrides for primitives (agents, etc.)\n  #versions?: VersionOverrides;\n\n  get pubsub() {\n    return this.#pubsub;\n  }\n\n  get agentThreadStreamRuntime() {\n    return agentThreadStreamRuntime;\n  }\n\n  get workers(): readonly MastraWorker[] {\n    return this.#workers;\n  }\n\n  getWorker<T extends MastraWorker>(name: string): T | undefined {\n    return this.#workers.find(w => w.name === name) as T | undefined;\n  }\n\n  get backgroundTaskManager() {\n    return this.#backgroundTaskManager;\n  }\n\n  /**\n   * Returns the workflow scheduler owned by the SchedulerWorker,\n   * or undefined if the scheduler is not enabled / not yet started.\n   *\n   * The scheduler is created when `startWorkers()` initializes the\n   * SchedulerWorker (guarded by `#shouldEnableScheduler()`). Use it\n   * to create, pause, resume, or delete schedules imperatively.\n   */\n  get scheduler(): WorkflowScheduler | undefined {\n    return this.#findSchedulerWorker()?.scheduler;\n  }\n\n  get datasets(): DatasetsManager {\n    if (!this.#datasets) {\n      this.#datasets = new DatasetsManager(this);\n    }\n    return this.#datasets;\n  }\n\n  /**\n   * Gets the currently configured ID generator function.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   idGenerator: context =>\n   *     context?.idType === 'message' && context.threadId\n   *       ? `msg-${context.threadId}-${Date.now()}`\n   *       : `custom-${Date.now()}`\n   * });\n   * const generator = mastra.getIdGenerator();\n   * console.log(generator?.({ idType: 'message', threadId: 'thread-123' })); // \\\"msg-thread-123-1234567890\\\"\n   * ```\n   */\n  public getIdGenerator() {\n    return this.#idGenerator;\n  }\n\n  /**\n   * Gets the currently configured editor instance.\n   * The editor is responsible for handling agent instantiation and configuration.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   editor: new MastraEditor({ logger })\n   * });\n   * const editor = mastra.getEditor();\n   * ```\n   */\n  public getEditor() {\n    return this.#editor;\n  }\n\n  /**\n   * Gets a registered channel provider by its key.\n   *\n   * @example\n   * ```typescript\n   * import { SlackProvider } from '@mastra/slack';\n   * const slack = mastra.getChannelProvider<SlackProvider>('slack');\n   * ```\n   */\n  public getChannelProvider<T extends ChannelProvider = ChannelProvider>(key: string): T | undefined {\n    return this.#channels?.[key] as T | undefined;\n  }\n\n  /**\n   * Gets all registered channel providers.\n   */\n  public getChannelProviders(): Record<string, ChannelProvider> | undefined {\n    return this.#channels;\n  }\n\n  /**\n   * Shorthand getter for platform channels.\n   * Usage: `mastra.channels.slack.connect(agentId)`\n   */\n  public get channels(): TChannels {\n    return (this.#channels ?? {}) as TChannels;\n  }\n\n  /**\n   * Returns the global version overrides configured on this Mastra instance.\n   * These are used as defaults when resolving sub-agent versions during delegation.\n   */\n  public getVersionOverrides(): VersionOverrides | undefined {\n    return this.#versions;\n  }\n\n  /**\n   * Returns the deployment environment name configured on this Mastra instance,\n   * falling back to `process.env.NODE_ENV` when unset, or `undefined` if neither\n   * is provided.\n   *\n   * Observability automatically reads this and attaches it to all signals so\n   * consumers can filter by environment without passing\n   * `tracingOptions.metadata.environment` on each call.\n   */\n  public getEnvironment(): string | undefined {\n    return this.#environment;\n  }\n\n  public getToolPayloadTransform(): ToolPayloadTransformPolicy | undefined {\n    return this.#toolPayloadTransform;\n  }\n\n  /**\n   * Gets the stored agents cache\n   * @internal\n   */\n  public getStoredAgentCache() {\n    return this.#storedAgentsCache;\n  }\n\n  /**\n   * Gets the stored scorers cache\n   * @internal\n   */\n  public getStoredScorerCache() {\n    return this.#storedScorersCache;\n  }\n\n  /**\n   * Generates a unique identifier using the configured generator or defaults to `crypto.randomUUID()`.\n   *\n   * This method is used internally by Mastra for creating unique IDs for various entities\n   * like workflow runs, agent conversations, and other resources that need unique identification.\n   *\n   * @param context - Optional context information about what type of ID is being generated\n   *                  and where it's being requested from. This allows custom ID generators\n   *                  to create deterministic IDs based on context.\n   *\n   * @throws {MastraError} When the custom ID generator returns an empty string\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const id = mastra.generateId();\n   * console.log(id); // \"550e8400-e29b-41d4-a716-446655440000\"\n   *\n   * // With context for deterministic IDs\n   * const messageId = mastra.generateId({\n   *   idType: 'message',\n   *   source: 'agent',\n   *   threadId: 'thread-123'\n   * });\n   * ```\n   */\n  public generateId(context?: IdGeneratorContext): string {\n    if (this.#idGenerator) {\n      const id = this.#idGenerator(context);\n      if (!id) {\n        const error = new MastraError({\n          id: 'MASTRA_ID_GENERATOR_RETURNED_EMPTY_STRING',\n          domain: ErrorDomain.MASTRA,\n          category: ErrorCategory.USER,\n          text: 'ID generator returned an empty string, which is not allowed',\n        });\n        this.#logger?.trackException(error);\n        throw error;\n      }\n      return id;\n    }\n    return randomUUID();\n  }\n\n  /**\n   * Sets a custom ID generator function for creating unique identifiers.\n   *\n   * The ID generator function will be used by `generateId()` instead of the default\n   * `crypto.randomUUID()`. This is useful for creating application-specific ID formats\n   * or integrating with existing ID generation systems. The function receives\n   * optional context about what is requesting the ID.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * mastra.setIdGenerator(context =>\n   *   context?.idType === 'run' && context.entityId\n   *     ? `run-${context.entityId}-${Date.now()}`\n   *     : `custom-${Date.now()}`\n   * );\n   * const id = mastra.generateId({ idType: 'run', entityId: 'agent-123' });\n   * console.log(id); // \"run-agent-123-1234567890\"\n   * ```\n   */\n  public setIdGenerator(idGenerator: MastraIdGenerator) {\n    this.#idGenerator = idGenerator;\n  }\n\n  /**\n   * Sets the server configuration for this Mastra instance.\n   *\n   * @param server - The server configuration object\n   *\n   * @example\n   * ```typescript\n   * mastra.setServer({ ...mastra.getServer(), auth: new MastraAuthWorkos() });\n   * ```\n   */\n  public setServer(server: ServerConfig): void {\n    this.#server = server;\n  }\n\n  /**\n   * Registers an exporter on the default observability instance.\n   *\n   * If the current observability is a no-op (user didn't configure any), it is\n   * first replaced with the provided entrypoint and the instance is registered\n   * as default. If a real observability entrypoint already exists, the exporter\n   * is added directly to the existing default instance.\n   *\n   * @param exporter - The exporter to register (e.g. a MastraPlatformExporter)\n   * @param instance - An ObservabilityInstance pre-configured with the exporter, used as default when bootstrapping\n   * @param entrypoint - A real ObservabilityEntrypoint to bootstrap if the current one is a no-op\n   */\n  public registerExporter(\n    exporter: ObservabilityExporter,\n    instance: ObservabilityInstance,\n    entrypoint: ObservabilityEntrypoint,\n  ): void {\n    if (this.#observability instanceof NoOpObservability) {\n      this.#observability = entrypoint;\n      this.#observability.setLogger({ logger: this.#logger });\n      this.#observability.setMastraContext({ mastra: this });\n      this.#observability.registerInstance('default', instance, true);\n    }\n\n    const defaultInstance = this.#observability.getDefaultInstance();\n    if (defaultInstance?.registerExporter) {\n      defaultInstance.registerExporter(exporter);\n    }\n  }\n\n  /**\n   * Creates a new Mastra instance with the provided configuration.\n   *\n   * The constructor initializes all the components specified in the config, sets up\n   * internal systems like logging and observability, and registers components with each other.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   agents: {\n   *     assistant: new Agent({\n   *       id: 'assistant',\n   *       name: 'Assistant',\n   *       instructions: 'You are a helpful assistant',\n   *       model: 'openai/gpt-5'\n   *     })\n   *   },\n   *   storage: new PostgresStore({\n   *     connectionString: process.env.DATABASE_URL\n   *   }),\n   *   logger: new PinoLogger({ name: 'MyApp' }),\n   *   observability: new Observability({\n   *     configs: { default: { serviceName: 'mastra', exporters: [new MastraStorageExporter()] } },\n   *   }),\n   * });\n   * ```\n   */\n  constructor(\n    config?: Config<\n      TAgents,\n      TWorkflows,\n      TVectors,\n      TTTS,\n      TLogger,\n      TMCPServers,\n      TScorers,\n      TTools,\n      TProcessors,\n      TMemory,\n      TChannels\n    >,\n  ) {\n    // Register AsyncLocalStorage-backed context resolvers so that DualLogger\n    // can correlate logs to the active span. Must happen before any agent runs.\n    initContextStorage();\n\n    // Server cache for temporary persistence and durable agent resumable streams\n    this.#serverCache = config?.cache ?? new InMemoryServerCache();\n\n    // Set the editor if provided and register this Mastra instance with it\n    this.#editor = config?.editor;\n    if (this.#editor && typeof this.#editor.registerWithMastra === 'function') {\n      this.#editor.registerWithMastra(this);\n    }\n\n    // Store global version overrides\n    this.#versions = config?.versions;\n\n    // Resolve deployment environment: explicit config wins, else fall back to\n    // NODE_ENV. Leave undefined if neither is set rather than guessing.\n    this.#environment = config?.environment ?? process.env.NODE_ENV;\n    this.#toolPayloadTransform = normalizeToolPayloadTransformPolicy(\n      config?.transform ?? (config as any)?.toolPayloadProjection,\n    );\n\n    if (config?.pubsub) {\n      this.#pubsub = config.pubsub;\n    } else {\n      this.#pubsub = new EventEmitterPubSub();\n    }\n\n    this.#events = {};\n    for (const topic in config?.events ?? {}) {\n      if (!Array.isArray(config?.events?.[topic])) {\n        this.#events[topic] = [config?.events?.[topic] as any];\n      } else {\n        this.#events[topic] = config?.events?.[topic] ?? [];\n      }\n    }\n\n    // Initialize workers based on config.\n    // MASTRA_WORKERS env var:\n    //   - \"false\": disables all event processing in this instance\n    //   - comma-separated names (e.g. \"scheduler,orchestration\"): only those\n    //     workers will be started by `startWorkers()` when called without an\n    //     explicit `name` argument. Construction still creates all workers so\n    //     a later explicit `startWorkers('foo')` still works.\n    const rawWorkersEnv = process.env.MASTRA_WORKERS;\n    let workersOption: MastraWorker[] | false | undefined;\n    if (rawWorkersEnv === 'false') {\n      workersOption = false;\n    } else {\n      workersOption = config?.workers;\n      if (rawWorkersEnv && rawWorkersEnv !== 'false') {\n        const names = rawWorkersEnv\n          .split(',')\n          .map(s => s.trim())\n          .filter(Boolean);\n        if (names.length > 0) {\n          this.#workerFilter = new Set(names);\n        }\n      }\n    }\n\n    if (workersOption === false) {\n      // Explicitly disabled — no event processing in this instance.\n      // PubSub still exists for publishing events.\n    } else if (Array.isArray(workersOption)) {\n      this.#workers = workersOption;\n      for (const w of this.#workers) {\n        w.__registerMastra(this);\n      }\n    } else {\n      // Default: auto-create workers based on config.\n      //\n      // Skip OrchestrationWorker when the configured pubsub doesn't support\n      // pull delivery (e.g. EventEmitter, GCP Pub/Sub push) — those transports\n      // don't have a read loop to drive a worker, and Mastra wires\n      // `handleWorkflowEvent` directly to the pubsub during startWorkers().\n      const pubsubModes = this.#pubsub.supportedModes ?? ['pull'];\n      const defaultWorkers: MastraWorker[] = [];\n      if (pubsubModes.includes('pull')) {\n        defaultWorkers.push(new OrchestrationWorker());\n      }\n      // SchedulerWorker is added lazily in startWorkers() rather than here\n      // because workflows (and their schedule configs) are registered after\n      // this block runs, so #hasScheduledWorkflow is not yet set.\n      if (config?.backgroundTasks?.enabled) {\n        defaultWorkers.push(new BackgroundTaskWorker(config.backgroundTasks));\n      }\n      this.#workers = defaultWorkers;\n      for (const w of this.#workers) {\n        w.__registerMastra(this);\n      }\n    }\n\n    let logger: TLogger;\n    if (config?.logger === false) {\n      logger = noopLogger as unknown as TLogger;\n    } else {\n      if (config?.logger) {\n        logger = config.logger;\n      } else {\n        const levelOnEnv =\n          process.env.NODE_ENV === 'production' && process.env.MASTRA_DEV !== 'true' ? LogLevel.WARN : LogLevel.INFO;\n        logger = new ConsoleLogger({ name: 'Mastra', level: levelOnEnv }) as unknown as TLogger;\n      }\n    }\n    this.#logger = logger;\n\n    this.#idGenerator = config?.idGenerator;\n\n    let storage = config?.storage;\n\n    if (storage) {\n      storage = augmentWithInit(storage);\n    }\n\n    // Validate and assign observability instance\n    if (config?.observability) {\n      if (typeof config.observability.getDefaultInstance === 'function') {\n        this.#observability = config.observability;\n        // Set logger early\n        this.#observability.setLogger({ logger: this.#logger });\n      } else {\n        this.#logger?.warn(\n          'Observability configuration error: Expected an Observability instance, but received a config object. ' +\n            'Import and instantiate: import { Observability, MastraStorageExporter } from \"@mastra/observability\"; ' +\n            'then pass: observability: new Observability({ configs: { default: { serviceName: \"mastra\", exporters: [new MastraStorageExporter()] } } }). ' +\n            'Observability has been disabled.',\n        );\n        this.#observability = new NoOpObservability();\n      }\n    } else {\n      this.#observability = new NoOpObservability();\n    }\n\n    // Wrap the logger in a DualLogger so all existing this.logger.info(...) calls\n    // also forward to loggerVNext (observability structured logging).\n    // This is transparent — no call sites need to change.\n    // Uses a lazy getter so loggerVNext is always resolved at call time\n    // (observability may not be fully initialized yet at this point).\n    const dualLogger = new DualLogger(this.#logger, () => this.loggerVNext);\n    this.#logger = dualLogger as unknown as TLogger;\n\n    this.#storage = storage;\n\n    this.#backgroundTaskConfig = config?.backgroundTasks;\n    // Auto-create the background-task manager only when this Mastra is\n    // running workers. When `workers: false`, the consumer of the\n    // background-tasks topic must live elsewhere — the producer can still\n    // construct its own `BackgroundTaskManager` and call `init()` directly\n    // (see redis-streams cross-process tests for that pattern). Initializing\n    // a worker here would compete with the dedicated worker process for\n    // dispatch events.\n    if (workersOption !== false) {\n      this.#ensureBackgroundTaskManager();\n    }\n\n    this.#schedulerConfig = config?.scheduler;\n\n    // Initialize all primitive storage objects first, we need to do this before adding primitives to avoid circular dependencies\n    this.#vectors = {} as TVectors;\n    this.#mcpServers = {} as TMCPServers;\n    this.#tts = {} as TTTS;\n    this.#agents = {} as TAgents;\n    this.#scorers = {} as TScorers;\n    this.#tools = {} as TTools;\n    this.#processors = {} as TProcessors;\n    this.#memory = {} as TMemory;\n    this.#workflows = {} as TWorkflows;\n    this.#gateways = {} as Record<string, MastraModelGateway>;\n\n    // Now add primitives - order matters for auto-registration\n    // Tools and processors should be added before agents and MCP servers that might use them\n    // Note: We validate each entry to handle cases where config was spread ({ ...config })\n    // which can cause undefined values if the source object had getters or non-enumerable properties\n    if (config?.tools) {\n      Object.entries(config.tools).forEach(([key, tool]) => {\n        if (tool != null) {\n          this.addTool(tool, key);\n        }\n      });\n    }\n\n    if (config?.processors) {\n      Object.entries(config.processors).forEach(([key, processor]) => {\n        if (processor != null) {\n          this.addProcessor(processor, key);\n        }\n      });\n    }\n\n    if (config?.memory) {\n      Object.entries(config.memory).forEach(([key, memory]) => {\n        if (memory != null) {\n          this.addMemory(memory, key);\n        }\n      });\n    }\n\n    if (config?.vectors) {\n      Object.entries(config.vectors).forEach(([key, vector]) => {\n        if (vector != null) {\n          this.addVector(vector, key);\n        }\n      });\n    }\n\n    if (config?.workspace) {\n      this.#workspace = config.workspace;\n      // Also register in the workspaces registry for direct lookup by ID\n      this.addWorkspace(config.workspace, undefined, { source: 'mastra' });\n    }\n\n    if (config?.scorers) {\n      Object.entries(config.scorers).forEach(([key, scorer]) => {\n        if (scorer != null) {\n          this.addScorer(scorer, key, { source: 'code' });\n        }\n      });\n    }\n\n    if (config?.workflows) {\n      Object.entries(config.workflows).forEach(([key, workflow]) => {\n        if (workflow != null) {\n          this.addWorkflow(workflow, key);\n        }\n      });\n    }\n\n    if (config?.gateways) {\n      Object.entries(config.gateways).forEach(([key, gateway]) => {\n        if (gateway != null) {\n          this.addGateway(gateway, key);\n        }\n      });\n    }\n\n    // Auto-register default gateways (MastraGateway, NetlifyGateway, ModelsDevGateway)\n    // so they're available via listGateways() without explicit config.\n    // Skip duplicates so user-provided gateways above take precedence.\n    // Added directly to #gateways to avoid triggering #syncGatewayRegistry for built-ins.\n    for (const gateway of defaultGateways) {\n      const key = gateway.getId();\n      if (!(this.#gateways as Record<string, MastraModelGateway>)[key]) {\n        (this.#gateways as Record<string, MastraModelGateway>)[key] = gateway;\n      }\n    }\n\n    // Add MCP servers and agents last since they might reference other primitives\n    if (config?.mcpServers) {\n      Object.entries(config.mcpServers).forEach(([key, server]) => {\n        if (server != null) {\n          this.addMCPServer(server, key);\n        }\n      });\n    }\n\n    if (config?.tts) {\n      Object.entries(config.tts).forEach(([key, tts]) => {\n        if (tts != null) {\n          (this.#tts as Record<string, MastraTTS>)[key] = tts;\n        }\n      });\n    }\n\n    if (config?.server) {\n      this.#server = config.server;\n    }\n\n    // Register channels and merge their routes into server config\n    if (config?.channels) {\n      this.#channels = config.channels;\n      const channelRoutes: ApiRoute[] = [];\n\n      for (const [, channel] of Object.entries(config.channels)) {\n        if (channel == null) continue;\n\n        // Attach the channel to this Mastra instance\n        if (channel.__attach) {\n          channel.__attach(this);\n        }\n\n        // Collect routes from the channel\n        const routes = channel.getRoutes();\n        channelRoutes.push(...routes);\n      }\n\n      // Merge channel routes into server config\n      if (channelRoutes.length > 0) {\n        const existingRoutes = this.#server?.apiRoutes ?? [];\n        this.#server = {\n          ...this.#server,\n          apiRoutes: [...existingRoutes, ...channelRoutes],\n        };\n      }\n    }\n\n    // Agents must be added after server config so that channel webhook routes\n    // are appended to (not replaced by) the server config.\n    if (config?.agents) {\n      Object.entries(config.agents).forEach(([key, agent]) => {\n        if (agent != null) {\n          this.addAgent(agent, key);\n        }\n      });\n    }\n\n    registerHook(AvailableHooks.ON_SCORER_RUN, createOnScorerHook(this));\n\n    /*\n      Initialize observability with Mastra context (after storage configured)\n    */\n    this.#observability.setMastraContext({ mastra: this });\n\n    this.setLogger({ logger });\n\n    // Initialize channels asynchronously (auto-provision apps, etc.)\n    // This runs after all agents are registered so configs are available\n    if (this.#channels) {\n      void Promise.resolve().then(async () => {\n        for (const [key, channel] of Object.entries(this.#channels ?? {})) {\n          if (channel.initialize) {\n            try {\n              await channel.initialize();\n            } catch (err) {\n              console.error(`[Mastra] Failed to initialize channel \"${key}\":`, err);\n            }\n          }\n        }\n      });\n    }\n  }\n\n  #ensureBackgroundTaskManager(): void {\n    if (!this.#backgroundTaskConfig?.enabled || !this.#storage || this.#backgroundTaskManager) {\n      return;\n    }\n\n    const bgManager = new BackgroundTaskManager(this.#backgroundTaskConfig);\n    bgManager.__registerMastra(this);\n    this.#backgroundTaskManager = bgManager;\n\n    // Wire statically-registered tools into the manager's name-keyed registry\n    // so cross-process workers can resolve dispatched tasks. Tools added later\n    // via `addTool()` are propagated through the same path.\n    const tools = this.#tools as Record<string, ToolAction<any, any, any, any>> | undefined;\n    if (tools) {\n      for (const [name, tool] of Object.entries(tools)) {\n        this.#registerToolWithBackgroundManager(name, tool);\n      }\n    }\n\n    void bgManager.init(this.#pubsub).catch(error => {\n      this.#logger?.error('Failed to initialize background task manager', error);\n    });\n  }\n\n  /**\n   * Build a `ToolExecutor` adapter for a Mastra-registered tool and stash it\n   * on the background task manager's static registry. Skipped if the tool has\n   * no `execute` (declarative-only tools, e.g. MCP descriptors).\n   */\n  #registerToolWithBackgroundManager(name: string, tool: ToolAction<any, any, any, any>): void {\n    if (!this.#backgroundTaskManager) return;\n    if (typeof tool.execute !== 'function') return;\n    const execute = tool.execute.bind(tool);\n    this.#backgroundTaskManager.registerStaticExecutor(name, {\n      execute: async (args, options) => {\n        // Cross-process workers don't have access to the producer's\n        // request/workspace context. Statically-resolvable tools should\n        // tolerate a minimal context (abortSignal only). Tools that need\n        // closure-captured state must run in-process via TaskContext.\n        return execute(\n          args as any,\n          {\n            toolCallId: '',\n            messages: [],\n            abortSignal: options?.abortSignal,\n          } as any,\n        );\n      },\n    });\n  }\n\n  /**\n   * Returns the flat list of declarative schedules sourced from currently\n   * registered workflows. Single-schedule workflows yield one entry keyed by\n   * `wf_<encoded(workflowId)>`. Array-form workflows yield one entry per array\n   * entry keyed by `wf_<encoded(workflowId)>__<encoded(scheduleId)>` so the\n   * prefix uniquely identifies \"all rows owned by this workflow's declarative\n   * config\" even when ids contain `__` or other delimiter-like characters.\n   */\n  #collectDeclarativeSchedules(): Array<{\n    scheduleId: string;\n    workflowId: string;\n    cfg: WorkflowScheduleConfig;\n  }> {\n    const out: Array<{ scheduleId: string; workflowId: string; cfg: WorkflowScheduleConfig }> = [];\n    const workflows = this.#workflows as Record<string, AnyWorkflow>;\n    for (const workflow of Object.values(workflows ?? {})) {\n      const configs = collectWorkflowScheduleConfigs(workflow);\n      if (configs.length === 0) continue;\n      const isArrayForm = configs.length > 1 || (configs.length === 1 && configs[0]!.id !== undefined);\n      for (const cfg of configs) {\n        const scheduleId = isArrayForm\n          ? declarativeScheduleRowId(workflow.id, cfg.id)\n          : declarativeScheduleRowId(workflow.id);\n        out.push({ scheduleId, workflowId: workflow.id, cfg });\n      }\n    }\n    return out;\n  }\n\n  #shouldEnableScheduler(): boolean {\n    if (this.#schedulerConfig?.enabled === false) return false;\n    if (this.#schedulerConfig?.enabled === true) return true;\n    return this.#hasScheduledWorkflow;\n  }\n\n  /**\n   * Find the SchedulerWorker from the workers list (if present).\n   */\n  #findSchedulerWorker(): SchedulerWorker | undefined {\n    return this.#workers.find((w): w is SchedulerWorker => w.name === 'scheduler') as SchedulerWorker | undefined;\n  }\n\n  /**\n   * Sync code-declared schedule configs to the database. Called by\n   * SchedulerWorker during init and by addWorkflow() for late registrations.\n   *\n   * @internal — public so SchedulerWorker can call it, not part of the user API.\n   */\n  async registerDeclarativeSchedules(schedulesStore: SchedulesStorage): Promise<void> {\n    const declared = this.#collectDeclarativeSchedules();\n    const declaredIds = new Set(declared.map(d => d.scheduleId));\n\n    // Group declared ids by workflow so we can detect orphans (rows that\n    // start with `wf_<encoded(workflowId)>` but aren't in the current declared\n    // set). Seed an empty entry for every registered workflow first so that\n    // workflows which removed all their schedules across a redeploy still\n    // have their old rows cleaned up.\n    const declaredIdsByWorkflow = new Map<string, Set<string>>();\n    const workflows = this.#workflows as Record<string, AnyWorkflow> | undefined;\n    for (const workflow of Object.values(workflows ?? {})) {\n      declaredIdsByWorkflow.set(workflow.id, new Set());\n    }\n    for (const { workflowId, scheduleId } of declared) {\n      if (!declaredIdsByWorkflow.has(workflowId)) declaredIdsByWorkflow.set(workflowId, new Set());\n      declaredIdsByWorkflow.get(workflowId)!.add(scheduleId);\n    }\n\n    for (const { scheduleId, workflowId, cfg } of declared) {\n      try {\n        const existing = await schedulesStore.getSchedule(scheduleId);\n        const now = Date.now();\n        const target: Schedule['target'] = {\n          type: 'workflow',\n          workflowId,\n          inputData: cfg.inputData,\n          initialState: cfg.initialState,\n          requestContext: cfg.requestContext,\n        };\n\n        if (!existing) {\n          await schedulesStore.createSchedule({\n            id: scheduleId,\n            target,\n            cron: cfg.cron,\n            timezone: cfg.timezone,\n            status: 'active',\n            nextFireAt: computeNextFireAt(cfg.cron, { timezone: cfg.timezone, after: now }),\n            createdAt: now,\n            updatedAt: now,\n            metadata: cfg.metadata,\n          });\n          continue;\n        }\n\n        // Diff config fields and patch the existing row if anything changed.\n        // We deliberately leave `status` alone — a row may have been paused\n        // out-of-band via storage, and a redeploy shouldn't unpause it.\n        const patch: ScheduleUpdate = {};\n        const cronChanged = existing.cron !== cfg.cron;\n        const timezoneChanged = (existing.timezone ?? undefined) !== (cfg.timezone ?? undefined);\n\n        if (cronChanged) patch.cron = cfg.cron;\n        if (timezoneChanged) patch.timezone = cfg.timezone;\n        if (!targetsEqual(existing.target, target)) patch.target = target;\n        if (!metadataEqual(existing.metadata, cfg.metadata)) patch.metadata = cfg.metadata;\n\n        // Cron or timezone change invalidates the stored nextFireAt — recompute\n        // from now so we don't fire on the old schedule.\n        if (cronChanged || timezoneChanged) {\n          patch.nextFireAt = computeNextFireAt(cfg.cron, { timezone: cfg.timezone, after: now });\n        }\n\n        if (Object.keys(patch).length > 0) {\n          await schedulesStore.updateSchedule(scheduleId, patch);\n        }\n      } catch (error) {\n        this.#logger?.error('Failed to register declarative schedule', { scheduleId, workflowId, error });\n      }\n    }\n\n    // Orphan deletion: drop any Mastra-managed declarative schedule rows\n    // (id starts with `wf_<workflowId>` or `wf_<workflowId>__`) that are no\n    // longer declared in code. This covers two cases:\n    //   1. A registered workflow's array-form entries shrunk across deploys.\n    //   2. The owning workflow itself was deleted from code. Leaving these\n    //      rows behind would have the scheduler keep firing for a workflow\n    //      the processor can't resolve, producing infinite event-redelivery\n    //      loops (see WorkflowEventProcessor#dispatch).\n    // User-created schedules (via the schedules API) don't use the `wf_`\n    // prefix, so they're untouched.\n    const allRows = await schedulesStore.listSchedules();\n    for (const row of allRows) {\n      if (declaredIds.has(row.id)) continue;\n      if (!row.id.startsWith('wf_')) continue;\n      const ownerWorkflowId = ownerWorkflowIdForRow(row.id, declaredIdsByWorkflow) ?? ownerWorkflowIdFromRowId(row.id);\n      if (!ownerWorkflowId) continue;\n      try {\n        await schedulesStore.deleteSchedule(row.id);\n      } catch (error) {\n        this.#logger?.error('Failed to delete orphaned declarative schedule', {\n          scheduleId: row.id,\n          workflowId: ownerWorkflowId,\n          error,\n        });\n      }\n    }\n  }\n\n  /**\n   * Auto-enables the background task manager when an agent with sub-agents is\n   * registered. Sub-agent delegation runs in the background by default so the\n   * parent stream stays responsive; that requires the manager to be available.\n   * No-op when the user explicitly opted out via `backgroundTasks.enabled: false`.\n   *\n   * Eligible agents: any agent whose `agents` field is either a static record\n   * with at least one entry OR a dynamic (function-based) resolver. Function\n   * resolvers are evaluated per request, so we can't inspect their contents\n   * here — but if the caller bothered to wire one up, we enable defensively\n   * so those resolved sub-agents also dispatch in the background.\n   */\n  #maybeEnableBackgroundTasksForAgent(agent: Agent<any>): void {\n    // Already running — nothing to do\n    if (this.#backgroundTaskManager) return;\n\n    // Explicit opt-out\n    if (this.#backgroundTaskConfig?.enabled === false) return;\n\n    if (!agent.__hasSubAgentsConfigured?.()) return;\n\n    this.#backgroundTaskConfig = { ...(this.#backgroundTaskConfig ?? {}), enabled: true };\n    this.#ensureBackgroundTaskManager();\n  }\n\n  /**\n   * Retrieves a registered agent by its name.\n   *\n   * @template TAgentName - The specific agent name type from the registered agents\n   * @throws {MastraError} When the agent with the specified name is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   agents: {\n   *     weatherAgent: new Agent({\n   *       id: 'weather-agent',\n   *       name: 'weather-agent',\n   *       instructions: 'You provide weather information',\n   *       model: 'openai/gpt-5'\n   *     })\n   *   }\n   * });\n   * const agent = mastra.getAgent('weatherAgent');\n   * const response = await agent.generate('What is the weather?');\n   * ```\n   */\n  public getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName];\n  public getAgent<TAgentName extends keyof TAgents>(\n    name: TAgentName,\n    version: { versionId: string } | { status?: 'draft' | 'published' },\n  ): Promise<TAgents[TAgentName]>;\n  public getAgent<TAgentName extends keyof TAgents>(\n    name: TAgentName,\n    version?: { versionId: string } | { status?: 'draft' | 'published' },\n  ): TAgents[TAgentName] | Promise<TAgents[TAgentName]> {\n    const agent = this.#agents?.[name];\n    if (!agent) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_AGENT_BY_NAME_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Agent with name ${String(name)} not found`,\n        details: {\n          status: 404,\n          agentName: String(name),\n          agents: Object.keys(this.#agents ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    if (!version) {\n      return this.#agents[name];\n    }\n\n    return this.resolveVersionedAgent(agent, version);\n  }\n\n  /**\n   * Returns the `AgentChannels` instances for all registered agents.\n   * Keys are agent IDs.\n   */\n  public getChannels(): Record<string, AgentChannels> {\n    const result: Record<string, AgentChannels> = {};\n    for (const [agentKey, agent] of Object.entries(this.#agents ?? {})) {\n      const agentChannels = agent.getChannels();\n      if (agentChannels instanceof AgentChannels) {\n        result[agentKey] = agentChannels;\n      }\n    }\n    return result;\n  }\n\n  /**\n   * Retrieves a registered agent by its unique ID.\n   *\n   * This method searches for an agent using its internal ID property. If no agent\n   * is found with the given ID, it also attempts to find an agent using the ID as\n   * a name.\n   *\n   * @throws {MastraError} When no agent is found with the specified ID\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   agents: {\n   *     assistant: new Agent({\n   *       id: 'assistant',\n   *       name: 'assistant',\n   *       instructions: 'You are a helpful assistant',\n   *       model: 'openai/gpt-5'\n   *     })\n   *   }\n   * });\n   *\n   * const assistant = mastra.getAgent('assistant');\n   * const sameAgent = mastra.getAgentById(assistant.id);\n   * ```\n   */\n  public getAgentById<TAgentName extends keyof TAgents>(id: TAgents[TAgentName]['id']): TAgents[TAgentName];\n  public getAgentById<TAgentName extends keyof TAgents>(\n    id: TAgents[TAgentName]['id'],\n    version: { versionId: string } | { status?: 'draft' | 'published' },\n  ): Promise<TAgents[TAgentName]>;\n  public getAgentById<TAgentName extends keyof TAgents>(\n    id: TAgents[TAgentName]['id'],\n    version?: { versionId: string } | { status?: 'draft' | 'published' },\n  ): TAgents[TAgentName] | Promise<TAgents[TAgentName]> {\n    let agent = Object.values(this.#agents).find(a => a.id === id);\n\n    if (!agent) {\n      try {\n        agent = this.getAgent(id as keyof TAgents) as TAgents[TAgentName];\n      } catch {\n        // do nothing\n      }\n    }\n\n    if (!agent) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_AGENT_BY_AGENT_ID_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Agent with id ${String(id)} not found`,\n        details: {\n          status: 404,\n          agentId: String(id),\n          agents: Object.keys(this.#agents ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    if (!version) {\n      return agent as TAgents[TAgentName];\n    }\n\n    return this.resolveVersionedAgent(agent as TAgents[TAgentName], version);\n  }\n\n  /**\n   * Resolve a versioned variant of an agent by applying stored overrides from the editor.\n   *\n   * Requires the editor package to be configured — throws\n   * `MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP` if it is not.\n   *\n   * @param agent - The code-defined agent to resolve a version for.\n   * @param version - Selects a version by ID or publication status.\n   * @returns A forked agent instance with the stored overrides applied.\n   */\n  public async resolveVersionedAgent<TAgent extends Agent>(\n    agent: TAgent,\n    version: VersionSelector | { status?: 'draft' | 'published' },\n  ): Promise<TAgent> {\n    const editor = this.getEditor();\n\n    if (!editor) {\n      const error = new MastraError({\n        id: 'MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: 'Versioned agent lookup requires the editor package to be configured',\n        details: {\n          status: 400,\n          agentId: agent.id,\n          ...(version && 'versionId' in version ? { versionId: version.versionId } : {}),\n          ...(version && 'status' in version && version.status ? { versionStatus: version.status } : {}),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    return editor.agent.applyStoredOverrides(\n      agent,\n      'versionId' in version ? version : { status: version.status ?? 'published' },\n    ) as Promise<TAgent>;\n  }\n\n  /**\n   * Returns all registered agents as a record keyed by their names.\n   *\n   * This method provides access to the complete registry of agents, allowing you to\n   * iterate over them, check what agents are available, or perform bulk operations.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   agents: {\n   *     weatherAgent: new Agent({ id: 'weather-agent', name: 'weather', model: 'openai/gpt-4o' }),\n   *     supportAgent: new Agent({ id: 'support-agent', name: 'support', model: 'openai/gpt-4o' })\n   *   }\n   * });\n   *\n   * const allAgents = mastra.listAgents();\n   * console.log(Object.keys(allAgents)); // ['weatherAgent', 'supportAgent']\n   * ```\n   */\n  public listAgents() {\n    return this.#agents;\n  }\n\n  /**\n   * Adds a new agent to the Mastra instance.\n   *\n   * This method allows dynamic registration of agents after the Mastra instance\n   * has been created. The agent will be initialized with the current logger.\n   *\n   * @throws {MastraError} When an agent with the same key already exists\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const newAgent = new Agent({\n   *   id: 'chat-agent',\n   *   name: 'Chat Assistant',\n   *   model: 'openai/gpt-4o'\n   * });\n   * mastra.addAgent(newAgent); // Uses agent.id as key\n   * // or\n   * mastra.addAgent(newAgent, 'customKey'); // Uses custom key\n   *\n   * // Durable agents (e.g., InngestAgent) are also supported:\n   * const durableAgent = createInngestAgent({ agent: newAgent, inngest });\n   * mastra.addAgent(durableAgent); // Auto-registers required workflows\n   * ```\n   */\n  public addAgent<A extends Agent | ToolLoopAgentLike | DurableAgentLike>(\n    agent: A,\n    key?: string,\n    options?: { source?: DefinitionSource },\n  ): void {\n    if (!agent) {\n      throw createUndefinedPrimitiveError('agent', agent, key);\n    }\n\n    // Handle durable agent wrappers (e.g., InngestAgent)\n    // These wrap a regular Agent with execution engine-specific capabilities\n    if (isDurableAgentLike(agent)) {\n      const durableAgent = agent as DurableAgentLike;\n      const underlyingAgent = durableAgent.agent;\n      const agentKey = key || durableAgent.id;\n\n      // Check if already registered\n      const agents = this.#agents as Record<string, Agent<any>>;\n      if (agents[agentKey]) {\n        const logger = this.getLogger();\n        logger.debug(`Agent with key ${agentKey} already exists. Skipping addition.`);\n        return;\n      }\n\n      // Set the Mastra instance on the durable agent for observability\n      durableAgent.__setMastra?.(this);\n\n      // Initialize the underlying agent (needed for tools, memory, etc.)\n      underlyingAgent.__setLogger(this.#logger);\n      underlyingAgent.__registerMastra(this);\n      underlyingAgent.__registerPrimitives({\n        logger: this.getLogger(),\n        storage: this.getStorage(),\n        agents: agents,\n        tts: this.#tts,\n        vectors: this.#vectors,\n      });\n\n      // Store the durable wrapper in #agents (not the underlying agent)\n      // This ensures getAgentById returns the wrapper so .stream() uses durable execution.\n      // The cast is safe because DurableAgent extends Agent directly, and InngestAgent uses\n      // a Proxy that forwards all Agent method calls to the underlying agent.\n      agents[agentKey] = durableAgent as unknown as Agent<any>;\n\n      // Register durable workflows if the wrapper provides them\n      const durableWorkflows = durableAgent.getDurableWorkflows?.() ?? [];\n      for (const workflow of durableWorkflows) {\n        this.addWorkflow(workflow, workflow.id);\n      }\n\n      return;\n    }\n\n    let mastraAgent: Agent<any, any, any>;\n    if (isToolLoopAgentLike(agent)) {\n      // Pass the config key as the name if the ToolLoopAgent doesn't have an id\n      mastraAgent = toolLoopAgentToMastraAgent(agent, { fallbackName: key });\n    } else {\n      mastraAgent = agent as Agent;\n    }\n    const agentKey = key || mastraAgent.id;\n    const agents = this.#agents as Record<string, Agent<any>>;\n    if (agents[agentKey]) {\n      return;\n    }\n\n    // Initialize the agent\n    mastraAgent.__setLogger(this.#logger);\n    mastraAgent.__registerMastra(this);\n    mastraAgent.__registerPrimitives({\n      logger: this.getLogger(),\n      storage: this.getStorage(),\n      agents: agents,\n      tts: this.#tts,\n      vectors: this.#vectors,\n    });\n\n    // Set the source if provided\n    if (options?.source) {\n      mastraAgent.source = options.source;\n    }\n\n    agents[agentKey] = mastraAgent;\n\n    // Register configured processor workflows from the agent\n    // Use .then() to handle async resolution without blocking the constructor\n    // This excludes memory-derived processors to avoid triggering memory factory functions\n    mastraAgent\n      .getConfiguredProcessorWorkflows()\n      .then(processorWorkflows => {\n        for (const workflow of processorWorkflows) {\n          this.addWorkflow(workflow, workflow.id);\n        }\n      })\n      .catch(err => {\n        this.#logger?.debug(`Failed to register processor workflows for agent ${agentKey}:`, err);\n      });\n\n    // Register agent workspace in the workspaces registry for direct lookup.\n    // Dynamic workspace functions may return undefined without request context — that's fine,\n    // the if (workspace) guard below will skip registration and they'll register lazily later.\n    if (mastraAgent.hasOwnWorkspace?.()) {\n      Promise.resolve(mastraAgent.getWorkspace?.())\n        .then(workspace => {\n          if (workspace) {\n            this.addWorkspace(workspace, undefined, {\n              source: 'agent',\n              agentId: mastraAgent.id ?? agentKey,\n              agentName: mastraAgent.name,\n            });\n          }\n        })\n        .catch(err => {\n          this.#logger?.debug(`Failed to register workspace for agent ${agentKey}:`, err);\n        });\n    }\n\n    // Register scorers from the agent to the Mastra instance\n    // This makes agent-level scorers discoverable via mastra.getScorer()/getScorerById()\n    mastraAgent\n      .listScorers()\n      .then(scorers => {\n        for (const [, entry] of Object.entries(scorers || {})) {\n          this.addScorer(entry.scorer, undefined, { source: 'code' });\n        }\n      })\n      .catch(err => {\n        this.#logger?.debug(`Failed to register scorers from agent ${agentKey}:`, err);\n      });\n\n    // Set up AgentChannels for manual adapter configurations\n    const agentChannelsInstance = mastraAgent.getChannels();\n    if (agentChannelsInstance) {\n      agentChannelsInstance.__setLogger(this.#logger);\n      const channelRoutes = agentChannelsInstance.getWebhookRoutes();\n      if (channelRoutes.length > 0) {\n        this.#server = {\n          ...this.#server,\n          apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n        };\n      }\n      void agentChannelsInstance.initialize(this);\n    }\n  }\n\n  /**\n   * Removes an agent from the Mastra instance by its key or ID.\n   * Used when stored agents are updated/deleted to allow fresh data to be loaded.\n   *\n   * @param keyOrId - The agent key or ID to remove\n   * @returns true if an agent was removed, false if no agent was found\n   *\n   * @example\n   * ```typescript\n   * // Remove by key\n   * mastra.removeAgent('myAgent');\n   *\n   * // Remove by ID\n   * mastra.removeAgent('agent-123');\n   * ```\n   */\n  public removeAgent(keyOrId: string): boolean {\n    const agents = this.#agents as Record<string, Agent<any>>;\n\n    // Try direct key lookup first\n    if (agents[keyOrId]) {\n      const agentId = agents[keyOrId]?.id;\n      delete agents[keyOrId];\n      // Clear from stored agents cache to prevent stale data\n      if (agentId) {\n        this.#storedAgentsCache.delete(agentId);\n      }\n      return true;\n    }\n\n    // Try finding by ID\n    const key = Object.keys(agents).find(k => agents[k]?.id === keyOrId);\n    if (key) {\n      const agentId = agents[key]?.id;\n      delete agents[key];\n      // Clear from stored agents cache to prevent stale data\n      if (agentId) {\n        this.#storedAgentsCache.delete(agentId);\n      }\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Retrieves a registered vector store by its name.\n   *\n   * @template TVectorName - The specific vector store name type from the registered vectors\n   * @throws {MastraError} When the vector store with the specified name is not found\n   *\n   * @example Using a vector store for semantic search\n   * ```typescript\n   * import { PineconeVector } from '@mastra/pinecone';\n   * import { OpenAIEmbedder } from '@mastra/embedders';\n   *\n   * const mastra = new Mastra({\n   *   vectors: {\n   *     knowledge: new PineconeVector({\n   *       apiKey: process.env.PINECONE_API_KEY,\n   *       indexName: 'knowledge-base',\n   *       embedder: new OpenAIEmbedder({\n   *         apiKey: process.env.OPENAI_API_KEY,\n   *         model: 'text-embedding-3-small'\n   *       })\n   *     }),\n   *     products: new PineconeVector({\n   *       apiKey: process.env.PINECONE_API_KEY,\n   *       indexName: 'product-catalog'\n   *     })\n   *   }\n   * });\n   *\n   * // Get a vector store and perform semantic search\n   * const knowledgeBase = mastra.getVector('knowledge');\n   * const results = await knowledgeBase.query({\n   *   query: 'How to reset password?',\n   *   topK: 5\n   * });\n   *\n   * console.log('Relevant documents:', results);\n   * ```\n   */\n  public getVector<TVectorName extends keyof TVectors>(name: TVectorName): TVectors[TVectorName] {\n    const vector = this.#vectors?.[name];\n    if (!vector) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_VECTOR_BY_NAME_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Vector with name ${String(name)} not found`,\n        details: {\n          status: 404,\n          vectorName: String(name),\n          vectors: Object.keys(this.#vectors ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n    return vector;\n  }\n\n  /**\n   * Retrieves a specific vector store instance by its ID.\n   *\n   * This method searches for a vector store by its internal ID property.\n   * If not found by ID, it falls back to searching by registration key.\n   *\n   * @throws {MastraError} When the specified vector store is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   vectors: {\n   *     embeddings: chromaVector\n   *   }\n   * });\n   *\n   * const vectorStore = mastra.getVectorById('chroma-123');\n   * ```\n   */\n  public getVectorById<TVectorName extends keyof TVectors>(id: TVectors[TVectorName]['id']): TVectors[TVectorName] {\n    const allVectors = this.#vectors ?? ({} as Record<string, MastraVector>);\n\n    // First try to find by internal ID\n    for (const vector of Object.values(allVectors)) {\n      if (vector.id === id) {\n        return vector as TVectors[TVectorName];\n      }\n    }\n\n    // Fallback to searching by registration key\n    const vectorByKey = allVectors[id];\n    if (vectorByKey) {\n      return vectorByKey as TVectors[TVectorName];\n    }\n\n    const error = new MastraError({\n      id: 'MASTRA_GET_VECTOR_BY_ID_NOT_FOUND',\n      domain: ErrorDomain.MASTRA,\n      category: ErrorCategory.USER,\n      text: `Vector store with id ${id} not found`,\n      details: {\n        status: 404,\n        vectorId: String(id),\n        vectors: Object.keys(allVectors).join(', '),\n      },\n    });\n    this.#logger?.trackException(error);\n    throw error;\n  }\n\n  /**\n   * Returns all registered vector stores as a record keyed by their names.\n   *\n   * @example Listing all vector stores\n   * ```typescript\n   * const mastra = new Mastra({\n   *   vectors: {\n   *     documents: new PineconeVector({ indexName: 'docs' }),\n   *     images: new PineconeVector({ indexName: 'images' }),\n   *     products: new ChromaVector({ collectionName: 'products' })\n   *   }\n   * });\n   *\n   * const allVectors = mastra.getVectors();\n   * console.log(Object.keys(allVectors)); // ['documents', 'images', 'products']\n   *\n   * // Check vector store types and configurations\n   * for (const [name, vectorStore] of Object.entries(allVectors)) {\n   *   console.log(`Vector store ${name}:`, vectorStore.constructor.name);\n   * }\n   * ```\n   */\n  public listVectors(): TVectors | undefined {\n    return this.#vectors;\n  }\n\n  /**\n   * Adds a new vector store to the Mastra instance.\n   *\n   * This method allows dynamic registration of vector stores after the Mastra instance\n   * has been created. The vector store will be initialized with the current logger.\n   *\n   * @throws {MastraError} When a vector store with the same key already exists\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const newVector = new ChromaVector({ id: 'chroma-embeddings' });\n   * mastra.addVector(newVector); // Uses vector.id as key\n   * // or\n   * mastra.addVector(newVector, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addVector<V extends MastraVector>(vector: V, key?: string): void {\n    if (!vector) {\n      throw createUndefinedPrimitiveError('vector', vector, key);\n    }\n    const vectorKey = key || vector.id;\n    const vectors = this.#vectors as Record<string, MastraVector>;\n    if (vectors[vectorKey]) {\n      return;\n    }\n\n    // Initialize the vector with the logger\n    vector.__setLogger(this.#logger || this.getLogger());\n    vectors[vectorKey] = vector;\n  }\n\n  /**\n   * @deprecated Use listVectors() instead\n   */\n  public getVectors(): TVectors | undefined {\n    console.warn('getVectors() is deprecated. Use listVectors() instead.');\n    return this.listVectors();\n  }\n\n  /**\n   * Gets the currently configured deployment provider.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   deployer: new VercelDeployer({\n   *     token: process.env.VERCEL_TOKEN,\n   *     projectId: process.env.VERCEL_PROJECT_ID\n   *   })\n   * });\n   *\n   * const deployer = mastra.getDeployer();\n   * if (deployer) {\n   *   await deployer.deploy({\n   *     name: 'my-mastra-app',\n   *     environment: 'production'\n   *   });\n   * }\n   * ```\n   */\n  public getDeployer() {\n    return this.#deployer;\n  }\n\n  /**\n   * Gets the global workspace instance.\n   * Workspace provides file storage, skills, and code execution capabilities.\n   * Agents inherit this workspace unless they have their own configured.\n   *\n   * @example\n   * ```typescript\n   * const workspace = mastra.getWorkspace();\n   * if (workspace?.skills) {\n   *   const skills = await workspace.skills.list();\n   * }\n   * ```\n   */\n  public getWorkspace(): Workspace | undefined {\n    return this.#workspace;\n  }\n\n  /**\n   * Retrieves a registered workspace by its ID.\n   *\n   * @throws {MastraError} When the workspace with the specified ID is not found\n   *\n   * @example\n   * ```typescript\n   * const workspace = mastra.getWorkspaceById('workspace-123');\n   * const files = await workspace.filesystem.readdir('/');\n   * ```\n   */\n  public getWorkspaceById(id: string): Workspace {\n    const entry = this.#workspaces[id];\n    if (!entry) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_WORKSPACE_BY_ID_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Workspace with id ${id} not found`,\n        details: {\n          status: 404,\n          workspaceId: id,\n          availableIds: Object.keys(this.#workspaces).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n    return entry.workspace;\n  }\n\n  /**\n   * Returns all registered workspaces as a record keyed by their IDs.\n   *\n   * @example\n   * ```typescript\n   * const workspaces = mastra.listWorkspaces();\n   * for (const [id, entry] of Object.entries(workspaces)) {\n   *   console.log(`Workspace ${id}: ${entry.workspace.name} (source: ${entry.source})`);\n   * }\n   * ```\n   */\n  public listWorkspaces(): Record<string, RegisteredWorkspace> {\n    return { ...this.#workspaces };\n  }\n\n  /**\n   * Adds a new workspace to the Mastra instance.\n   *\n   * This method allows dynamic registration of workspaces after the Mastra instance\n   * has been created. Workspaces are keyed by their ID.\n   *\n   * @example\n   * ```typescript\n   * const workspace = new Workspace({\n   *   id: 'project-workspace',\n   *   name: 'Project Workspace',\n   *   filesystem: new LocalFilesystem({ rootPath: './workspace' })\n   * });\n   * mastra.addWorkspace(workspace);\n   * ```\n   */\n  public addWorkspace(\n    workspace: AnyWorkspace,\n    key?: string,\n    metadata?: { source?: 'mastra' | 'agent'; agentId?: string; agentName?: string },\n  ): void {\n    if (!workspace) {\n      throw createUndefinedPrimitiveError('workspace', workspace, key);\n    }\n    const source = metadata?.source ?? (metadata?.agentId || metadata?.agentName ? 'agent' : 'mastra');\n    if (source === 'agent' && (!metadata?.agentId || !metadata?.agentName)) {\n      throw new MastraError({\n        id: 'MASTRA_ADD_WORKSPACE_MISSING_AGENT_METADATA',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: 'Agent workspaces must include agentId and agentName.',\n        details: { status: 400, workspaceId: key || workspace.id },\n      });\n    }\n    const workspaceKey = key || workspace.id;\n    if (this.#workspaces[workspaceKey]) {\n      return;\n    }\n\n    this.#workspaces[workspaceKey] = {\n      workspace,\n      source,\n      ...(metadata?.agentId ? { agentId: metadata.agentId } : {}),\n      ...(metadata?.agentName ? { agentName: metadata.agentName } : {}),\n    };\n  }\n\n  /**\n   * Retrieves a registered workflow by its ID.\n   *\n   * @template TWorkflowId - The specific workflow ID type from the registered workflows\n   * @throws {MastraError} When the workflow with the specified ID is not found\n   *\n   * @example Getting and executing a workflow\n   * ```typescript\n   * import { createWorkflow, createStep } from '@mastra/core/workflows';\n   * import { z } from 'zod/v4';\n   *\n   * const processDataWorkflow = createWorkflow({\n   *   name: 'process-data',\n   *   triggerSchema: z.object({ input: z.string() })\n   * })\n   *   .then(validateStep)\n   *   .then(transformStep)\n   *   .then(saveStep)\n   *   .commit();\n   *\n   * const mastra = new Mastra({\n   *   workflows: {\n   *     dataProcessor: processDataWorkflow\n   *   }\n   * });\n   * ```\n   */\n  public getWorkflow<TWorkflowId extends keyof TWorkflows>(\n    id: TWorkflowId,\n    { serialized }: { serialized?: boolean } = {},\n  ): TWorkflows[TWorkflowId] {\n    const workflow = this.#workflows?.[id];\n    if (!workflow) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Workflow with ID ${String(id)} not found`,\n        details: {\n          status: 404,\n          workflowId: String(id),\n          workflows: Object.keys(this.#workflows ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    if (serialized) {\n      return { name: workflow.name } as TWorkflows[TWorkflowId];\n    }\n\n    return workflow;\n  }\n\n  __registerInternalWorkflow(workflow: Workflow) {\n    workflow.__registerMastra(this);\n    workflow.__registerPrimitives({\n      logger: this.getLogger(),\n    });\n    this.#internalMastraWorkflows[workflow.id] = workflow;\n  }\n\n  __hasInternalWorkflow(id: string): boolean {\n    return Object.values(this.#internalMastraWorkflows).some(workflow => workflow.id === id);\n  }\n\n  __getInternalWorkflow(id: string): Workflow {\n    const workflow = Object.values(this.#internalMastraWorkflows).find(a => a.id === id);\n    if (!workflow) {\n      throw new MastraError({\n        id: 'MASTRA_GET_INTERNAL_WORKFLOW_BY_ID_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.SYSTEM,\n        text: `Workflow with id ${String(id)} not found`,\n        details: {\n          status: 404,\n          workflowId: String(id),\n        },\n      });\n    }\n\n    return workflow;\n  }\n\n  /**\n   * Retrieves a registered workflow by its unique ID.\n   *\n   * This method searches for a workflow using its internal ID property. If no workflow\n   * is found with the given ID, it also attempts to find a workflow using the ID as\n   * a name.\n   *\n   * @throws {MastraError} When no workflow is found with the specified ID\n   *\n   * @example Finding a workflow by ID\n   * ```typescript\n   * const mastra = new Mastra({\n   *   workflows: {\n   *     dataProcessor: createWorkflow({\n   *       name: 'process-data',\n   *       triggerSchema: z.object({ input: z.string() })\n   *     }).commit()\n   *   }\n   * });\n   *\n   * // Get the workflow's ID\n   * const workflow = mastra.getWorkflow('dataProcessor');\n   * const workflowId = workflow.id;\n   *\n   * // Later, retrieve the workflow by ID\n   * const sameWorkflow = mastra.getWorkflowById(workflowId);\n   * console.log(sameWorkflow.name); // \"process-data\"\n   * ```\n   */\n  public getWorkflowById<TWorkflowName extends keyof TWorkflows>(\n    id: TWorkflows[TWorkflowName]['id'],\n  ): TWorkflows[TWorkflowName] {\n    let workflow = Object.values(this.#workflows).find(a => a.id === id);\n\n    if (!workflow) {\n      try {\n        workflow = this.getWorkflow(id);\n      } catch {\n        // do nothing\n      }\n    }\n\n    if (!workflow) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Workflow with id ${String(id)} not found`,\n        details: {\n          status: 404,\n          workflowId: String(id),\n          workflows: Object.keys(this.#workflows ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    return workflow as TWorkflows[TWorkflowName];\n  }\n\n  public async listActiveWorkflowRuns(): Promise<WorkflowRuns> {\n    const storage = this.#storage;\n    if (!storage) {\n      this.#logger.debug('Cannot get active workflow runs. Mastra storage is not initialized');\n      return { runs: [], total: 0 };\n    }\n\n    // Get all workflows with default engine type\n    const defaultEngineWorkflows = Object.values(this.#workflows).filter(workflow => workflow.engineType === 'default');\n\n    // Collect all active runs for workflows with default engine type\n    const allRuns: WorkflowRuns['runs'] = [];\n    let allTotal = 0;\n\n    for (const workflow of defaultEngineWorkflows) {\n      const runningRuns = await workflow.listWorkflowRuns({ status: 'running' });\n      const waitingRuns = await workflow.listWorkflowRuns({ status: 'waiting' });\n\n      allRuns.push(...runningRuns.runs, ...waitingRuns.runs);\n      allTotal += runningRuns.total + waitingRuns.total;\n    }\n\n    return {\n      runs: allRuns,\n      total: allTotal,\n    };\n  }\n\n  public async restartAllActiveWorkflowRuns(): Promise<void> {\n    const activeRuns = await this.listActiveWorkflowRuns();\n    if (activeRuns.runs.length > 0) {\n      this.#logger.debug(\n        `Restarting ${activeRuns.runs.length} active workflow run${activeRuns.runs.length > 1 ? 's' : ''}`,\n      );\n    }\n    for (const runSnapshot of activeRuns.runs) {\n      const workflow = this.getWorkflowById(runSnapshot.workflowName);\n      try {\n        const run = await workflow.createRun({ runId: runSnapshot.runId });\n        await run.restart();\n        this.#logger.debug('Restarted workflow run', { workflow: runSnapshot.workflowName, runId: runSnapshot.runId });\n      } catch (error) {\n        this.#logger.error('Failed to restart workflow run', {\n          workflow: runSnapshot.workflowName,\n          runId: runSnapshot.runId,\n          error,\n        });\n      }\n    }\n  }\n\n  /**\n   * Returns all registered scorers as a record keyed by their IDs.\n   *\n   * @example Listing all scorers\n   * ```typescript\n   * import { HelpfulnessScorer, AccuracyScorer, RelevanceScorer } from '@mastra/scorers';\n   *\n   * const mastra = new Mastra({\n   *   scorers: {\n   *     helpfulness: new HelpfulnessScorer(),\n   *     accuracy: new AccuracyScorer(),\n   *     relevance: new RelevanceScorer()\n   *   }\n   * });\n   *\n   * const allScorers = mastra.listScorers();\n   * console.log(Object.keys(allScorers)); // ['helpfulness', 'accuracy', 'relevance']\n   *\n   * // Check scorer configurations\n   * for (const [id, scorer] of Object.entries(allScorers)) {\n   *   console.log(`Scorer ${id}:`, scorer.id, scorer.name, scorer.description);\n   * }\n   * ```\n   */\n  public listScorers() {\n    return this.#scorers;\n  }\n\n  /**\n   * Adds a new scorer to the Mastra instance.\n   *\n   * This method allows dynamic registration of scorers after the Mastra instance\n   * has been created.\n   *\n   * If a scorer with the same key already exists, this method leaves the existing\n   * scorer registered and returns.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const newScorer = new MastraScorer({\n   *   id: 'quality-scorer',\n   *   name: 'Quality Scorer'\n   * });\n   * mastra.addScorer(newScorer); // Uses scorer.id as key\n   * // or\n   * mastra.addScorer(newScorer, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addScorer<S extends MastraScorer<any, any, any, any>>(\n    scorer: S,\n    key?: string,\n    options?: { source?: DefinitionSource },\n  ): void {\n    if (!scorer) {\n      throw createUndefinedPrimitiveError('scorer', scorer, key);\n    }\n    const scorerKey = key || scorer.id;\n    const scorers = this.#scorers as Record<string, MastraScorer<any, any, any, any>>;\n    if (scorers[scorerKey]) {\n      return;\n    }\n\n    // Register Mastra instance with scorer to enable custom gateway access\n    scorer.__registerMastra(this);\n\n    // Set the source if provided\n    if (options?.source) {\n      scorer.source = options.source;\n    }\n\n    scorers[scorerKey] = scorer;\n  }\n\n  /**\n   * Retrieves a registered scorer by its key.\n   *\n   * @template TScorerKey - The specific scorer key type from the registered scorers\n   * @throws {MastraError} When the scorer with the specified key is not found\n   *\n   * @example Getting and using a scorer\n   * ```typescript\n   * import { HelpfulnessScorer, AccuracyScorer } from '@mastra/scorers';\n   *\n   * const mastra = new Mastra({\n   *   scorers: {\n   *     helpfulness: new HelpfulnessScorer({\n   *       model: 'openai/gpt-4o',\n   *       criteria: 'Rate how helpful this response is'\n   *     }),\n   *     accuracy: new AccuracyScorer({\n   *       model: 'openai/gpt-5'\n   *     })\n   *   }\n   * });\n   *\n   * // Get a specific scorer\n   * const helpfulnessScorer = mastra.getScorer('helpfulness');\n   * const score = await helpfulnessScorer.score({\n   *   input: 'How do I reset my password?',\n   *   output: 'You can reset your password by clicking the forgot password link.',\n   *   expected: 'Detailed password reset instructions'\n   * });\n   *\n   * console.log('Helpfulness score:', score);\n   * ```\n   */\n  public getScorer<TScorerKey extends keyof TScorers>(key: TScorerKey): TScorers[TScorerKey] {\n    const scorer = this.#scorers?.[key];\n    if (!scorer) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_SCORER_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Scorer with ${String(key)} not found`,\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n    return scorer;\n  }\n\n  /**\n   * Retrieves a registered scorer by its name.\n   *\n   * This method searches through all registered scorers to find one with the specified name.\n   * Unlike `getScorer()` which uses the registration key, this method uses the scorer's\n   * internal name property.\n   *\n   * @throws {MastraError} When no scorer is found with the specified name\n   *\n   * @example Finding a scorer by name\n   * ```typescript\n   * import { HelpfulnessScorer } from '@mastra/scorers';\n   *\n   * const mastra = new Mastra({\n   *   scorers: {\n   *     myHelpfulnessScorer: new HelpfulnessScorer({\n   *       name: 'helpfulness-evaluator',\n   *       model: 'openai/gpt-5'\n   *     })\n   *   }\n   * });\n   *\n   * // Find scorer by its internal name, not the registration key\n   * const scorer = mastra.getScorerById('helpfulness-evaluator');\n   * const score = await scorer.score({\n   *   input: 'question',\n   *   output: 'answer'\n   * });\n   * ```\n   */\n  public getScorerById<TScorerName extends keyof TScorers>(id: TScorers[TScorerName]['id']): TScorers[TScorerName] {\n    for (const [_key, value] of Object.entries(this.#scorers ?? {})) {\n      if (value.id === id || value?.name === id) {\n        return value as TScorers[TScorerName];\n      }\n    }\n\n    const error = new MastraError({\n      id: 'MASTRA_GET_SCORER_BY_ID_NOT_FOUND',\n      domain: ErrorDomain.MASTRA,\n      category: ErrorCategory.USER,\n      text: `Scorer with id ${String(id)} not found`,\n    });\n    this.#logger?.trackException(error);\n    throw error;\n  }\n\n  /**\n   * Removes a scorer from the Mastra instance by its key or ID.\n   *\n   * @param keyOrId - The scorer key or ID to remove\n   * @returns true if a scorer was removed, false if no scorer was found\n   */\n  public removeScorer(keyOrId: string): boolean {\n    const scorers = this.#scorers as Record<string, MastraScorer<any, any, any, any>> | undefined;\n    if (!scorers) return false;\n\n    // Try direct key lookup first\n    if (scorers[keyOrId]) {\n      const scorerId = scorers[keyOrId]?.id;\n      delete scorers[keyOrId];\n      // Clear from stored scorers cache to prevent stale data\n      if (scorerId) {\n        this.#storedScorersCache.delete(scorerId);\n      }\n      return true;\n    }\n\n    // Try finding by ID or name\n    const key = Object.keys(scorers).find(k => scorers[k]?.id === keyOrId || scorers[k]?.name === keyOrId);\n    if (key) {\n      const scorerId = scorers[key]?.id;\n      delete scorers[key];\n      // Clear from stored scorers cache to prevent stale data\n      if (scorerId) {\n        this.#storedScorersCache.delete(scorerId);\n      }\n      return true;\n    }\n\n    return false;\n  }\n\n  // =========================================================================\n  // Prompt Blocks\n  // =========================================================================\n\n  /**\n   * Returns all registered prompt blocks.\n   */\n  public listPromptBlocks(): Record<string, StorageResolvedPromptBlockType> {\n    return this.#promptBlocks;\n  }\n\n  /**\n   * Registers a prompt block in the Mastra instance's runtime registry.\n   *\n   * @param promptBlock - The resolved prompt block to register\n   * @param key - Optional registration key (defaults to promptBlock.id)\n   */\n  public addPromptBlock(promptBlock: StorageResolvedPromptBlockType, key?: string): void {\n    const blockKey = key || promptBlock.id;\n    if (this.#promptBlocks[blockKey]) {\n      return;\n    }\n    this.#promptBlocks[blockKey] = promptBlock;\n  }\n\n  /**\n   * Retrieves a registered prompt block by its key.\n   *\n   * @throws {MastraError} When the prompt block with the specified key is not found\n   */\n  public getPromptBlock(key: string): StorageResolvedPromptBlockType {\n    const block = this.#promptBlocks[key];\n    if (!block) {\n      throw new MastraError({\n        id: 'MASTRA_GET_PROMPT_BLOCK_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Prompt block with key ${key} not found`,\n      });\n    }\n    return block;\n  }\n\n  /**\n   * Retrieves a registered prompt block by its ID.\n   *\n   * @throws {MastraError} When no prompt block is found with the specified ID\n   */\n  public getPromptBlockById(id: string): StorageResolvedPromptBlockType {\n    for (const [, block] of Object.entries(this.#promptBlocks)) {\n      if (block.id === id) {\n        return block;\n      }\n    }\n\n    throw new MastraError({\n      id: 'MASTRA_GET_PROMPT_BLOCK_BY_ID_NOT_FOUND',\n      domain: ErrorDomain.MASTRA,\n      category: ErrorCategory.USER,\n      text: `Prompt block with id ${id} not found`,\n    });\n  }\n\n  /**\n   * Removes a prompt block from the Mastra instance by its key or ID.\n   *\n   * @param keyOrId - The prompt block key or ID to remove\n   * @returns true if a prompt block was removed, false if not found\n   */\n  public removePromptBlock(keyOrId: string): boolean {\n    if (this.#promptBlocks[keyOrId]) {\n      delete this.#promptBlocks[keyOrId];\n      return true;\n    }\n\n    const key = Object.keys(this.#promptBlocks).find(k => this.#promptBlocks[k]?.id === keyOrId);\n    if (key) {\n      delete this.#promptBlocks[key];\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Retrieves a specific tool by registration key.\n   *\n   * @throws {MastraError} When the specified tool is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   tools: {\n   *     calculator: calculatorTool,\n   *     weather: weatherTool\n   *   }\n   * });\n   *\n   * const tool = mastra.getTool('calculator');\n   * ```\n   */\n  public getTool<TToolName extends keyof TTools>(name: TToolName): TTools[TToolName] {\n    if (!this.#tools || !this.#tools[name]) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_TOOL_BY_NAME_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Tool with name ${String(name)} not found`,\n        details: {\n          status: 404,\n          toolName: String(name),\n          tools: Object.keys(this.#tools ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n    return this.#tools[name];\n  }\n\n  /**\n   * Retrieves a specific tool by its ID.\n   *\n   * @throws {MastraError} When the specified tool is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   tools: {\n   *     calculator: calculatorTool\n   *   }\n   * });\n   *\n   * const tool = mastra.getToolById('calculator-tool-id');\n   * ```\n   */\n  public getToolById<TToolName extends keyof TTools>(id: TTools[TToolName]['id']): TTools[TToolName] {\n    const allTools = this.#tools;\n\n    if (!allTools) {\n      throw new MastraError({\n        id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Tool with id ${id} not found`,\n      });\n    }\n    // First try to find by internal ID\n    for (const tool of Object.values(allTools)) {\n      if (tool.id === id) {\n        return tool as TTools[TToolName];\n      }\n    }\n\n    // Fallback to searching by registration key\n    const toolByKey = allTools[id];\n    if (toolByKey) {\n      return toolByKey as TTools[TToolName];\n    }\n\n    const error = new MastraError({\n      id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n      domain: ErrorDomain.MASTRA,\n      category: ErrorCategory.USER,\n      text: `Tool with id ${id} not found`,\n      details: {\n        status: 404,\n        toolId: String(id),\n        tools: Object.keys(allTools).join(', '),\n      },\n    });\n    this.#logger?.trackException(error);\n    throw error;\n  }\n\n  /**\n   * Lists all configured tools.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   tools: {\n   *     calculator: calculatorTool,\n   *     weather: weatherTool\n   *   }\n   * });\n   *\n   * const tools = mastra.listTools();\n   * Object.entries(tools || {}).forEach(([name, tool]) => {\n   *   console.log(`Tool \"${name}\":`, tool.id);\n   * });\n   * ```\n   */\n  public listTools(): TTools | undefined {\n    return this.#tools;\n  }\n\n  /**\n   * Adds a new tool to the Mastra instance.\n   *\n   * This method allows dynamic registration of tools after the Mastra instance\n   * has been created.\n   *\n   * @throws {MastraError} When a tool with the same key already exists\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const newTool = createTool({\n   *   id: 'calculator-tool',\n   *   description: 'Performs calculations'\n   * });\n   * mastra.addTool(newTool); // Uses tool.id as key\n   * // or\n   * mastra.addTool(newTool, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addTool<T extends ToolAction<any, any, any, any>>(tool: T, key?: string): void {\n    if (!tool) {\n      throw createUndefinedPrimitiveError('tool', tool, key);\n    }\n    const toolKey = key || tool.id;\n    const tools = this.#tools as Record<string, ToolAction<any, any, any, any>>;\n    if (tools[toolKey]) {\n      return;\n    }\n\n    tools[toolKey] = tool;\n\n    // If the background-task manager has already initialized, register the\n    // newly-added tool with its static registry so cross-process workers can\n    // resolve dispatches for it. If init hasn't happened yet, the registry\n    // will be populated wholesale in #ensureBackgroundTaskManager().\n    if (this.#backgroundTaskManager) {\n      this.#registerToolWithBackgroundManager(toolKey, tool);\n    }\n  }\n\n  /**\n   * Retrieves a specific processor by registration key.\n   *\n   * @throws {MastraError} When the specified processor is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   processors: {\n   *     validator: validatorProcessor,\n   *     transformer: transformerProcessor\n   *   }\n   * });\n   *\n   * const processor = mastra.getProcessor('validator');\n   * ```\n   */\n  public getProcessor<TProcessorName extends keyof TProcessors>(name: TProcessorName): TProcessors[TProcessorName] {\n    if (!this.#processors || !this.#processors[name]) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_PROCESSOR_BY_NAME_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Processor with name ${String(name)} not found`,\n        details: {\n          status: 404,\n          processorName: String(name),\n          processors: Object.keys(this.#processors ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n    return this.#processors[name];\n  }\n\n  /**\n   * Retrieves a specific processor by its ID.\n   *\n   * @throws {MastraError} When the specified processor is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   processors: {\n   *     validator: validatorProcessor\n   *   }\n   * });\n   *\n   * const processor = mastra.getProcessorById('validator-processor-id');\n   * ```\n   */\n  public getProcessorById<TProcessorName extends keyof TProcessors>(\n    id: TProcessors[TProcessorName]['id'],\n  ): TProcessors[TProcessorName] {\n    const allProcessors = this.#processors;\n\n    if (!allProcessors) {\n      throw new MastraError({\n        id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Processor with id ${id} not found`,\n      });\n    }\n\n    // First try to find by internal ID\n    for (const processor of Object.values(allProcessors)) {\n      if (processor.id === id) {\n        return processor as TProcessors[TProcessorName];\n      }\n    }\n\n    // Fallback to searching by registration key\n    const processorByKey = allProcessors[id];\n    if (processorByKey) {\n      return processorByKey as TProcessors[TProcessorName];\n    }\n\n    const error = new MastraError({\n      id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n      domain: ErrorDomain.MASTRA,\n      category: ErrorCategory.USER,\n      text: `Processor with id ${id} not found`,\n      details: {\n        status: 404,\n        processorId: String(id),\n        processors: Object.keys(allProcessors).join(', '),\n      },\n    });\n    this.#logger?.trackException(error);\n    throw error;\n  }\n\n  /**\n   * Lists all configured processors.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   processors: {\n   *     validator: validatorProcessor,\n   *     transformer: transformerProcessor\n   *   }\n   * });\n   *\n   * const processors = mastra.listProcessors();\n   * Object.entries(processors || {}).forEach(([name, processor]) => {\n   *   console.log(`Processor \"${name}\":`, processor.id);\n   * });\n   * ```\n   */\n  public listProcessors(): TProcessors | undefined {\n    return this.#processors;\n  }\n\n  /**\n   * Adds a new processor to the Mastra instance.\n   *\n   * This method allows dynamic registration of processors after the Mastra instance\n   * has been created.\n   *\n   * @throws {MastraError} When a processor with the same key already exists\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const newProcessor = {\n   *   id: 'text-processor',\n   *   processInput: async (messages) => messages\n   * };\n   * mastra.addProcessor(newProcessor); // Uses processor.id as key\n   * // or\n   * mastra.addProcessor(newProcessor, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addProcessor<P extends Processor>(processor: P, key?: string): void {\n    if (!processor) {\n      throw createUndefinedPrimitiveError('processor', processor, key);\n    }\n    const processorKey = key || processor.id;\n    const processors = this.#processors as Record<string, Processor>;\n    if (processors[processorKey]) {\n      return;\n    }\n\n    // Register Mastra with the processor if it supports it\n    if (typeof processor.__registerMastra === 'function') {\n      processor.__registerMastra(this);\n    }\n\n    processors[processorKey] = processor;\n  }\n\n  /**\n   * Registers a processor configuration with agent context.\n   * This tracks which agents use which processors with what configuration.\n   *\n   * @param processor - The processor instance\n   * @param agentId - The ID of the agent that uses this processor\n   * @param type - Whether this is an input or output processor\n   */\n  public addProcessorConfiguration(processor: Processor, agentId: string, type: 'input' | 'output'): void {\n    const processorId = processor.id;\n    if (!this.#processorConfigurations.has(processorId)) {\n      this.#processorConfigurations.set(processorId, []);\n    }\n    const configs = this.#processorConfigurations.get(processorId)!;\n\n    // Check if this exact configuration already exists\n    const exists = configs.some(c => c.agentId === agentId && c.type === type);\n    if (!exists) {\n      configs.push({ processor, agentId, type });\n    }\n  }\n\n  /**\n   * Gets all processor configurations for a specific processor ID.\n   *\n   * @param processorId - The ID of the processor\n   * @returns Array of configurations with agent context\n   */\n  public getProcessorConfigurations(\n    processorId: string,\n  ): Array<{ processor: Processor; agentId: string; type: 'input' | 'output' }> {\n    return this.#processorConfigurations.get(processorId) || [];\n  }\n\n  /**\n   * Gets all processor configurations.\n   *\n   * @returns Map of processor IDs to their configurations\n   */\n  public listProcessorConfigurations(): Map<\n    string,\n    Array<{ processor: Processor; agentId: string; type: 'input' | 'output' }>\n  > {\n    return this.#processorConfigurations;\n  }\n\n  /**\n   * Retrieves a registered memory instance by its registration key.\n   *\n   * @throws {MastraError} When the memory instance with the specified key is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   memory: {\n   *     chat: new Memory({ storage })\n   *   }\n   * });\n   *\n   * const chatMemory = mastra.getMemory('chat');\n   * ```\n   */\n  public getMemory<TMemoryName extends keyof TMemory>(name: TMemoryName): TMemory[TMemoryName] {\n    if (!this.#memory || !this.#memory[name]) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_MEMORY_BY_KEY_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Memory with key ${String(name)} not found`,\n        details: {\n          status: 404,\n          memoryKey: String(name),\n          memory: Object.keys(this.#memory ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n    return this.#memory[name];\n  }\n\n  /**\n   * Retrieves a registered memory instance by its ID.\n   *\n   * Searches through all registered memory instances and returns the one whose ID matches.\n   *\n   * @throws {MastraError} When no memory instance with the specified ID is found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   memory: {\n   *     chat: new Memory({ id: 'chat-memory', storage })\n   *   }\n   * });\n   *\n   * const memory = mastra.getMemoryById('chat-memory');\n   * ```\n   */\n  public getMemoryById(id: string): MastraMemory {\n    const allMemory = this.#memory;\n    if (allMemory) {\n      for (const [, memory] of Object.entries(allMemory)) {\n        if (memory.id === id) {\n          return memory;\n        }\n      }\n    }\n\n    const error = new MastraError({\n      id: 'MASTRA_GET_MEMORY_BY_ID_NOT_FOUND',\n      domain: ErrorDomain.MASTRA,\n      category: ErrorCategory.USER,\n      text: `Memory with id ${id} not found`,\n      details: {\n        status: 404,\n        memoryId: id,\n        availableIds: Object.values(allMemory ?? {})\n          .map(m => m.id)\n          .join(', '),\n      },\n    });\n    this.#logger?.trackException(error);\n    throw error;\n  }\n\n  /**\n   * Returns all registered memory instances as a record keyed by their names.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   memory: {\n   *     chat: new Memory({ storage }),\n   *     longTerm: new Memory({ storage })\n   *   }\n   * });\n   *\n   * const allMemory = mastra.listMemory();\n   * console.log(Object.keys(allMemory)); // ['chat', 'longTerm']\n   * ```\n   */\n  public listMemory(): TMemory | undefined {\n    return this.#memory;\n  }\n\n  /**\n   * Adds a new memory instance to the Mastra instance.\n   *\n   * This method allows dynamic registration of memory instances after the Mastra instance\n   * has been created.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const chatMemory = new Memory({\n   *   id: 'chat-memory',\n   *   storage: mastra.getStorage()\n   * });\n   * mastra.addMemory(chatMemory); // Uses memory.id as key\n   * // or\n   * mastra.addMemory(chatMemory, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addMemory<M extends MastraMemory>(memory: M, key?: string): void {\n    if (!memory) {\n      throw createUndefinedPrimitiveError('memory', memory, key);\n    }\n    const memoryKey = key || memory.id;\n    const memoryRegistry = this.#memory as Record<string, MastraMemory>;\n    if (memoryRegistry[memoryKey]) {\n      return;\n    }\n\n    memory.__registerMastra(this);\n    if (!memory.hasOwnStorage) {\n      const storage = this.getStorage();\n      if (storage) {\n        memory.setStorage(storage);\n      }\n    }\n\n    memoryRegistry[memoryKey] = memory;\n  }\n\n  /**\n   * Returns all registered workflows as a record keyed by their IDs.\n   *\n   * @example Listing all workflows\n   * ```typescript\n   * const mastra = new Mastra({\n   *   workflows: {\n   *     dataProcessor: createWorkflow({...}).commit(),\n   *     emailSender: createWorkflow({...}).commit(),\n   *     reportGenerator: createWorkflow({...}).commit()\n   *   }\n   * });\n   *\n   * const allWorkflows = mastra.listWorkflows();\n   * console.log(Object.keys(allWorkflows)); // ['dataProcessor', 'emailSender', 'reportGenerator']\n   *\n   * // Execute all workflows with sample data\n   * for (const [id, workflow] of Object.entries(allWorkflows)) {\n   *   console.log(`Workflow ${id}:`, workflow.name);\n   *   // const result = await workflow.execute(sampleData);\n   * }\n   * ```\n   */\n  public listWorkflows(props: { serialized?: boolean } = {}): Record<string, Workflow> {\n    if (props.serialized) {\n      return Object.entries(this.#workflows).reduce((acc, [k, v]) => {\n        return {\n          ...acc,\n          [k]: { name: v.name },\n        };\n      }, {});\n    }\n    return this.#workflows;\n  }\n\n  /**\n   * Adds a new workflow to the Mastra instance.\n   *\n   * This method allows dynamic registration of workflows after the Mastra instance\n   * has been created. The workflow will be initialized with Mastra and primitives.\n   *\n   * @throws {MastraError} When a workflow with the same key already exists\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const newWorkflow = createWorkflow({\n   *   id: 'data-pipeline',\n   *   name: 'Data Pipeline'\n   * }).commit();\n   * mastra.addWorkflow(newWorkflow); // Uses workflow.id as key\n   * // or\n   * mastra.addWorkflow(newWorkflow, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addWorkflow(workflow: AnyWorkflow, key?: string): void {\n    if (!workflow) {\n      throw createUndefinedPrimitiveError('workflow', workflow, key);\n    }\n    const workflowKey = key || workflow.id;\n    const workflows = this.#workflows as Record<string, AnyWorkflow>;\n    if (workflows[workflowKey]) {\n      return;\n    }\n\n    // Note on schedules: a workflow declaring a `schedule` is auto-promoted to\n    // the evented engine by the `createWorkflow` factory. We don't reject default-\n    // engine workflows that happen to carry schedule configs — those would only\n    // exist if a user constructed `Workflow` directly, in which case they've\n    // explicitly opted out of the factory's promotion behavior and we trust them.\n    const scheduleConfigs = collectWorkflowScheduleConfigs(workflow);\n    const hasSchedule = scheduleConfigs.length > 0;\n\n    // Initialize the workflow with Mastra and primitives\n    workflow.__registerMastra(this);\n    workflow.__registerPrimitives({\n      logger: this.getLogger(),\n      storage: this.getStorage(),\n    });\n    if (!workflow.committed) {\n      workflow.commit();\n    }\n    workflows[workflowKey] = workflow;\n\n    this.registerStaticWorkflowScorers(workflow);\n\n    // If a schedule is declared, mark the flag and register into the\n    // running scheduler worker (if already started).\n    if (hasSchedule) {\n      this.#hasScheduledWorkflow = true;\n      const worker = this.#findSchedulerWorker();\n      if (worker?.scheduler) {\n        void (async () => {\n          try {\n            const schedulesStore = await this.#storage?.getStore('schedules');\n            if (!schedulesStore) return;\n            await this.registerDeclarativeSchedules(schedulesStore);\n          } catch (error) {\n            this.#logger?.error('Failed to register declarative schedule for workflow', {\n              workflowId: workflow.id,\n              error,\n            });\n          }\n        })();\n      }\n      // If the worker doesn't exist yet (workers not started), schedules\n      // will be registered when SchedulerWorker.init() runs.\n    }\n  }\n\n  private registerStaticWorkflowScorers(workflow: AnyWorkflow): void {\n    for (const step of Object.values(workflow.steps ?? {})) {\n      const scorers = step.scorers;\n      if (!scorers || typeof scorers === 'function') {\n        continue;\n      }\n\n      for (const [, entry] of Object.entries(scorers)) {\n        this.addScorer(entry.scorer, undefined, { source: 'code' });\n      }\n    }\n  }\n\n  /**\n   * Sets the storage provider for the Mastra instance.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   *\n   * // Set PostgreSQL storage\n   * mastra.setStorage(new PostgresStore({\n   *   connectionString: process.env.DATABASE_URL\n   * }));\n   *\n   * // Now agents can use memory with the storage\n   * const agent = new Agent({\n   *   id: 'assistant',\n   *   name: 'assistant',\n   *   memory: new Memory({ storage: mastra.getStorage() })\n   * });\n   * ```\n   */\n  public setStorage(storage: MastraCompositeStore) {\n    this.#storage = augmentWithInit(storage);\n    this.#ensureBackgroundTaskManager();\n    // If storage was attached after construction, the SchedulerWorker\n    // will pick it up when startWorkers() is called.\n  }\n\n  public setLogger({ logger }: { logger: TLogger }) {\n    // Wrap the new logger in a DualLogger to maintain dual-write to loggerVNext\n    const dualLogger = new DualLogger(logger, () => this.loggerVNext);\n    this.#logger = dualLogger as unknown as TLogger;\n\n    if (this.#agents) {\n      Object.keys(this.#agents).forEach(key => {\n        this.#agents?.[key]?.__setLogger(this.#logger);\n      });\n    }\n\n    if (this.#deployer) {\n      this.#deployer.__setLogger(this.#logger);\n    }\n\n    if (this.#tts) {\n      Object.keys(this.#tts).forEach(key => {\n        this.#tts?.[key]?.__setLogger(this.#logger);\n      });\n    }\n\n    if (this.#storage) {\n      this.#storage.__setLogger(this.#logger);\n    }\n\n    if (this.#vectors) {\n      Object.keys(this.#vectors).forEach(key => {\n        this.#vectors?.[key]?.__setLogger(this.#logger);\n      });\n    }\n\n    if (this.#mcpServers) {\n      Object.keys(this.#mcpServers).forEach(key => {\n        this.#mcpServers?.[key]?.__setLogger(this.#logger);\n      });\n    }\n\n    if (this.#workflows) {\n      Object.keys(this.#workflows).forEach(key => {\n        this.#workflows?.[key]?.__setLogger(this.#logger);\n      });\n    }\n\n    if (this.#serverAdapter) {\n      this.#serverAdapter.__setLogger(this.#logger);\n    }\n\n    if (this.#workspace) {\n      this.#workspace.__setLogger(this.#logger);\n    }\n\n    if (this.#memory) {\n      Object.keys(this.#memory).forEach(key => {\n        this.#memory?.[key]?.__setLogger(this.#logger);\n      });\n    }\n\n    // Pass the raw logger (not the DualLogger) to observability to avoid circular forwarding\n    this.#observability.setLogger({ logger });\n  }\n\n  /**\n   * Gets all registered text-to-speech (TTS) providers.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   tts: {\n   *     openai: new OpenAITTS({\n   *       apiKey: process.env.OPENAI_API_KEY,\n   *       voice: 'alloy'\n   *     })\n   *   }\n   * });\n   *\n   * const ttsProviders = mastra.getTTS();\n   * const openaiTTS = ttsProviders?.openai;\n   * if (openaiTTS) {\n   *   const audioBuffer = await openaiTTS.synthesize('Hello, world!');\n   * }\n   * ```\n   */\n  public getTTS() {\n    return this.#tts;\n  }\n\n  /**\n   * Gets the currently configured logger instance.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   logger: new PinoLogger({\n   *     name: 'MyApp',\n   *     level: 'info'\n   *   })\n   * });\n   *\n   * const logger = mastra.getLogger();\n   * logger.info('Application started');\n   * logger.error('An error occurred', { error: 'details' });\n   * ```\n   */\n  public getLogger() {\n    return this.#logger;\n  }\n\n  /**\n   * Gets the currently configured storage provider.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./data.db' })\n   * });\n   *\n   * // Use the storage in agent memory\n   * const agent = new Agent({\n   *   id: 'assistant',\n   *   name: 'assistant',\n   *   memory: new Memory({\n   *     storage: mastra.getStorage()\n   *   })\n   * });\n   * ```\n   */\n  public getStorage() {\n    return this.#storage;\n  }\n\n  get observability(): ObservabilityEntrypoint {\n    return this.#observability;\n  }\n\n  /**\n   * Structured logging API for observability.\n   * Logs emitted via this API will not have trace correlation when used outside a span.\n   * Use for startup logs, background jobs, or other non-traced scenarios.\n   *\n   * Note: For the infrastructure logger (IMastraLogger), use getLogger() instead.\n   */\n  get loggerVNext(): LoggerContext {\n    return this.#observability.getDefaultInstance()?.getLoggerContext?.() ?? noOpLoggerContext;\n  }\n\n  /**\n   * Direct metrics API for use outside trace context.\n   * Metrics emitted via this API will not have auto correlation or cost context from spans.\n   * Use for background jobs, startup metrics, or other non-traced scenarios.\n   */\n  get metrics(): MetricsContext {\n    return this.#observability.getDefaultInstance()?.getMetricsContext?.() ?? noOpMetricsContext;\n  }\n\n  public getServerMiddleware() {\n    return this.#serverMiddleware;\n  }\n\n  public getServerCache() {\n    return this.#serverCache;\n  }\n\n  public setServerMiddleware(serverMiddleware: Middleware | Middleware[]) {\n    if (typeof serverMiddleware === 'function') {\n      this.#serverMiddleware = [\n        {\n          handler: serverMiddleware,\n          path: '/api/*',\n        },\n      ];\n      return;\n    }\n\n    if (!Array.isArray(serverMiddleware)) {\n      const error = new MastraError({\n        id: 'MASTRA_SET_SERVER_MIDDLEWARE_INVALID_TYPE',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Invalid middleware: expected a function or array, received ${typeof serverMiddleware}`,\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    this.#serverMiddleware = serverMiddleware.map(m => {\n      if (typeof m === 'function') {\n        return {\n          handler: m,\n          path: '/api/*',\n        };\n      }\n      return {\n        handler: m.handler,\n        path: m.path || '/api/*',\n      };\n    });\n  }\n\n  public getServer() {\n    return this.#server;\n  }\n\n  /**\n   * Sets the server adapter for this Mastra instance.\n   *\n   * The server adapter provides access to the underlying server app (e.g., Hono, Express)\n   * and allows users to call routes directly via `app.fetch()` instead of making HTTP requests.\n   *\n   * This is typically called by `createHonoServer` or similar factory functions during\n   * server initialization.\n   *\n   * @param adapter - The server adapter instance (e.g., MastraServer from @mastra/hono or @mastra/express)\n   *\n   * @example\n   * ```typescript\n   * const app = new Hono();\n   * const adapter = new MastraServer({ app, mastra });\n   * mastra.setMastraServer(adapter);\n   * ```\n   */\n  public setMastraServer(adapter: MastraServerBase): void {\n    if (this.#serverAdapter) {\n      this.#logger?.debug(\n        'Replacing existing server adapter. Only one adapter should be registered per Mastra instance.',\n      );\n    }\n    this.#serverAdapter = adapter;\n    // Inject the logger into the adapter\n    if (this.#logger) {\n      adapter.__setLogger(this.#logger);\n    }\n  }\n\n  /**\n   * Gets the server adapter for this Mastra instance.\n   *\n   * @returns The server adapter, or undefined if not set\n   *\n   * @example\n   * ```typescript\n   * const adapter = mastra.getMastraServer();\n   * if (adapter) {\n   *   const app = adapter.getApp<Hono>();\n   * }\n   * ```\n   */\n  public getMastraServer(): MastraServerBase | undefined {\n    return this.#serverAdapter;\n  }\n\n  /**\n   * Gets the server app from the server adapter.\n   *\n   * This is a convenience method that calls `getMastraServer()?.getApp<T>()`.\n   * Use this to access the underlying server framework's app instance (e.g., Hono, Express)\n   * for direct operations like calling routes via `app.fetch()`.\n   *\n   * @template T - The expected type of the app (e.g., Hono, Express Application)\n   * @returns The server app, or undefined if no adapter is set\n   *\n   * @example\n   * ```typescript\n   * // After createHonoServer() is called:\n   * const app = mastra.getServerApp<Hono>();\n   *\n   * // Call routes directly without HTTP overhead\n   * const response = await app?.fetch(new Request('http://localhost/health'));\n   * const data = await response?.json();\n   * ```\n   */\n  public getServerApp<T = unknown>(): T | undefined {\n    return this.#serverAdapter?.getApp<T>();\n  }\n\n  public getBundlerConfig() {\n    return this.#bundler;\n  }\n\n  public async listLogsByRunId({\n    runId,\n    transportId,\n    fromDate,\n    toDate,\n    logLevel,\n    filters,\n    page,\n    perPage,\n  }: {\n    runId: string;\n    transportId: string;\n    fromDate?: Date;\n    toDate?: Date;\n    logLevel?: LogLevel;\n    filters?: Record<string, any>;\n    page?: number;\n    perPage?: number;\n  }) {\n    if (!transportId) {\n      const error = new MastraError({\n        id: 'MASTRA_LIST_LOGS_BY_RUN_ID_MISSING_TRANSPORT',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: 'Transport ID is required',\n        details: {\n          runId,\n          transportId,\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    if (!this.#logger?.listLogsByRunId) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_LOGS_BY_RUN_ID_LOGGER_NOT_CONFIGURED',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.SYSTEM,\n        text: 'Logger is not configured or does not support listLogsByRunId operation',\n        details: {\n          runId,\n          transportId,\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    return await this.#logger.listLogsByRunId({\n      runId,\n      transportId,\n      fromDate,\n      toDate,\n      logLevel,\n      filters,\n      page,\n      perPage,\n    });\n  }\n\n  public async listLogs(\n    transportId: string,\n    params?: {\n      fromDate?: Date;\n      toDate?: Date;\n      logLevel?: LogLevel;\n      filters?: Record<string, any>;\n      page?: number;\n      perPage?: number;\n    },\n  ) {\n    if (!transportId) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_LOGS_MISSING_TRANSPORT',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: 'Transport ID is required',\n        details: {\n          transportId,\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    if (!this.#logger) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_LOGS_LOGGER_NOT_CONFIGURED',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.SYSTEM,\n        text: 'Logger is not set',\n        details: {\n          transportId,\n        },\n      });\n      throw error;\n    }\n\n    return await this.#logger.listLogs(transportId, params);\n  }\n\n  /**\n   * Gets all registered Model Context Protocol (MCP) server instances.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   mcpServers: {\n   *     filesystem: new FileSystemMCPServer({\n   *       rootPath: '/app/data'\n   *     })\n   *   }\n   * });\n   *\n   * const mcpServers = mastra.getMCPServers();\n   * if (mcpServers) {\n   *   const fsServer = mcpServers.filesystem;\n   *   const tools = await fsServer.listTools();\n   * }\n   * ```\n   */\n  public listMCPServers(): Record<string, MCPServerBase> | undefined {\n    return this.#mcpServers;\n  }\n\n  /**\n   * Adds a new MCP server to the Mastra instance.\n   *\n   * This method allows dynamic registration of MCP servers after the Mastra instance\n   * has been created. The server will be initialized with ID, Mastra instance, and logger.\n   *\n   * @throws {MastraError} When an MCP server with the same key already exists\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra();\n   * const newServer = new FileSystemMCPServer({\n   *   rootPath: '/data'\n   * });\n   * mastra.addMCPServer(newServer); // Uses server.id as key\n   * // or\n   * mastra.addMCPServer(newServer, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addMCPServer<M extends MCPServerBase>(server: M, key?: string): void {\n    if (!server) {\n      throw createUndefinedPrimitiveError('mcp-server', server, key);\n    }\n    // If a key is provided, try to set it as the ID\n    // The setId method will only update if the ID wasn't explicitly set by the user\n    if (key) {\n      server.setId(key);\n    }\n\n    // Now resolve the ID after potentially setting it\n    const resolvedId = server.id;\n    if (!resolvedId) {\n      const error = new MastraError({\n        id: 'MASTRA_ADD_MCP_SERVER_MISSING_ID',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: 'MCP server must expose an id or be registered under one',\n        details: { status: 400 },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n\n    const serverKey = key ?? resolvedId;\n    const servers = this.#mcpServers as Record<string, MCPServerBase>;\n    if (servers[serverKey]) {\n      return;\n    }\n\n    // Initialize the server\n    server.__registerMastra(this);\n    server.__setLogger(this.getLogger());\n    servers[serverKey] = server;\n  }\n\n  /**\n   * Retrieves a specific MCP server instance by registration key.\n   *\n   * @throws {MastraError} When the specified MCP server is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   mcpServers: {\n   *     filesystem: new FileSystemMCPServer({...})\n   *   }\n   * });\n   *\n   * const fsServer = mastra.getMCPServer('filesystem');\n   * const tools = await fsServer.listTools();\n   * ```\n   */\n  public getMCPServer<TMCPServerName extends keyof TMCPServers>(\n    name: TMCPServerName,\n  ): TMCPServers[TMCPServerName] | undefined {\n    if (!this.#mcpServers || !this.#mcpServers[name]) {\n      this.#logger?.debug(`MCP server with name ${String(name)} not found`);\n      return undefined as TMCPServers[TMCPServerName] | undefined;\n    }\n    return this.#mcpServers[name];\n  }\n\n  /**\n   * Retrieves a specific Model Context Protocol (MCP) server instance by its logical ID.\n   *\n   * This method searches for an MCP server using its logical ID. If a version is specified,\n   * it returns the exact version match. If no version is provided, it returns the server\n   * with the most recent release date.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   mcpServers: {\n   *     filesystem: new FileSystemMCPServer({\n   *       id: 'fs-server',\n   *       version: '1.0.0',\n   *       rootPath: '/app/data'\n   *     })\n   *   }\n   * });\n   *\n   * const fsServer = mastra.getMCPServerById('fs-server');\n   * if (fsServer) {\n   *   const tools = await fsServer.listTools();\n   * }\n   * ```\n   */\n  public getMCPServerById<TMCPServerName extends keyof TMCPServers>(\n    serverId: TMCPServers[TMCPServerName]['id'],\n    version?: string,\n  ): TMCPServers[TMCPServerName] | undefined {\n    if (!this.#mcpServers) {\n      return undefined;\n    }\n\n    const allRegisteredServers = Object.values(this.#mcpServers || {});\n\n    const matchingLogicalIdServers = allRegisteredServers.filter(server => server.id === serverId);\n\n    if (matchingLogicalIdServers.length === 0) {\n      this.#logger?.debug(`No MCP servers found with logical ID: ${serverId}`);\n      return undefined;\n    }\n\n    if (version) {\n      const specificVersionServer = matchingLogicalIdServers.find(server => server.version === version);\n      if (!specificVersionServer) {\n        this.#logger?.debug(`MCP server with logical ID '${serverId}' found, but not version '${version}'.`);\n      }\n      return specificVersionServer as TMCPServers[TMCPServerName] | undefined;\n    } else {\n      // No version specified, find the one with the most recent releaseDate\n      if (matchingLogicalIdServers.length === 1) {\n        return matchingLogicalIdServers[0] as TMCPServers[TMCPServerName];\n      }\n\n      matchingLogicalIdServers.sort((a, b) => {\n        // Ensure releaseDate exists and is a string before creating a Date object\n        const dateAVal = a.releaseDate && typeof a.releaseDate === 'string' ? new Date(a.releaseDate).getTime() : NaN;\n        const dateBVal = b.releaseDate && typeof b.releaseDate === 'string' ? new Date(b.releaseDate).getTime() : NaN;\n\n        if (isNaN(dateAVal) && isNaN(dateBVal)) return 0;\n        if (isNaN(dateAVal)) return 1; // Treat invalid/missing dates as older\n        if (isNaN(dateBVal)) return -1; // Treat invalid/missing dates as older\n\n        return dateBVal - dateAVal; // Sorts in descending order of time (latest first)\n      });\n\n      // After sorting, the first element should be the latest if its date is valid\n      if (matchingLogicalIdServers.length > 0) {\n        const latestServer = matchingLogicalIdServers[0];\n        if (\n          latestServer &&\n          latestServer.releaseDate &&\n          typeof latestServer.releaseDate === 'string' &&\n          !isNaN(new Date(latestServer.releaseDate).getTime())\n        ) {\n          return latestServer as TMCPServers[TMCPServerName];\n        }\n      }\n      this.#logger?.warn(\n        `Could not determine the latest server for logical ID '${serverId}' due to invalid or missing release dates, or no servers left after filtering.`,\n      );\n      return undefined;\n    }\n  }\n\n  public async addTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n    await this.#pubsub.subscribe(topic, listener);\n  }\n\n  public async removeTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n    await this.#pubsub.unsubscribe(topic, listener);\n  }\n\n  /**\n   * Process a single workflow event. Shared entry point used by:\n   * - pull-mode workers (OrchestrationWorker)\n   * - in-process push pubsubs (EventEmitterPubSub) wired during startWorkers()\n   * - HTTP push delivered to `POST /api/workers/events`\n   *\n   * Returns `{ ok: true }` on success; the caller should ack/return 2xx.\n   * Returns `{ ok: false, retry: true }` on transient failure; the caller\n   * should nack/return 5xx so the broker retries.\n   */\n  public async handleWorkflowEvent(event: Event): Promise<{ ok: true } | { ok: false; retry: boolean }> {\n    if (!this.#workflowEventProcessor) {\n      this.#workflowEventProcessor = new WorkflowEventProcessor({ mastra: this });\n    }\n    return this.#workflowEventProcessor.handle(event);\n  }\n\n  /**\n   * Initialize and start workers. If `name` is provided, starts only\n   * that worker. Otherwise starts all registered workers and subscribes\n   * user-defined event listeners.\n   */\n  public async startWorkers(name?: string): Promise<void> {\n    // Lazily inject the SchedulerWorker if the scheduler should be enabled\n    // and no scheduler worker is registered yet. This runs after all\n    // workflows have been registered (unlike the constructor's default-workers\n    // block), so #hasScheduledWorkflow is accurate.\n    if (!name && this.#shouldEnableScheduler() && this.#storage && !this.#findSchedulerWorker()) {\n      const sw = new SchedulerWorker(this.#schedulerConfig);\n      sw.__registerMastra(this);\n      this.#workers.push(sw);\n    }\n\n    const deps: WorkerDeps = {\n      pubsub: this.#pubsub,\n      storage: this.#storage!,\n      logger: this.#logger as unknown as IMastraLogger,\n      mastra: this,\n    };\n\n    let targets: MastraWorker[];\n    if (name) {\n      targets = this.#workers.filter(w => w.name === name);\n      if (targets.length === 0) {\n        throw new Error(`Worker \"${name}\" not found. Available: ${this.#workers.map(w => w.name).join(', ')}`);\n      }\n    } else if (this.#workerFilter) {\n      targets = this.#workers.filter(w => this.#workerFilter!.has(w.name));\n      if (targets.length === 0) {\n        this.#logger?.warn?.(\n          `MASTRA_WORKERS=${[...this.#workerFilter].join(',')} did not match any registered workers (have: ${this.#workers.map(w => w.name).join(', ')})`,\n        );\n      }\n    } else {\n      targets = this.#workers;\n    }\n\n    for (const worker of targets) {\n      await worker.init(deps);\n      await worker.start();\n    }\n\n    // For push-mode pubsubs (e.g. EventEmitterPubSub) there is no\n    // OrchestrationWorker pulling events — wire handleWorkflowEvent directly\n    // to the pubsub so workflow events still get processed in-process.\n    if (!name) {\n      const modes = this.#pubsub.supportedModes ?? ['pull'];\n      const pushOnly = modes.includes('push') && !modes.includes('pull');\n      if (pushOnly && !this.#pushSubscription) {\n        const cb: EventCallback = (event, ack) => {\n          void this.handleWorkflowEvent(event)\n            .then(result => {\n              if (result.ok && ack) {\n                return ack().catch(err =>\n                  this.#logger?.error?.('Error acking workflow event in push subscription', err),\n                );\n              }\n              // Push transports without nack semantics (EventEmitter) treat\n              // a non-ack as a failure signal; we already logged inside handle().\n            })\n            .catch(err => this.#logger?.error?.('Unhandled error in workflow event push subscription', err));\n        };\n        await this.#pubsub.subscribe('workflows', cb);\n        this.#pushSubscription = { topic: 'workflows', cb };\n      }\n    }\n\n    // Subscribe user-defined event listeners (non-workflow topics, or legacy inline WEP)\n    // Only when starting all workers (not when targeting a specific one).\n    // Idempotent: skip pairs we've already subscribed.\n    if (!name) {\n      for (const topic in this.#events) {\n        if (!this.#events[topic]) {\n          continue;\n        }\n\n        const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];\n        for (const listener of listeners) {\n          const alreadySubscribed = this.#userEventSubscriptions.some(\n            sub => sub.topic === topic && sub.cb === listener,\n          );\n          if (alreadySubscribed) continue;\n          await this.#pubsub.subscribe(topic, listener);\n          this.#userEventSubscriptions.push({ topic, cb: listener });\n        }\n      }\n    }\n  }\n\n  /**\n   * Stop all running workers and unsubscribe event listeners.\n   */\n  public async stopWorkers(): Promise<void> {\n    // Stop registered workers in reverse order\n    for (const worker of [...this.#workers].reverse()) {\n      if (worker.isRunning) {\n        await worker.stop();\n      }\n    }\n\n    // Tear down the in-process push subscription wired during startWorkers().\n    if (this.#pushSubscription) {\n      await this.#pubsub.unsubscribe(this.#pushSubscription.topic, this.#pushSubscription.cb);\n      this.#pushSubscription = undefined;\n    }\n\n    // Unsubscribe only the (topic, listener) pairs we actually registered in\n    // startWorkers() — keeps stopWorkers() symmetric with startWorkers() and\n    // avoids unsubscribing listeners that startWorkers never owned.\n    for (const { topic, cb } of this.#userEventSubscriptions) {\n      await this.#pubsub.unsubscribe(topic, cb);\n    }\n    this.#userEventSubscriptions = [];\n\n    await this.#pubsub.flush();\n  }\n\n  /**\n   * @deprecated Use {@link Mastra.startWorkers} instead. Will be removed in a\n   * future release.\n   */\n  public async startEventEngine(name?: string): Promise<void> {\n    return this.startWorkers(name);\n  }\n\n  /**\n   * @deprecated Use {@link Mastra.stopWorkers} instead. Will be removed in a\n   * future release.\n   */\n  public async stopEventEngine(): Promise<void> {\n    return this.stopWorkers();\n  }\n\n  /**\n   * Retrieves a registered gateway by its key.\n   *\n   * @throws {MastraError} When the gateway with the specified key is not found\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   gateways: {\n   *     myGateway: new CustomGateway()\n   *   }\n   * });\n   *\n   * const gateway = mastra.getGateway('myGateway');\n   * ```\n   */\n  public getGateway(key: string): MastraModelGateway {\n    const gateway = this.#gateways?.[key];\n    if (!gateway) {\n      const error = new MastraError({\n        id: 'MASTRA_GET_GATEWAY_BY_KEY_NOT_FOUND',\n        domain: ErrorDomain.MASTRA,\n        category: ErrorCategory.USER,\n        text: `Gateway with key ${key} not found`,\n        details: {\n          status: 404,\n          gatewayKey: key,\n          gateways: Object.keys(this.#gateways ?? {}).join(', '),\n        },\n      });\n      this.#logger?.trackException(error);\n      throw error;\n    }\n    return gateway;\n  }\n\n  /**\n   * Retrieves a registered gateway by its ID.\n   *\n   * Searches through all registered gateways and returns the one whose ID matches.\n   * If a gateway doesn't have an explicit ID, its name is used as the ID.\n   *\n   * @throws {MastraError} When no gateway with the specified ID is found\n   *\n   * @example\n   * ```typescript\n   * class CustomGateway extends MastraModelGateway {\n   *   readonly id = 'custom-gateway-v1';\n   *   readonly name = 'Custom Gateway';\n   *   // ...\n   * }\n   *\n   * const mastra = new Mastra({\n   *   gateways: {\n   *     myGateway: new CustomGateway()\n   *   }\n   * });\n   *\n   * const gateway = mastra.getGatewayById('custom-gateway-v1');\n   * ```\n   */\n  public getGatewayById(id: string): MastraModelGateway {\n    const gateways = this.#gateways ?? {};\n    for (const gateway of Object.values(gateways)) {\n      if (gateway.getId() === id) {\n        return gateway;\n      }\n    }\n\n    const error = new MastraError({\n      id: 'MASTRA_GET_GATEWAY_BY_ID_NOT_FOUND',\n      domain: ErrorDomain.MASTRA,\n      category: ErrorCategory.USER,\n      text: `Gateway with ID ${id} not found`,\n      details: {\n        status: 404,\n        gatewayId: id,\n        availableIds: Object.values(gateways)\n          .map(g => g.getId())\n          .join(', '),\n      },\n    });\n    this.#logger?.trackException(error);\n    throw error;\n  }\n\n  /**\n   * Returns all registered gateways as a record keyed by their names.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   gateways: {\n   *     netlify: new NetlifyGateway(),\n   *     custom: new CustomGateway()\n   *   }\n   * });\n   *\n   * const allGateways = mastra.listGateways();\n   * console.log(Object.keys(allGateways)); // ['netlify', 'custom']\n   * ```\n   */\n  public listGateways(): Record<string, MastraModelGateway> | undefined {\n    return this.#gateways;\n  }\n\n  /**\n   * Adds a new gateway to the Mastra instance.\n   *\n   * This method allows dynamic registration of gateways after the Mastra instance\n   * has been created. Gateways enable access to LLM providers through custom\n   * authentication and routing logic.\n   *\n   * If no key is provided, the gateway's ID (or name if no ID is set) will be used as the key.\n   *\n   * @example\n   * ```typescript\n   * import { MastraModelGateway } from '@mastra/core';\n   *\n   * class CustomGateway extends MastraModelGateway {\n   *   readonly id = 'custom-gateway-v1';  // Optional, defaults to name\n   *   readonly name = 'custom';\n   *   readonly prefix = 'custom';\n   *\n   *   async fetchProviders() {\n   *     return {\n   *       myProvider: {\n   *         name: 'My Provider',\n   *         models: ['model-1', 'model-2'],\n   *         apiKeyEnvVar: 'MY_API_KEY',\n   *         gateway: 'custom'\n   *       }\n   *     };\n   *   }\n   *\n   *   buildUrl(modelId: string) {\n   *     return 'https://api.myprovider.com/v1';\n   *   }\n   *\n   *   async getApiKey(modelId: string) {\n   *     return process.env.MY_API_KEY || '';\n   *   }\n   *\n   *   async resolveLanguageModel({ modelId, providerId, apiKey }) {\n   *     const baseURL = this.buildUrl(`${providerId}/${modelId}`);\n   *     return createOpenAICompatible({\n   *       name: providerId,\n   *       apiKey,\n   *       baseURL,\n   *       supportsStructuredOutputs: true,\n   *     }).chatModel(modelId);\n   *   }\n   * }\n   *\n   * const mastra = new Mastra();\n   * const newGateway = new CustomGateway();\n   * mastra.addGateway(newGateway); // Uses gateway.getId() as key (gateway.id)\n   * // or\n   * mastra.addGateway(newGateway, 'customKey'); // Uses custom key\n   * ```\n   */\n  public addGateway(gateway: MastraModelGateway, key?: string): void {\n    if (!gateway) {\n      throw createUndefinedPrimitiveError('gateway', gateway, key);\n    }\n    const gatewayKey = key || gateway.getId();\n    const gateways = this.#gateways as Record<string, MastraModelGateway>;\n    if (gateways[gatewayKey]) {\n      return;\n    }\n\n    gateways[gatewayKey] = gateway;\n\n    // Register custom gateways with the registry for type generation\n    this.#syncGatewayRegistry();\n  }\n\n  /**\n   * Sync custom gateways with the GatewayRegistry for type generation\n   * @private\n   */\n  #syncGatewayRegistry(): void {\n    try {\n      // Only sync in dev mode (when MASTRA_DEV is set)\n      if (process.env.MASTRA_DEV !== 'true' && process.env.MASTRA_DEV !== '1') {\n        return;\n      }\n\n      // Trigger sync immediately (non-blocking, but logs progress)\n      import('../llm/model/provider-registry.js')\n        .then(async ({ GatewayRegistry }) => {\n          const registry = GatewayRegistry.getInstance();\n          const customGateways = Object.values(this.#gateways || {});\n          registry.registerCustomGateways(customGateways);\n\n          // Log that we're syncing\n          const logger = this.getLogger();\n          logger.info('🔄 Syncing custom gateway types...');\n\n          // Trigger a sync to regenerate types\n          await registry.syncGateways(true);\n\n          logger.info('✅ Custom gateway types synced! Restart your TypeScript server to see autocomplete.');\n        })\n        .catch(err => {\n          const logger = this.getLogger();\n          logger.debug('Gateway registry sync skipped:', err);\n        });\n    } catch (err) {\n      // Silent fail - this is a dev-only feature\n      const logger = this.getLogger();\n      logger.debug('Gateway registry sync failed:', err);\n    }\n  }\n\n  /**\n   * Gracefully shuts down the Mastra instance and cleans up all resources.\n   *\n   * This method performs a clean shutdown of all Mastra components, including:\n   * - tracing registry and all tracing instances\n   * - Event engine and pub/sub system\n   * - All registered components and their resources\n   *\n   * It's important to call this method when your application is shutting down\n   * to ensure proper cleanup and prevent resource leaks.\n   *\n   * @example\n   * ```typescript\n   * const mastra = new Mastra({\n   *   agents: { myAgent },\n   *   workflows: { myWorkflow }\n   * });\n   *\n   * // Graceful shutdown on SIGINT\n   * process.on('SIGINT', async () => {\n   *   await mastra.shutdown();\n   *   process.exit(0);\n   * });\n   * ```\n   */\n  async shutdown(): Promise<void> {\n    // SchedulerWorker is stopped as part of stopWorkers().\n    await this.stopWorkers();\n    // Shutdown observability registry, exporters, etc...\n    await this.#observability.shutdown();\n\n    this.#logger?.info('Mastra shutdown completed');\n  }\n\n  // This method is only used internally for server hnadlers that require temporary persistence\n  public get serverCache() {\n    return this.#serverCache;\n  }\n}\n"]}