{"version":3,"sources":["../src/mastra/index.ts"],"names":["MastraError","DatasetsManager","randomUUID","NoOpObservability","initContextStorage","InMemoryServerCache","EventEmitterPubSub","WorkflowEventProcessor","noopLogger","LogLevel","ConsoleLogger","augmentWithInit","DualLogger","defaultGateways","registerHook","createOnScorerHook","isToolLoopAgentLike","toolLoopAgentToMastraAgent","noOpLoggerContext","noOpMetricsContext"],"mappings":";;;;;;;;;;;;;;;;;;AAqDA,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;AAkOO,IAAM,SAAN,MAcL;AAAA,EACA,QAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EACA,cAAA;AAAA,EACA,IAAA;AAAA,EACA,SAAA;AAAA,EACA,oBAGK,EAAC;AAAA,EAEN,QAAA;AAAA,EACA,QAAA;AAAA,EACA,MAAA;AAAA,EACA,WAAA;AAAA,EACA,wBAAA,uBACM,GAAA,EAAI;AAAA,EACV,OAAA;AAAA,EACA,UAAA;AAAA,EACA,cAAmD,EAAC;AAAA,EACpD,O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AAS,KAAK,SAAA,EAAU;AAC9B,QAAA,MAAA,CAAO,KAAA,CAAM,kCAAkC,GAAG,CAAA;AAAA,MACpD,CAAC,CAAA;AAAA,IACL,SAAS,GAAA,EAAK;AAEZ,MAAA,MAAM,MAAA,GAAS,KAAK,SAAA,EAAU;AAC9B,MAAA,MAAA,CAAO,KAAA,CAAM,iCAAiC,GAAG,CAAA;AAAA,IACnD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2BA,MAAM,QAAA,GAA0B;AAC9B,IAAA,MAAM,KAAK,eAAA,EAAgB;AAE3B,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-VJVGGWEJ.cjs","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../agent';\nimport type { BundlerConfig } from '../bundler/types';\nimport { InMemoryServerCache } from '../cache';\nimport type { MastraServerCache } from '../cache';\nimport type { AgentChannels } from '../channels/agent-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 } 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 { Middleware, ServerConfig } from '../server/types';\nimport type { MastraCompositeStore, WorkflowRuns } from '../storage';\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 } from '../tools';\nimport type { MastraTTS } from '../tts';\nimport type { MastraIdGenerator, IdGeneratorContext } from '../types';\nimport type { MastraVector } from '../vector';\nimport type { AnyWorkflow, Workflow } from '../workflows';\nimport { WorkflowEventProcessor } from '../workflows/evented/workflow-event-processor';\nimport type { AnyWorkspace, RegisteredWorkspace, Workspace } from '../workspace';\nimport { createOnScorerHook } from './hooks';\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 * 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> {\n  /**\n   * Agents are autonomous systems that can make decisions and take actions.\n   * Accepts both Mastra Agent instances and AI SDK v6 ToolLoopAgent instances.\n   * ToolLoopAgent instances are automatically converted to Mastra Agents.\n   */\n  agents?: { [K in keyof TAgents]: TAgents[K] | ToolLoopAgentLike };\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, DefaultExporter, CloudExporter, SensitiveDataFilter } from '@mastra/observability';\n   *\n   * new Mastra({\n   *   observability: new Observability({\n   *     configs: {\n   *       default: {\n   *         serviceName: 'mastra',\n   *         exporters: [new DefaultExporter(), new CloudExporter()],\n   *         spanOutputProcessors: [new SensitiveDataFilter()],\n   *       },\n   *     },\n   *   })\n   * })\n   * ```\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   * 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/**\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> {\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  #gateways?: Record<string, MastraModelGateway>;\n\n  #events: {\n    [topic: string]: ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n  } = {};\n  #internalMastraWorkflows: Record<string, Workflow> = {};\n  // This is only used internally for server handlers that require temporary persistence\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\n  get pubsub() {\n    return this.#pubsub;\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 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 CloudExporter)\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 DefaultExporter()] } },\n   *   }),\n   * });\n   * ```\n   */\n  constructor(\n    config?: Config<TAgents, TWorkflows, TVectors, TTTS, TLogger, TMCPServers, TScorers, TTools, TProcessors, TMemory>,\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    // This is only used internally for server handlers that require temporary persistence\n    this.#serverCache = 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    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    const workflowEventProcessor = new WorkflowEventProcessor({ mastra: this });\n    const workflowEventCb = async (event: Event, cb?: () => Promise<void>): Promise<void> => {\n      try {\n        await workflowEventProcessor.process(event, cb);\n      } catch (e) {\n        this.getLogger()?.error('Error processing event', e);\n      }\n    };\n    if (this.#events.workflows) {\n      this.#events.workflows.push(workflowEventCb);\n    } else {\n      this.#events.workflows = [workflowEventCb];\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, DefaultExporter } from \"@mastra/observability\"; ' +\n            'then pass: observability: new Observability({ configs: { default: { serviceName: \"mastra\", exporters: [new DefaultExporter()] } } }). ' +\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    // 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    // 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\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) {\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  private async resolveVersionedAgent<TAgent extends Agent>(\n    agent: TAgent,\n    version: { versionId: string } | { 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   */\n  public addAgent<A extends Agent | ToolLoopAgentLike>(\n    agent: A,\n    key?: string,\n    options?: { source?: DefinitionSource },\n  ): void {\n    if (!agent) {\n      throw createUndefinedPrimitiveError('agent', agent, key);\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;\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    // Register webhook routes and initialize channels\n    const agentChannels = mastraAgent.getChannels();\n    if (agentChannels) {\n      agentChannels.__setLogger(this.#logger);\n      const channelRoutes = agentChannels.getWebhookRoutes();\n      if (channelRoutes.length > 0) {\n        this.#server = {\n          ...this.#server,\n          apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n        };\n      }\n      void agentChannels.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   * @throws {MastraError} When a scorer with the same key already exists\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\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    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    // 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\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  }\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  public async startEventEngine() {\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        await this.#pubsub.subscribe(topic, listener);\n      }\n    }\n  }\n\n  public async stopEventEngine() {\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        await this.#pubsub.unsubscribe(topic, listener);\n      }\n    }\n\n    await this.#pubsub.flush();\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    await this.stopEventEngine();\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"]}