@mastra/core 1.55.0-alpha.2 → 1.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +86 -0
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/durable/index.cjs +1 -1
- package/dist/agent/durable/index.js +1 -1
- package/dist/agent/index.cjs +2 -2
- package/dist/agent/index.js +2 -2
- package/dist/{agent-BvRfRKIt.js → agent-0y2cApTZ.js} +57 -82
- package/dist/agent-0y2cApTZ.js.map +1 -0
- package/dist/agent-builder/ee/index.cjs +1 -1
- package/dist/agent-builder/ee/index.js +1 -1
- package/dist/agent-controller/index.cjs +1 -1
- package/dist/agent-controller/index.js +1 -1
- package/dist/{agent-controller-CM6tQSMj.js → agent-controller-ByW51eCC.js} +5 -5
- package/dist/{agent-controller-CM6tQSMj.js.map → agent-controller-ByW51eCC.js.map} +1 -1
- package/dist/{agent-controller-C75dc544.cjs → agent-controller-DahKlMET.cjs} +5 -5
- package/dist/{agent-controller-C75dc544.cjs.map → agent-controller-DahKlMET.cjs.map} +1 -1
- package/dist/{agent-CwUYflGG.cjs → agent-um2LJs-0.cjs} +57 -82
- package/dist/agent-um2LJs-0.cjs.map +1 -0
- package/dist/background-tasks/index.cjs +1 -1
- package/dist/background-tasks/index.js +1 -1
- package/dist/{background-tasks-AKlv5tIo.js → background-tasks-CM94BIj8.js} +2 -2
- package/dist/{background-tasks-AKlv5tIo.js.map → background-tasks-CM94BIj8.js.map} +1 -1
- package/dist/{background-tasks-Chpan7PB.cjs → background-tasks-CobPW4Z3.cjs} +2 -2
- package/dist/{background-tasks-Chpan7PB.cjs.map → background-tasks-CobPW4Z3.cjs.map} +1 -1
- package/dist/browser/index.cjs +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/channels/index.cjs +2 -2
- package/dist/channels/index.js +2 -2
- package/dist/{channels-BW52ccH_.cjs → channels-BgbloDjB.cjs} +2 -2
- package/dist/{channels-BW52ccH_.cjs.map → channels-BgbloDjB.cjs.map} +1 -1
- package/dist/{channels-Da9lEAi1.js → channels-MegO_4KL.js} +2 -2
- package/dist/{channels-Da9lEAi1.js.map → channels-MegO_4KL.js.map} +1 -1
- package/dist/coding-agent/index.cjs +1 -1
- package/dist/coding-agent/index.js +1 -1
- package/dist/{create-durable-agent-DmTTvoGi.cjs → create-durable-agent-ChmjQwzE.cjs} +8 -8
- package/dist/{create-durable-agent-DmTTvoGi.cjs.map → create-durable-agent-ChmjQwzE.cjs.map} +1 -1
- package/dist/{create-durable-agent-Bd4Bm5FV.js → create-durable-agent-DH_dWTMR.js} +8 -8
- package/dist/{create-durable-agent-Bd4Bm5FV.js.map → create-durable-agent-DH_dWTMR.js.map} +1 -1
- package/dist/datasets/index.cjs +1 -1
- package/dist/datasets/index.js +1 -1
- package/dist/{dist-C077BlAN.js → dist-BZBxELZo.js} +2 -2
- package/dist/{dist-C077BlAN.js.map → dist-BZBxELZo.js.map} +1 -1
- package/dist/{dist-CsR_D1uk.cjs → dist-ftJxyNRx.cjs} +2 -2
- package/dist/{dist-CsR_D1uk.cjs.map → dist-ftJxyNRx.cjs.map} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/evals/index.cjs +1 -1
- package/dist/evals/index.js +1 -1
- package/dist/evals/scoreTraces/index.cjs +1 -1
- package/dist/evals/scoreTraces/index.js +1 -1
- package/dist/harness/index.cjs +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/llm/index.cjs +5 -5
- package/dist/llm/index.js +5 -5
- package/dist/{llm-DlVyw1cX.js → llm-DGuYy_Nx.js} +5 -5
- package/dist/{llm-DlVyw1cX.js.map → llm-DGuYy_Nx.js.map} +1 -1
- package/dist/{llm-Bjt2hZ3f.cjs → llm-DmAhSSgh.cjs} +5 -5
- package/dist/{llm-Bjt2hZ3f.cjs.map → llm-DmAhSSgh.cjs.map} +1 -1
- package/dist/loop/index.cjs +1 -1
- package/dist/loop/index.js +1 -1
- package/dist/{manager-CYGpXJfK.js → manager-DDRcONBK.js} +3 -3
- package/dist/{manager-CYGpXJfK.js.map → manager-DDRcONBK.js.map} +1 -1
- package/dist/{manager-BjrFnt_A.cjs → manager-DqHiikx1.cjs} +3 -3
- package/dist/{manager-BjrFnt_A.cjs.map → manager-DqHiikx1.cjs.map} +1 -1
- package/dist/mastra/index.cjs +1 -1
- package/dist/mastra/index.js +1 -1
- package/dist/{mastra-CVLF1dWt.js → mastra-B6CffFOC.js} +9 -9
- package/dist/{mastra-CVLF1dWt.js.map → mastra-B6CffFOC.js.map} +1 -1
- package/dist/{mastra-Bxx9WPf6.cjs → mastra-BlT9srQJ.cjs} +9 -9
- package/dist/{mastra-Bxx9WPf6.cjs.map → mastra-BlT9srQJ.cjs.map} +1 -1
- package/dist/memory/index.cjs +1 -1
- package/dist/memory/index.js +1 -1
- package/dist/{model-CA0WLISt.js → model-DQzxkQqM.js} +2 -2
- package/dist/{model-CA0WLISt.js.map → model-DQzxkQqM.js.map} +1 -1
- package/dist/{model-DMVq6nAS.cjs → model-Iow-mV9i.cjs} +2 -2
- package/dist/{model-DMVq6nAS.cjs.map → model-Iow-mV9i.cjs.map} +1 -1
- package/dist/{models-dev-Cbus1Uh2.js → models-dev-BFOUCgyS.js} +2 -2
- package/dist/{models-dev-Cbus1Uh2.js.map → models-dev-BFOUCgyS.js.map} +1 -1
- package/dist/{models-dev-D_X4VMSu.cjs → models-dev-BUEaCBxL.cjs} +2 -2
- package/dist/{models-dev-D_X4VMSu.cjs.map → models-dev-BUEaCBxL.cjs.map} +1 -1
- package/dist/{netlify-C-nnPVSj.js → netlify-7eHXUkln.js} +2 -2
- package/dist/{netlify-C-nnPVSj.js.map → netlify-7eHXUkln.js.map} +1 -1
- package/dist/{netlify-CUuCnmtd.cjs → netlify-Db5icdAJ.cjs} +2 -2
- package/dist/{netlify-CUuCnmtd.cjs.map → netlify-Db5icdAJ.cjs.map} +1 -1
- package/dist/processor-provider/index.cjs +1 -1
- package/dist/processor-provider/index.js +1 -1
- package/dist/processors/index.cjs +2 -2
- package/dist/processors/index.js +2 -2
- package/dist/processors/processors/index.d.ts +1 -1
- package/dist/processors/processors/index.d.ts.map +1 -1
- package/dist/processors/tool-result-reminder.d.ts +23 -0
- package/dist/processors/tool-result-reminder.d.ts.map +1 -1
- package/dist/{provider-registry-BFknh6Fu.cjs → provider-registry-DRJihW5_.cjs} +6 -6
- package/dist/{provider-registry-BFknh6Fu.cjs.map → provider-registry-DRJihW5_.cjs.map} +1 -1
- package/dist/{provider-registry-DIbls44Z.js → provider-registry-DzSSAz1R.js} +6 -6
- package/dist/{provider-registry-DIbls44Z.js.map → provider-registry-DzSSAz1R.js.map} +1 -1
- package/dist/relevance/index.cjs +2 -2
- package/dist/relevance/index.js +2 -2
- package/dist/stream/index.cjs +3 -3
- package/dist/stream/index.js +3 -3
- package/dist/{stream-tlVjYkAO.cjs → stream-D-cHV05r.cjs} +3 -3
- package/dist/{stream-tlVjYkAO.cjs.map → stream-D-cHV05r.cjs.map} +1 -1
- package/dist/{stream-Cd_isEZJ.js → stream-DJaosaeO.js} +3 -3
- package/dist/{stream-Cd_isEZJ.js.map → stream-DJaosaeO.js.map} +1 -1
- package/dist/test-utils/llm-mock.cjs +1 -1
- package/dist/test-utils/llm-mock.js +1 -1
- package/dist/tool-loop-agent/index.cjs +1 -1
- package/dist/tool-loop-agent/index.js +1 -1
- package/dist/{tool-loop-agent-th9L-ls9.cjs → tool-loop-agent-ByrutV2Q.cjs} +4 -4
- package/dist/{tool-loop-agent-th9L-ls9.cjs.map → tool-loop-agent-ByrutV2Q.cjs.map} +1 -1
- package/dist/{tool-loop-agent-CcT-TTcT.js → tool-loop-agent-BzHXZDL3.js} +4 -4
- package/dist/{tool-loop-agent-CcT-TTcT.js.map → tool-loop-agent-BzHXZDL3.js.map} +1 -1
- package/dist/{trip-wire-Cj0cJivR.js → trip-wire-DxpTS3jV.js} +2 -2
- package/dist/{trip-wire-Cj0cJivR.js.map → trip-wire-DxpTS3jV.js.map} +1 -1
- package/dist/{trip-wire-BNzxirr0.cjs → trip-wire-utCESgMt.cjs} +2 -2
- package/dist/{trip-wire-BNzxirr0.cjs.map → trip-wire-utCESgMt.cjs.map} +1 -1
- package/dist/{utils-BoQofieM.cjs → utils-CPUQn5dX.cjs} +2 -2
- package/dist/{utils-BoQofieM.cjs.map → utils-CPUQn5dX.cjs.map} +1 -1
- package/dist/{utils-DUfAZ4gr.js → utils-CrKEOVUo.js} +2 -2
- package/dist/{utils-DUfAZ4gr.js.map → utils-CrKEOVUo.js.map} +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.js +1 -1
- package/dist/worker/index.cjs +1 -1
- package/dist/worker/index.js +1 -1
- package/dist/{worker-DwlyX5l8.js → worker-Ciya6mfo.js} +3 -3
- package/dist/{worker-DwlyX5l8.js.map → worker-Ciya6mfo.js.map} +1 -1
- package/dist/{worker-CsbZPhWb.cjs → worker-YT_pMttZ.cjs} +3 -3
- package/dist/{worker-CsbZPhWb.cjs.map → worker-YT_pMttZ.cjs.map} +1 -1
- package/dist/{workflow-BR5D6ij_.cjs → workflow-DcS_0R0Z.cjs} +3 -3
- package/dist/{workflow-BR5D6ij_.cjs.map → workflow-DcS_0R0Z.cjs.map} +1 -1
- package/dist/{workflow-OjZRiiCG.js → workflow-k6s0ESOR.js} +3 -3
- package/dist/{workflow-OjZRiiCG.js.map → workflow-k6s0ESOR.js.map} +1 -1
- package/dist/workflows/evented/index.cjs +1 -1
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/index.cjs +1 -1
- package/dist/workflows/index.js +1 -1
- package/package.json +12 -12
- package/dist/agent-BvRfRKIt.js.map +0 -1
- package/dist/agent-CwUYflGG.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mastra-CVLF1dWt.js","names":["#pubsubProxy","#pubsub","#workers","#backgroundTaskManager","#findSchedulerWorker","#datasets","#idGenerator","#editor","#channels","#schedules","#schedulesConfig","#versions","#environment","#toolPayloadTransform","#storedAgentsCache","#storedScorersCache","#logger","#server","#studio","#observability","#serverCache","#recoveryConfig","#events","#workerFilter","#workersDisabled","#loggerExplicit","#storageExplicit","#observabilityExplicit","#storage","#backgroundTaskConfig","#ensureBackgroundTaskManager","#schedulerConfig","#notificationDispatchConfig","#vectors","#mcpServers","#tts","#agents","#scorers","#tools","#processors","#memory","#workflows","#gateways","#workspace","#hiddenWorkflowKeys","#serverExplicit","#studioExplicit","#harnesses","#onScorerHook","#registerToolWithBackgroundManager","#hasScheduledWorkflow","#schedulerRequested","#collectDeclarativeSchedules","#deployer","#workspaces","#internalMastraWorkflows","#runScopedWorkflowTimestamps","#runScopeRefcounts","#runScopes","#sweepStaleRunScopedWorkflows","#releaseRunScope","#ownsWorkflow","#runTracingContexts","#promptBlocks","#processorConfigurations","#workersStarted","#ensureSchedulingWorkersStarted","#notificationDispatchReady","#schedulingWorkersStartPromise","#startSchedulingWorkers","#shouldEnableScheduler","#findAgentScheduleWorker","#detectExistingAgentSchedules","#detectExistingNotificationDispatch","#serverAdapter","#serverMiddleware","#bundler","#workflowEventProcessor","#wirePushWorkflowSubscription","#userEventSubscriptions","#pushSubscription","#executionWorkersStarted","#executionWorkersStartPromise","#startExecutionWorkers","#syncGatewayRegistry"],"sources":["../src/notifications/workflow.ts","../src/mastra/index.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport type { Schedule } from '../storage/domains/schedules/base';\nimport { createStep, createWorkflow } from '../workflows/evented';\nimport { computeNextFireAt } from '../workflows/scheduler';\nimport { dispatchDueNotifications } from './dispatcher';\n\nexport const NOTIFICATION_DISPATCH_WORKFLOW_ID = '__mastra_notification_dispatcher';\n\n/**\n * Schedule row id for the lazily-created dispatcher schedule. Deliberately\n * NOT `wf_`-prefixed: `registerDeclarativeSchedules` orphan-cleanup deletes\n * `wf_`-prefixed rows that are no longer declared in code, and this row is\n * created imperatively (like heartbeat rows) on first deferred notification.\n */\nexport const NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID = '__mastra_notification_dispatch';\n\nexport const NOTIFICATION_DISPATCH_DEFAULT_CRON = '*/1 * * * *';\nexport const NOTIFICATION_DISPATCH_DEFAULT_BATCH_SIZE = 100;\n\nexport type NotificationDispatchConfig = {\n /** Defaults to true. Set false to opt out of automatic scheduled dispatch. */\n enabled?: boolean;\n cron?: string;\n batchSize?: number;\n};\n\nexport function parseNotificationDispatchNow(input?: string): Date {\n const now = input ? new Date(input) : new Date();\n if (Number.isNaN(now.getTime())) {\n throw new Error(`Invalid notification dispatch time: ${input}`);\n }\n return now;\n}\n\n/**\n * Builds the imperative schedule row that drives the notification dispatcher.\n * Created lazily by `Mastra.__ensureNotificationDispatchReady()` on the first\n * deferred notification, rather than declared on the workflow, so idle apps\n * never start the scheduler.\n */\nexport function buildNotificationDispatchSchedule({\n cron = NOTIFICATION_DISPATCH_DEFAULT_CRON,\n batchSize = NOTIFICATION_DISPATCH_DEFAULT_BATCH_SIZE,\n}: Omit<NotificationDispatchConfig, 'enabled'> = {}): Schedule {\n const now = Date.now();\n return {\n id: NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID,\n target: {\n type: 'workflow',\n workflowId: NOTIFICATION_DISPATCH_WORKFLOW_ID,\n inputData: { limit: batchSize },\n },\n cron,\n status: 'active',\n nextFireAt: computeNextFireAt(cron, { after: now }),\n createdAt: now,\n updatedAt: now,\n metadata: { internal: true, feature: 'notifications' },\n };\n}\n\nexport function createNotificationDispatchWorkflow({\n batchSize = NOTIFICATION_DISPATCH_DEFAULT_BATCH_SIZE,\n}: Omit<NotificationDispatchConfig, 'enabled' | 'cron'> = {}) {\n const dispatchStep = createStep({\n id: 'dispatch-due-notifications',\n inputSchema: z.object({\n now: z.string().optional(),\n limit: z.number().optional(),\n }),\n outputSchema: z.object({\n delivered: z.number(),\n failed: z.number(),\n }),\n execute: async ({ inputData, mastra }) => {\n const storage = await mastra.getStorage()?.getStore('notifications');\n if (!storage) {\n return { delivered: 0, failed: 0 };\n }\n\n const now = parseNotificationDispatchNow(inputData.now);\n\n const result = await dispatchDueNotifications({\n mastra,\n storage,\n now,\n limit: inputData.limit ?? batchSize,\n });\n\n return { delivered: result.delivered.length, failed: result.failed.length };\n },\n });\n\n return createWorkflow({\n id: NOTIFICATION_DISPATCH_WORKFLOW_ID,\n inputSchema: z.object({\n now: z.string().optional(),\n limit: z.number().optional(),\n }),\n outputSchema: z.object({\n delivered: z.number(),\n failed: z.number(),\n }),\n })\n .then(dispatchStep)\n .commit();\n}\n","import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../agent';\nimport { createDurableAgent } from '../agent/durable/create-durable-agent';\nimport { agentThreadStreamRuntime } from '../agent/thread-stream-runtime';\nimport type { DurableAgentLike } from '../agent/types';\nimport { isDurableAgentLike } from '../agent/types';\nimport type { AgentController } from '../agent-controller';\nimport { BackgroundTaskManager } from '../background-tasks';\nimport type { BackgroundTaskManagerConfig } from '../background-tasks/types';\nimport type { BundlerConfig } from '../bundler/types';\nimport { InMemoryServerCache } from '../cache';\nimport type { MastraServerCache } from '../cache';\nimport { AgentChannels } from '../channels';\nimport type { ChannelProvider } from '../channels';\nimport { DatasetsManager } from '../datasets/manager.js';\nimport type { MastraDeployer } from '../deployer';\nimport type { IMastraEditor } from '../editor';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../error';\nimport type { MastraScorer } from '../evals';\nimport { EventEmitterPubSub } from '../events/event-emitter';\nimport type { PubSub } from '../events/pubsub';\nimport type { Event, EventCallback } from '../events/types';\nimport type { Harness } from '../harness';\nimport { AvailableHooks, deregisterHook, registerHook } from '../hooks';\nimport { LicenseClient } from '../license';\nimport type { MastraModelGatewayInterface } from '../llm/model/gateways';\nimport { getGatewayId } from '../llm/model/gateways';\nimport { defaultGateways } from '../llm/model/gateways/defaults';\nimport { LogLevel, noopLogger, ConsoleLogger, DualLogger } from '../logger';\nimport type { IMastraLogger } from '../logger';\nimport type { MCPServerBase } from '../mcp';\nimport type { MastraMemory } from '../memory';\nimport type { NotificationDispatchConfig } from '../notifications/workflow';\nimport {\n buildNotificationDispatchSchedule,\n createNotificationDispatchWorkflow,\n NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID,\n} from '../notifications/workflow';\nimport type {\n DefinitionSource,\n ObservabilityEntrypoint,\n ObservabilityExporter,\n ObservabilityInstance,\n LoggerContext,\n MetricsContext,\n TracingContext,\n} from '../observability';\nimport { NoOpObservability, noOpLoggerContext, noOpMetricsContext } from '../observability';\nimport { initContextStorage } from '../observability/context-storage';\nimport type { Processor } from '../processors';\nimport { Schedules } from '../schedules/schedules';\nimport type { SchedulesConfig, ScheduleHooks } from '../schedules/types';\nimport type { MastraServerBase } from '../server/base';\nimport type { ApiRoute, Middleware, ServerConfig, StudioConfig } from '../server/types';\nimport type { MastraCompositeStore, WorkflowRuns } from '../storage';\nimport { InMemoryStore } from '../storage';\nimport { BackgroundTasksInMemory } from '../storage/domains/background-tasks/inmemory';\nimport { InMemoryDB } from '../storage/domains/inmemory-db';\nimport type { Schedule, ScheduleUpdate, SchedulesStorage } from '../storage/domains/schedules/base';\nimport { WorkflowsInMemory } from '../storage/domains/workflows/inmemory';\nimport { augmentWithInit } from '../storage/storageWithInit';\nimport type { StorageResolvedPromptBlockType } from '../storage/types';\nimport type { ToolLoopAgentLike } from '../tool-loop-agent';\nimport { isToolLoopAgentLike, toolLoopAgentToMastraAgent } from '../tool-loop-agent';\nimport type { ToolAction, ToolPayloadTransformPolicy } from '../tools';\nimport { normalizeToolPayloadTransformPolicy } from '../tools/payload-transform';\nimport type { MastraTTS } from '../tts';\nimport type { MastraIdGenerator, IdGeneratorContext } from '../types';\nimport type { MastraVector } from '../vector';\nimport { OrchestrationWorker, SchedulerWorker, BackgroundTaskWorker } from '../worker';\nimport type { MastraWorker, WorkerDeps } from '../worker';\nimport type { AnyWorkflow, Workflow } from '../workflows';\nimport { WorkflowEventProcessor } from '../workflows/evented/workflow-event-processor';\nimport { computeNextFireAt } from '../workflows/scheduler';\nimport type { WorkflowScheduleConfig, SchedulerConfig, Scheduler } from '../workflows/scheduler';\nimport type { AnyWorkspace, RegisteredWorkspace, Workspace } from '../workspace';\nimport { createOnScorerHook } from './hooks';\nimport { __registerMastraCtor } from './mastra-ctor-holder';\nimport type { RunScope } from './run-scope';\nimport { createRunScope } from './run-scope';\nimport type { VersionOverrides, VersionSelector } from './types';\n\n/**\n * Creates an error for when a null/undefined value is passed to an add* method.\n * This commonly occurs when config is spread ({ ...config }) and the original\n * object had getters or non-enumerable properties.\n */\nfunction createUndefinedPrimitiveError(\n type:\n | 'agent'\n | 'tool'\n | 'processor'\n | 'vector'\n | 'scorer'\n | 'workflow'\n | 'mcp-server'\n | 'gateway'\n | 'memory'\n | 'workspace',\n value: null | undefined,\n key?: string,\n): MastraError {\n const typeLabel = type === 'mcp-server' ? 'MCP server' : type;\n const errorId = `MASTRA_ADD_${type.toUpperCase().replace('-', '_')}_UNDEFINED` as Uppercase<string>;\n return new MastraError({\n id: errorId,\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Cannot add ${typeLabel}: ${typeLabel} is ${value === null ? 'null' : 'undefined'}. This may occur if config was spread ({ ...config }) and the original object had getters or non-enumerable properties.`,\n details: { status: 400, ...(key && { key }) },\n });\n}\n\n/**\n * Stable JSON-shape comparison for two `Schedule.target` values. Uses\n * JSON.stringify because targets are plain JSON-serializable objects (the\n * storage layer round-trips them through the same encoding). Covers the\n * `inputData` / `initialState` / `requestContext` payload fields that we\n * want to detect changes on across redeploys.\n */\nfunction targetsEqual(a: Schedule['target'] | undefined, b: Schedule['target']): boolean {\n if (a === b) return true;\n if (!a) return false;\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Reads the declarative schedule configs off a workflow. Supports both the\n * new `getScheduleConfigs(): WorkflowScheduleConfig[]` accessor on the evented\n * engine and a legacy `getScheduleConfig(): WorkflowScheduleConfig | undefined`\n * fallback used in tests that inject a fake getter.\n */\nfunction collectWorkflowScheduleConfigs(workflow: unknown): WorkflowScheduleConfig[] {\n const w = workflow as {\n getScheduleConfigs?: () => WorkflowScheduleConfig[] | undefined;\n getScheduleConfig?: () => WorkflowScheduleConfig | WorkflowScheduleConfig[] | undefined;\n };\n if (typeof w.getScheduleConfigs === 'function') {\n return w.getScheduleConfigs() ?? [];\n }\n if (typeof w.getScheduleConfig === 'function') {\n const cfg = w.getScheduleConfig();\n if (!cfg) return [];\n return Array.isArray(cfg) ? cfg : [cfg];\n }\n return [];\n}\n\n/**\n * Builds the storage row id for a declarative schedule. Workflow and schedule\n * ids are URL-encoded so delimiters in user-supplied ids cannot collide\n * across workflows (e.g. `foo__bar` single vs `foo` array-entry `bar`).\n */\nfunction declarativeScheduleRowId(workflowId: string, scheduleId?: string): string {\n const encodedWorkflow = encodeURIComponent(workflowId);\n if (scheduleId === undefined) return `wf_${encodedWorkflow}`;\n return `wf_${encodedWorkflow}__${encodeURIComponent(scheduleId)}`;\n}\n\n/**\n * Determines whether a stored schedule row id belongs to one of the registered\n * workflows. Returns the owning workflow id when the row id either equals\n * `wf_<encoded(workflowId)>` (single-schedule form) or starts with\n * `wf_<encoded(workflowId)>__` (array form). Returns undefined when no\n * registered workflow owns the row.\n */\nfunction ownerWorkflowIdForRow(rowId: string, byWorkflow: Map<string, Set<string>>): string | undefined {\n for (const workflowId of byWorkflow.keys()) {\n const prefix = `wf_${encodeURIComponent(workflowId)}`;\n if (rowId === prefix || rowId.startsWith(`${prefix}__`)) {\n return workflowId;\n }\n }\n return undefined;\n}\n\n/**\n * Decodes the owning workflow id directly from a `wf_<encoded>` /\n * `wf_<encoded>__<...>` row id without needing the workflow to be in the\n * current registry. Used to identify rows whose workflow has been deleted\n * from code so we can clean them up on startup.\n */\nfunction ownerWorkflowIdFromRowId(rowId: string): string | undefined {\n if (!rowId.startsWith('wf_')) return undefined;\n const rest = rowId.slice('wf_'.length);\n const sep = rest.indexOf('__');\n const encoded = sep === -1 ? rest : rest.slice(0, sep);\n if (!encoded) return undefined;\n try {\n return decodeURIComponent(encoded);\n } catch {\n return undefined;\n }\n}\n\n/** See {@link targetsEqual}. Same approach for free-form metadata. */\nfunction metadataEqual(a: Record<string, unknown> | null | undefined, b: Record<string, unknown> | undefined): boolean {\n const aNorm = a ?? undefined;\n const bNorm = b ?? undefined;\n if (aNorm === bNorm) return true;\n if (!aNorm || !bNorm) return false;\n return JSON.stringify(aNorm) === JSON.stringify(bNorm);\n}\n\n/**\n * Configuration interface for initializing a Mastra instance.\n *\n * The Config interface defines all the optional components that can be registered\n * with a Mastra instance, including agents, workflows, storage, logging, and more.\n *\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of workflow instances\n * @template TVectors - Record of vector store instances\n * @template TTTS - Record of text-to-speech instances\n * @template TLogger - Logger implementation type\n * @template TVNextNetworks - Record of agent network instances\n * @template TMCPServers - Record of MCP server instances\n * @template TScorers - Record of scorer instances\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'Weather Agent',\n * instructions: 'You help with weather information',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport interface Config<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n string,\n ToolAction<any, any, any, any, any, any>\n >,\n TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>,\n TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>,\n> {\n /**\n * Agents are autonomous systems that can make decisions and take actions.\n * Accepts Mastra Agent instances, AI SDK v6 ToolLoopAgent instances,\n * and durable agent wrappers (e.g., InngestAgent from createInngestAgent).\n * ToolLoopAgent and durable agents are automatically handled during registration.\n */\n agents?: { [K in keyof TAgents]: TAgents[K] | ToolLoopAgentLike | DurableAgentLike };\n\n /**\n * Storage provider for persisting data, conversation history, and workflow state.\n * Required for agent memory and workflow persistence.\n */\n storage?: MastraCompositeStore;\n\n /**\n * Vector stores for semantic search and retrieval-augmented generation (RAG).\n * Used for storing and querying embeddings.\n */\n vectors?: TVectors;\n\n /**\n * Logger implementation for application logging and debugging.\n * Set to `false` to disable logging entirely.\n * @default `INFO` level in development, `WARN` in production.\n */\n logger?: TLogger | false;\n\n /**\n * Workflows provide type-safe, composable task execution with built-in error handling.\n */\n workflows?: TWorkflows;\n\n /**\n * AgentControllers to host on this Mastra instance, keyed by id. Each\n * registered AgentController uses this Mastra (its storage, agents, gateways,\n * and observability) instead of building its own internal one, and is\n * reachable via {@link Mastra.getAgentController} /\n * {@link Mastra.listAgentControllers}. This is how a server exposes multiple\n * AgentControllers' sessions over HTTP.\n */\n agentControllers?: Record<string, AgentController<any>>;\n\n /**\n * Harnesses to host on this Mastra instance, keyed by id.\n *\n * @deprecated Use {@link MastraConfig.agentControllers} instead. `harnesses`\n * is retained as a backwards-compatible alias and will be removed in a future\n * major. Entries from both keys are merged, with `agentControllers` taking\n * precedence on key collisions.\n */\n harnesses?: Record<string, Harness<any>>;\n\n /**\n * Text-to-speech providers for voice synthesis capabilities.\n */\n tts?: TTTS;\n\n /**\n * Observability entrypoint for tracking model interactions and tracing.\n * Pass an instance of the Observability class from @mastra/observability.\n *\n * @example\n * ```typescript\n * import { Observability, MastraStorageExporter, MastraPlatformExporter } from '@mastra/observability';\n *\n * new Mastra({\n * observability: new Observability({\n * configs: {\n * default: {\n * serviceName: 'mastra',\n * exporters: [new MastraStorageExporter(), new MastraPlatformExporter()],\n * },\n * },\n * })\n * })\n * ```\n *\n * `Observability` auto-applies a `SensitiveDataFilter` span output processor\n * to every configured instance. Set `sensitiveDataFilter: false` on the\n * registry config to opt out, or pass a `SensitiveDataFilterOptions` object\n * to customize it.\n */\n observability?: ObservabilityEntrypoint;\n\n /**\n * Custom ID generator function for creating unique identifiers.\n * Receives optional context about what type of ID is being generated\n * and where it's being requested from.\n * @default `crypto.randomUUID()`\n */\n idGenerator?: MastraIdGenerator;\n\n /**\n * Deployment provider for publishing applications to cloud platforms.\n */\n deployer?: MastraDeployer;\n\n /**\n * Server configuration for HTTP endpoints and middleware.\n */\n server?: ServerConfig;\n\n /**\n * Studio-specific authentication and authorization configuration.\n *\n * When configured, Studio uses separate auth from the server (API) auth,\n * allowing different providers for internal team members vs external customers.\n *\n * - `server.auth` handles API authentication (external customers)\n * - `studio.auth` handles Studio authentication (internal team)\n *\n * **Dual auth is opt-in:** If `studio.auth` is not configured, Studio requests\n * fall back to `server.auth` for backward compatibility. To enable strict\n * separation between Studio and API auth, configure both `studio.auth` and\n * `server.auth`.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * server: {\n * auth: new MastraAuthWorkos({ ... }), // External customers\n * },\n * studio: {\n * auth: new MastraAuthOkta({ ... }), // Internal team\n * rbac: new StaticRBACProvider({\n * roles: DEFAULT_ROLES,\n * getUserRoles: (user) => [user.role],\n * }),\n * },\n * });\n * ```\n */\n studio?: StudioConfig;\n\n /**\n * MCP servers provide tools and resources that agents can use.\n */\n mcpServers?: TMCPServers;\n\n /**\n * Bundler configuration for packaging and deployment.\n */\n bundler?: BundlerConfig;\n\n /**\n * Pub/sub system for event-driven communication between components.\n * @default EventEmitterPubSub\n */\n pubsub?: PubSub;\n\n /**\n * Server cache for storing stream events and other temporary data.\n * Used by durable agents for resumable streams - clients can disconnect\n * and reconnect without missing events.\n *\n * When provided, durable agents created without their own cache will\n * inherit this cache instance.\n *\n * @default InMemoryServerCache\n */\n cache?: MastraServerCache;\n\n /**\n * Scorers help assess the quality of agent responses and workflow outputs.\n */\n scorers?: TScorers;\n\n /**\n * Tools are reusable functions that agents can use to interact with external systems.\n */\n tools?: TTools;\n\n /**\n * Processors transform inputs and outputs for agents and workflows.\n */\n processors?: TProcessors;\n\n /**\n * Memory instances that can be referenced by stored agents.\n * Keys are used to look up memory instances when resolving stored agent configurations.\n */\n memory?: TMemory;\n\n /**\n * Global workspace for file storage, skills, and code execution.\n * Agents inherit this workspace unless they have their own configured.\n * Skills are accessed via workspace.skills when skills is configured.\n */\n workspace?: AnyWorkspace;\n\n /**\n * Custom model router gateways for accessing LLM providers.\n * Gateways handle provider-specific authentication, URL construction, and model resolution.\n */\n gateways?: Record<string, MastraModelGatewayInterface>;\n\n /**\n * Event handlers for custom application events.\n * Maps event topics to handler functions for event-driven architectures.\n */\n events?: {\n [topic: string]: (\n event: Event,\n cb?: () => Promise<void>,\n ) => Promise<void> | ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n };\n\n /**\n * Editor instance for handling agent instantiation and configuration.\n * The editor handles complex instantiation logic including memory resolution.\n */\n editor?: IMastraEditor;\n\n /**\n * Global version overrides for primitives.\n * When set, sub-agent delegation (and future primitive resolution) will\n * resolve the specified version instead of the code-defined default.\n *\n * @example\n * ```typescript\n * new Mastra({\n * versions: {\n * agents: {\n * 'researcher-agent': { versionId: '123' },\n * 'writer-agent': { status: 'published' },\n * },\n * },\n * });\n * ```\n */\n versions?: VersionOverrides;\n\n /**\n * Background task configuration for running tool calls asynchronously.\n * When configured, agents can dispatch tool executions to run in the background\n * while the conversation continues.\n */\n backgroundTasks?: BackgroundTaskManagerConfig;\n\n /**\n * Scheduler configuration for cron-driven workflow triggers.\n *\n * The scheduler is auto-enabled when any registered workflow declares a\n * `schedule` config or when `scheduler.enabled` is true. It requires a\n * storage adapter implementing the `schedules` domain (e.g. `@mastra/libsql`).\n */\n scheduler?: SchedulerConfig;\n\n /**\n * Notification runtime configuration. Notification dispatch is scheduled automatically by default.\n */\n notifications?: {\n dispatch?: NotificationDispatchConfig;\n };\n\n /**\n * Schedules runtime configuration. A single lifecycle-hook bundle runs for\n * every agent-schedule fire and is invoked by the agent-schedule worker\n * around schedule-driven agent runs; hooks branch per agent via the\n * `agentId` on each context. Configuring hooks here (rather than on the\n * Agent) lets both code-defined and stored agents share the same hook\n * surface, since stored agents cannot define functions in their serialized\n * config.\n */\n schedules?: SchedulesConfig<Mastra>;\n\n /**\n * Platform channels for messaging integrations (Slack, Discord, etc.).\n * Routes are automatically registered and agents can reference channel configs.\n *\n * @example\n * ```typescript\n * import { SlackProvider } from '@mastra/slack';\n *\n * new Mastra({\n * channels: {\n * slack: new SlackProvider({\n * configToken: process.env.SLACK_APP_CONFIG_TOKEN,\n * refreshToken: process.env.SLACK_APP_CONFIG_REFRESH_TOKEN,\n * }),\n * },\n * });\n * ```\n */\n channels?: TChannels;\n\n /**\n * Deployment environment name (e.g. `'production'`, `'staging'`, `'development'`).\n * When set, the value is automatically attached to all observability signals\n * so they can be filtered by environment without passing\n * `tracingOptions.metadata.environment` on every call.\n *\n * If unset, falls back to `process.env.NODE_ENV`. If neither is set the field\n * is left undefined rather than guessed.\n *\n * Per-call `tracingOptions.metadata.environment` always takes precedence.\n *\n * @example\n * ```typescript\n * new Mastra({\n * environment: 'production',\n * observability: new Observability({ ... }),\n * })\n * ```\n */\n environment?: string;\n /**\n * Optional central transform policy for tool payloads before they are\n * serialized into display streams or user-visible transcripts.\n */\n transform?: ToolPayloadTransformPolicy;\n /**\n * Configure which workers run in this Mastra instance.\n *\n * - `undefined` (default): Auto-creates default workers (existing behavior)\n * - `false`: Disables all event processing — useful when running standalone workers separately\n * - `MastraWorker[]`: Additional workers merged with the auto-created\n * defaults. A custom worker replaces a default with the same `name`;\n * duplicate names within the array throw. Use `false` to run no workers.\n */\n workers?: MastraWorker[] | false;\n\n /**\n * Boot-time recovery behavior for orphaned agent/workflow runs.\n *\n * `durableAgents` controls whether the deployer will automatically call\n * {@link Mastra.recoverAllDurableAgents} for every registered `DurableAgent`\n * when the server starts (right after `restartAllActiveWorkflowRuns`).\n *\n * - `'off'` (default): the deployer never auto-recovers durable agent runs.\n * Operators can still call `mastra.recoverAllDurableAgents()` or\n * `agent.recoverActiveRuns()` by hand.\n * - `'auto'`: the deployer will invoke `recoverAllDurableAgents()` on boot,\n * re-driving every RUNNING durable agent run discovered in storage.\n *\n * Opt-in only. Auto-recovery re-runs the agentic loop from the last persisted\n * snapshot, so it re-issues LLM calls (real cost) and re-executes tool calls\n * (must be idempotent). In multi-instance deploys every replica will race to\n * recover the same runs, since there is no lease/lock yet.\n *\n * @default { durableAgents: 'off' }\n */\n recovery?: MastraRecoveryConfig;\n\n /**\n * Marks this instance as an internally-owned ephemeral Mastra — e.g. the\n * fallback instance a standalone `Agent` lazily creates so its\n * prepare-stream workflow has a pubsub-equipped Mastra to run on.\n *\n * Ephemeral instances skip module-level scorer-hook registration: they have\n * no agent/scorer/editor registries for the hook to resolve against, so the\n * hook could never persist a score — but the module-level emitter would\n * retain the instance (and everything it references) for the lifetime of\n * the process, leaking one Mastra graph per discarded standalone Agent\n * (#19404).\n *\n * @internal Not part of the public API — do not set this on application\n * Mastra instances; it silently disables scorer persistence.\n */\n __ephemeral?: boolean;\n}\n\n/**\n * Boot-time recovery configuration. See {@link Mastra['recoveryConfig']}.\n */\nexport interface MastraRecoveryConfig {\n /**\n * Auto-recover orphaned RUNNING durable agent runs on server boot.\n * @default 'off'\n */\n durableAgents?: 'auto' | 'off';\n}\n\n/**\n * The central orchestrator for Mastra applications, managing agents, workflows, storage, logging, observability, and more.\n *\n * The `Mastra` class serves as the main entry point and registry for all components in a Mastra application.\n * It coordinates the interaction between agents, workflows, storage systems, and other services.\n\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of modern workflow instances\n * @template TVectors - Record of vector store instances for semantic search and RAG\n * @template TTTS - Record of text-to-speech provider instances\n * @template TLogger - Logger implementation type for application logging\n * @template TVNextNetworks - Record of next-generation agent network instances\n * @template TMCPServers - Record of Model Context Protocol server instances\n * @template TScorers - Record of evaluation scorer instances for measuring AI performance\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'Weather Agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5',\n * tools: [getWeatherTool]\n * })\n * },\n * workflows: { dataWorkflow },\n * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport class Mastra<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n string,\n ToolAction<any, any, any, any, any, any>\n >,\n TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>,\n TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>,\n> {\n #vectors?: TVectors;\n #agents: TAgents;\n #logger: TLogger;\n #loggerExplicit = false;\n #workflows: TWorkflows;\n #harnesses: Record<string, Harness<any>> = {};\n #hiddenWorkflowKeys = new Set<string>();\n #observability: ObservabilityEntrypoint;\n #observabilityExplicit = false;\n #onScorerHook?: ReturnType<typeof createOnScorerHook>;\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 #storageExplicit = false;\n #recoveryConfig: MastraRecoveryConfig = { durableAgents: 'off' };\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 #serverExplicit = false;\n #studio?: StudioConfig;\n #studioExplicit = false;\n #serverAdapter?: MastraServerBase;\n #mcpServers?: TMCPServers;\n #bundler?: BundlerConfig;\n #idGenerator?: MastraIdGenerator;\n #pubsub: PubSub;\n #backgroundTaskConfig?: BackgroundTaskManagerConfig;\n #backgroundTaskManager?: BackgroundTaskManager;\n #schedulerConfig?: SchedulerConfig;\n #notificationDispatchConfig?: NotificationDispatchConfig;\n /**\n * Tracks whether any registered workflow has declared a `schedule` config.\n * Used as a fast short-circuit so users without scheduled workflows pay\n * zero cost beyond a boolean check.\n */\n #hasScheduledWorkflow = false;\n #gateways?: Record<string, MastraModelGatewayInterface>;\n #channels?: TChannels;\n #schedules?: Schedules;\n #schedulesConfig?: SchedulesConfig<Mastra>;\n #environment?: string;\n #toolPayloadTransform?: ToolPayloadTransformPolicy;\n #workers: MastraWorker[] = [];\n #workerFilter?: Set<string>;\n /**\n * Set when the user (or `MASTRA_WORKERS=false`) explicitly disabled all event\n * processing in this instance via `workers: false`. Gates lazy scheduler /\n * agent-schedule worker injection so runtime triggers (e.g.\n * `schedules.create()`) don't resurrect workers the user opted out of.\n */\n #workersDisabled = false;\n /**\n * Tracks whether `startWorkers()` has already run. Used to decide whether\n * lazy scheduler injection (e.g. from `mastra.schedules.create()` after boot)\n * needs to also `init`/`start` the worker, or whether the normal\n * `startWorkers()` path will pick it up.\n */\n #workersStarted = false;\n /**\n * Set when something has signalled that the scheduler is needed at runtime\n * (e.g. an agent schedule was registered via `__ensureScheduleRuntimeReady()`).\n * Causes `#shouldEnableScheduler()` to return `true` even when there are no\n * declarative scheduled workflows, unless the user explicitly set\n * `scheduler: { enabled: false }`.\n */\n #schedulerRequested = false;\n /**\n * Set once `__ensureNotificationDispatchReady()` has upserted the dispatcher\n * schedule row and requested the scheduler. Makes repeated deferred\n * notification creates free after the first one.\n */\n #notificationDispatchReady = false;\n /**\n * In-flight promise for `#ensureSchedulingWorkersStarted()`. Serializes\n * concurrent startup requests so two callers can't both pass the\n * worker-existence checks and double-subscribe to the scheduling topics.\n */\n #schedulingWorkersStartPromise?: Promise<void>;\n /**\n * In-flight promise for `__ensureExecutionWorkersStarted()`. Serializes\n * concurrent lazy startups triggered by background-task dispatches so two\n * first dispatches on a cold instance can't both init/start the same\n * workers.\n */\n #executionWorkersStartPromise?: Promise<void>;\n /**\n * Fast path for `__ensureExecutionWorkersStarted()`. Set once the execution\n * workers + push wiring are confirmed running; reset by `stopWorkers()`.\n * Kept separate from `#workersStarted`, which partial `startWorkers(name)`\n * calls also set without starting the workflow consumer.\n */\n #executionWorkersStarted = false;\n // Lazily-constructed processor used by handleWorkflowEvent(). Shared between\n // pull-mode workers (OrchestrationWorker) and push-mode entry points\n // (in-process EventEmitter listener, the /api/workers/events HTTP route).\n #workflowEventProcessor?: WorkflowEventProcessor;\n // Callback registered against the pubsub when running in push mode so we can\n // unsubscribe it cleanly during stopWorkers().\n #pushSubscription?: { topic: string; cb: EventCallback };\n // Tracks (topic, listener) pairs registered against the pubsub on behalf of\n // user-defined event listeners during startWorkers(). Used to make\n // startWorkers()/stopWorkers() idempotent — a second startWorkers() call\n // must not double-subscribe the same listener.\n #userEventSubscriptions: Array<{\n topic: string;\n cb: (event: Event, ack?: () => Promise<void>) => Promise<void>;\n }> = [];\n\n #events: {\n [topic: string]: ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n } = {};\n #internalMastraWorkflows: Record<string, AnyWorkflow> = {};\n // Tracks registration timestamps for run-scoped internal workflows so a lazy\n // TTL sweep can evict entries from abandoned suspended runs that were never\n // resumed. Unscoped (singleton) entries are not tracked — they live forever.\n #runScopedWorkflowTimestamps: Map<string, { registeredAt: number; runId: string }> = new Map();\n // Per-run bag of non-serializable runtime state (SaveQueueManager,\n // BackgroundTaskManager, MessageList, abort controllers, dynamic tool sets…)\n // shared across step factories within a single run. Never persisted, never\n // published. Lifecycle is refcounted against `__registerInternalWorkflow`\n // calls for the same runId so multiple workflows sharing a run (e.g. an\n // agentic-loop wrapping an agentic-execution) keep the scope alive until the\n // last unregisters. See `./run-scope.ts`.\n #runScopes: Map<string, RunScope> = new Map();\n #runScopeRefcounts: Map<string, number> = new Map();\n // Run-scoped internal workflows older than this TTL (ms) are evicted during\n // the lazy sweep that runs on each new registration.\n static readonly INTERNAL_WORKFLOW_TTL_MS = 30 * 60 * 1000; // 30 minutes\n // Per-run tracing context for evented workflow runs. `currentSpan` is a\n // non-serializable AISpan, so it cannot ride the engine's pubsub events —\n // the event processor reads it from here, keyed by runId, instead.\n #runTracingContexts: Map<string, TracingContext> = new Map();\n // Server cache for temporary persistence and durable agent resumable streams\n #serverCache: MastraServerCache;\n // Cache for stored agents to allow in-memory modifications (like model changes) to persist across requests\n #storedAgentsCache: Map<string, Agent> = new Map();\n // Cache for stored scorers to allow in-memory modifications to persist across requests\n #storedScorersCache: Map<string, MastraScorer<any, any, any, any>> = new Map();\n // Registry for prompt blocks (stored or code-defined)\n #promptBlocks: Record<string, StorageResolvedPromptBlockType> = {};\n // Editor instance for handling agent instantiation and configuration\n #editor?: IMastraEditor;\n #datasets?: DatasetsManager;\n // Global version overrides for primitives (agents, etc.)\n #versions?: VersionOverrides;\n // Cached pubsub proxy that tags internal-workflow events with `_localOnly`\n // so the broker skips relaying multi-MB payloads to non-owning instances.\n #pubsubProxy?: PubSub;\n\n get pubsub(): PubSub {\n if (!this.#pubsubProxy) {\n const raw = this.#pubsub;\n const self = this;\n this.#pubsubProxy = new Proxy(raw, {\n get(target, prop, _receiver) {\n if (prop === 'publish') {\n return function publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>) {\n // Internal execution-workflows / agentic-loops are run-scoped:\n // only the owning instance needs their events. Pass `localOnly`\n // so the broker delivers locally + echoes back to the sender,\n // but does NOT fan out to other clients (avoids serialising\n // cumulative stepResults blobs — often 9 MB+ — across the unix\n // socket). The flag rides on the publish-frame envelope, not on\n // event.data, so WEP consumers never see it.\n if (topic === 'workflows' || topic === 'workflows-finish') {\n const data = event.data as Record<string, unknown> | undefined;\n const wfId = data?.workflowId as string | undefined;\n const rId = data?.runId as string | undefined;\n // Walk parentWorkflow chain to root — nested internal workflows\n // (e.g. `executionWorkflow` inside `agentic-loop`) carry an\n // immediate workflowId that isn't itself in the internal registry,\n // but their root parent (the registered agentic-loop) is. If any\n // ancestor matches an internal registration, this instance owns\n // the run and the event should stay local. Also tag publishes\n // for workflow ids only known to this instance's public registry\n // (e.g. background scheduler runs like the notification\n // dispatcher) — they have no cross-instance consumer.\n const isOwnedHere = (() => {\n if (wfId && rId && self.__hasInternalWorkflow(wfId, rId)) return true;\n let parent = data?.parentWorkflow as\n | { workflowId?: string; runId?: string; parentWorkflow?: unknown }\n | undefined;\n let depth = 0;\n while (parent && depth < 16) {\n const pwfId = parent.workflowId;\n const prId = parent.runId;\n if (pwfId && prId && self.__hasInternalWorkflow(pwfId, prId)) return true;\n parent = parent.parentWorkflow as typeof parent;\n depth++;\n }\n // Scheduler-spawned background workflows: runId carries the\n // schedule row id prefix — `sched_wf_<workflowId>_<timestamp>`\n // for declarative schedules, or the imperative notification\n // dispatcher row id. These ticks fire on every instance\n // independently — events are only meaningful to the\n // publishing process.\n if (rId && rId.startsWith('sched_wf_')) return true;\n if (rId && rId.startsWith(`sched_${NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID}_`)) return true;\n return false;\n })();\n if (isOwnedHere) {\n return target.publish(topic, event, { localOnly: true });\n }\n } else if (topic.startsWith('workflow.events.v2.')) {\n // Per-run watch stream events. Only the publishing process\n // consumes these (execution-engine subscribes per-run). No\n // cross-instance fan-out needed.\n return target.publish(topic, event, { localOnly: true });\n }\n return target.publish(topic, event);\n };\n }\n // Bind methods to `target` so private field access (#subscribers etc.)\n // works correctly — JS Proxies set `this` to the proxy, which breaks\n // private fields since they are scoped to the declaring class instance.\n const val = Reflect.get(target, prop, target);\n if (typeof val === 'function') {\n return val.bind(target);\n }\n return val;\n },\n }) as PubSub;\n }\n return this.#pubsubProxy;\n }\n\n get agentThreadStreamRuntime() {\n return agentThreadStreamRuntime;\n }\n\n get workers(): readonly MastraWorker[] {\n return this.#workers;\n }\n\n getWorker<T extends MastraWorker>(name: string): T | undefined {\n return this.#workers.find(w => w.name === name) as T | undefined;\n }\n\n get backgroundTaskManager() {\n return this.#backgroundTaskManager;\n }\n\n /**\n * Returns the workflow scheduler owned by the SchedulerWorker,\n * or undefined if the scheduler is not enabled / not yet started.\n *\n * The scheduler is created when `startWorkers()` initializes the\n * SchedulerWorker (guarded by `#shouldEnableScheduler()`).\n *\n * This is runtime plumbing (the cron tick loop). To create, list, pause,\n * resume, or delete schedules use `mastra.schedules` instead.\n *\n * @internal\n */\n get scheduler(): Scheduler | undefined {\n return this.#findSchedulerWorker()?.scheduler;\n }\n\n get datasets(): DatasetsManager {\n if (!this.#datasets) {\n this.#datasets = new DatasetsManager(this);\n }\n return this.#datasets;\n }\n\n /**\n * Gets the currently configured ID generator function.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * idGenerator: context =>\n * context?.idType === 'message' && context.threadId\n * ? `msg-${context.threadId}-${Date.now()}`\n * : `custom-${Date.now()}`\n * });\n * const generator = mastra.getIdGenerator();\n * console.log(generator?.({ idType: 'message', threadId: 'thread-123' })); // \\\"msg-thread-123-1234567890\\\"\n * ```\n */\n public getIdGenerator() {\n return this.#idGenerator;\n }\n\n /**\n * Gets the currently configured editor instance.\n * The editor is responsible for handling agent instantiation and configuration.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * editor: new MastraEditor({ logger })\n * });\n * const editor = mastra.getEditor();\n * ```\n */\n public getEditor() {\n return this.#editor;\n }\n\n /**\n * Gets a registered channel provider by its key.\n *\n * @example\n * ```typescript\n * import { SlackProvider } from '@mastra/slack';\n * const slack = mastra.getChannelProvider<SlackProvider>('slack');\n * ```\n */\n public getChannelProvider<T extends ChannelProvider = ChannelProvider>(key: string): T | undefined {\n return this.#channels?.[key] as T | undefined;\n }\n\n /**\n * Gets all registered channel providers.\n */\n public getChannelProviders(): Record<string, ChannelProvider> | undefined {\n return this.#channels;\n }\n\n /**\n * Shorthand getter for platform channels.\n * Usage: `mastra.channels.slack.connect(agentId)`\n */\n public get channels(): TChannels {\n return (this.#channels ?? {}) as TChannels;\n }\n\n /**\n * Canonical entrypoint for schedules — recurring agent or workflow runs\n * persisted as schedule rows discriminated by `target.type` (`'agent'` or\n * `'workflow'`). Use to create, list, update, pause/resume, manually fire,\n * or inspect trigger history for schedules across any agent or workflow.\n *\n * Lazily constructed. Operates against `getStorage()?.getStore('schedules')`.\n *\n * @example\n * ```ts\n * const schedule = await mastra.schedules.create({\n * agentId: 'pinger',\n * name: 'morning-checkin',\n * cron: '0 9 * * *',\n * prompt: 'good morning, anything to report?',\n * threadId: 't1',\n * resourceId: 'u1',\n * });\n * await mastra.schedules.list({ agentId: 'pinger' });\n * ```\n */\n public get schedules(): Schedules {\n this.#schedules ??= new Schedules(this as unknown as Mastra);\n return this.#schedules;\n }\n\n /**\n * Returns the schedule lifecycle hook bundle configured via\n * `new Mastra({ schedules: { ... } })`, if any. A single bundle runs for\n * every agent-schedule fire; hooks branch per agent via the `agentId` on\n * each context. Internal: consumed by the {@link AgentScheduleWorker} to\n * invoke `prepare`, `onFinish`, `onError`, and `onAbort` around\n * schedule-driven runs.\n *\n * @internal\n */\n __getScheduleHooks(): ScheduleHooks<Mastra> | undefined {\n return this.#schedulesConfig;\n }\n\n /**\n * Returns the global version overrides configured on this Mastra instance.\n * These are used as defaults when resolving sub-agent versions during delegation.\n */\n public getVersionOverrides(): VersionOverrides | undefined {\n return this.#versions;\n }\n\n /**\n * Returns the deployment environment name configured on this Mastra instance,\n * falling back to `process.env.NODE_ENV` when unset, or `undefined` if neither\n * is provided.\n *\n * Observability automatically reads this and attaches it to all signals so\n * consumers can filter by environment without passing\n * `tracingOptions.metadata.environment` on each call.\n */\n public getEnvironment(): string | undefined {\n return this.#environment;\n }\n\n public getToolPayloadTransform(): ToolPayloadTransformPolicy | undefined {\n return this.#toolPayloadTransform;\n }\n\n /**\n * Gets the stored agents cache\n * @internal\n */\n public getStoredAgentCache() {\n return this.#storedAgentsCache;\n }\n\n /**\n * Gets the stored scorers cache\n * @internal\n */\n public getStoredScorerCache() {\n return this.#storedScorersCache;\n }\n\n /**\n * Generates a unique identifier using the configured generator or defaults to `crypto.randomUUID()`.\n *\n * This method is used internally by Mastra for creating unique IDs for various entities\n * like workflow runs, agent conversations, and other resources that need unique identification.\n *\n * @param context - Optional context information about what type of ID is being generated\n * and where it's being requested from. This allows custom ID generators\n * to create deterministic IDs based on context.\n *\n * @throws {MastraError} When the custom ID generator returns an empty string\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const id = mastra.generateId();\n * console.log(id); // \"550e8400-e29b-41d4-a716-446655440000\"\n *\n * // With context for deterministic IDs\n * const messageId = mastra.generateId({\n * idType: 'message',\n * source: 'agent',\n * threadId: 'thread-123'\n * });\n * ```\n */\n public generateId(context?: IdGeneratorContext): string {\n if (this.#idGenerator) {\n const id = this.#idGenerator(context);\n if (!id) {\n const error = new MastraError({\n id: 'MASTRA_ID_GENERATOR_RETURNED_EMPTY_STRING',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'ID generator returned an empty string, which is not allowed',\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return id;\n }\n return randomUUID();\n }\n\n /**\n * Sets a custom ID generator function for creating unique identifiers.\n *\n * The ID generator function will be used by `generateId()` instead of the default\n * `crypto.randomUUID()`. This is useful for creating application-specific ID formats\n * or integrating with existing ID generation systems. The function receives\n * optional context about what is requesting the ID.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * mastra.setIdGenerator(context =>\n * context?.idType === 'run' && context.entityId\n * ? `run-${context.entityId}-${Date.now()}`\n * : `custom-${Date.now()}`\n * );\n * const id = mastra.generateId({ idType: 'run', entityId: 'agent-123' });\n * console.log(id); // \"run-agent-123-1234567890\"\n * ```\n */\n public setIdGenerator(idGenerator: MastraIdGenerator) {\n this.#idGenerator = idGenerator;\n }\n\n /**\n * Sets the server configuration for this Mastra instance.\n *\n * @param server - The server configuration object\n *\n * @example\n * ```typescript\n * mastra.setServer({ ...mastra.getServer(), auth: new MastraAuthWorkos() });\n * ```\n */\n public setServer(server: ServerConfig): void {\n this.#server = server;\n }\n\n /**\n * Sets the studio configuration for this Mastra instance.\n *\n * The studio configuration controls authentication and authorization for Studio UI,\n * separate from the server configuration. This enables dual auth patterns where\n * Studio users (e.g., internal team) use different auth than API consumers.\n *\n * @param studio - The studio configuration object\n *\n * @example\n * ```typescript\n * // Set studio auth separately from server auth\n * mastra.setStudio({\n * auth: new MastraAuthStudio(),\n * rbac: new MastraRBACStudio({ roleMapping: { admin: ['*'] } }),\n * });\n * ```\n */\n public setStudio(studio: StudioConfig): void {\n this.#studio = studio;\n }\n\n /**\n * Registers an exporter on the default observability instance.\n *\n * If the current observability is a no-op (user didn't configure any), it is\n * first replaced with the provided entrypoint and the instance is registered\n * as default. If a real observability entrypoint already exists, the exporter\n * is added directly to the existing default instance.\n *\n * @param exporter - The exporter to register (e.g. a MastraPlatformExporter)\n * @param instance - An ObservabilityInstance pre-configured with the exporter, used as default when bootstrapping\n * @param entrypoint - A real ObservabilityEntrypoint to bootstrap if the current one is a no-op\n */\n public registerExporter(\n exporter: ObservabilityExporter,\n instance: ObservabilityInstance,\n entrypoint: ObservabilityEntrypoint,\n ): void {\n if (this.#observability instanceof NoOpObservability) {\n this.#observability = entrypoint;\n this.#observability.setLogger({ logger: this.#logger });\n this.#observability.setMastraContext({ mastra: this });\n this.#observability.registerInstance('default', instance, true);\n }\n\n const defaultInstance = this.#observability.getDefaultInstance();\n if (defaultInstance?.registerExporter) {\n defaultInstance.registerExporter(exporter);\n }\n }\n\n /**\n * Creates a new Mastra instance with the provided configuration.\n *\n * The constructor initializes all the components specified in the config, sets up\n * internal systems like logging and observability, and registers components with each other.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * id: 'assistant',\n * name: 'Assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }),\n * logger: new PinoLogger({ name: 'MyApp' }),\n * observability: new Observability({\n * configs: { default: { serviceName: 'mastra', exporters: [new MastraStorageExporter()] } },\n * }),\n * });\n * ```\n */\n constructor(\n config?: Config<\n TAgents,\n TWorkflows,\n TVectors,\n TTTS,\n TLogger,\n TMCPServers,\n TScorers,\n TTools,\n TProcessors,\n TMemory,\n TChannels\n >,\n ) {\n // Register AsyncLocalStorage-backed context resolvers so that DualLogger\n // can correlate logs to the active span. Must happen before any agent runs.\n initContextStorage();\n\n // Server cache for temporary persistence and durable agent resumable streams\n this.#serverCache = config?.cache ?? new InMemoryServerCache();\n\n // Boot-time recovery policy for durable agent runs. Default is 'off' so\n // that an install can't silently re-run tools/LLM calls on restart; opt-in\n // via `recovery: { durableAgents: 'auto' }` matches the existing\n // `restartAllActiveWorkflowRuns` boot hook.\n this.#recoveryConfig = {\n durableAgents: config?.recovery?.durableAgents ?? 'off',\n };\n\n this.#editor = config?.editor;\n\n // Store global version overrides\n this.#versions = config?.versions;\n\n // Resolve deployment environment: explicit config wins, else fall back to\n // NODE_ENV. Leave undefined if neither is set rather than guessing.\n this.#environment = config?.environment ?? process.env.NODE_ENV;\n this.#toolPayloadTransform = normalizeToolPayloadTransformPolicy(\n config?.transform ?? (config as any)?.toolPayloadProjection,\n );\n\n if (config?.pubsub) {\n this.#pubsub = config.pubsub;\n } else {\n this.#pubsub = new EventEmitterPubSub();\n }\n\n this.#events = {};\n for (const topic in config?.events ?? {}) {\n if (!Array.isArray(config?.events?.[topic])) {\n this.#events[topic] = [config?.events?.[topic] as any];\n } else {\n this.#events[topic] = config?.events?.[topic] ?? [];\n }\n }\n\n // Initialize workers based on config.\n // MASTRA_WORKERS env var:\n // - \"false\": disables all event processing in this instance\n // - comma-separated names (e.g. \"scheduler,orchestration\"): only those\n // workers will be started by `startWorkers()` when called without an\n // explicit `name` argument. Construction still creates all workers so\n // a later explicit `startWorkers('foo')` still works.\n const rawWorkersEnv = process.env.MASTRA_WORKERS;\n let workersOption: MastraWorker[] | false | undefined;\n if (rawWorkersEnv === 'false') {\n workersOption = false;\n } else {\n workersOption = config?.workers;\n if (rawWorkersEnv && rawWorkersEnv !== 'false') {\n const names = rawWorkersEnv\n .split(',')\n .map(s => s.trim())\n .filter(Boolean);\n if (names.length > 0) {\n this.#workerFilter = new Set(names);\n }\n }\n }\n\n if (workersOption === false) {\n // Explicitly disabled — no event processing in this instance.\n // PubSub still exists for publishing events. Record the opt-out so\n // runtime triggers (e.g. schedules.create()) don't lazily inject\n // scheduler / agent-schedule workers behind the user's back.\n this.#workersDisabled = true;\n } else {\n // Auto-create default workers based on config.\n //\n // Skip OrchestrationWorker when the configured pubsub doesn't support\n // pull delivery (e.g. EventEmitter, GCP Pub/Sub push) — those transports\n // don't have a read loop to drive a worker, and Mastra wires\n // `handleWorkflowEvent` directly to the pubsub during startWorkers().\n const pubsubModes = this.#pubsub.supportedModes ?? ['pull'];\n const defaultWorkers: MastraWorker[] = [];\n if (pubsubModes.includes('pull')) {\n defaultWorkers.push(new OrchestrationWorker());\n }\n // SchedulerWorker is added lazily in startWorkers() rather than here\n // because workflows (and their schedule configs) are registered after\n // this block runs, so #hasScheduledWorkflow is not yet set.\n if (config?.backgroundTasks?.enabled) {\n defaultWorkers.push(new BackgroundTaskWorker(config.backgroundTasks));\n }\n // Merge custom workers with the defaults: a custom worker replaces a\n // default sharing its name (e.g. a custom OrchestrationWorker), and\n // duplicate names within the custom array fail loud.\n const customWorkers = workersOption ?? [];\n const customNames = new Set<string>();\n for (const w of customWorkers) {\n if (customNames.has(w.name)) {\n throw new Error(`Duplicate worker name \"${w.name}\" in the 'workers' option`);\n }\n customNames.add(w.name);\n }\n this.#workers = [...defaultWorkers.filter(w => !customNames.has(w.name)), ...customWorkers];\n for (const w of this.#workers) {\n w.__registerMastra(this);\n }\n }\n\n let logger: TLogger;\n if (config?.logger === false) {\n logger = noopLogger as unknown as TLogger;\n this.#loggerExplicit = true;\n } else {\n if (config?.logger) {\n logger = config.logger;\n this.#loggerExplicit = true;\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 // Default to an in-memory store when none is configured. The evented\n // workflow engine uses storage as the source of truth for cross-branch\n // coordination in parallel/foreach steps, so a missing store would cause\n // parallel branches to silently fail to aggregate. In-memory is the safe\n // default for `new Mastra({})` / tests; production callers always override.\n let storage: MastraCompositeStore;\n if (config?.storage) {\n storage = config.storage;\n this.#storageExplicit = true;\n } else {\n storage = new InMemoryStore();\n this.#logger?.warn(\n 'No `storage` configured on Mastra — falling back to an in-memory store. ' +\n 'In-memory storage is not durable: all data is lost on restart, and it is not safe for production. ' +\n 'Configure a persistent storage adapter (e.g. @mastra/libsql, @mastra/pg, @mastra/cloudflare).',\n );\n }\n storage = augmentWithInit(storage);\n\n // The evented workflow engine (used internally by the agentic loop) requires\n // `workflows` and `backgroundTasks` storage domains. When a user provides a\n // MastraCompositeStore with only specific domains (e.g. just `notifications`),\n // these infrastructure domains may be missing. Patch them in with lightweight\n // in-memory defaults so the engine works transparently without requiring users\n // to configure internal implementation details.\n if (storage.stores) {\n if (!storage.stores.workflows || !storage.stores.backgroundTasks) {\n const fallbackDb = new InMemoryDB();\n if (!storage.stores.workflows) {\n storage.stores.workflows = new WorkflowsInMemory({ db: fallbackDb });\n }\n if (!storage.stores.backgroundTasks) {\n storage.stores.backgroundTasks = new BackgroundTasksInMemory({ db: fallbackDb });\n }\n }\n }\n\n // Validate and assign observability instance\n if (config?.observability) {\n this.#observabilityExplicit = true;\n if (typeof config.observability.getDefaultInstance === 'function') {\n this.#observability = config.observability;\n // Set logger early\n this.#observability.setLogger({ logger: this.#logger });\n } else {\n this.#logger?.warn(\n 'Observability configuration error: Expected an Observability instance, but received a config object. ' +\n 'Import and instantiate: import { Observability, MastraStorageExporter } from \"@mastra/observability\"; ' +\n 'then pass: observability: new Observability({ configs: { default: { serviceName: \"mastra\", exporters: [new MastraStorageExporter()] } } }). ' +\n 'Observability has been disabled.',\n );\n this.#observability = new NoOpObservability();\n }\n } else {\n this.#observability = new NoOpObservability();\n }\n\n // Wrap the logger in a DualLogger so all existing this.logger.info(...) calls\n // also forward to loggerVNext (observability structured logging).\n // This is transparent — no call sites need to change.\n // Uses a lazy getter so loggerVNext is always resolved at call time\n // (observability may not be fully initialized yet at this point).\n const dualLogger = new DualLogger(this.#logger, () => this.loggerVNext);\n this.#logger = dualLogger as unknown as TLogger;\n\n this.#storage = storage;\n\n // Give storage adapters a back-pointer to this Mastra instance so they\n // can look up code-defined agents, editor config, etc. when needed\n // (e.g. filesystem code-mode snapshot filtering).\n storage?.__registerMastra?.(this as unknown as Parameters<NonNullable<typeof storage.__registerMastra>>[0]);\n\n // Register the editor after storage is assigned so code mode can overlay\n // filesystem-backed editor storage while preserving app storage domains.\n if (this.#editor && typeof this.#editor.registerWithMastra === 'function') {\n this.#editor.registerWithMastra(this);\n }\n\n // Kick off background license validation against the license server when\n // an enterprise license key is configured. Fire-and-forget: LicenseClient\n // caches the result, schedules revalidation, and fails open on network\n // errors, so this never blocks or throws during construction.\n if (process.env.MASTRA_LICENSE_KEY || process.env.MASTRA_EE_LICENSE) {\n LicenseClient.getInstance(this.#logger)\n .validate()\n .catch(() => {\n // Failures are logged and handled inside LicenseClient.\n });\n }\n\n this.#backgroundTaskConfig = config?.backgroundTasks;\n // Always create the background-task manager when background tasks are\n // enabled. When workers are disabled (`workers: false`) or when a\n // MASTRA_WORKERS filter is set that excludes 'backgroundTasks', the\n // manager runs in 'producer' mode: it can enqueue/dispatch tasks and\n // receive completion notifications via the fan-out result topic, but\n // does NOT join the worker consumer group — so it won't compete with\n // a dedicated BackgroundTaskWorker process for dispatch events.\n const bgWorkerFiltered = this.#workerFilter && !this.#workerFilter.has('backgroundTasks');\n this.#ensureBackgroundTaskManager(workersOption === false || bgWorkerFiltered ? 'producer' : undefined);\n\n this.#schedulerConfig = config?.scheduler;\n this.#notificationDispatchConfig = config?.notifications?.dispatch;\n this.#schedulesConfig = config?.schedules;\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, MastraModelGatewayInterface>;\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 (this.#notificationDispatchConfig?.enabled !== false) {\n const workflow = createNotificationDispatchWorkflow(this.#notificationDispatchConfig);\n this.addWorkflow(workflow, workflow.id);\n this.#hiddenWorkflowKeys.add(workflow.id);\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 = getGatewayId(gateway);\n // Check by logical ID to avoid duplicates when a user-registered gateway\n // exists under a different registry key but has the same gateway ID.\n const existingGateways = Object.values(this.#gateways as Record<string, MastraModelGatewayInterface>);\n const alreadyRegistered = existingGateways.some(\n existingGateway => existingGateway != null && getGatewayId(existingGateway) === key,\n );\n if (!alreadyRegistered) {\n (this.#gateways as Record<string, MastraModelGatewayInterface>)[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 this.#serverExplicit = true;\n }\n\n if (config?.studio) {\n this.#studio = config.studio;\n this.#studioExplicit = true;\n }\n\n // Register channels and merge their routes into server config\n if (config?.channels) {\n this.#channels = config.channels;\n const channelRoutes: ApiRoute[] = [];\n\n for (const [, channel] of Object.entries(config.channels)) {\n if (channel == null) continue;\n\n // Attach the channel to this Mastra instance\n if (channel.__attach) {\n channel.__attach(this);\n }\n\n // Collect routes from the channel\n const routes = channel.getRoutes();\n channelRoutes.push(...routes);\n }\n\n // Merge channel routes into server config\n if (channelRoutes.length > 0) {\n const existingRoutes = this.#server?.apiRoutes ?? [];\n this.#server = {\n ...this.#server,\n apiRoutes: [...existingRoutes, ...channelRoutes],\n };\n }\n }\n\n // Agents must be added after server config so that channel webhook routes\n // are appended to (not replaced by) the server config.\n if (config?.agents) {\n Object.entries(config.agents).forEach(([key, agent]) => {\n if (agent != null) {\n this.addAgent(agent, key);\n }\n });\n }\n\n // `harnesses` is the deprecated alias of `agentControllers`; merge both,\n // letting `agentControllers` win on key collisions.\n const agentControllerEntries = {\n ...(config?.harnesses ?? {}),\n ...(config?.agentControllers ?? {}),\n };\n for (const [key, agentController] of Object.entries(agentControllerEntries)) {\n this.#harnesses[key] = agentController;\n agentController.__registerMastra(this);\n\n // Set up AgentControllerChannels for manual adapter configurations,\n // mirroring the agent channels wiring in `addAgent`.\n const controllerChannels = agentController.getChannels();\n if (controllerChannels) {\n controllerChannels.__setLogger(this.#logger);\n const channelRoutes = controllerChannels.getWebhookRoutes();\n if (channelRoutes.length > 0) {\n this.#server = {\n ...this.#server,\n apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n };\n }\n controllerChannels.initialize(this).catch(err => {\n this.#logger?.error(`Failed to initialize channels for agent controller ${key}:`, err);\n });\n }\n }\n\n // `registerHook` adds to a module-level emitter that never drops handlers on\n // its own. Keep the reference so short-lived internal Mastras can release it\n // on teardown (see `__unregisterHooks`); otherwise their handler fires on\n // every scorer run for the lifetime of the process. Ephemeral instances\n // (standalone-Agent fallbacks) skip registration entirely: their hook can\n // never resolve a scorer, and the emitter would pin the instance against GC\n // for the process lifetime (#19404).\n if (!config?.__ephemeral) {\n this.#onScorerHook = createOnScorerHook(this);\n registerHook(AvailableHooks.ON_SCORER_RUN, this.#onScorerHook);\n }\n\n /*\n Initialize observability with Mastra context (after storage configured)\n */\n this.#observability.setMastraContext({ mastra: this });\n\n this.setLogger({ logger });\n\n // Initialize channels asynchronously (auto-provision apps, etc.)\n // This runs after all agents are registered so configs are available\n if (this.#channels) {\n void Promise.resolve().then(async () => {\n for (const [key, channel] of Object.entries(this.#channels ?? {})) {\n if (channel.initialize) {\n try {\n await channel.initialize();\n } catch (err) {\n console.error(`[Mastra] Failed to initialize channel \"${key}\":`, err);\n }\n }\n }\n });\n }\n }\n\n #ensureBackgroundTaskManager(modeOverride?: 'producer' | 'worker' | 'full'): void {\n if (!this.#backgroundTaskConfig?.enabled || !this.#storage || this.#backgroundTaskManager) {\n return;\n }\n\n // Derive the effective mode from the worker configuration when no\n // explicit override is given. Late call-sites (#maybeEnableBackgroundTasksForAgent,\n // setStorage) don't know the worker topology, so we derive it here to\n // ensure producer mode is consistently applied when workers are disabled\n // or the backgroundTasks worker is excluded by the MASTRA_WORKERS filter.\n const effectiveMode =\n modeOverride ??\n (this.#workersDisabled || (this.#workerFilter && !this.#workerFilter.has('backgroundTasks'))\n ? 'producer'\n : undefined);\n\n const managerConfig = effectiveMode\n ? { ...this.#backgroundTaskConfig, mode: effectiveMode }\n : this.#backgroundTaskConfig;\n const bgManager = new BackgroundTaskManager(managerConfig);\n bgManager.__registerMastra(this);\n this.#backgroundTaskManager = bgManager;\n\n // Wire statically-registered tools into the manager's name-keyed registry\n // so cross-process workers can resolve dispatched tasks. Tools added later\n // via `addTool()` are propagated through the same path.\n const tools = this.#tools as Record<string, ToolAction<any, any, any, any>> | undefined;\n if (tools) {\n for (const [name, tool] of Object.entries(tools)) {\n this.#registerToolWithBackgroundManager(name, tool);\n }\n }\n\n void bgManager.init(this.#pubsub).catch(error => {\n this.#logger?.error('Failed to initialize background task manager', error);\n });\n }\n\n /**\n * Build a `ToolExecutor` adapter for a Mastra-registered tool and stash it\n * on the background task manager's static registry. Skipped if the tool has\n * no `execute` (declarative-only tools, e.g. MCP descriptors).\n */\n #registerToolWithBackgroundManager(name: string, tool: ToolAction<any, any, any, any>): void {\n if (!this.#backgroundTaskManager) return;\n if (typeof tool.execute !== 'function') return;\n const execute = tool.execute.bind(tool);\n this.#backgroundTaskManager.registerStaticExecutor(name, {\n execute: async (args, options) => {\n // Cross-process workers don't have access to the producer's\n // request/workspace context. Statically-resolvable tools should\n // tolerate a minimal context (abortSignal only). Tools that need\n // closure-captured state must run in-process via TaskContext.\n return execute(\n args as any,\n {\n toolCallId: '',\n messages: [],\n abortSignal: options?.abortSignal,\n } as any,\n );\n },\n });\n }\n\n /**\n * Returns the flat list of declarative schedules sourced from currently\n * registered workflows. Single-schedule workflows yield one entry keyed by\n * `wf_<encoded(workflowId)>`. Array-form workflows yield one entry per array\n * entry keyed by `wf_<encoded(workflowId)>__<encoded(scheduleId)>` so the\n * prefix uniquely identifies \"all rows owned by this workflow's declarative\n * config\" even when ids contain `__` or other delimiter-like characters.\n */\n #collectDeclarativeSchedules(): Array<{\n scheduleId: string;\n workflowId: string;\n cfg: WorkflowScheduleConfig;\n }> {\n const out: Array<{ scheduleId: string; workflowId: string; cfg: WorkflowScheduleConfig }> = [];\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n for (const workflow of Object.values(workflows ?? {})) {\n const configs = collectWorkflowScheduleConfigs(workflow);\n if (configs.length === 0) continue;\n const isArrayForm = configs.length > 1 || (configs.length === 1 && configs[0]!.id !== undefined);\n for (const cfg of configs) {\n const scheduleId = isArrayForm\n ? declarativeScheduleRowId(workflow.id, cfg.id)\n : declarativeScheduleRowId(workflow.id);\n out.push({ scheduleId, workflowId: workflow.id, cfg });\n }\n }\n return out;\n }\n\n #shouldEnableScheduler(): boolean {\n // Honour an explicit `workers: false` opt-out — the user disabled all\n // event processing in this instance, so never auto-inject scheduler /\n // agent-schedule workers (even when scheduler.enabled is true or a\n // schedule is created at runtime). Standalone workers are expected to\n // run the scheduler separately.\n if (this.#workersDisabled) return false;\n if (this.#schedulerConfig?.enabled === false) return false;\n if (this.#schedulerConfig?.enabled === true) return true;\n return this.#hasScheduledWorkflow || this.#schedulerRequested;\n }\n\n /**\n * Find the SchedulerWorker from the workers list (if present).\n */\n #findSchedulerWorker(): SchedulerWorker | undefined {\n return this.#workers.find((w): w is SchedulerWorker => w.name === 'scheduler') as SchedulerWorker | undefined;\n }\n\n /**\n * Find the AgentScheduleWorker from the workers list (if present).\n */\n #findAgentScheduleWorker(): MastraWorker | undefined {\n return this.#workers.find(w => w.name === 'agent-schedule');\n }\n\n /**\n * Sync code-declared schedule configs to the database. Called by\n * SchedulerWorker during init and by addWorkflow() for late registrations.\n *\n * @internal — public so SchedulerWorker can call it, not part of the user API.\n */\n async registerDeclarativeSchedules(schedulesStore: SchedulesStorage): Promise<void> {\n const declared = this.#collectDeclarativeSchedules();\n const declaredIds = new Set(declared.map(d => d.scheduleId));\n\n // Group declared ids by workflow so we can detect orphans (rows that\n // start with `wf_<encoded(workflowId)>` but aren't in the current declared\n // set). Seed an empty entry for every registered workflow first so that\n // workflows which removed all their schedules across a redeploy still\n // have their old rows cleaned up.\n const declaredIdsByWorkflow = new Map<string, Set<string>>();\n const workflows = this.#workflows as Record<string, AnyWorkflow> | undefined;\n for (const workflow of Object.values(workflows ?? {})) {\n declaredIdsByWorkflow.set(workflow.id, new Set());\n }\n for (const { workflowId, scheduleId } of declared) {\n if (!declaredIdsByWorkflow.has(workflowId)) declaredIdsByWorkflow.set(workflowId, new Set());\n declaredIdsByWorkflow.get(workflowId)!.add(scheduleId);\n }\n\n for (const { scheduleId, workflowId, cfg } of declared) {\n try {\n const existing = await schedulesStore.getSchedule(scheduleId);\n const now = Date.now();\n const target: Schedule['target'] = {\n type: 'workflow',\n workflowId,\n inputData: cfg.inputData,\n initialState: cfg.initialState,\n requestContext: cfg.requestContext,\n };\n\n if (!existing) {\n await schedulesStore.createSchedule({\n id: scheduleId,\n target,\n cron: cfg.cron,\n timezone: cfg.timezone,\n status: 'active',\n nextFireAt: computeNextFireAt(cfg.cron, { timezone: cfg.timezone, after: now }),\n createdAt: now,\n updatedAt: now,\n metadata: cfg.metadata,\n });\n continue;\n }\n\n // Diff config fields and patch the existing row if anything changed.\n // We deliberately leave `status` alone — a row may have been paused\n // out-of-band via storage, and a redeploy shouldn't unpause it.\n const patch: ScheduleUpdate = {};\n const cronChanged = existing.cron !== cfg.cron;\n const timezoneChanged = (existing.timezone ?? undefined) !== (cfg.timezone ?? undefined);\n\n if (cronChanged) patch.cron = cfg.cron;\n if (timezoneChanged) patch.timezone = cfg.timezone;\n if (!targetsEqual(existing.target, target)) patch.target = target;\n if (!metadataEqual(existing.metadata, cfg.metadata)) patch.metadata = cfg.metadata;\n\n // Cron or timezone change invalidates the stored nextFireAt — recompute\n // from now so we don't fire on the old schedule.\n if (cronChanged || timezoneChanged) {\n patch.nextFireAt = computeNextFireAt(cfg.cron, { timezone: cfg.timezone, after: now });\n }\n\n if (Object.keys(patch).length > 0) {\n await schedulesStore.updateSchedule(scheduleId, patch);\n }\n } catch (error) {\n this.#logger?.error('Failed to register declarative schedule', { scheduleId, workflowId, error });\n }\n }\n\n // Orphan deletion: drop any Mastra-managed declarative schedule rows\n // (id starts with `wf_<workflowId>` or `wf_<workflowId>__`) that are no\n // longer declared in code. This covers two cases:\n // 1. A registered workflow's array-form entries shrunk across deploys.\n // 2. The owning workflow itself was deleted from code. Leaving these\n // rows behind would have the scheduler keep firing for a workflow\n // the processor can't resolve, producing infinite event-redelivery\n // loops (see WorkflowEventProcessor#dispatch).\n // User-created schedules (via the schedules API) don't use the `wf_`\n // prefix, so they're untouched.\n const allRows = await schedulesStore.listSchedules();\n for (const row of allRows) {\n if (declaredIds.has(row.id)) continue;\n if (!row.id.startsWith('wf_')) continue;\n const ownerWorkflowId = ownerWorkflowIdForRow(row.id, declaredIdsByWorkflow) ?? ownerWorkflowIdFromRowId(row.id);\n if (!ownerWorkflowId) continue;\n try {\n await schedulesStore.deleteSchedule(row.id);\n } catch (error) {\n this.#logger?.error('Failed to delete orphaned declarative schedule', {\n scheduleId: row.id,\n workflowId: ownerWorkflowId,\n error,\n });\n }\n }\n }\n\n /**\n * Auto-enables the background task manager when an agent with sub-agents is\n * registered. Sub-agent delegation runs in the background by default so the\n * parent stream stays responsive; that requires the manager to be available.\n * No-op when the user explicitly opted out via `backgroundTasks.enabled: false`.\n *\n * Eligible agents: any agent whose `agents` field is either a static record\n * with at least one entry OR a dynamic (function-based) resolver. Function\n * resolvers are evaluated per request, so we can't inspect their contents\n * here — but if the caller bothered to wire one up, we enable defensively\n * so those resolved sub-agents also dispatch in the background.\n */\n #maybeEnableBackgroundTasksForAgent(agent: Agent<any>): void {\n // Already running — nothing to do\n if (this.#backgroundTaskManager) return;\n\n // Explicit opt-out\n if (this.#backgroundTaskConfig?.enabled === false) return;\n\n if (!agent.__hasSubAgentsConfigured?.()) return;\n\n this.#backgroundTaskConfig = { ...(this.#backgroundTaskConfig ?? {}), enabled: true };\n this.#ensureBackgroundTaskManager();\n }\n\n /**\n * Retrieves a registered agent by its name.\n *\n * @template TAgentName - The specific agent name type from the registered agents\n * @throws {MastraError} When the agent with the specified name is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'weather-agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n * const agent = mastra.getAgent('weatherAgent');\n * const response = await agent.generate('What is the weather?');\n * ```\n */\n public getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName];\n public getAgent<TAgentName extends keyof TAgents>(\n name: TAgentName,\n version: { versionId: string } | { status?: 'draft' | 'published' },\n ): Promise<TAgents[TAgentName]>;\n public getAgent<TAgentName extends keyof TAgents>(\n name: TAgentName,\n version?: { versionId: string } | { status?: 'draft' | 'published' },\n ): TAgents[TAgentName] | Promise<TAgents[TAgentName]> {\n const agent = this.#agents?.[name];\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with name ${String(name)} not found`,\n details: {\n status: 404,\n agentName: String(name),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!version) {\n return this.#agents[name];\n }\n\n return this.resolveVersionedAgent(agent, version);\n }\n\n /**\n * Returns the `AgentChannels` instances for all registered agents and\n * agent controllers. Keys are agent / agent controller registration keys.\n * A controller's channels — also attached to its mode agents — are\n * reported once, under the controller's key.\n */\n public getChannels(): Record<string, AgentChannels> {\n const result: Record<string, AgentChannels> = {};\n // Collect controller channels first so mode agents carrying a\n // controller's channels instance aren't double-reported under agent\n // keys. (Identity match rather than `instanceof AgentControllerChannels`:\n // a value import of that class from here recreates the module cycle\n // documented at the top of this file.)\n const controllerEntries: Array<[string, AgentChannels]> = [];\n const controllerOwned = new Set<AgentChannels>();\n for (const [controllerKey, controller] of Object.entries(this.#harnesses ?? {})) {\n const controllerChannels = controller.getChannels();\n if (controllerChannels) {\n controllerEntries.push([controllerKey, controllerChannels]);\n controllerOwned.add(controllerChannels);\n }\n }\n for (const [agentKey, agent] of Object.entries(this.#agents ?? {})) {\n const agentChannels = agent.getChannels();\n if (agentChannels instanceof AgentChannels && !controllerOwned.has(agentChannels)) {\n result[agentKey] = agentChannels;\n }\n }\n for (const [controllerKey, controllerChannels] of controllerEntries) {\n if (result[controllerKey]) {\n this.#logger?.warn(\n `Channels key collision: an agent and an agent controller are both registered under '${controllerKey}'; reporting the controller's channels.`,\n );\n }\n result[controllerKey] = controllerChannels;\n }\n return result;\n }\n\n /**\n * Retrieves a registered agent by its unique ID.\n *\n * This method searches for an agent using its internal ID property. If no agent\n * is found with the given ID, it also attempts to find an agent using the ID as\n * a name.\n *\n * @throws {MastraError} When no agent is found with the specified ID\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * const assistant = mastra.getAgent('assistant');\n * const sameAgent = mastra.getAgentById(assistant.id);\n * ```\n */\n public getAgentById<TAgentName extends keyof TAgents>(id: TAgents[TAgentName]['id']): TAgents[TAgentName];\n public getAgentById<TAgentName extends keyof TAgents>(\n id: TAgents[TAgentName]['id'],\n version: { versionId: string } | { status?: 'draft' | 'published' },\n ): Promise<TAgents[TAgentName]>;\n public getAgentById<TAgentName extends keyof TAgents>(\n id: TAgents[TAgentName]['id'],\n version?: { versionId: string } | { status?: 'draft' | 'published' },\n ): TAgents[TAgentName] | Promise<TAgents[TAgentName]> {\n let agent = Object.values(this.#agents).find(a => a.id === id);\n\n if (!agent) {\n try {\n agent = this.getAgent(id as keyof TAgents) as TAgents[TAgentName];\n } catch {\n // do nothing\n }\n }\n\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_AGENT_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with id ${String(id)} not found`,\n details: {\n status: 404,\n agentId: String(id),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!version) {\n return agent as TAgents[TAgentName];\n }\n\n return this.resolveVersionedAgent(agent as TAgents[TAgentName], version);\n }\n\n /**\n * Resolve a versioned variant of an agent by applying stored overrides from the editor.\n *\n * Requires the editor package to be configured — throws\n * `MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP` if it is not.\n *\n * @param agent - The code-defined agent to resolve a version for.\n * @param version - Selects a version by ID or publication status.\n * @returns A forked agent instance with the stored overrides applied.\n */\n public async resolveVersionedAgent<TAgent extends Agent>(\n agent: TAgent,\n version: VersionSelector | { status?: 'draft' | 'published' },\n ): Promise<TAgent> {\n const editor = this.getEditor();\n\n if (!editor) {\n const error = new MastraError({\n id: 'MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Versioned agent lookup requires the editor package to be configured',\n details: {\n status: 400,\n agentId: agent.id,\n ...(version && 'versionId' in version ? { versionId: version.versionId } : {}),\n ...(version && 'status' in version && version.status ? { versionStatus: version.status } : {}),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return editor.agent.applyStoredOverrides(\n agent,\n 'versionId' in version ? version : { status: version.status ?? 'published' },\n ) as Promise<TAgent>;\n }\n\n /**\n * Returns all registered agents as a record keyed by their names.\n *\n * This method provides access to the complete registry of agents, allowing you to\n * iterate over them, check what agents are available, or perform bulk operations.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({ id: 'weather-agent', name: 'weather', model: 'openai/gpt-4o' }),\n * supportAgent: new Agent({ id: 'support-agent', name: 'support', model: 'openai/gpt-4o' })\n * }\n * });\n *\n * const allAgents = mastra.listAgents();\n * console.log(Object.keys(allAgents)); // ['weatherAgent', 'supportAgent']\n * ```\n */\n public listAgents() {\n return this.#agents;\n }\n\n /**\n * Get an AgentController hosted on this Mastra instance by its registration\n * key (the key it was registered under in `new Mastra({ agentControllers })`).\n * Returns `undefined` when none is registered under that key. Server route\n * handlers use this to create and drive sessions over HTTP.\n *\n * @example\n * ```typescript\n * const code = new AgentController({ id: 'code-controller', modes });\n * const mastra = new Mastra({ agentControllers: { code } });\n *\n * mastra.getAgentController('code'); // → the AgentController (by key)\n * ```\n */\n public getAgentController(key: string): AgentController<any> | undefined {\n return this.#harnesses[key];\n }\n\n /**\n * Get an AgentController hosted on this Mastra instance by its unique `id`\n * (the `id` passed to the `AgentController` constructor). Falls back to a\n * registration-key lookup when none matches by id, mirroring\n * {@link getAgentById}. Returns `undefined` when none is found.\n *\n * @example\n * ```typescript\n * const code = new AgentController({ id: 'code-controller', modes });\n * const mastra = new Mastra({ agentControllers: { code } });\n *\n * mastra.getAgentControllerById('code-controller'); // → by id\n * ```\n */\n public getAgentControllerById(id: string): AgentController<any> | undefined {\n return Object.values(this.#harnesses).find(controller => controller.id === id) ?? this.#harnesses[id];\n }\n\n /**\n * List all AgentControllers hosted on this Mastra instance, keyed by their\n * registration key.\n */\n public listAgentControllers(): Record<string, AgentController<any>> {\n return this.#harnesses;\n }\n\n /**\n * Get a Harness hosted on this Mastra instance by its registration key.\n *\n * @deprecated Use {@link Mastra.getAgentController} instead.\n */\n public getHarness(key: string): Harness<any> | undefined {\n return this.getAgentController(key);\n }\n\n /**\n * Get a Harness hosted on this Mastra instance by its unique `id`.\n *\n * @deprecated Use {@link Mastra.getAgentControllerById} instead.\n */\n public getHarnessById(id: string): Harness<any> | undefined {\n return this.getAgentControllerById(id);\n }\n\n /**\n * List all Harnesses hosted on this Mastra instance, keyed by their\n * registration key.\n *\n * @deprecated Use {@link Mastra.listAgentControllers} instead.\n */\n public listHarnesses(): Record<string, Harness<any>> {\n return this.listAgentControllers();\n }\n\n /**\n * Adds a new agent to the Mastra instance.\n *\n * This method allows dynamic registration of agents after the Mastra instance\n * has been created. The agent will be initialized with the current logger.\n *\n * @throws {MastraError} When an agent with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newAgent = new Agent({\n * id: 'chat-agent',\n * name: 'Chat Assistant',\n * model: 'openai/gpt-4o'\n * });\n * mastra.addAgent(newAgent); // Uses agent.id as key\n * // or\n * mastra.addAgent(newAgent, 'customKey'); // Uses custom key\n *\n * // Durable agents (e.g., InngestAgent) are also supported:\n * const durableAgent = createInngestAgent({ agent: newAgent, inngest });\n * mastra.addAgent(durableAgent); // Auto-registers required workflows\n * ```\n */\n public addAgent<A extends Agent | ToolLoopAgentLike | DurableAgentLike>(\n agent: A,\n key?: string,\n options?: { source?: DefinitionSource },\n ): void {\n if (!agent) {\n throw createUndefinedPrimitiveError('agent', agent, key);\n }\n\n // Auto-wrap regular Agents that opted in via AgentConfig.durable.\n // The wrapped agent then flows into the isDurableAgentLike branch below,\n // which handles __setMastra, workflow registration, and channel routes.\n //\n // Statically importing `createDurableAgent` here is safe because `agent.ts`\n // imports `Mastra` type-only, so there is no `agent → mastra` runtime edge\n // to close the init cycle. See the import note in `agent/agent.ts`.\n //\n // A standalone durable `Agent` satisfies `isDurableAgentLike` via a\n // self-referential `.agent` getter (see `Agent#agent`), so we must\n // discriminate against a real wrapper by checking `agent.agent !== agent`.\n // Real wrappers (e.g. `DurableAgent`, `InngestAgent`) point `.agent` at a\n // distinct inner `Agent`; the standalone placeholder points at itself.\n const isRealDurableWrapper = isDurableAgentLike(agent) && (agent as DurableAgentLike).agent !== (agent as unknown);\n if (!isRealDurableWrapper && (agent as Agent).durable) {\n const durableOption = (agent as Agent).durable;\n const opts = durableOption === true ? {} : { ...(durableOption as object) };\n agent = createDurableAgent({ agent: agent as Agent, ...opts }) as unknown as A;\n }\n\n // Handle durable agent wrappers (e.g., InngestAgent)\n // These wrap a regular Agent with execution engine-specific capabilities\n if (isDurableAgentLike(agent)) {\n const durableAgent = agent as DurableAgentLike;\n const underlyingAgent = durableAgent.agent;\n const agentKey = key || durableAgent.id;\n\n // Check if already registered\n const agents = this.#agents as Record<string, Agent<any>>;\n if (agents[agentKey]) {\n const logger = this.getLogger();\n logger.debug(`Agent with key ${agentKey} already exists. Skipping addition.`);\n return;\n }\n\n // Set the Mastra instance on the durable agent for observability\n durableAgent.__setMastra?.(this);\n\n // Propagate the definition source (e.g. 'fs') onto both the wrapper and\n // the underlying agent. The durable branch returns early below, so it\n // never reaches the shared `options?.source` handling.\n if (options?.source) {\n (durableAgent as unknown as Agent<any>).source = options.source;\n underlyingAgent.source = options.source;\n }\n\n // Initialize the underlying agent (needed for tools, memory, etc.)\n underlyingAgent.__setLogger(this.#logger);\n underlyingAgent.__registerMastra(this);\n underlyingAgent.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n\n // Store the durable wrapper in #agents (not the underlying agent)\n // This ensures getAgentById returns the wrapper so .stream() uses durable execution.\n // The cast is safe because DurableAgent extends Agent directly, and InngestAgent uses\n // a Proxy that forwards all Agent method calls to the underlying agent.\n agents[agentKey] = durableAgent as unknown as Agent<any>;\n\n // Register durable workflows if the wrapper provides them\n const durableWorkflows = durableAgent.getDurableWorkflows?.() ?? [];\n for (const workflow of durableWorkflows) {\n this.addWorkflow(workflow, workflow.id);\n }\n\n // 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 underlyingAgent\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 durable 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 (underlyingAgent.hasOwnWorkspace?.()) {\n Promise.resolve(underlyingAgent.getWorkspace?.())\n .then(workspace => {\n if (workspace) {\n this.addWorkspace(workspace, undefined, {\n source: 'agent',\n agentId: durableAgent.id ?? agentKey,\n agentName: durableAgent.name,\n });\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register workspace for durable agent ${agentKey}:`, err);\n });\n }\n\n // Register scorers from the underlying agent so durable runs can resolve\n // them via mastra.getScorer()/getScorerById() at workflow time.\n underlyingAgent\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 durable agent ${agentKey}:`, err);\n });\n\n // Register durable-agent-owned tools with the background task manager.\n // Namespaced as `agentId:toolName` to avoid cross-agent collisions.\n // Use agentKey (derived from durableAgent.id) rather than underlyingAgent.id\n // because the dispatch side uses the durable wrapper's identity.\n if (this.#backgroundTaskManager) {\n const durableAgentId = durableAgent.id ?? agentKey;\n Promise.resolve(underlyingAgent.listTools())\n .then(agentTools => {\n for (const [toolKey, tool] of Object.entries(agentTools || {})) {\n if (tool && typeof (tool as any).execute === 'function') {\n this.#registerToolWithBackgroundManager(\n `${durableAgentId}:${toolKey}`,\n tool as ToolAction<any, any, any, any>,\n );\n }\n }\n })\n .catch(err => {\n this.#logger?.debug(\n `Failed to register durable agent tools for background tasks (agent ${agentKey}):`,\n err,\n );\n });\n }\n\n // Set up AgentChannels for manual adapter configurations\n const agentChannelsInstance = underlyingAgent.getChannels();\n if (agentChannelsInstance) {\n agentChannelsInstance.__setLogger(this.#logger);\n const channelRoutes = agentChannelsInstance.getWebhookRoutes();\n if (channelRoutes.length > 0) {\n this.#server = {\n ...this.#server,\n apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n };\n }\n agentChannelsInstance.initialize(this).catch(err => {\n this.#logger?.error(`Failed to initialize channels for durable agent ${agentKey}:`, err);\n });\n }\n\n return;\n }\n\n let mastraAgent: Agent<any, any, any>;\n if (isToolLoopAgentLike(agent)) {\n // Pass the config key as the name if the ToolLoopAgent doesn't have an id\n mastraAgent = toolLoopAgentToMastraAgent(agent, { fallbackName: key });\n } else {\n mastraAgent = agent as Agent;\n }\n const agentKey = key || mastraAgent.id;\n const agents = this.#agents as Record<string, Agent<any>>;\n if (agents[agentKey]) {\n return;\n }\n\n // Initialize the agent\n mastraAgent.__setLogger(this.#logger);\n mastraAgent.__registerMastra(this);\n mastraAgent.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n\n // Set the source if provided\n if (options?.source) {\n mastraAgent.source = options.source;\n }\n\n agents[agentKey] = mastraAgent;\n\n // Register configured processor workflows from the agent\n // Use .then() to handle async resolution without blocking the constructor\n // This excludes memory-derived processors to avoid triggering memory factory functions\n mastraAgent\n .getConfiguredProcessorWorkflows()\n .then(processorWorkflows => {\n for (const workflow of processorWorkflows) {\n this.addWorkflow(workflow, workflow.id);\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register processor workflows for agent ${agentKey}:`, err);\n });\n\n // Register agent workspace in the workspaces registry for direct lookup.\n // Dynamic workspace functions may return undefined without request context — that's fine,\n // the if (workspace) guard below will skip registration and they'll register lazily later.\n if (mastraAgent.hasOwnWorkspace?.()) {\n Promise.resolve(mastraAgent.getWorkspace?.())\n .then(workspace => {\n if (workspace) {\n this.addWorkspace(workspace, undefined, {\n source: 'agent',\n agentId: mastraAgent.id ?? agentKey,\n agentName: mastraAgent.name,\n });\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register workspace for agent ${agentKey}:`, err);\n });\n }\n\n // Register scorers from the agent to the Mastra instance\n // This makes agent-level scorers discoverable via mastra.getScorer()/getScorerById()\n mastraAgent\n .listScorers()\n .then(scorers => {\n for (const [, entry] of Object.entries(scorers || {})) {\n this.addScorer(entry.scorer, undefined, { source: 'code' });\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register scorers from agent ${agentKey}:`, err);\n });\n\n // Register agent-owned tools with the background task manager's static\n // executor registry so cross-process workers can resolve dispatched tasks\n // for tools that are only attached to an agent (not top-level on Mastra).\n // Keys are namespaced as `agentId:toolName` to avoid cross-agent collisions\n // when multiple agents define tools with the same config key.\n // Dynamic (function-based) tools are resolved lazily and cannot be\n // eagerly registered — only static tool records are wired here.\n if (this.#backgroundTaskManager) {\n const agentId = mastraAgent.id ?? agentKey;\n Promise.resolve(mastraAgent.listTools())\n .then(agentTools => {\n for (const [toolKey, tool] of Object.entries(agentTools || {})) {\n if (tool && typeof (tool as any).execute === 'function') {\n this.#registerToolWithBackgroundManager(`${agentId}:${toolKey}`, tool as ToolAction<any, any, any, any>);\n }\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register agent tools for background tasks (agent ${agentKey}):`, err);\n });\n }\n\n // Set up AgentChannels for manual adapter configurations\n const agentChannelsInstance = mastraAgent.getChannels();\n if (agentChannelsInstance) {\n agentChannelsInstance.__setLogger(this.#logger);\n const channelRoutes = agentChannelsInstance.getWebhookRoutes();\n if (channelRoutes.length > 0) {\n this.#server = {\n ...this.#server,\n apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n };\n }\n agentChannelsInstance.initialize(this).catch(err => {\n this.#logger?.error(`Failed to initialize channels for agent ${agentKey}:`, err);\n });\n }\n }\n\n /**\n * Registers a map of file-system routed agents (discovered from\n * `agents/<name>/` directories) into this Mastra instance.\n *\n * Code-registered agents win on name collisions: if an agent with the same\n * key already exists, the file-system agent is skipped and a warning is\n * logged. Otherwise each agent is added via {@link addAgent} with\n * `source: 'fs'`.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsAgents(fsAgents: Record<string, Agent | ToolLoopAgentLike | DurableAgentLike>): void {\n if (!fsAgents) {\n return;\n }\n\n const agents = this.#agents as Record<string, Agent<any>>;\n for (const [key, agent] of Object.entries(fsAgents)) {\n if (agent == null) {\n continue;\n }\n if (agents[key]) {\n this.getLogger().warn(\n `File-system routed agent \"${key}\" conflicts with a code-registered agent of the same name. Keeping the code-registered agent.`,\n );\n continue;\n }\n this.addAgent(agent, key, { source: 'fs' });\n }\n }\n\n /**\n * Registers a map of file-system routed workflows (discovered from\n * `workflows/*.ts` files) into this Mastra instance.\n *\n * Code-registered workflows win on name collisions: if a workflow with the\n * same key already exists, the file-system workflow is skipped and a warning\n * is logged. Otherwise each workflow is added via {@link addWorkflow} with\n * its key.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsWorkflows(fsWorkflows: Record<string, AnyWorkflow>): void {\n if (!fsWorkflows) {\n return;\n }\n\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n for (const [key, workflow] of Object.entries(fsWorkflows)) {\n if (workflow == null) {\n continue;\n }\n if (workflows[key]) {\n this.getLogger().warn(\n `File-system routed workflow \"${key}\" conflicts with a code-registered workflow of the same name. Keeping the code-registered workflow.`,\n );\n continue;\n }\n this.addWorkflow(workflow, key);\n }\n }\n\n /**\n * Registers a file-system routed logger (discovered from `logger.ts`) into\n * this Mastra instance.\n *\n * Code-registered loggers win: if the user already passed `logger` to the\n * `new Mastra({logger})` constructor (including `logger: false`), the\n * file-system logger is skipped and a warning is logged. Otherwise the\n * fs-provided logger replaces the default ConsoleLogger via {@link setLogger}.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsLogger(fsLogger: TLogger): void {\n if (!fsLogger) {\n return;\n }\n\n if (this.#loggerExplicit) {\n this.getLogger().warn(\n `File-system routed logger conflicts with a code-registered logger. Keeping the code-registered logger.`,\n );\n return;\n }\n\n this.setLogger({ logger: fsLogger });\n }\n\n /**\n * Registers a file-system routed storage instance (discovered from\n * `storage.ts`) into this Mastra instance.\n *\n * Code-registered storage wins: if the user already passed `storage` to the\n * `new Mastra({storage})` constructor, the file-system storage is skipped\n * and a warning is logged. Otherwise the fs-provided storage replaces the\n * default InMemoryStore via {@link setStorage}.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsStorage(fsStorage: MastraCompositeStore): void {\n if (!fsStorage) {\n return;\n }\n\n if (this.#storageExplicit) {\n this.getLogger().warn(\n `File-system routed storage conflicts with a code-registered storage. Keeping the code-registered storage.`,\n );\n return;\n }\n\n this.setStorage(fsStorage);\n }\n\n /**\n * Registers a file-system routed observability instance (discovered from\n * `observability.ts`) into this Mastra instance.\n *\n * Code-registered observability wins: if the user already passed\n * `observability` to the `new Mastra({observability})` constructor, the\n * file-system instance is skipped with a warning.\n *\n * @internal\n */\n public __registerFsObservability(fsObservability: ObservabilityEntrypoint): void {\n if (!fsObservability) {\n return;\n }\n\n if (this.#observabilityExplicit) {\n this.getLogger().warn(\n `File-system routed observability conflicts with a code-registered observability. Keeping the code-registered observability.`,\n );\n return;\n }\n\n if (typeof fsObservability.getDefaultInstance !== 'function') {\n this.getLogger().warn(\n `File-system routed observability.ts did not export a valid ObservabilityEntrypoint. Ignoring.`,\n );\n return;\n }\n\n this.#observability = fsObservability;\n // Pass the raw logger (not the DualLogger) to observability to avoid\n // circular forwarding, mirroring setLogger().\n const rawLogger = this.#logger instanceof DualLogger ? this.#logger.baseLogger : this.#logger;\n this.#observability.setLogger({ logger: rawLogger as any });\n this.#observability.setMastraContext({ mastra: this as any });\n }\n\n /**\n * Registers a file-system routed server config (discovered from\n * `server.ts`) into this Mastra instance.\n *\n * Code-registered server config wins on collision.\n *\n * @internal\n */\n public __registerFsServer(fsServer: ServerConfig): void {\n if (!fsServer) {\n return;\n }\n\n if (this.#serverExplicit) {\n this.getLogger().warn(\n `File-system routed server config conflicts with a code-registered server config. Keeping the code-registered server config.`,\n );\n return;\n }\n\n // Preserve apiRoutes accumulated during construction (e.g. channel\n // webhook routes) — they live on #server even when the user never\n // passed a server config explicitly.\n const existingRoutes = this.#server?.apiRoutes ?? [];\n const fsRoutes = fsServer.apiRoutes ?? [];\n const mergedRoutes = [...existingRoutes, ...fsRoutes];\n this.setServer({\n ...fsServer,\n ...(mergedRoutes.length > 0 ? { apiRoutes: mergedRoutes } : {}),\n });\n }\n\n /**\n * Registers a file-system routed studio config (discovered from\n * `studio.ts`) into this Mastra instance.\n *\n * Code-registered studio config wins on collision.\n *\n * @internal\n */\n public __registerFsStudio(fsStudio: StudioConfig): void {\n if (!fsStudio) {\n return;\n }\n\n if (this.#studioExplicit) {\n this.getLogger().warn(\n `File-system routed studio config conflicts with a code-registered studio config. Keeping the code-registered studio config.`,\n );\n return;\n }\n\n this.setStudio(fsStudio);\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 * Removes a registered workspace by its ID.\n *\n * When `destroy` is true, the workspace is destroyed before it is removed from\n * the registry. If destruction fails, the workspace remains registered and the\n * error is rethrown.\n *\n * @example\n * ```typescript\n * await mastra.removeWorkspace('workspace-123', { destroy: true });\n * ```\n */\n public async removeWorkspace(id: string, options?: { destroy?: boolean }): Promise<boolean> {\n const entry = this.#workspaces[id];\n if (!entry) {\n return false;\n }\n\n if (options?.destroy) {\n await entry.workspace.destroy();\n }\n\n delete this.#workspaces[id];\n\n if (this.#workspace === entry.workspace) {\n this.#workspace = undefined;\n }\n\n return true;\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 /**\n * Register a workflow under an internal-only registry.\n *\n * - Without `runId`: stored at the bare `${id}` slot. Used by single-instance\n * internal workflows (background tasks, score-traces) that are looked up\n * without a runId.\n * - With `runId`: stored *only* at `${id}:${runId}`. Concurrent or nested\n * invocations that share a workflow id (e.g. a parent and a sub-agent both\n * registering their `agentic-loop`) each get their own closure-bound\n * instance keyed by run, and the bare `${id}` slot is never overwritten by\n * a run-scoped registration — so a run-scoped lookup can never resolve a\n * *different* run's instance via an id scan.\n */\n __registerInternalWorkflow(workflow: AnyWorkflow, runId?: string) {\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n });\n if (runId) {\n const key = `${workflow.id}:${runId}`;\n const isNewRegistration = !this.#internalMastraWorkflows[key];\n this.#internalMastraWorkflows[key] = workflow;\n this.#runScopedWorkflowTimestamps.set(key, { registeredAt: Date.now(), runId });\n // Pair the registration with a runScope. Multiple workflows can share a\n // runId (parent + nested); we refcount so the scope outlives the first\n // unregister and dies with the last.\n if (isNewRegistration) {\n this.#runScopeRefcounts.set(runId, (this.#runScopeRefcounts.get(runId) ?? 0) + 1);\n if (!this.#runScopes.has(runId)) {\n this.#runScopes.set(runId, createRunScope());\n }\n }\n this.#sweepStaleRunScopedWorkflows();\n } else {\n this.#internalMastraWorkflows[workflow.id] = workflow;\n }\n }\n\n /**\n * Remove a runId-scoped registration. The unscoped `${id}` entry is left intact\n * so single-instance callers (background tasks, score-traces) continue to resolve.\n *\n * Decrements the refcount for the runScope tied to this runId; when the\n * count hits zero the scope is dropped along with every reference it held.\n */\n __unregisterInternalWorkflow(id: string, runId: string) {\n const key = `${id}:${runId}`;\n const wasRegistered = !!this.#internalMastraWorkflows[key];\n delete this.#internalMastraWorkflows[key];\n this.#runScopedWorkflowTimestamps.delete(key);\n if (wasRegistered) {\n this.#releaseRunScope(runId);\n }\n }\n\n /**\n * Get the existing runScope for a runId without creating one.\n * Returns undefined when no internal workflow has been registered against\n * the runId — callers should treat this as the run not yet being bootstrapped.\n */\n __getRunScope(runId: string): RunScope | undefined {\n return this.#runScopes.get(runId);\n }\n\n /**\n * Idempotently allocate a runScope for a runId. Used by call sites (like\n * `loop()`) that need to populate the scope *before* the internal workflow\n * registration lands. The scope is held until the matching internal-workflow\n * registration is released or the TTL sweep evicts it.\n *\n * Bumps the refcount so the scope cannot be freed before the caller is done\n * with it; callers MUST pair this with `__releaseRunScope(runId)`.\n */\n __createRunScope(runId: string): RunScope {\n let scope = this.#runScopes.get(runId);\n if (!scope) {\n scope = createRunScope();\n this.#runScopes.set(runId, scope);\n }\n this.#runScopeRefcounts.set(runId, (this.#runScopeRefcounts.get(runId) ?? 0) + 1);\n return scope;\n }\n\n /**\n * Decrement the runScope refcount; drops the scope when the count reaches\n * zero. Public so callers that called `__createRunScope` directly (e.g.,\n * `loop()` hydration) can release their hold without unregistering a\n * workflow.\n */\n __releaseRunScope(runId: string): void {\n this.#releaseRunScope(runId);\n }\n\n #releaseRunScope(runId: string): void {\n const next = (this.#runScopeRefcounts.get(runId) ?? 0) - 1;\n if (next <= 0) {\n this.#runScopeRefcounts.delete(runId);\n this.#runScopes.delete(runId);\n } else {\n this.#runScopeRefcounts.set(runId, next);\n }\n }\n\n __hasInternalWorkflow(id: string, runId?: string): boolean {\n if (runId) {\n // Only the exact run-scoped entry or the genuinely-unscoped slot — never\n // another run's `${id}:${otherRunId}` registration.\n return !!this.#internalMastraWorkflows[`${id}:${runId}`] || !!this.#internalMastraWorkflows[id];\n }\n return !!this.#internalMastraWorkflows[id];\n }\n\n /**\n * Returns `true` when this Mastra instance can resolve the workflow\n * identified by `workflowId` + `runId`. Mirrors the resolution order in\n * the WEP's `#dispatch` — internal registry → nested (parentWorkflow\n * present) → public registry — without side-effects.\n *\n * Used by the push-subscription guard in {@link startWorkers} to drop\n * cross-process events for internal workflows that belong to another\n * process.\n */\n #ownsWorkflow(workflowId: string, runId: string, parentWorkflow: unknown): boolean {\n // 1. Internal registry (run-scoped execution-workflow, agentic-loop, etc.)\n if (this.__hasInternalWorkflow(workflowId, runId)) return true;\n // 2. Nested workflow — walk up the parentWorkflow chain to the root and\n // verify that the root workflow is owned by this instance. Without this\n // check, cross-process subscribers would process foreign nested events\n // (the parentWorkflow field is truthy on both processes) and publish\n // spurious workflow.fail events that kill the correct owner's run.\n if (parentWorkflow) {\n let root = parentWorkflow as { workflowId?: string; runId?: string; parentWorkflow?: unknown };\n while (root.parentWorkflow) {\n root = root.parentWorkflow as typeof root;\n }\n const rootId = root.workflowId as string | undefined;\n const rootRunId = root.runId as string | undefined;\n if (rootId && rootRunId) {\n return this.#ownsWorkflow(rootId, rootRunId, undefined);\n }\n // Malformed chain — fall through to public registry check below.\n }\n // 3. Public workflow registry — direct lookup to avoid telemetry noise\n // from getWorkflowById() on the expected \"foreign workflow\" path.\n const workflows = this.#workflows as Record<string, AnyWorkflow> | undefined;\n if (workflows?.[workflowId]) return true;\n return Object.values(workflows ?? {}).some(w => w.id === workflowId);\n }\n\n __getInternalWorkflow(id: string, runId?: string): AnyWorkflow {\n const workflow = runId\n ? (this.#internalMastraWorkflows[`${id}:${runId}`] ?? this.#internalMastraWorkflows[id])\n : this.#internalMastraWorkflows[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 * @internal Records the tracing context for an evented workflow run so the\n * event processor can nest step spans under the run's parent span. The\n * `currentSpan` is non-serializable, so it is held here rather than passed\n * through the engine's pubsub events.\n */\n __registerRunTracingContext(runId: string, tracingContext: TracingContext) {\n this.#runTracingContexts.set(runId, tracingContext);\n }\n\n /** @internal Returns the tracing context recorded for an evented workflow run. */\n __getRunTracingContext(runId: string): TracingContext | undefined {\n return this.#runTracingContexts.get(runId);\n }\n\n /** @internal Clears the tracing context once an evented workflow run finishes. */\n __unregisterRunTracingContext(runId: string) {\n this.#runTracingContexts.delete(runId);\n }\n\n /**\n * Lazily evict run-scoped internal workflow entries that have exceeded\n * {@link Mastra.INTERNAL_WORKFLOW_TTL_MS}. Called on every new run-scoped\n * registration so cleanup is proportional to activity — zero overhead when\n * the system is idle.\n */\n #sweepStaleRunScopedWorkflows() {\n const now = Date.now();\n for (const [key, entry] of this.#runScopedWorkflowTimestamps) {\n if (now - entry.registeredAt > Mastra.INTERNAL_WORKFLOW_TTL_MS) {\n delete this.#internalMastraWorkflows[key];\n this.#runScopedWorkflowTimestamps.delete(key);\n // Release the matching scope using the runId we stored at registration\n // time — never parse it back out of the composite key, since callers\n // can pass runIds that contain ':'.\n this.#releaseRunScope(entry.runId);\n // Surface the eviction so operators can investigate long-suspended\n // runs that never resumed. The refcounted lifecycle in\n // `__createRunScope`/`__releaseRunScope` covers the happy path; this\n // branch only fires when a registration was abandoned past the TTL.\n this.#logger.warn('Evicted stale run-scoped workflow after TTL expired', {\n runId: entry.runId,\n ageMs: now - entry.registeredAt,\n ttlMs: Mastra.INTERNAL_WORKFLOW_TTL_MS,\n });\n }\n }\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 const activeRunsByWorkflow = await Promise.all(\n defaultEngineWorkflows.map(workflow => workflow.listActiveWorkflowRuns()),\n );\n\n const allRuns = activeRunsByWorkflow.flatMap(activeRuns => activeRuns.runs);\n const allTotal = activeRunsByWorkflow.reduce((total, activeRuns) => total + activeRuns.total, 0);\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 * The resolved boot-time recovery configuration for this Mastra instance.\n * See {@link Config.recovery}.\n */\n get recoveryConfig(): MastraRecoveryConfig {\n return this.#recoveryConfig;\n }\n\n /**\n * Re-drive every orphaned RUNNING durable-agent run across every registered\n * `DurableAgent`. Delegates to `DurableAgent.recoverActiveRuns()` on each\n * agent that supports it (default-engine durable agents only — Inngest and\n * other externally-executed durable wrappers run their own recovery).\n *\n * Intended to be called once on server boot, after\n * `restartAllActiveWorkflowRuns()`. The deployer wires this up automatically\n * when `recovery.durableAgents` is set to `'auto'` in the Mastra config; you\n * can also call it directly if you need finer control (e.g. running it in a\n * cron, or gating it behind a leader election).\n *\n * Requires persistent storage — with an in-memory store there is nothing to\n * recover after a process restart, so this is a no-op and returns zeroed\n * counts.\n */\n public async recoverAllDurableAgents(): Promise<{\n agents: number;\n recovered: number;\n succeeded: number;\n failed: number;\n }> {\n if (!this.#storage) {\n this.#logger.debug('Cannot recover durable agents. Mastra storage is not initialized');\n return { agents: 0, recovered: 0, succeeded: 0, failed: 0 };\n }\n\n const durableAgents: DurableAgentLike[] = [];\n for (const agent of Object.values(this.#agents ?? {})) {\n if (agent && isDurableAgentLike(agent)) {\n durableAgents.push(agent);\n }\n }\n\n if (durableAgents.length === 0) {\n return { agents: 0, recovered: 0, succeeded: 0, failed: 0 };\n }\n\n this.#logger.debug(\n `Recovering active durable-agent runs across ${durableAgents.length} agent${durableAgents.length > 1 ? 's' : ''}`,\n );\n\n let recovered = 0;\n let succeeded = 0;\n let failed = 0;\n\n for (const agent of durableAgents) {\n try {\n const result = await agent.recoverActiveRuns();\n recovered += result.recovered.length;\n succeeded += result.succeeded;\n failed += result.failed;\n } catch (error) {\n this.#logger.error('Failed to recover active runs for durable agent', {\n agentId: agent.id,\n error,\n });\n }\n }\n\n return { agents: durableAgents.length, recovered, succeeded, failed };\n }\n\n /**\n * Returns all registered scorers as a record keyed by their IDs.\n *\n * @example Listing all scorers\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer, RelevanceScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer(),\n * accuracy: new AccuracyScorer(),\n * relevance: new RelevanceScorer()\n * }\n * });\n *\n * const allScorers = mastra.listScorers();\n * console.log(Object.keys(allScorers)); // ['helpfulness', 'accuracy', 'relevance']\n *\n * // Check scorer configurations\n * for (const [id, scorer] of Object.entries(allScorers)) {\n * console.log(`Scorer ${id}:`, scorer.id, scorer.name, scorer.description);\n * }\n * ```\n */\n public listScorers() {\n return this.#scorers;\n }\n\n /**\n * Adds a new scorer to the Mastra instance.\n *\n * This method allows dynamic registration of scorers after the Mastra instance\n * has been created.\n *\n * If a scorer with the same key already exists, this method leaves the existing\n * scorer registered and returns.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newScorer = new MastraScorer({\n * id: 'quality-scorer',\n * name: 'Quality Scorer'\n * });\n * mastra.addScorer(newScorer); // Uses scorer.id as key\n * // or\n * mastra.addScorer(newScorer, 'customKey'); // Uses custom key\n * ```\n */\n public addScorer<S extends MastraScorer<any, any, any, any>>(\n scorer: S,\n key?: string,\n options?: { source?: DefinitionSource },\n ): void {\n if (!scorer) {\n throw createUndefinedPrimitiveError('scorer', scorer, key);\n }\n const scorerKey = key || scorer.id;\n const scorers = this.#scorers as Record<string, MastraScorer<any, any, any, any>>;\n if (scorers[scorerKey]) {\n return;\n }\n\n // Register Mastra instance with scorer to enable custom gateway access\n scorer.__registerMastra(this);\n\n // Set the source if provided\n if (options?.source) {\n scorer.source = options.source;\n }\n\n scorers[scorerKey] = scorer;\n }\n\n /**\n * Retrieves a registered scorer by its key.\n *\n * @template TScorerKey - The specific scorer key type from the registered scorers\n * @throws {MastraError} When the scorer with the specified key is not found\n *\n * @example Getting and using a scorer\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer({\n * model: 'openai/gpt-4o',\n * criteria: 'Rate how helpful this response is'\n * }),\n * accuracy: new AccuracyScorer({\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Get a specific scorer\n * const helpfulnessScorer = mastra.getScorer('helpfulness');\n * const score = await helpfulnessScorer.score({\n * input: 'How do I reset my password?',\n * output: 'You can reset your password by clicking the forgot password link.',\n * expected: 'Detailed password reset instructions'\n * });\n *\n * console.log('Helpfulness score:', score);\n * ```\n */\n public getScorer<TScorerKey extends keyof TScorers>(key: TScorerKey): TScorers[TScorerKey] {\n const scorer = this.#scorers?.[key];\n if (!scorer) {\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with ${String(key)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return scorer;\n }\n\n /**\n * Retrieves a registered scorer by its name.\n *\n * This method searches through all registered scorers to find one with the specified name.\n * Unlike `getScorer()` which uses the registration key, this method uses the scorer's\n * internal name property.\n *\n * @throws {MastraError} When no scorer is found with the specified name\n *\n * @example Finding a scorer by name\n * ```typescript\n * import { HelpfulnessScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * myHelpfulnessScorer: new HelpfulnessScorer({\n * name: 'helpfulness-evaluator',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Find scorer by its internal name, not the registration key\n * const scorer = mastra.getScorerById('helpfulness-evaluator');\n * const score = await scorer.score({\n * input: 'question',\n * output: 'answer'\n * });\n * ```\n */\n public getScorerById<TScorerName extends keyof TScorers>(id: TScorers[TScorerName]['id']): TScorers[TScorerName] {\n for (const [_key, value] of Object.entries(this.#scorers ?? {})) {\n if (value.id === id || value?.name === id) {\n return value as TScorers[TScorerName];\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with id ${String(id)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Removes a scorer from the Mastra instance by its key or ID.\n *\n * @param keyOrId - The scorer key or ID to remove\n * @returns true if a scorer was removed, false if no scorer was found\n */\n public removeScorer(keyOrId: string): boolean {\n const scorers = this.#scorers as Record<string, MastraScorer<any, any, any, any>> | undefined;\n if (!scorers) return false;\n\n // Try direct key lookup first\n if (scorers[keyOrId]) {\n const scorerId = scorers[keyOrId]?.id;\n delete scorers[keyOrId];\n // Clear from stored scorers cache to prevent stale data\n if (scorerId) {\n this.#storedScorersCache.delete(scorerId);\n }\n return true;\n }\n\n // Try finding by ID or name\n const key = Object.keys(scorers).find(k => scorers[k]?.id === keyOrId || scorers[k]?.name === keyOrId);\n if (key) {\n const scorerId = scorers[key]?.id;\n delete scorers[key];\n // Clear from stored scorers cache to prevent stale data\n if (scorerId) {\n this.#storedScorersCache.delete(scorerId);\n }\n return true;\n }\n\n return false;\n }\n\n // =========================================================================\n // Prompt Blocks\n // =========================================================================\n\n /**\n * Returns all registered prompt blocks.\n */\n public listPromptBlocks(): Record<string, StorageResolvedPromptBlockType> {\n return this.#promptBlocks;\n }\n\n /**\n * Registers a prompt block in the Mastra instance's runtime registry.\n *\n * @param promptBlock - The resolved prompt block to register\n * @param key - Optional registration key (defaults to promptBlock.id)\n */\n public addPromptBlock(promptBlock: StorageResolvedPromptBlockType, key?: string): void {\n const blockKey = key || promptBlock.id;\n if (this.#promptBlocks[blockKey]) {\n return;\n }\n this.#promptBlocks[blockKey] = promptBlock;\n }\n\n /**\n * Retrieves a registered prompt block by its key.\n *\n * @throws {MastraError} When the prompt block with the specified key is not found\n */\n public getPromptBlock(key: string): StorageResolvedPromptBlockType {\n const block = this.#promptBlocks[key];\n if (!block) {\n throw new MastraError({\n id: 'MASTRA_GET_PROMPT_BLOCK_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Prompt block with key ${key} not found`,\n });\n }\n return block;\n }\n\n /**\n * Retrieves a registered prompt block by its ID.\n *\n * @throws {MastraError} When no prompt block is found with the specified ID\n */\n public getPromptBlockById(id: string): StorageResolvedPromptBlockType {\n for (const [, block] of Object.entries(this.#promptBlocks)) {\n if (block.id === id) {\n return block;\n }\n }\n\n throw new MastraError({\n id: 'MASTRA_GET_PROMPT_BLOCK_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Prompt block with id ${id} not found`,\n });\n }\n\n /**\n * Removes a prompt block from the Mastra instance by its key or ID.\n *\n * @param keyOrId - The prompt block key or ID to remove\n * @returns true if a prompt block was removed, false if not found\n */\n public removePromptBlock(keyOrId: string): boolean {\n if (this.#promptBlocks[keyOrId]) {\n delete this.#promptBlocks[keyOrId];\n return true;\n }\n\n const key = Object.keys(this.#promptBlocks).find(k => this.#promptBlocks[k]?.id === keyOrId);\n if (key) {\n delete this.#promptBlocks[key];\n return true;\n }\n\n return false;\n }\n\n /**\n * Retrieves a specific tool by registration key.\n *\n * @throws {MastraError} When the specified tool is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool,\n * weather: weatherTool\n * }\n * });\n *\n * const tool = mastra.getTool('calculator');\n * ```\n */\n public getTool<TToolName extends keyof TTools>(name: TToolName): TTools[TToolName] {\n if (!this.#tools || !this.#tools[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_TOOL_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with name ${String(name)} not found`,\n details: {\n status: 404,\n toolName: String(name),\n tools: Object.keys(this.#tools ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#tools[name];\n }\n\n /**\n * Retrieves a specific tool by its ID.\n *\n * @throws {MastraError} When the specified tool is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool\n * }\n * });\n *\n * const tool = mastra.getToolById('calculator-tool-id');\n * ```\n */\n public getToolById<TToolName extends keyof TTools>(id: TTools[TToolName]['id']): TTools[TToolName] {\n const allTools = this.#tools;\n\n if (!allTools) {\n throw new MastraError({\n id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with id ${id} not found`,\n });\n }\n // First try to find by internal ID\n for (const tool of Object.values(allTools)) {\n if (tool.id === id) {\n return tool as TTools[TToolName];\n }\n }\n\n // Fallback to searching by registration key\n const toolByKey = allTools[id];\n if (toolByKey) {\n return toolByKey as TTools[TToolName];\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with id ${id} not found`,\n details: {\n status: 404,\n toolId: String(id),\n tools: Object.keys(allTools).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Lists all configured tools.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool,\n * weather: weatherTool\n * }\n * });\n *\n * const tools = mastra.listTools();\n * Object.entries(tools || {}).forEach(([name, tool]) => {\n * console.log(`Tool \"${name}\":`, tool.id);\n * });\n * ```\n */\n public listTools(): TTools | undefined {\n return this.#tools;\n }\n\n /**\n * Adds a new tool to the Mastra instance.\n *\n * This method allows dynamic registration of tools after the Mastra instance\n * has been created.\n *\n * @throws {MastraError} When a tool with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newTool = createTool({\n * id: 'calculator-tool',\n * description: 'Performs calculations'\n * });\n * mastra.addTool(newTool); // Uses tool.id as key\n * // or\n * mastra.addTool(newTool, 'customKey'); // Uses custom key\n * ```\n */\n public addTool<T extends ToolAction<any, any, any, any>>(tool: T, key?: string): void {\n if (!tool) {\n throw createUndefinedPrimitiveError('tool', tool, key);\n }\n const toolKey = key || tool.id;\n const tools = this.#tools as Record<string, ToolAction<any, any, any, any>>;\n if (tools[toolKey]) {\n return;\n }\n\n tools[toolKey] = tool;\n\n // If the background-task manager has already initialized, register the\n // newly-added tool with its static registry so cross-process workers can\n // resolve dispatches for it. If init hasn't happened yet, the registry\n // will be populated wholesale in #ensureBackgroundTaskManager().\n if (this.#backgroundTaskManager) {\n this.#registerToolWithBackgroundManager(toolKey, tool);\n }\n }\n\n /**\n * Removes a tool from the Mastra instance by its registration key.\n *\n * Also unregisters the tool's static executor from the background task\n * manager, if one was registered.\n *\n * @returns `true` if a tool was removed, `false` if no tool was registered under the key\n *\n * @example\n * ```typescript\n * mastra.removeTool('calculator-tool');\n * ```\n */\n public removeTool(key: string): boolean {\n const tools = this.#tools as Record<string, ToolAction<any, any, any, any>>;\n if (!tools[key]) {\n return false;\n }\n delete tools[key];\n this.#backgroundTaskManager?.unregisterStaticExecutor(key);\n return true;\n }\n\n /**\n * Retrieves a specific processor by registration key.\n *\n * @throws {MastraError} When the specified processor is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor,\n * transformer: transformerProcessor\n * }\n * });\n *\n * const processor = mastra.getProcessor('validator');\n * ```\n */\n public getProcessor<TProcessorName extends keyof TProcessors>(name: TProcessorName): TProcessors[TProcessorName] {\n if (!this.#processors || !this.#processors[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with name ${String(name)} not found`,\n details: {\n status: 404,\n processorName: String(name),\n processors: Object.keys(this.#processors ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#processors[name];\n }\n\n /**\n * Retrieves a specific processor by its ID.\n *\n * @throws {MastraError} When the specified processor is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor\n * }\n * });\n *\n * const processor = mastra.getProcessorById('validator-processor-id');\n * ```\n */\n public getProcessorById<TProcessorName extends keyof TProcessors>(\n id: TProcessors[TProcessorName]['id'],\n ): TProcessors[TProcessorName] {\n const allProcessors = this.#processors;\n\n if (!allProcessors) {\n throw new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with id ${id} not found`,\n });\n }\n\n // First try to find by internal ID\n for (const processor of Object.values(allProcessors)) {\n if (processor.id === id) {\n return processor as TProcessors[TProcessorName];\n }\n }\n\n // Fallback to searching by registration key\n const processorByKey = allProcessors[id];\n if (processorByKey) {\n return processorByKey as TProcessors[TProcessorName];\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with id ${id} not found`,\n details: {\n status: 404,\n processorId: String(id),\n processors: Object.keys(allProcessors).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Lists all configured processors.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor,\n * transformer: transformerProcessor\n * }\n * });\n *\n * const processors = mastra.listProcessors();\n * Object.entries(processors || {}).forEach(([name, processor]) => {\n * console.log(`Processor \"${name}\":`, processor.id);\n * });\n * ```\n */\n public listProcessors(): TProcessors | undefined {\n return this.#processors;\n }\n\n /**\n * Adds a new processor to the Mastra instance.\n *\n * This method allows dynamic registration of processors after the Mastra instance\n * has been created.\n *\n * @throws {MastraError} When a processor with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newProcessor = {\n * id: 'text-processor',\n * processInput: async (messages) => messages\n * };\n * mastra.addProcessor(newProcessor); // Uses processor.id as key\n * // or\n * mastra.addProcessor(newProcessor, 'customKey'); // Uses custom key\n * ```\n */\n public addProcessor<P extends Processor>(processor: P, key?: string): void {\n if (!processor) {\n throw createUndefinedPrimitiveError('processor', processor, key);\n }\n const processorKey = key || processor.id;\n const processors = this.#processors as Record<string, Processor>;\n if (processors[processorKey]) {\n return;\n }\n\n // Register Mastra with the processor if it supports it\n if (typeof processor.__registerMastra === 'function') {\n processor.__registerMastra(this);\n }\n\n processors[processorKey] = processor;\n }\n\n /**\n * Registers a processor configuration with agent context.\n * This tracks which agents use which processors with what configuration.\n *\n * @param processor - The processor instance\n * @param agentId - The ID of the agent that uses this processor\n * @param type - Whether this is an input or output processor\n */\n public addProcessorConfiguration(processor: Processor, agentId: string, type: 'input' | 'output'): void {\n const processorId = processor.id;\n if (!this.#processorConfigurations.has(processorId)) {\n this.#processorConfigurations.set(processorId, []);\n }\n const configs = this.#processorConfigurations.get(processorId)!;\n\n // Check if this exact configuration already exists\n const exists = configs.some(c => c.agentId === agentId && c.type === type);\n if (!exists) {\n configs.push({ processor, agentId, type });\n }\n }\n\n /**\n * Gets all processor configurations for a specific processor ID.\n *\n * @param processorId - The ID of the processor\n * @returns Array of configurations with agent context\n */\n public getProcessorConfigurations(\n processorId: string,\n ): Array<{ processor: Processor; agentId: string; type: 'input' | 'output' }> {\n return this.#processorConfigurations.get(processorId) || [];\n }\n\n /**\n * Gets all processor configurations.\n *\n * @returns Map of processor IDs to their configurations\n */\n public listProcessorConfigurations(): Map<\n string,\n Array<{ processor: Processor; agentId: string; type: 'input' | 'output' }>\n > {\n return this.#processorConfigurations;\n }\n\n /**\n * Retrieves a registered memory instance by its registration key.\n *\n * @throws {MastraError} When the memory instance with the specified key is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * memory: {\n * chat: new Memory({ storage })\n * }\n * });\n *\n * const chatMemory = mastra.getMemory('chat');\n * ```\n */\n public getMemory<TMemoryName extends keyof TMemory>(name: TMemoryName): TMemory[TMemoryName] {\n if (!this.#memory || !this.#memory[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_MEMORY_BY_KEY_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Memory with key ${String(name)} not found`,\n details: {\n status: 404,\n memoryKey: String(name),\n memory: Object.keys(this.#memory ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#memory[name];\n }\n\n /**\n * Retrieves a registered memory instance by its ID.\n *\n * Searches through all registered memory instances and returns the one whose ID matches.\n *\n * @throws {MastraError} When no memory instance with the specified ID is found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * memory: {\n * chat: new Memory({ id: 'chat-memory', storage })\n * }\n * });\n *\n * const memory = mastra.getMemoryById('chat-memory');\n * ```\n */\n public getMemoryById(id: string): MastraMemory {\n const allMemory = this.#memory;\n if (allMemory) {\n for (const [, memory] of Object.entries(allMemory)) {\n if (memory.id === id) {\n return memory;\n }\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_MEMORY_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Memory with id ${id} not found`,\n details: {\n status: 404,\n memoryId: id,\n availableIds: Object.values(allMemory ?? {})\n .map(m => m.id)\n .join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Returns all registered memory instances as a record keyed by their names.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * memory: {\n * chat: new Memory({ storage }),\n * longTerm: new Memory({ storage })\n * }\n * });\n *\n * const allMemory = mastra.listMemory();\n * console.log(Object.keys(allMemory)); // ['chat', 'longTerm']\n * ```\n */\n public listMemory(): TMemory | undefined {\n return this.#memory;\n }\n\n /**\n * Adds a new memory instance to the Mastra instance.\n *\n * This method allows dynamic registration of memory instances after the Mastra instance\n * has been created.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const chatMemory = new Memory({\n * id: 'chat-memory',\n * storage: mastra.getStorage()\n * });\n * mastra.addMemory(chatMemory); // Uses memory.id as key\n * // or\n * mastra.addMemory(chatMemory, 'customKey'); // Uses custom key\n * ```\n */\n public addMemory<M extends MastraMemory>(memory: M, key?: string): void {\n if (!memory) {\n throw createUndefinedPrimitiveError('memory', memory, key);\n }\n const memoryKey = key || memory.id;\n const memoryRegistry = this.#memory as Record<string, MastraMemory>;\n if (memoryRegistry[memoryKey]) {\n return;\n }\n\n memory.__registerMastra(this);\n if (!memory.hasOwnStorage) {\n const storage = this.getStorage();\n if (storage) {\n memory.setStorage(storage);\n }\n }\n\n memoryRegistry[memoryKey] = memory;\n }\n\n /**\n * Returns all registered workflows as a record keyed by their IDs.\n *\n * @example Listing all workflows\n * ```typescript\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: createWorkflow({...}).commit(),\n * emailSender: createWorkflow({...}).commit(),\n * reportGenerator: createWorkflow({...}).commit()\n * }\n * });\n *\n * const allWorkflows = mastra.listWorkflows();\n * console.log(Object.keys(allWorkflows)); // ['dataProcessor', 'emailSender', 'reportGenerator']\n *\n * // Execute all workflows with sample data\n * for (const [id, workflow] of Object.entries(allWorkflows)) {\n * console.log(`Workflow ${id}:`, workflow.name);\n * // const result = await workflow.execute(sampleData);\n * }\n * ```\n */\n public listWorkflows(props: { serialized?: boolean } = {}): Record<string, Workflow> {\n const workflows = Object.fromEntries(\n Object.entries(this.#workflows).filter(([key]) => !this.#hiddenWorkflowKeys.has(key)),\n ) as Record<string, Workflow>;\n\n if (props.serialized) {\n return Object.entries(workflows).reduce((acc, [k, v]) => {\n return {\n ...acc,\n [k]: { name: v.name },\n };\n }, {});\n }\n return workflows;\n }\n\n /**\n * Adds a new workflow to the Mastra instance.\n *\n * This method allows dynamic registration of workflows after the Mastra instance\n * has been created. The workflow will be initialized with Mastra and primitives.\n *\n * @throws {MastraError} When a workflow with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newWorkflow = createWorkflow({\n * id: 'data-pipeline',\n * name: 'Data Pipeline'\n * }).commit();\n * mastra.addWorkflow(newWorkflow); // Uses workflow.id as key\n * // or\n * mastra.addWorkflow(newWorkflow, 'customKey'); // Uses custom key\n * ```\n */\n public addWorkflow(workflow: AnyWorkflow, key?: string): void {\n if (!workflow) {\n throw createUndefinedPrimitiveError('workflow', workflow, key);\n }\n const workflowKey = key || workflow.id;\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n if (workflows[workflowKey]) {\n return;\n }\n\n // Note on schedules: a workflow declaring a `schedule` is auto-promoted to\n // the evented engine by the `createWorkflow` factory. We don't reject default-\n // engine workflows that happen to carry schedule configs — those would only\n // exist if a user constructed `Workflow` directly, in which case they've\n // explicitly opted out of the factory's promotion behavior and we trust them.\n const scheduleConfigs = collectWorkflowScheduleConfigs(workflow);\n const hasSchedule = scheduleConfigs.length > 0;\n\n // Initialize the workflow with Mastra and primitives\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n });\n if (!workflow.committed) {\n workflow.commit();\n }\n workflows[workflowKey] = workflow;\n\n this.registerStaticWorkflowScorers(workflow);\n\n // If a schedule is declared, mark the flag and register into the\n // running scheduler worker (if already started).\n if (hasSchedule) {\n this.#hasScheduledWorkflow = true;\n const worker = this.#findSchedulerWorker();\n if (worker?.scheduler) {\n void (async () => {\n try {\n const schedulesStore = await this.#storage?.getStore('schedules');\n if (!schedulesStore) return;\n await this.registerDeclarativeSchedules(schedulesStore);\n } catch (error) {\n this.#logger?.error('Failed to register declarative schedule for workflow', {\n workflowId: workflow.id,\n error,\n });\n }\n })();\n }\n // If the worker doesn't exist yet (workers not started), schedules\n // will be registered when SchedulerWorker.init() runs.\n }\n }\n\n /**\n * Signal that a schedule has been registered imperatively at runtime\n * (e.g. `mastra.schedules.create()` after `startWorkers()`). Flips the\n * scheduler-requested flag and, if workers are already running,\n * lazily injects + starts both the scheduler and agent-schedule workers.\n *\n * @internal\n */\n async __ensureScheduleRuntimeReady(): Promise<void> {\n this.#schedulerRequested = true;\n if (this.#workersStarted) {\n await this.#ensureSchedulingWorkersStarted();\n }\n }\n\n /**\n * Signal that a deferred notification exists and the dispatcher schedule is\n * needed. Lazily upserts the dispatcher schedule row (imperative, non-`wf_`\n * id so declarative orphan-cleanup leaves it alone) and requests the\n * scheduler — mirroring `__ensureScheduleRuntimeReady()`. Idle apps that\n * never defer a notification never start the scheduler (see #18864).\n *\n * @internal\n */\n async __ensureNotificationDispatchReady(): Promise<void> {\n if (this.#notificationDispatchReady) return;\n if (this.#notificationDispatchConfig?.enabled === false) return;\n if (this.#workersDisabled) return;\n if (this.#schedulerConfig?.enabled === false) return;\n if (!this.#storage) return;\n\n try {\n const schedulesStore = await this.#storage.getStore('schedules');\n if (!schedulesStore) return;\n\n const desired = buildNotificationDispatchSchedule(this.#notificationDispatchConfig);\n const existing = await schedulesStore.getSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n if (!existing) {\n try {\n await schedulesStore.createSchedule(desired);\n } catch (err) {\n // Another instance may have created the row concurrently — only\n // rethrow if it's still missing.\n const raced = await schedulesStore.getSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n if (!raced) throw err;\n }\n } else {\n // Patch the row if the dispatch config changed across deploys.\n const patch: ScheduleUpdate = {};\n if (existing.cron !== desired.cron) {\n patch.cron = desired.cron;\n patch.nextFireAt = desired.nextFireAt;\n }\n if (!targetsEqual(existing.target, desired.target)) patch.target = desired.target;\n if (Object.keys(patch).length > 0) {\n await schedulesStore.updateSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID, patch);\n }\n }\n } catch (err) {\n // Leave #notificationDispatchReady unset so the next deferred\n // notification retries the upsert.\n this.#logger?.warn?.('Failed to ensure notification dispatch schedule', err as any);\n return;\n }\n\n this.#notificationDispatchReady = true;\n this.#schedulerRequested = true;\n if (this.#workersStarted) {\n await this.#ensureSchedulingWorkersStarted();\n }\n }\n\n /**\n * Lazily inject and start the SchedulerWorker (and AgentScheduleWorker when\n * needed) after `startWorkers()` has already run. Used by features that\n * surface a need for the scheduler at runtime (e.g.\n * `mastra.schedules.create()`). No-op when the scheduler is disabled, no\n * storage is configured, or the workers are already present.\n *\n * @internal\n */\n async #ensureSchedulingWorkersStarted(): Promise<void> {\n // Memoize the in-flight startup so concurrent callers can't both pass the\n // worker-existence checks and start duplicate workers (which would\n // double-subscribe to the scheduling topics on push-based pubsubs).\n if (!this.#schedulingWorkersStartPromise) {\n this.#schedulingWorkersStartPromise = this.#startSchedulingWorkers().finally(() => {\n this.#schedulingWorkersStartPromise = undefined;\n });\n }\n await this.#schedulingWorkersStartPromise;\n }\n\n async #startSchedulingWorkers(): Promise<void> {\n if (!this.#shouldEnableScheduler()) return;\n if (!this.#storage) return;\n\n const deps: WorkerDeps = {\n pubsub: this.#pubsub,\n storage: this.#storage,\n logger: this.#logger as unknown as IMastraLogger,\n mastra: this,\n };\n\n if (!this.#findSchedulerWorker()) {\n const sw = new SchedulerWorker(this.#schedulerConfig);\n sw.__registerMastra(this);\n this.#workers.push(sw);\n await sw.init(deps);\n await sw.start();\n }\n\n if (!this.#findAgentScheduleWorker()) {\n const { AgentScheduleWorker } = await import('../schedules/worker');\n const asw = new AgentScheduleWorker();\n asw.__registerMastra(this);\n this.#workers.push(asw);\n await asw.init(deps);\n await asw.start();\n }\n }\n\n /**\n * Detect agent-schedule rows in storage on boot. Used by\n * `#shouldEnableScheduler` to flip the scheduler-requested flag when\n * imperative agent schedules persisted from a previous process exist —\n * without this, a fresh boot with only DB-side agent schedules would skip\n * starting the scheduler and agent-schedule workers entirely.\n *\n * @internal\n */\n async #detectExistingAgentSchedules(): Promise<void> {\n if (this.#schedulerRequested) return;\n if (!this.#storage) return;\n try {\n const schedulesStore = await this.#storage.getStore('schedules');\n if (!schedulesStore) return;\n const existing = await schedulesStore.listSchedules({ ownerType: 'agent' });\n if (existing.length === 0) return;\n this.#schedulerRequested = true;\n } catch (err) {\n this.#logger?.warn?.('Failed to detect existing agent schedules on boot', err as any);\n }\n }\n\n /**\n * Detect the lazily-created notification dispatcher schedule row on boot.\n * A previous process upserts the row via `__ensureNotificationDispatchReady()`\n * when a deferred notification is created; a fresh boot must then start the\n * scheduler so pending deferred notifications still get dispatched.\n * Mirrors `#detectExistingAgentSchedules`.\n *\n * @internal\n */\n async #detectExistingNotificationDispatch(): Promise<void> {\n if (this.#schedulerRequested) return;\n if (this.#notificationDispatchConfig?.enabled === false) return;\n if (!this.#storage) return;\n try {\n const schedulesStore = await this.#storage.getStore('schedules');\n if (!schedulesStore) return;\n const existing = await schedulesStore.getSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n if (!existing) return;\n this.#schedulerRequested = true;\n } catch (err) {\n this.#logger?.warn?.('Failed to detect existing notification dispatch schedule on boot', err as any);\n }\n }\n\n private registerStaticWorkflowScorers(workflow: AnyWorkflow): void {\n for (const step of Object.values(workflow.steps ?? {})) {\n const scorers = step.scorers;\n if (!scorers || typeof scorers === 'function') {\n continue;\n }\n\n for (const [, entry] of Object.entries(scorers)) {\n this.addScorer(entry.scorer, undefined, { source: 'code' });\n }\n }\n }\n\n /**\n * Sets the storage provider for the Mastra instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n *\n * // Set PostgreSQL storage\n * mastra.setStorage(new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }));\n *\n * // Now agents can use memory with the storage\n * const agent = new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * memory: new Memory({ storage: mastra.getStorage() })\n * });\n * ```\n */\n public setStorage(storage: MastraCompositeStore) {\n this.#storage = augmentWithInit(storage);\n this.#storage?.__registerMastra?.(this as unknown as Parameters<NonNullable<typeof storage.__registerMastra>>[0]);\n this.#ensureBackgroundTaskManager();\n // If storage was attached after construction, the SchedulerWorker\n // will pick it up when startWorkers() is called.\n }\n\n public setLogger({ logger }: { logger: TLogger }) {\n // Wrap the new logger in a DualLogger to maintain dual-write to loggerVNext\n const dualLogger = new DualLogger(logger, () => this.loggerVNext);\n this.#logger = dualLogger as unknown as TLogger;\n\n if (this.#agents) {\n Object.keys(this.#agents).forEach(key => {\n this.#agents?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#deployer) {\n this.#deployer.__setLogger(this.#logger);\n }\n\n if (this.#tts) {\n Object.keys(this.#tts).forEach(key => {\n this.#tts?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#storage) {\n this.#storage.__setLogger(this.#logger);\n }\n\n if (this.#vectors) {\n Object.keys(this.#vectors).forEach(key => {\n this.#vectors?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#mcpServers) {\n Object.keys(this.#mcpServers).forEach(key => {\n this.#mcpServers?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#workflows) {\n Object.keys(this.#workflows).forEach(key => {\n this.#workflows?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#serverAdapter) {\n this.#serverAdapter.__setLogger(this.#logger);\n }\n\n if (this.#workspace) {\n this.#workspace.__setLogger(this.#logger);\n }\n\n if (this.#memory) {\n Object.keys(this.#memory).forEach(key => {\n this.#memory?.[key]?.__setLogger(this.#logger);\n });\n }\n\n // Pass the raw logger (not the DualLogger) to observability to avoid circular forwarding\n this.#observability.setLogger({ logger });\n }\n\n /**\n * Gets all registered text-to-speech (TTS) providers.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tts: {\n * openai: new OpenAITTS({\n * apiKey: process.env.OPENAI_API_KEY,\n * voice: 'alloy'\n * })\n * }\n * });\n *\n * const ttsProviders = mastra.getTTS();\n * const openaiTTS = ttsProviders?.openai;\n * if (openaiTTS) {\n * const audioBuffer = await openaiTTS.synthesize('Hello, world!');\n * }\n * ```\n */\n public getTTS() {\n return this.#tts;\n }\n\n /**\n * Gets the currently configured logger instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * logger: new PinoLogger({\n * name: 'MyApp',\n * level: 'info'\n * })\n * });\n *\n * const logger = mastra.getLogger();\n * logger.info('Application started');\n * logger.error('An error occurred', { error: 'details' });\n * ```\n */\n public getLogger() {\n return this.#logger;\n }\n\n /**\n * Gets the currently configured storage provider.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./data.db' })\n * });\n *\n * // Use the storage in agent memory\n * const agent = new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * memory: new Memory({\n * storage: mastra.getStorage()\n * })\n * });\n * ```\n */\n public getStorage() {\n return this.#storage;\n }\n\n get observability(): ObservabilityEntrypoint {\n return this.#observability;\n }\n\n /**\n * Structured logging API for observability.\n * Logs emitted via this API will not have trace correlation when used outside a span.\n * Use for startup logs, background jobs, or other non-traced scenarios.\n *\n * Note: For the infrastructure logger (IMastraLogger), use getLogger() instead.\n */\n get loggerVNext(): LoggerContext {\n return this.#observability.getDefaultInstance()?.getLoggerContext?.() ?? noOpLoggerContext;\n }\n\n /**\n * Direct metrics API for use outside trace context.\n * Metrics emitted via this API will not have auto correlation or cost context from spans.\n * Use for background jobs, startup metrics, or other non-traced scenarios.\n */\n get metrics(): MetricsContext {\n return this.#observability.getDefaultInstance()?.getMetricsContext?.() ?? noOpMetricsContext;\n }\n\n public getServerMiddleware() {\n return this.#serverMiddleware;\n }\n\n public getServerCache() {\n return this.#serverCache;\n }\n\n public setServerMiddleware(serverMiddleware: Middleware | Middleware[]) {\n if (typeof serverMiddleware === 'function') {\n this.#serverMiddleware = [\n {\n handler: serverMiddleware,\n path: '/api/*',\n },\n ];\n return;\n }\n\n if (!Array.isArray(serverMiddleware)) {\n const error = new MastraError({\n id: 'MASTRA_SET_SERVER_MIDDLEWARE_INVALID_TYPE',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Invalid middleware: expected a function or array, received ${typeof serverMiddleware}`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n this.#serverMiddleware = serverMiddleware.map(m => {\n if (typeof m === 'function') {\n return {\n handler: m,\n path: '/api/*',\n };\n }\n return {\n handler: m.handler,\n path: m.path || '/api/*',\n };\n });\n }\n\n public getServer() {\n return this.#server;\n }\n\n /**\n * Gets the Studio-specific authentication and authorization configuration.\n *\n * @returns The studio config, or undefined if not configured\n *\n * @example\n * ```typescript\n * const studioConfig = mastra.getStudio();\n * if (studioConfig?.auth) {\n * // Studio has separate auth configured\n * }\n * ```\n */\n public getStudio() {\n return this.#studio;\n }\n\n /**\n * Sets the server adapter for this Mastra instance.\n *\n * The server adapter provides access to the underlying server app (e.g., Hono, Express)\n * and allows users to call routes directly via `app.fetch()` instead of making HTTP requests.\n *\n * This is typically called by `createHonoServer` or similar factory functions during\n * server initialization.\n *\n * @param adapter - The server adapter instance (e.g., MastraServer from @mastra/hono or @mastra/express)\n *\n * @example\n * ```typescript\n * const app = new Hono();\n * const adapter = new MastraServer({ app, mastra });\n * mastra.setMastraServer(adapter);\n * ```\n */\n public setMastraServer(adapter: MastraServerBase): void {\n if (this.#serverAdapter) {\n this.#logger?.debug(\n 'Replacing existing server adapter. Only one adapter should be registered per Mastra instance.',\n );\n }\n this.#serverAdapter = adapter;\n // Inject the logger into the adapter\n if (this.#logger) {\n adapter.__setLogger(this.#logger);\n }\n }\n\n /**\n * Gets the server adapter for this Mastra instance.\n *\n * @returns The server adapter, or undefined if not set\n *\n * @example\n * ```typescript\n * const adapter = mastra.getMastraServer();\n * if (adapter) {\n * const app = adapter.getApp<Hono>();\n * }\n * ```\n */\n public getMastraServer(): MastraServerBase | undefined {\n return this.#serverAdapter;\n }\n\n /**\n * Gets the server app from the server adapter.\n *\n * This is a convenience method that calls `getMastraServer()?.getApp<T>()`.\n * Use this to access the underlying server framework's app instance (e.g., Hono, Express)\n * for direct operations like calling routes via `app.fetch()`.\n *\n * @template T - The expected type of the app (e.g., Hono, Express Application)\n * @returns The server app, or undefined if no adapter is set\n *\n * @example\n * ```typescript\n * // After createHonoServer() is called:\n * const app = mastra.getServerApp<Hono>();\n *\n * // Call routes directly without HTTP overhead\n * const response = await app?.fetch(new Request('http://localhost/health'));\n * const data = await response?.json();\n * ```\n */\n public getServerApp<T = unknown>(): T | undefined {\n return this.#serverAdapter?.getApp<T>();\n }\n\n public getBundlerConfig() {\n return this.#bundler;\n }\n\n public async listLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n transportId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_LIST_LOGS_BY_RUN_ID_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger?.listLogsByRunId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_BY_RUN_ID_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not configured or does not support listLogsByRunId operation',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return await this.#logger.listLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n });\n }\n\n public async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not set',\n details: {\n transportId,\n },\n });\n throw error;\n }\n\n return await this.#logger.listLogs(transportId, params);\n }\n\n /**\n * Gets all registered Model Context Protocol (MCP) server instances.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const mcpServers = mastra.getMCPServers();\n * if (mcpServers) {\n * const fsServer = mcpServers.filesystem;\n * const tools = await fsServer.listTools();\n * }\n * ```\n */\n public listMCPServers(): Record<string, MCPServerBase> | undefined {\n return this.#mcpServers;\n }\n\n /**\n * Adds a new MCP server to the Mastra instance.\n *\n * This method allows dynamic registration of MCP servers after the Mastra instance\n * has been created. The server will be initialized with ID, Mastra instance, and logger.\n *\n * @throws {MastraError} When an MCP server with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newServer = new FileSystemMCPServer({\n * rootPath: '/data'\n * });\n * mastra.addMCPServer(newServer); // Uses server.id as key\n * // or\n * mastra.addMCPServer(newServer, 'customKey'); // Uses custom key\n * ```\n */\n public addMCPServer<M extends MCPServerBase>(server: M, key?: string): void {\n if (!server) {\n throw createUndefinedPrimitiveError('mcp-server', server, key);\n }\n // If a key is provided, try to set it as the ID\n // The setId method will only update if the ID wasn't explicitly set by the user\n if (key) {\n server.setId(key);\n }\n\n // Now resolve the ID after potentially setting it\n const resolvedId = server.id;\n if (!resolvedId) {\n const error = new MastraError({\n id: 'MASTRA_ADD_MCP_SERVER_MISSING_ID',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'MCP server must expose an id or be registered under one',\n details: { status: 400 },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n const serverKey = key ?? resolvedId;\n const servers = this.#mcpServers as Record<string, MCPServerBase>;\n if (servers[serverKey]) {\n return;\n }\n\n // Initialize the server\n server.__registerMastra(this);\n server.__setLogger(this.getLogger());\n servers[serverKey] = server;\n }\n\n /**\n * Retrieves a specific MCP server instance by registration key.\n *\n * @throws {MastraError} When the specified MCP server is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({...})\n * }\n * });\n *\n * const fsServer = mastra.getMCPServer('filesystem');\n * const tools = await fsServer.listTools();\n * ```\n */\n public getMCPServer<TMCPServerName extends keyof TMCPServers>(\n name: TMCPServerName,\n ): TMCPServers[TMCPServerName] | undefined {\n if (!this.#mcpServers || !this.#mcpServers[name]) {\n this.#logger?.debug(`MCP server with name ${String(name)} not found`);\n return undefined as TMCPServers[TMCPServerName] | undefined;\n }\n return this.#mcpServers[name];\n }\n\n /**\n * Retrieves a specific Model Context Protocol (MCP) server instance by its logical ID.\n *\n * This method searches for an MCP server using its logical ID. If a version is specified,\n * it returns the exact version match. If no version is provided, it returns the server\n * with the most recent release date.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * id: 'fs-server',\n * version: '1.0.0',\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const fsServer = mastra.getMCPServerById('fs-server');\n * if (fsServer) {\n * const tools = await fsServer.listTools();\n * }\n * ```\n */\n public getMCPServerById<TMCPServerName extends keyof TMCPServers>(\n serverId: TMCPServers[TMCPServerName]['id'],\n version?: string,\n ): TMCPServers[TMCPServerName] | undefined {\n if (!this.#mcpServers) {\n return undefined;\n }\n\n const allRegisteredServers = Object.values(this.#mcpServers || {});\n\n const matchingLogicalIdServers = allRegisteredServers.filter(server => server.id === serverId);\n\n if (matchingLogicalIdServers.length === 0) {\n this.#logger?.debug(`No MCP servers found with logical ID: ${serverId}`);\n return undefined;\n }\n\n if (version) {\n const specificVersionServer = matchingLogicalIdServers.find(server => server.version === version);\n if (!specificVersionServer) {\n this.#logger?.debug(`MCP server with logical ID '${serverId}' found, but not version '${version}'.`);\n }\n return specificVersionServer as TMCPServers[TMCPServerName] | undefined;\n } else {\n // No version specified, find the one with the most recent releaseDate\n if (matchingLogicalIdServers.length === 1) {\n return matchingLogicalIdServers[0] as TMCPServers[TMCPServerName];\n }\n\n matchingLogicalIdServers.sort((a, b) => {\n // Ensure releaseDate exists and is a string before creating a Date object\n const dateAVal = a.releaseDate && typeof a.releaseDate === 'string' ? new Date(a.releaseDate).getTime() : NaN;\n const dateBVal = b.releaseDate && typeof b.releaseDate === 'string' ? new Date(b.releaseDate).getTime() : NaN;\n\n if (isNaN(dateAVal) && isNaN(dateBVal)) return 0;\n if (isNaN(dateAVal)) return 1; // Treat invalid/missing dates as older\n if (isNaN(dateBVal)) return -1; // Treat invalid/missing dates as older\n\n return dateBVal - dateAVal; // Sorts in descending order of time (latest first)\n });\n\n // After sorting, the first element should be the latest if its date is valid\n if (matchingLogicalIdServers.length > 0) {\n const latestServer = matchingLogicalIdServers[0];\n if (\n latestServer &&\n latestServer.releaseDate &&\n typeof latestServer.releaseDate === 'string' &&\n !isNaN(new Date(latestServer.releaseDate).getTime())\n ) {\n return latestServer as TMCPServers[TMCPServerName];\n }\n }\n this.#logger?.warn(\n `Could not determine the latest server for logical ID '${serverId}' due to invalid or missing release dates, or no servers left after filtering.`,\n );\n return undefined;\n }\n }\n\n public async addTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.subscribe(topic, listener);\n }\n\n public async removeTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.unsubscribe(topic, listener);\n }\n\n /**\n * Process a single workflow event. Shared entry point used by:\n * - pull-mode workers (OrchestrationWorker)\n * - in-process push pubsubs (EventEmitterPubSub) wired during startWorkers()\n * - HTTP push delivered to `POST /api/workers/events`\n *\n * Returns `{ ok: true }` on success; the caller should ack/return 2xx.\n * Returns `{ ok: false, retry: true }` on transient failure; the caller\n * should nack/return 5xx so the broker retries.\n */\n public async handleWorkflowEvent(event: Event): Promise<{ ok: true } | { ok: false; retry: boolean }> {\n if (!this.#workflowEventProcessor) {\n this.#workflowEventProcessor = new WorkflowEventProcessor({ mastra: this });\n }\n return this.#workflowEventProcessor.handle(event);\n }\n\n /**\n * Initialize and start workers. If `name` is provided, starts only\n * that worker. Otherwise starts all registered workers and subscribes\n * user-defined event listeners.\n */\n public async startWorkers(name?: string): Promise<void> {\n // Initialize storage before any read so adapters that open/create their\n // stores in init() are ready. The scheduler warm-up tick also persists a\n // workflow snapshot on start(), which can race a lazy init() that creates\n // `mastra_workflow_snapshot` (\"no such table\" on SQL stores, see #17905).\n // init() is idempotent and a no-op when disabled.\n if (this.#storage) {\n await this.#storage.init();\n }\n\n // Flip the scheduler-requested flag if any agent-schedule rows\n // exist in storage from a previous boot. Without this, a process\n // that boots with only DB-side agent schedules (no in-code declarative\n // schedules and no imperative `schedules.create()` calls yet) would\n // skip injecting the scheduler + agent-schedule workers entirely. This\n // reads the schedules store, so it must run after storage.init() above.\n if (!name) {\n await this.#detectExistingAgentSchedules();\n // Same idea for the notification dispatcher: a previous process may\n // have lazily created the dispatcher schedule row because deferred\n // notifications were in play.\n await this.#detectExistingNotificationDispatch();\n }\n\n // Lazily inject the SchedulerWorker + AgentScheduleWorker if the\n // scheduler should be enabled and they're not already registered.\n // This runs after all workflows have been registered (unlike the\n // constructor's default-workers block), so #hasScheduledWorkflow is\n // accurate.\n if (!name && this.#shouldEnableScheduler() && this.#storage) {\n if (!this.#findSchedulerWorker()) {\n const sw = new SchedulerWorker(this.#schedulerConfig);\n sw.__registerMastra(this);\n this.#workers.push(sw);\n }\n if (!this.#findAgentScheduleWorker()) {\n const { AgentScheduleWorker } = await import('../schedules/worker');\n const asw = new AgentScheduleWorker();\n asw.__registerMastra(this);\n this.#workers.push(asw);\n }\n }\n\n const deps: WorkerDeps = {\n pubsub: this.#pubsub,\n storage: this.#storage!,\n logger: this.#logger as unknown as IMastraLogger,\n mastra: this,\n };\n\n let targets: MastraWorker[];\n if (name) {\n targets = this.#workers.filter(w => w.name === name);\n if (targets.length === 0) {\n throw new Error(`Worker \"${name}\" not found. Available: ${this.#workers.map(w => w.name).join(', ')}`);\n }\n } else if (this.#workerFilter) {\n targets = this.#workers.filter(w => this.#workerFilter!.has(w.name));\n if (targets.length === 0) {\n this.#logger?.warn?.(\n `MASTRA_WORKERS=${[...this.#workerFilter].join(',')} did not match any registered workers (have: ${this.#workers.map(w => w.name).join(', ')})`,\n );\n }\n } else {\n targets = this.#workers;\n }\n\n // When explicitly starting the backgroundTasks worker (e.g.\n // `startWorkers('backgroundTasks')`), upgrade a producer-mode manager to\n // full mode so the worker can subscribe to dispatch events. Without this,\n // a manager created at construction time as 'producer' (because\n // MASTRA_WORKERS excluded backgroundTasks) would be reused by the worker\n // but never subscribe to the dispatch topic.\n if (\n name === 'backgroundTasks' &&\n this.#backgroundTaskManager &&\n this.#backgroundTaskManager.config.mode === 'producer'\n ) {\n await this.#backgroundTaskManager.shutdown();\n this.#backgroundTaskManager = undefined;\n this.#ensureBackgroundTaskManager('full');\n }\n\n for (const worker of targets) {\n await worker.init(deps);\n await worker.start();\n }\n\n // For push-mode pubsubs (e.g. EventEmitterPubSub) there is no\n // OrchestrationWorker pulling events — wire handleWorkflowEvent directly\n // to the pubsub so workflow events still get processed in-process.\n if (!name) {\n await this.#wirePushWorkflowSubscription();\n }\n\n // Subscribe user-defined event listeners (non-workflow topics, or legacy inline WEP)\n // Only when starting all workers (not when targeting a specific one).\n // Idempotent: skip pairs we've already subscribed.\n if (!name) {\n for (const topic in this.#events) {\n if (!this.#events[topic]) {\n continue;\n }\n\n const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];\n for (const listener of listeners) {\n const alreadySubscribed = this.#userEventSubscriptions.some(\n sub => sub.topic === topic && sub.cb === listener,\n );\n if (alreadySubscribed) continue;\n await this.#pubsub.subscribe(topic, listener);\n this.#userEventSubscriptions.push({ topic, cb: listener });\n }\n }\n }\n\n // Track that the boot path has executed at least once so subsequent\n // runtime signals (e.g. `mastra.schedules.create()`) know whether they need\n // to lazily inject + start additional workers themselves.\n this.#workersStarted = true;\n }\n\n /**\n * Wire `handleWorkflowEvent` directly to the pubsub when it is push-only\n * (no pull mode for an OrchestrationWorker to drive). Idempotent — no-op\n * when the pubsub supports pull or the subscription already exists.\n * Shared by `startWorkers()` and `__ensureExecutionWorkersStarted()`.\n */\n async #wirePushWorkflowSubscription(): Promise<void> {\n const modes = this.#pubsub.supportedModes ?? ['pull'];\n const pushOnly = modes.includes('push') && !modes.includes('pull');\n if (pushOnly && !this.#pushSubscription) {\n const cb: EventCallback = (event, ack, nack) => {\n // In cross-process push environments (e.g. UnixSocketPubSub),\n // every subscriber receives every event — including events for\n // internal workflows registered on a different process. Skip\n // events whose workflow exists in neither the internal nor the\n // public registry so only the owning process handles them.\n // Without this guard the WEP would publish workflow.fail,\n // propagating through workflows-finish and erroneously\n // terminating the correct process's run.\n const data = event.data as Record<string, unknown> | undefined;\n const wfId = data?.workflowId as string | undefined;\n const rId = data?.runId as string | undefined;\n if (wfId && rId && !this.#ownsWorkflow(wfId, rId, data?.parentWorkflow)) {\n if (ack) {\n void ack().catch(err => this.#logger?.error?.('Error acking skipped workflow event', err));\n }\n return;\n }\n\n void this.handleWorkflowEvent(event)\n .then(result => {\n if (result.ok) {\n if (ack) {\n return ack().catch(err =>\n this.#logger?.error?.('Error acking workflow event in push subscription', err),\n );\n }\n return;\n }\n // Non-ok result: ask the transport to redeliver (nack) when the\n // handle layer says retry. The WEP tracks per-event delivery\n // attempts and eventually returns `retry: false` to break the\n // loop and surface a terminal workflow.fail. For terminal\n // failures we ack so the event is dropped from the transport.\n if (result.retry) {\n if (nack) {\n return nack().catch(err =>\n this.#logger?.error?.('Error nacking workflow event in push subscription', err),\n );\n }\n // Transport does not support nack. Do NOT ack — acking a\n // retryable failure would drop the event and silently lose\n // the workflow run. Log and let the transport's own delivery\n // semantics decide (most non-ack transports redeliver until\n // explicitly acked).\n this.#logger?.error?.('Retryable workflow event cannot be requeued because nack is unavailable', {\n type: event.type,\n runId: event.runId,\n });\n return;\n }\n if (ack) {\n return ack().catch(err =>\n this.#logger?.error?.('Error acking terminal workflow event in push subscription', err),\n );\n }\n })\n .catch(err => this.#logger?.error?.('Unhandled error in workflow event push subscription', err));\n };\n await this.#pubsub.subscribe('workflows', cb);\n this.#pushSubscription = { topic: 'workflows', cb };\n }\n }\n\n /**\n * Ensure the execution-side machinery — the `orchestration` and\n * `backgroundTasks` workers, plus the push-mode workflow subscription —\n * is running. Called lazily by {@link BackgroundTaskManager} when a task\n * is dispatched or resumed, so background tasks execute in \"library mode\"\n * where nothing ever calls `startWorkers()` (no server, no `mastra dev`;\n * see #19339).\n *\n * Deliberately narrower than `startWorkers()`: it never injects or starts\n * the scheduler/agent-schedule workers and never subscribes user event\n * listeners — dispatching a background task must not boot cron machinery\n * as a side effect.\n *\n * Honors the same opt-outs as the rest of the worker lifecycle:\n * `workers: false` / `MASTRA_WORKERS=false` (standalone-worker topologies\n * run their own worker processes, so this instance must not start local\n * ones) and the `MASTRA_WORKERS` name filter.\n *\n * The fast path is its own `#executionWorkersStarted` flag, NOT\n * `#workersStarted` — the latter is set by any `startWorkers(name)` call,\n * including partial named starts (e.g. `startWorkers('backgroundTasks')`)\n * that never start the orchestration worker or push wiring, which would\n * leave dispatched tasks stuck again. The pass itself is idempotent\n * (per-worker `isRunning` checks, idempotent push wiring), so running it\n * once after a full `startWorkers()` boot is a cheap no-op.\n *\n * @internal\n */\n async __ensureExecutionWorkersStarted(): Promise<void> {\n if (this.#executionWorkersStarted) return;\n if (this.#workersDisabled) return;\n // Memoize the in-flight startup so concurrent first dispatches on a cold\n // instance share one start instead of racing worker.init()/start().\n // Cleared on settle so a dispatch after stopWorkers() can start again.\n if (!this.#executionWorkersStartPromise) {\n this.#executionWorkersStartPromise = this.#startExecutionWorkers().finally(() => {\n this.#executionWorkersStartPromise = undefined;\n });\n }\n await this.#executionWorkersStartPromise;\n }\n\n async #startExecutionWorkers(): Promise<void> {\n // Storage init is memoized (see augmentWithInit) — cheap when already run.\n if (this.#storage) {\n await this.#storage.init();\n }\n\n const deps: WorkerDeps = {\n pubsub: this.#pubsub,\n storage: this.#storage!,\n logger: this.#logger as unknown as IMastraLogger,\n mastra: this,\n };\n\n for (const worker of this.#workers) {\n if (worker.name !== 'orchestration' && worker.name !== 'backgroundTasks') continue;\n if (this.#workerFilter && !this.#workerFilter.has(worker.name)) continue;\n if (worker.isRunning) continue;\n await worker.init(deps);\n await worker.start();\n }\n\n await this.#wirePushWorkflowSubscription();\n this.#executionWorkersStarted = true;\n }\n\n /**\n * Stop all running workers and unsubscribe event listeners.\n */\n public async stopWorkers(): Promise<void> {\n // A background-task dispatch may have kicked off a lazy execution-worker\n // start (`__ensureExecutionWorkersStarted`) that is still in flight. Wait\n // for it so the teardown below covers what it started — otherwise the\n // start finishes after this method returns, leaving workers running and\n // subscriptions wired behind a \"stopped\" instance. Failures are already\n // logged by the start path; here they just mean there is less to stop.\n while (this.#executionWorkersStartPromise) {\n await this.#executionWorkersStartPromise.catch(() => {});\n }\n\n // Stop registered workers in reverse order\n for (const worker of [...this.#workers].reverse()) {\n if (worker.isRunning) {\n await worker.stop();\n }\n }\n\n // Tear down the in-process push subscription wired during startWorkers().\n if (this.#pushSubscription) {\n await this.#pubsub.unsubscribe(this.#pushSubscription.topic, this.#pushSubscription.cb);\n this.#pushSubscription = undefined;\n }\n\n // Unsubscribe only the (topic, listener) pairs we actually registered in\n // startWorkers() — keeps stopWorkers() symmetric with startWorkers() and\n // avoids unsubscribing listeners that startWorkers never owned.\n for (const { topic, cb } of this.#userEventSubscriptions) {\n await this.#pubsub.unsubscribe(topic, cb);\n }\n this.#userEventSubscriptions = [];\n\n await this.#pubsub.flush();\n this.#workersStarted = false;\n this.#executionWorkersStarted = false;\n }\n\n /**\n * Release the module-level hooks this instance registered in its constructor.\n * The scorer hook is added to a shared emitter that never drops handlers on\n * its own, so short-lived internal/ephemeral Mastras must call this on teardown\n * or their handler keeps firing (and failing to resolve the scorer) on every\n * scorer run for the rest of the process. Idempotent.\n * @internal\n */\n __unregisterHooks(): void {\n if (this.#onScorerHook) {\n deregisterHook(AvailableHooks.ON_SCORER_RUN, this.#onScorerHook);\n this.#onScorerHook = undefined;\n }\n }\n\n /**\n * @deprecated Use {@link Mastra.startWorkers} instead. Will be removed in a\n * future release.\n */\n public async startEventEngine(name?: string): Promise<void> {\n return this.startWorkers(name);\n }\n\n /**\n * @deprecated Use {@link Mastra.stopWorkers} instead. Will be removed in a\n * future release.\n */\n public async stopEventEngine(): Promise<void> {\n return this.stopWorkers();\n }\n\n /**\n * Retrieves a registered gateway by its key.\n *\n * @throws {MastraError} When the gateway with the specified key is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * gateways: {\n * myGateway: new CustomGateway()\n * }\n * });\n *\n * const gateway = mastra.getGateway('myGateway');\n * ```\n */\n public getGateway(key: string): MastraModelGatewayInterface {\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): MastraModelGatewayInterface {\n const gateways = this.#gateways ?? {};\n for (const gateway of Object.values(gateways)) {\n if (getGatewayId(gateway) === 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 => getGatewayId(g))\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 registration keys.\n *\n * Gateways can be plain objects that satisfy `MastraModelGatewayInterface` or\n * classes that extend `MastraModelGateway`.\n *\n * @example\n * ```typescript\n * import { createOpenAICompatible } from '@ai-sdk/openai-compatible-v6';\n * import { MastraModelGateway, type MastraModelGatewayInterface } from '@mastra/core/llm';\n *\n * const plainGateway: MastraModelGatewayInterface = {\n * id: 'plain-gateway',\n * name: 'Plain Gateway',\n * async fetchProviders() { return {}; },\n * buildUrl() { return undefined; },\n * async getApiKey() { return ''; },\n * resolveLanguageModel(args) { return createOpenAICompatible({ name: args.providerId, apiKey: args.apiKey }).chatModel(args.modelId); },\n * };\n *\n * class ClassGateway extends MastraModelGateway {\n * readonly id = 'class-gateway';\n * readonly name = 'Class Gateway';\n * // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.\n * }\n *\n * const mastra = new Mastra({\n * gateways: {\n * plain: plainGateway,\n * class: new ClassGateway(),\n * },\n * });\n *\n * const allGateways = mastra.listGateways();\n * console.log(Object.keys(allGateways ?? {})); // ['plain', 'class']\n * ```\n */\n public listGateways(): Record<string, MastraModelGatewayInterface> | 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 will be used as the key.\n *\n * @example Plain object gateway\n * ```typescript\n * import type { MastraModelGatewayInterface } from '@mastra/core/llm';\n *\n * const customGateway: MastraModelGatewayInterface = {\n * id: 'custom-gateway-v1',\n * name: 'Custom Gateway',\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-gateway-v1',\n * },\n * };\n * },\n * buildUrl() {\n * return 'https://api.myprovider.com/v1';\n * },\n * async getApiKey() {\n * return process.env.MY_API_KEY || '';\n * },\n * async resolveLanguageModel({ modelId, providerId, apiKey }) {\n * const provider = createOpenAICompatible({\n * name: providerId,\n * apiKey,\n * baseURL: this.buildUrl(),\n * supportsStructuredOutputs: true,\n * });\n * return provider.chatModel(modelId);\n * },\n * };\n *\n * const mastra = new Mastra();\n * mastra.addGateway(customGateway);\n * ```\n *\n * @example Convenience base class\n * ```typescript\n * import { MastraModelGateway } from '@mastra/core/llm';\n *\n * class CustomGateway extends MastraModelGateway {\n * readonly id = 'custom-gateway-v1';\n * readonly name = 'Custom Gateway';\n *\n * // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.\n * }\n *\n * mastra.addGateway(new CustomGateway(), 'customKey');\n * ```\n */\n public addGateway(gateway: MastraModelGatewayInterface, key?: string): void {\n if (!gateway) {\n throw createUndefinedPrimitiveError('gateway', gateway, key);\n }\n const gatewayKey = key || getGatewayId(gateway);\n const gateways = this.#gateways as Record<string, MastraModelGatewayInterface>;\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 * - registered workspaces (sandbox processes, filesystem handles, LSP, browser)\n * - All registered components and their resources\n *\n * It's important to call this method when your application is shutting down\n * to ensure proper cleanup and prevent resource leaks.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: { myAgent },\n * workflows: { myWorkflow }\n * });\n *\n * // Graceful shutdown on SIGINT\n * process.on('SIGINT', async () => {\n * await mastra.shutdown();\n * process.exit(0);\n * });\n * ```\n */\n async shutdown(): Promise<void> {\n // SchedulerWorker is stopped as part of stopWorkers().\n await this.stopWorkers();\n\n const workspaceIds = Object.keys(this.#workspaces);\n const teardownResults = await Promise.allSettled(\n workspaceIds.map(id => this.removeWorkspace(id, { destroy: true })),\n );\n teardownResults.forEach((result, index) => {\n if (result.status === 'rejected') {\n this.#logger?.error('Failed to destroy workspace during shutdown', {\n workspaceId: workspaceIds[index],\n error: result.reason,\n });\n }\n });\n\n // Tear down hosted Harnesses (interval handlers, workspaces) before closing storage,\n // since teardown may still flush to the shared store.\n const harnessKeys = Object.keys(this.#harnesses);\n const harnessTeardown = await Promise.allSettled(harnessKeys.map(key => this.#harnesses[key]!.destroy()));\n harnessTeardown.forEach((result, index) => {\n if (result.status === 'rejected') {\n this.#logger?.error('Failed to destroy harness during shutdown', {\n harnessKey: harnessKeys[index],\n error: result.reason,\n });\n }\n });\n\n // Close storage to release OS file handles (critical on Windows: open WAL/shm\n // handles cause EBUSY when callers try to fs.rm the storage dir after shutdown).\n if (this.#storage?.close) {\n await this.#storage.close();\n }\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\n// Publish the constructor so `Agent`'s ephemeral-Mastra path can build one\n// without a static `agent → mastra` runtime import (which would re-create the\n// init cycle documented in `agent/agent.ts`). Runs once, after the class above\n// is initialized. See `./mastra-ctor-holder`.\n__registerMastraCtor(Mastra);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAa,oCAAoC;;;;;;;AAQjD,MAAa,wCAAwC;AAErD,MAAa,qCAAqC;AAUlD,SAAgB,6BAA6B,OAAsB;CACjE,MAAM,MAAM,QAAQ,IAAI,KAAK,KAAK,oBAAI,IAAI,KAAK;CAC/C,IAAI,OAAO,MAAM,IAAI,QAAQ,CAAC,GAC5B,MAAM,IAAI,MAAM,uCAAuC,OAAO;CAEhE,OAAO;AACT;;;;;;;AAQA,SAAgB,kCAAkC,EAChD,OAAO,oCACP,YAAA,QAC+C,CAAC,GAAa;CAC7D,MAAM,MAAM,KAAK,IAAI;CACrB,OAAO;EACL,IAAI;EACJ,QAAQ;GACN,MAAM;GACN,YAAY;GACZ,WAAW,EAAE,OAAO,UAAU;EAChC;EACA;EACA,QAAQ;EACR,YAAY,kBAAkB,MAAM,EAAE,OAAO,IAAI,CAAC;EAClD,WAAW;EACX,WAAW;EACX,UAAU;GAAE,UAAU;GAAM,SAAS;EAAgB;CACvD;AACF;AAEA,SAAgB,mCAAmC,EACjD,YAAA,QACwD,CAAC,GAAG;CAC5D,MAAM,eAAe,WAAW;EAC9B,IAAI;EACJ,aAAa,EA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M,iCAAiC,GAAG;EACnD;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BA,MAAM,WAA0B;EAE9B,MAAM,KAAK,YAAY;EAEvB,MAAM,eAAe,OAAO,KAAK,KAAKY,WAAW;EAIjD,CAAA,MAH8B,QAAQ,WACpC,aAAa,KAAI,OAAM,KAAK,gBAAgB,IAAI,EAAE,SAAS,KAAK,CAAC,CAAC,CACpE,EAAA,CACgB,SAAS,QAAQ,UAAU;GACzC,IAAI,OAAO,WAAW,YACpB,KAAKtC,SAAS,MAAM,+CAA+C;IACjE,aAAa,aAAa;IAC1B,OAAO,OAAO;GAChB,CAAC;EAEL,CAAC;EAID,MAAM,cAAc,OAAO,KAAK,KAAK+B,UAAU;EAE/C,CAAA,MAD8B,QAAQ,WAAW,YAAY,KAAI,QAAO,KAAKA,WAAW,IAAI,CAAE,QAAQ,CAAC,CAAC,EAAA,CACxF,SAAS,QAAQ,UAAU;GACzC,IAAI,OAAO,WAAW,YACpB,KAAK/B,SAAS,MAAM,6CAA6C;IAC/D,YAAY,YAAY;IACxB,OAAO,OAAO;GAChB,CAAC;EAEL,CAAC;EAID,IAAI,KAAKY,UAAU,OACjB,MAAM,KAAKA,SAAS,MAAM;EAG5B,MAAM,KAAKT,eAAe,SAAS;EAEnC,KAAKH,SAAS,KAAK,2BAA2B;CAChD;CAGA,IAAW,cAAc;EACvB,OAAO,KAAKI;CACd;AACF;AAMA,qBAAqB,MAAM"}
|
|
1
|
+
{"version":3,"file":"mastra-B6CffFOC.js","names":["#pubsubProxy","#pubsub","#workers","#backgroundTaskManager","#findSchedulerWorker","#datasets","#idGenerator","#editor","#channels","#schedules","#schedulesConfig","#versions","#environment","#toolPayloadTransform","#storedAgentsCache","#storedScorersCache","#logger","#server","#studio","#observability","#serverCache","#recoveryConfig","#events","#workerFilter","#workersDisabled","#loggerExplicit","#storageExplicit","#observabilityExplicit","#storage","#backgroundTaskConfig","#ensureBackgroundTaskManager","#schedulerConfig","#notificationDispatchConfig","#vectors","#mcpServers","#tts","#agents","#scorers","#tools","#processors","#memory","#workflows","#gateways","#workspace","#hiddenWorkflowKeys","#serverExplicit","#studioExplicit","#harnesses","#onScorerHook","#registerToolWithBackgroundManager","#hasScheduledWorkflow","#schedulerRequested","#collectDeclarativeSchedules","#deployer","#workspaces","#internalMastraWorkflows","#runScopedWorkflowTimestamps","#runScopeRefcounts","#runScopes","#sweepStaleRunScopedWorkflows","#releaseRunScope","#ownsWorkflow","#runTracingContexts","#promptBlocks","#processorConfigurations","#workersStarted","#ensureSchedulingWorkersStarted","#notificationDispatchReady","#schedulingWorkersStartPromise","#startSchedulingWorkers","#shouldEnableScheduler","#findAgentScheduleWorker","#detectExistingAgentSchedules","#detectExistingNotificationDispatch","#serverAdapter","#serverMiddleware","#bundler","#workflowEventProcessor","#wirePushWorkflowSubscription","#userEventSubscriptions","#pushSubscription","#executionWorkersStarted","#executionWorkersStartPromise","#startExecutionWorkers","#syncGatewayRegistry"],"sources":["../src/notifications/workflow.ts","../src/mastra/index.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport type { Schedule } from '../storage/domains/schedules/base';\nimport { createStep, createWorkflow } from '../workflows/evented';\nimport { computeNextFireAt } from '../workflows/scheduler';\nimport { dispatchDueNotifications } from './dispatcher';\n\nexport const NOTIFICATION_DISPATCH_WORKFLOW_ID = '__mastra_notification_dispatcher';\n\n/**\n * Schedule row id for the lazily-created dispatcher schedule. Deliberately\n * NOT `wf_`-prefixed: `registerDeclarativeSchedules` orphan-cleanup deletes\n * `wf_`-prefixed rows that are no longer declared in code, and this row is\n * created imperatively (like heartbeat rows) on first deferred notification.\n */\nexport const NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID = '__mastra_notification_dispatch';\n\nexport const NOTIFICATION_DISPATCH_DEFAULT_CRON = '*/1 * * * *';\nexport const NOTIFICATION_DISPATCH_DEFAULT_BATCH_SIZE = 100;\n\nexport type NotificationDispatchConfig = {\n /** Defaults to true. Set false to opt out of automatic scheduled dispatch. */\n enabled?: boolean;\n cron?: string;\n batchSize?: number;\n};\n\nexport function parseNotificationDispatchNow(input?: string): Date {\n const now = input ? new Date(input) : new Date();\n if (Number.isNaN(now.getTime())) {\n throw new Error(`Invalid notification dispatch time: ${input}`);\n }\n return now;\n}\n\n/**\n * Builds the imperative schedule row that drives the notification dispatcher.\n * Created lazily by `Mastra.__ensureNotificationDispatchReady()` on the first\n * deferred notification, rather than declared on the workflow, so idle apps\n * never start the scheduler.\n */\nexport function buildNotificationDispatchSchedule({\n cron = NOTIFICATION_DISPATCH_DEFAULT_CRON,\n batchSize = NOTIFICATION_DISPATCH_DEFAULT_BATCH_SIZE,\n}: Omit<NotificationDispatchConfig, 'enabled'> = {}): Schedule {\n const now = Date.now();\n return {\n id: NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID,\n target: {\n type: 'workflow',\n workflowId: NOTIFICATION_DISPATCH_WORKFLOW_ID,\n inputData: { limit: batchSize },\n },\n cron,\n status: 'active',\n nextFireAt: computeNextFireAt(cron, { after: now }),\n createdAt: now,\n updatedAt: now,\n metadata: { internal: true, feature: 'notifications' },\n };\n}\n\nexport function createNotificationDispatchWorkflow({\n batchSize = NOTIFICATION_DISPATCH_DEFAULT_BATCH_SIZE,\n}: Omit<NotificationDispatchConfig, 'enabled' | 'cron'> = {}) {\n const dispatchStep = createStep({\n id: 'dispatch-due-notifications',\n inputSchema: z.object({\n now: z.string().optional(),\n limit: z.number().optional(),\n }),\n outputSchema: z.object({\n delivered: z.number(),\n failed: z.number(),\n }),\n execute: async ({ inputData, mastra }) => {\n const storage = await mastra.getStorage()?.getStore('notifications');\n if (!storage) {\n return { delivered: 0, failed: 0 };\n }\n\n const now = parseNotificationDispatchNow(inputData.now);\n\n const result = await dispatchDueNotifications({\n mastra,\n storage,\n now,\n limit: inputData.limit ?? batchSize,\n });\n\n return { delivered: result.delivered.length, failed: result.failed.length };\n },\n });\n\n return createWorkflow({\n id: NOTIFICATION_DISPATCH_WORKFLOW_ID,\n inputSchema: z.object({\n now: z.string().optional(),\n limit: z.number().optional(),\n }),\n outputSchema: z.object({\n delivered: z.number(),\n failed: z.number(),\n }),\n })\n .then(dispatchStep)\n .commit();\n}\n","import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../agent';\nimport { createDurableAgent } from '../agent/durable/create-durable-agent';\nimport { agentThreadStreamRuntime } from '../agent/thread-stream-runtime';\nimport type { DurableAgentLike } from '../agent/types';\nimport { isDurableAgentLike } from '../agent/types';\nimport type { AgentController } from '../agent-controller';\nimport { BackgroundTaskManager } from '../background-tasks';\nimport type { BackgroundTaskManagerConfig } from '../background-tasks/types';\nimport type { BundlerConfig } from '../bundler/types';\nimport { InMemoryServerCache } from '../cache';\nimport type { MastraServerCache } from '../cache';\nimport { AgentChannels } from '../channels';\nimport type { ChannelProvider } from '../channels';\nimport { DatasetsManager } from '../datasets/manager.js';\nimport type { MastraDeployer } from '../deployer';\nimport type { IMastraEditor } from '../editor';\nimport { MastraError, ErrorDomain, ErrorCategory } from '../error';\nimport type { MastraScorer } from '../evals';\nimport { EventEmitterPubSub } from '../events/event-emitter';\nimport type { PubSub } from '../events/pubsub';\nimport type { Event, EventCallback } from '../events/types';\nimport type { Harness } from '../harness';\nimport { AvailableHooks, deregisterHook, registerHook } from '../hooks';\nimport { LicenseClient } from '../license';\nimport type { MastraModelGatewayInterface } from '../llm/model/gateways';\nimport { getGatewayId } from '../llm/model/gateways';\nimport { defaultGateways } from '../llm/model/gateways/defaults';\nimport { LogLevel, noopLogger, ConsoleLogger, DualLogger } from '../logger';\nimport type { IMastraLogger } from '../logger';\nimport type { MCPServerBase } from '../mcp';\nimport type { MastraMemory } from '../memory';\nimport type { NotificationDispatchConfig } from '../notifications/workflow';\nimport {\n buildNotificationDispatchSchedule,\n createNotificationDispatchWorkflow,\n NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID,\n} from '../notifications/workflow';\nimport type {\n DefinitionSource,\n ObservabilityEntrypoint,\n ObservabilityExporter,\n ObservabilityInstance,\n LoggerContext,\n MetricsContext,\n TracingContext,\n} from '../observability';\nimport { NoOpObservability, noOpLoggerContext, noOpMetricsContext } from '../observability';\nimport { initContextStorage } from '../observability/context-storage';\nimport type { Processor } from '../processors';\nimport { Schedules } from '../schedules/schedules';\nimport type { SchedulesConfig, ScheduleHooks } from '../schedules/types';\nimport type { MastraServerBase } from '../server/base';\nimport type { ApiRoute, Middleware, ServerConfig, StudioConfig } from '../server/types';\nimport type { MastraCompositeStore, WorkflowRuns } from '../storage';\nimport { InMemoryStore } from '../storage';\nimport { BackgroundTasksInMemory } from '../storage/domains/background-tasks/inmemory';\nimport { InMemoryDB } from '../storage/domains/inmemory-db';\nimport type { Schedule, ScheduleUpdate, SchedulesStorage } from '../storage/domains/schedules/base';\nimport { WorkflowsInMemory } from '../storage/domains/workflows/inmemory';\nimport { augmentWithInit } from '../storage/storageWithInit';\nimport type { StorageResolvedPromptBlockType } from '../storage/types';\nimport type { ToolLoopAgentLike } from '../tool-loop-agent';\nimport { isToolLoopAgentLike, toolLoopAgentToMastraAgent } from '../tool-loop-agent';\nimport type { ToolAction, ToolPayloadTransformPolicy } from '../tools';\nimport { normalizeToolPayloadTransformPolicy } from '../tools/payload-transform';\nimport type { MastraTTS } from '../tts';\nimport type { MastraIdGenerator, IdGeneratorContext } from '../types';\nimport type { MastraVector } from '../vector';\nimport { OrchestrationWorker, SchedulerWorker, BackgroundTaskWorker } from '../worker';\nimport type { MastraWorker, WorkerDeps } from '../worker';\nimport type { AnyWorkflow, Workflow } from '../workflows';\nimport { WorkflowEventProcessor } from '../workflows/evented/workflow-event-processor';\nimport { computeNextFireAt } from '../workflows/scheduler';\nimport type { WorkflowScheduleConfig, SchedulerConfig, Scheduler } from '../workflows/scheduler';\nimport type { AnyWorkspace, RegisteredWorkspace, Workspace } from '../workspace';\nimport { createOnScorerHook } from './hooks';\nimport { __registerMastraCtor } from './mastra-ctor-holder';\nimport type { RunScope } from './run-scope';\nimport { createRunScope } from './run-scope';\nimport type { VersionOverrides, VersionSelector } from './types';\n\n/**\n * Creates an error for when a null/undefined value is passed to an add* method.\n * This commonly occurs when config is spread ({ ...config }) and the original\n * object had getters or non-enumerable properties.\n */\nfunction createUndefinedPrimitiveError(\n type:\n | 'agent'\n | 'tool'\n | 'processor'\n | 'vector'\n | 'scorer'\n | 'workflow'\n | 'mcp-server'\n | 'gateway'\n | 'memory'\n | 'workspace',\n value: null | undefined,\n key?: string,\n): MastraError {\n const typeLabel = type === 'mcp-server' ? 'MCP server' : type;\n const errorId = `MASTRA_ADD_${type.toUpperCase().replace('-', '_')}_UNDEFINED` as Uppercase<string>;\n return new MastraError({\n id: errorId,\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Cannot add ${typeLabel}: ${typeLabel} is ${value === null ? 'null' : 'undefined'}. This may occur if config was spread ({ ...config }) and the original object had getters or non-enumerable properties.`,\n details: { status: 400, ...(key && { key }) },\n });\n}\n\n/**\n * Stable JSON-shape comparison for two `Schedule.target` values. Uses\n * JSON.stringify because targets are plain JSON-serializable objects (the\n * storage layer round-trips them through the same encoding). Covers the\n * `inputData` / `initialState` / `requestContext` payload fields that we\n * want to detect changes on across redeploys.\n */\nfunction targetsEqual(a: Schedule['target'] | undefined, b: Schedule['target']): boolean {\n if (a === b) return true;\n if (!a) return false;\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Reads the declarative schedule configs off a workflow. Supports both the\n * new `getScheduleConfigs(): WorkflowScheduleConfig[]` accessor on the evented\n * engine and a legacy `getScheduleConfig(): WorkflowScheduleConfig | undefined`\n * fallback used in tests that inject a fake getter.\n */\nfunction collectWorkflowScheduleConfigs(workflow: unknown): WorkflowScheduleConfig[] {\n const w = workflow as {\n getScheduleConfigs?: () => WorkflowScheduleConfig[] | undefined;\n getScheduleConfig?: () => WorkflowScheduleConfig | WorkflowScheduleConfig[] | undefined;\n };\n if (typeof w.getScheduleConfigs === 'function') {\n return w.getScheduleConfigs() ?? [];\n }\n if (typeof w.getScheduleConfig === 'function') {\n const cfg = w.getScheduleConfig();\n if (!cfg) return [];\n return Array.isArray(cfg) ? cfg : [cfg];\n }\n return [];\n}\n\n/**\n * Builds the storage row id for a declarative schedule. Workflow and schedule\n * ids are URL-encoded so delimiters in user-supplied ids cannot collide\n * across workflows (e.g. `foo__bar` single vs `foo` array-entry `bar`).\n */\nfunction declarativeScheduleRowId(workflowId: string, scheduleId?: string): string {\n const encodedWorkflow = encodeURIComponent(workflowId);\n if (scheduleId === undefined) return `wf_${encodedWorkflow}`;\n return `wf_${encodedWorkflow}__${encodeURIComponent(scheduleId)}`;\n}\n\n/**\n * Determines whether a stored schedule row id belongs to one of the registered\n * workflows. Returns the owning workflow id when the row id either equals\n * `wf_<encoded(workflowId)>` (single-schedule form) or starts with\n * `wf_<encoded(workflowId)>__` (array form). Returns undefined when no\n * registered workflow owns the row.\n */\nfunction ownerWorkflowIdForRow(rowId: string, byWorkflow: Map<string, Set<string>>): string | undefined {\n for (const workflowId of byWorkflow.keys()) {\n const prefix = `wf_${encodeURIComponent(workflowId)}`;\n if (rowId === prefix || rowId.startsWith(`${prefix}__`)) {\n return workflowId;\n }\n }\n return undefined;\n}\n\n/**\n * Decodes the owning workflow id directly from a `wf_<encoded>` /\n * `wf_<encoded>__<...>` row id without needing the workflow to be in the\n * current registry. Used to identify rows whose workflow has been deleted\n * from code so we can clean them up on startup.\n */\nfunction ownerWorkflowIdFromRowId(rowId: string): string | undefined {\n if (!rowId.startsWith('wf_')) return undefined;\n const rest = rowId.slice('wf_'.length);\n const sep = rest.indexOf('__');\n const encoded = sep === -1 ? rest : rest.slice(0, sep);\n if (!encoded) return undefined;\n try {\n return decodeURIComponent(encoded);\n } catch {\n return undefined;\n }\n}\n\n/** See {@link targetsEqual}. Same approach for free-form metadata. */\nfunction metadataEqual(a: Record<string, unknown> | null | undefined, b: Record<string, unknown> | undefined): boolean {\n const aNorm = a ?? undefined;\n const bNorm = b ?? undefined;\n if (aNorm === bNorm) return true;\n if (!aNorm || !bNorm) return false;\n return JSON.stringify(aNorm) === JSON.stringify(bNorm);\n}\n\n/**\n * Configuration interface for initializing a Mastra instance.\n *\n * The Config interface defines all the optional components that can be registered\n * with a Mastra instance, including agents, workflows, storage, logging, and more.\n *\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of workflow instances\n * @template TVectors - Record of vector store instances\n * @template TTTS - Record of text-to-speech instances\n * @template TLogger - Logger implementation type\n * @template TVNextNetworks - Record of agent network instances\n * @template TMCPServers - Record of MCP server instances\n * @template TScorers - Record of scorer instances\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'Weather Agent',\n * instructions: 'You help with weather information',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport interface Config<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n string,\n ToolAction<any, any, any, any, any, any>\n >,\n TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>,\n TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>,\n> {\n /**\n * Agents are autonomous systems that can make decisions and take actions.\n * Accepts Mastra Agent instances, AI SDK v6 ToolLoopAgent instances,\n * and durable agent wrappers (e.g., InngestAgent from createInngestAgent).\n * ToolLoopAgent and durable agents are automatically handled during registration.\n */\n agents?: { [K in keyof TAgents]: TAgents[K] | ToolLoopAgentLike | DurableAgentLike };\n\n /**\n * Storage provider for persisting data, conversation history, and workflow state.\n * Required for agent memory and workflow persistence.\n */\n storage?: MastraCompositeStore;\n\n /**\n * Vector stores for semantic search and retrieval-augmented generation (RAG).\n * Used for storing and querying embeddings.\n */\n vectors?: TVectors;\n\n /**\n * Logger implementation for application logging and debugging.\n * Set to `false` to disable logging entirely.\n * @default `INFO` level in development, `WARN` in production.\n */\n logger?: TLogger | false;\n\n /**\n * Workflows provide type-safe, composable task execution with built-in error handling.\n */\n workflows?: TWorkflows;\n\n /**\n * AgentControllers to host on this Mastra instance, keyed by id. Each\n * registered AgentController uses this Mastra (its storage, agents, gateways,\n * and observability) instead of building its own internal one, and is\n * reachable via {@link Mastra.getAgentController} /\n * {@link Mastra.listAgentControllers}. This is how a server exposes multiple\n * AgentControllers' sessions over HTTP.\n */\n agentControllers?: Record<string, AgentController<any>>;\n\n /**\n * Harnesses to host on this Mastra instance, keyed by id.\n *\n * @deprecated Use {@link MastraConfig.agentControllers} instead. `harnesses`\n * is retained as a backwards-compatible alias and will be removed in a future\n * major. Entries from both keys are merged, with `agentControllers` taking\n * precedence on key collisions.\n */\n harnesses?: Record<string, Harness<any>>;\n\n /**\n * Text-to-speech providers for voice synthesis capabilities.\n */\n tts?: TTTS;\n\n /**\n * Observability entrypoint for tracking model interactions and tracing.\n * Pass an instance of the Observability class from @mastra/observability.\n *\n * @example\n * ```typescript\n * import { Observability, MastraStorageExporter, MastraPlatformExporter } from '@mastra/observability';\n *\n * new Mastra({\n * observability: new Observability({\n * configs: {\n * default: {\n * serviceName: 'mastra',\n * exporters: [new MastraStorageExporter(), new MastraPlatformExporter()],\n * },\n * },\n * })\n * })\n * ```\n *\n * `Observability` auto-applies a `SensitiveDataFilter` span output processor\n * to every configured instance. Set `sensitiveDataFilter: false` on the\n * registry config to opt out, or pass a `SensitiveDataFilterOptions` object\n * to customize it.\n */\n observability?: ObservabilityEntrypoint;\n\n /**\n * Custom ID generator function for creating unique identifiers.\n * Receives optional context about what type of ID is being generated\n * and where it's being requested from.\n * @default `crypto.randomUUID()`\n */\n idGenerator?: MastraIdGenerator;\n\n /**\n * Deployment provider for publishing applications to cloud platforms.\n */\n deployer?: MastraDeployer;\n\n /**\n * Server configuration for HTTP endpoints and middleware.\n */\n server?: ServerConfig;\n\n /**\n * Studio-specific authentication and authorization configuration.\n *\n * When configured, Studio uses separate auth from the server (API) auth,\n * allowing different providers for internal team members vs external customers.\n *\n * - `server.auth` handles API authentication (external customers)\n * - `studio.auth` handles Studio authentication (internal team)\n *\n * **Dual auth is opt-in:** If `studio.auth` is not configured, Studio requests\n * fall back to `server.auth` for backward compatibility. To enable strict\n * separation between Studio and API auth, configure both `studio.auth` and\n * `server.auth`.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * server: {\n * auth: new MastraAuthWorkos({ ... }), // External customers\n * },\n * studio: {\n * auth: new MastraAuthOkta({ ... }), // Internal team\n * rbac: new StaticRBACProvider({\n * roles: DEFAULT_ROLES,\n * getUserRoles: (user) => [user.role],\n * }),\n * },\n * });\n * ```\n */\n studio?: StudioConfig;\n\n /**\n * MCP servers provide tools and resources that agents can use.\n */\n mcpServers?: TMCPServers;\n\n /**\n * Bundler configuration for packaging and deployment.\n */\n bundler?: BundlerConfig;\n\n /**\n * Pub/sub system for event-driven communication between components.\n * @default EventEmitterPubSub\n */\n pubsub?: PubSub;\n\n /**\n * Server cache for storing stream events and other temporary data.\n * Used by durable agents for resumable streams - clients can disconnect\n * and reconnect without missing events.\n *\n * When provided, durable agents created without their own cache will\n * inherit this cache instance.\n *\n * @default InMemoryServerCache\n */\n cache?: MastraServerCache;\n\n /**\n * Scorers help assess the quality of agent responses and workflow outputs.\n */\n scorers?: TScorers;\n\n /**\n * Tools are reusable functions that agents can use to interact with external systems.\n */\n tools?: TTools;\n\n /**\n * Processors transform inputs and outputs for agents and workflows.\n */\n processors?: TProcessors;\n\n /**\n * Memory instances that can be referenced by stored agents.\n * Keys are used to look up memory instances when resolving stored agent configurations.\n */\n memory?: TMemory;\n\n /**\n * Global workspace for file storage, skills, and code execution.\n * Agents inherit this workspace unless they have their own configured.\n * Skills are accessed via workspace.skills when skills is configured.\n */\n workspace?: AnyWorkspace;\n\n /**\n * Custom model router gateways for accessing LLM providers.\n * Gateways handle provider-specific authentication, URL construction, and model resolution.\n */\n gateways?: Record<string, MastraModelGatewayInterface>;\n\n /**\n * Event handlers for custom application events.\n * Maps event topics to handler functions for event-driven architectures.\n */\n events?: {\n [topic: string]: (\n event: Event,\n cb?: () => Promise<void>,\n ) => Promise<void> | ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n };\n\n /**\n * Editor instance for handling agent instantiation and configuration.\n * The editor handles complex instantiation logic including memory resolution.\n */\n editor?: IMastraEditor;\n\n /**\n * Global version overrides for primitives.\n * When set, sub-agent delegation (and future primitive resolution) will\n * resolve the specified version instead of the code-defined default.\n *\n * @example\n * ```typescript\n * new Mastra({\n * versions: {\n * agents: {\n * 'researcher-agent': { versionId: '123' },\n * 'writer-agent': { status: 'published' },\n * },\n * },\n * });\n * ```\n */\n versions?: VersionOverrides;\n\n /**\n * Background task configuration for running tool calls asynchronously.\n * When configured, agents can dispatch tool executions to run in the background\n * while the conversation continues.\n */\n backgroundTasks?: BackgroundTaskManagerConfig;\n\n /**\n * Scheduler configuration for cron-driven workflow triggers.\n *\n * The scheduler is auto-enabled when any registered workflow declares a\n * `schedule` config or when `scheduler.enabled` is true. It requires a\n * storage adapter implementing the `schedules` domain (e.g. `@mastra/libsql`).\n */\n scheduler?: SchedulerConfig;\n\n /**\n * Notification runtime configuration. Notification dispatch is scheduled automatically by default.\n */\n notifications?: {\n dispatch?: NotificationDispatchConfig;\n };\n\n /**\n * Schedules runtime configuration. A single lifecycle-hook bundle runs for\n * every agent-schedule fire and is invoked by the agent-schedule worker\n * around schedule-driven agent runs; hooks branch per agent via the\n * `agentId` on each context. Configuring hooks here (rather than on the\n * Agent) lets both code-defined and stored agents share the same hook\n * surface, since stored agents cannot define functions in their serialized\n * config.\n */\n schedules?: SchedulesConfig<Mastra>;\n\n /**\n * Platform channels for messaging integrations (Slack, Discord, etc.).\n * Routes are automatically registered and agents can reference channel configs.\n *\n * @example\n * ```typescript\n * import { SlackProvider } from '@mastra/slack';\n *\n * new Mastra({\n * channels: {\n * slack: new SlackProvider({\n * configToken: process.env.SLACK_APP_CONFIG_TOKEN,\n * refreshToken: process.env.SLACK_APP_CONFIG_REFRESH_TOKEN,\n * }),\n * },\n * });\n * ```\n */\n channels?: TChannels;\n\n /**\n * Deployment environment name (e.g. `'production'`, `'staging'`, `'development'`).\n * When set, the value is automatically attached to all observability signals\n * so they can be filtered by environment without passing\n * `tracingOptions.metadata.environment` on every call.\n *\n * If unset, falls back to `process.env.NODE_ENV`. If neither is set the field\n * is left undefined rather than guessed.\n *\n * Per-call `tracingOptions.metadata.environment` always takes precedence.\n *\n * @example\n * ```typescript\n * new Mastra({\n * environment: 'production',\n * observability: new Observability({ ... }),\n * })\n * ```\n */\n environment?: string;\n /**\n * Optional central transform policy for tool payloads before they are\n * serialized into display streams or user-visible transcripts.\n */\n transform?: ToolPayloadTransformPolicy;\n /**\n * Configure which workers run in this Mastra instance.\n *\n * - `undefined` (default): Auto-creates default workers (existing behavior)\n * - `false`: Disables all event processing — useful when running standalone workers separately\n * - `MastraWorker[]`: Additional workers merged with the auto-created\n * defaults. A custom worker replaces a default with the same `name`;\n * duplicate names within the array throw. Use `false` to run no workers.\n */\n workers?: MastraWorker[] | false;\n\n /**\n * Boot-time recovery behavior for orphaned agent/workflow runs.\n *\n * `durableAgents` controls whether the deployer will automatically call\n * {@link Mastra.recoverAllDurableAgents} for every registered `DurableAgent`\n * when the server starts (right after `restartAllActiveWorkflowRuns`).\n *\n * - `'off'` (default): the deployer never auto-recovers durable agent runs.\n * Operators can still call `mastra.recoverAllDurableAgents()` or\n * `agent.recoverActiveRuns()` by hand.\n * - `'auto'`: the deployer will invoke `recoverAllDurableAgents()` on boot,\n * re-driving every RUNNING durable agent run discovered in storage.\n *\n * Opt-in only. Auto-recovery re-runs the agentic loop from the last persisted\n * snapshot, so it re-issues LLM calls (real cost) and re-executes tool calls\n * (must be idempotent). In multi-instance deploys every replica will race to\n * recover the same runs, since there is no lease/lock yet.\n *\n * @default { durableAgents: 'off' }\n */\n recovery?: MastraRecoveryConfig;\n\n /**\n * Marks this instance as an internally-owned ephemeral Mastra — e.g. the\n * fallback instance a standalone `Agent` lazily creates so its\n * prepare-stream workflow has a pubsub-equipped Mastra to run on.\n *\n * Ephemeral instances skip module-level scorer-hook registration: they have\n * no agent/scorer/editor registries for the hook to resolve against, so the\n * hook could never persist a score — but the module-level emitter would\n * retain the instance (and everything it references) for the lifetime of\n * the process, leaking one Mastra graph per discarded standalone Agent\n * (#19404).\n *\n * @internal Not part of the public API — do not set this on application\n * Mastra instances; it silently disables scorer persistence.\n */\n __ephemeral?: boolean;\n}\n\n/**\n * Boot-time recovery configuration. See {@link Mastra['recoveryConfig']}.\n */\nexport interface MastraRecoveryConfig {\n /**\n * Auto-recover orphaned RUNNING durable agent runs on server boot.\n * @default 'off'\n */\n durableAgents?: 'auto' | 'off';\n}\n\n/**\n * The central orchestrator for Mastra applications, managing agents, workflows, storage, logging, observability, and more.\n *\n * The `Mastra` class serves as the main entry point and registry for all components in a Mastra application.\n * It coordinates the interaction between agents, workflows, storage systems, and other services.\n\n * @template TAgents - Record of agent instances keyed by their names\n * @template TWorkflows - Record of modern workflow instances\n * @template TVectors - Record of vector store instances for semantic search and RAG\n * @template TTTS - Record of text-to-speech provider instances\n * @template TLogger - Logger implementation type for application logging\n * @template TVNextNetworks - Record of next-generation agent network instances\n * @template TMCPServers - Record of Model Context Protocol server instances\n * @template TScorers - Record of evaluation scorer instances for measuring AI performance\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'Weather Agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5',\n * tools: [getWeatherTool]\n * })\n * },\n * workflows: { dataWorkflow },\n * storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),\n * logger: new PinoLogger({ name: 'MyApp' })\n * });\n * ```\n */\nexport class Mastra<\n TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>,\n TWorkflows extends Record<string, AnyWorkflow> = Record<string, AnyWorkflow>,\n TVectors extends Record<string, MastraVector<any>> = Record<string, MastraVector<any>>,\n TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>,\n TLogger extends IMastraLogger = IMastraLogger,\n TMCPServers extends Record<string, MCPServerBase<any>> = Record<string, MCPServerBase<any>>,\n TScorers extends Record<string, MastraScorer<any, any, any, any>> = Record<string, MastraScorer<any, any, any, any>>,\n TTools extends Record<string, ToolAction<any, any, any, any, any, any>> = Record<\n string,\n ToolAction<any, any, any, any, any, any>\n >,\n TProcessors extends Record<string, Processor<any>> = Record<string, Processor<any>>,\n TMemory extends Record<string, MastraMemory> = Record<string, MastraMemory>,\n TChannels extends Record<string, ChannelProvider> = Record<string, ChannelProvider>,\n> {\n #vectors?: TVectors;\n #agents: TAgents;\n #logger: TLogger;\n #loggerExplicit = false;\n #workflows: TWorkflows;\n #harnesses: Record<string, Harness<any>> = {};\n #hiddenWorkflowKeys = new Set<string>();\n #observability: ObservabilityEntrypoint;\n #observabilityExplicit = false;\n #onScorerHook?: ReturnType<typeof createOnScorerHook>;\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 #storageExplicit = false;\n #recoveryConfig: MastraRecoveryConfig = { durableAgents: 'off' };\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 #serverExplicit = false;\n #studio?: StudioConfig;\n #studioExplicit = false;\n #serverAdapter?: MastraServerBase;\n #mcpServers?: TMCPServers;\n #bundler?: BundlerConfig;\n #idGenerator?: MastraIdGenerator;\n #pubsub: PubSub;\n #backgroundTaskConfig?: BackgroundTaskManagerConfig;\n #backgroundTaskManager?: BackgroundTaskManager;\n #schedulerConfig?: SchedulerConfig;\n #notificationDispatchConfig?: NotificationDispatchConfig;\n /**\n * Tracks whether any registered workflow has declared a `schedule` config.\n * Used as a fast short-circuit so users without scheduled workflows pay\n * zero cost beyond a boolean check.\n */\n #hasScheduledWorkflow = false;\n #gateways?: Record<string, MastraModelGatewayInterface>;\n #channels?: TChannels;\n #schedules?: Schedules;\n #schedulesConfig?: SchedulesConfig<Mastra>;\n #environment?: string;\n #toolPayloadTransform?: ToolPayloadTransformPolicy;\n #workers: MastraWorker[] = [];\n #workerFilter?: Set<string>;\n /**\n * Set when the user (or `MASTRA_WORKERS=false`) explicitly disabled all event\n * processing in this instance via `workers: false`. Gates lazy scheduler /\n * agent-schedule worker injection so runtime triggers (e.g.\n * `schedules.create()`) don't resurrect workers the user opted out of.\n */\n #workersDisabled = false;\n /**\n * Tracks whether `startWorkers()` has already run. Used to decide whether\n * lazy scheduler injection (e.g. from `mastra.schedules.create()` after boot)\n * needs to also `init`/`start` the worker, or whether the normal\n * `startWorkers()` path will pick it up.\n */\n #workersStarted = false;\n /**\n * Set when something has signalled that the scheduler is needed at runtime\n * (e.g. an agent schedule was registered via `__ensureScheduleRuntimeReady()`).\n * Causes `#shouldEnableScheduler()` to return `true` even when there are no\n * declarative scheduled workflows, unless the user explicitly set\n * `scheduler: { enabled: false }`.\n */\n #schedulerRequested = false;\n /**\n * Set once `__ensureNotificationDispatchReady()` has upserted the dispatcher\n * schedule row and requested the scheduler. Makes repeated deferred\n * notification creates free after the first one.\n */\n #notificationDispatchReady = false;\n /**\n * In-flight promise for `#ensureSchedulingWorkersStarted()`. Serializes\n * concurrent startup requests so two callers can't both pass the\n * worker-existence checks and double-subscribe to the scheduling topics.\n */\n #schedulingWorkersStartPromise?: Promise<void>;\n /**\n * In-flight promise for `__ensureExecutionWorkersStarted()`. Serializes\n * concurrent lazy startups triggered by background-task dispatches so two\n * first dispatches on a cold instance can't both init/start the same\n * workers.\n */\n #executionWorkersStartPromise?: Promise<void>;\n /**\n * Fast path for `__ensureExecutionWorkersStarted()`. Set once the execution\n * workers + push wiring are confirmed running; reset by `stopWorkers()`.\n * Kept separate from `#workersStarted`, which partial `startWorkers(name)`\n * calls also set without starting the workflow consumer.\n */\n #executionWorkersStarted = false;\n // Lazily-constructed processor used by handleWorkflowEvent(). Shared between\n // pull-mode workers (OrchestrationWorker) and push-mode entry points\n // (in-process EventEmitter listener, the /api/workers/events HTTP route).\n #workflowEventProcessor?: WorkflowEventProcessor;\n // Callback registered against the pubsub when running in push mode so we can\n // unsubscribe it cleanly during stopWorkers().\n #pushSubscription?: { topic: string; cb: EventCallback };\n // Tracks (topic, listener) pairs registered against the pubsub on behalf of\n // user-defined event listeners during startWorkers(). Used to make\n // startWorkers()/stopWorkers() idempotent — a second startWorkers() call\n // must not double-subscribe the same listener.\n #userEventSubscriptions: Array<{\n topic: string;\n cb: (event: Event, ack?: () => Promise<void>) => Promise<void>;\n }> = [];\n\n #events: {\n [topic: string]: ((event: Event, cb?: () => Promise<void>) => Promise<void>)[];\n } = {};\n #internalMastraWorkflows: Record<string, AnyWorkflow> = {};\n // Tracks registration timestamps for run-scoped internal workflows so a lazy\n // TTL sweep can evict entries from abandoned suspended runs that were never\n // resumed. Unscoped (singleton) entries are not tracked — they live forever.\n #runScopedWorkflowTimestamps: Map<string, { registeredAt: number; runId: string }> = new Map();\n // Per-run bag of non-serializable runtime state (SaveQueueManager,\n // BackgroundTaskManager, MessageList, abort controllers, dynamic tool sets…)\n // shared across step factories within a single run. Never persisted, never\n // published. Lifecycle is refcounted against `__registerInternalWorkflow`\n // calls for the same runId so multiple workflows sharing a run (e.g. an\n // agentic-loop wrapping an agentic-execution) keep the scope alive until the\n // last unregisters. See `./run-scope.ts`.\n #runScopes: Map<string, RunScope> = new Map();\n #runScopeRefcounts: Map<string, number> = new Map();\n // Run-scoped internal workflows older than this TTL (ms) are evicted during\n // the lazy sweep that runs on each new registration.\n static readonly INTERNAL_WORKFLOW_TTL_MS = 30 * 60 * 1000; // 30 minutes\n // Per-run tracing context for evented workflow runs. `currentSpan` is a\n // non-serializable AISpan, so it cannot ride the engine's pubsub events —\n // the event processor reads it from here, keyed by runId, instead.\n #runTracingContexts: Map<string, TracingContext> = new Map();\n // Server cache for temporary persistence and durable agent resumable streams\n #serverCache: MastraServerCache;\n // Cache for stored agents to allow in-memory modifications (like model changes) to persist across requests\n #storedAgentsCache: Map<string, Agent> = new Map();\n // Cache for stored scorers to allow in-memory modifications to persist across requests\n #storedScorersCache: Map<string, MastraScorer<any, any, any, any>> = new Map();\n // Registry for prompt blocks (stored or code-defined)\n #promptBlocks: Record<string, StorageResolvedPromptBlockType> = {};\n // Editor instance for handling agent instantiation and configuration\n #editor?: IMastraEditor;\n #datasets?: DatasetsManager;\n // Global version overrides for primitives (agents, etc.)\n #versions?: VersionOverrides;\n // Cached pubsub proxy that tags internal-workflow events with `_localOnly`\n // so the broker skips relaying multi-MB payloads to non-owning instances.\n #pubsubProxy?: PubSub;\n\n get pubsub(): PubSub {\n if (!this.#pubsubProxy) {\n const raw = this.#pubsub;\n const self = this;\n this.#pubsubProxy = new Proxy(raw, {\n get(target, prop, _receiver) {\n if (prop === 'publish') {\n return function publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>) {\n // Internal execution-workflows / agentic-loops are run-scoped:\n // only the owning instance needs their events. Pass `localOnly`\n // so the broker delivers locally + echoes back to the sender,\n // but does NOT fan out to other clients (avoids serialising\n // cumulative stepResults blobs — often 9 MB+ — across the unix\n // socket). The flag rides on the publish-frame envelope, not on\n // event.data, so WEP consumers never see it.\n if (topic === 'workflows' || topic === 'workflows-finish') {\n const data = event.data as Record<string, unknown> | undefined;\n const wfId = data?.workflowId as string | undefined;\n const rId = data?.runId as string | undefined;\n // Walk parentWorkflow chain to root — nested internal workflows\n // (e.g. `executionWorkflow` inside `agentic-loop`) carry an\n // immediate workflowId that isn't itself in the internal registry,\n // but their root parent (the registered agentic-loop) is. If any\n // ancestor matches an internal registration, this instance owns\n // the run and the event should stay local. Also tag publishes\n // for workflow ids only known to this instance's public registry\n // (e.g. background scheduler runs like the notification\n // dispatcher) — they have no cross-instance consumer.\n const isOwnedHere = (() => {\n if (wfId && rId && self.__hasInternalWorkflow(wfId, rId)) return true;\n let parent = data?.parentWorkflow as\n | { workflowId?: string; runId?: string; parentWorkflow?: unknown }\n | undefined;\n let depth = 0;\n while (parent && depth < 16) {\n const pwfId = parent.workflowId;\n const prId = parent.runId;\n if (pwfId && prId && self.__hasInternalWorkflow(pwfId, prId)) return true;\n parent = parent.parentWorkflow as typeof parent;\n depth++;\n }\n // Scheduler-spawned background workflows: runId carries the\n // schedule row id prefix — `sched_wf_<workflowId>_<timestamp>`\n // for declarative schedules, or the imperative notification\n // dispatcher row id. These ticks fire on every instance\n // independently — events are only meaningful to the\n // publishing process.\n if (rId && rId.startsWith('sched_wf_')) return true;\n if (rId && rId.startsWith(`sched_${NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID}_`)) return true;\n return false;\n })();\n if (isOwnedHere) {\n return target.publish(topic, event, { localOnly: true });\n }\n } else if (topic.startsWith('workflow.events.v2.')) {\n // Per-run watch stream events. Only the publishing process\n // consumes these (execution-engine subscribes per-run). No\n // cross-instance fan-out needed.\n return target.publish(topic, event, { localOnly: true });\n }\n return target.publish(topic, event);\n };\n }\n // Bind methods to `target` so private field access (#subscribers etc.)\n // works correctly — JS Proxies set `this` to the proxy, which breaks\n // private fields since they are scoped to the declaring class instance.\n const val = Reflect.get(target, prop, target);\n if (typeof val === 'function') {\n return val.bind(target);\n }\n return val;\n },\n }) as PubSub;\n }\n return this.#pubsubProxy;\n }\n\n get agentThreadStreamRuntime() {\n return agentThreadStreamRuntime;\n }\n\n get workers(): readonly MastraWorker[] {\n return this.#workers;\n }\n\n getWorker<T extends MastraWorker>(name: string): T | undefined {\n return this.#workers.find(w => w.name === name) as T | undefined;\n }\n\n get backgroundTaskManager() {\n return this.#backgroundTaskManager;\n }\n\n /**\n * Returns the workflow scheduler owned by the SchedulerWorker,\n * or undefined if the scheduler is not enabled / not yet started.\n *\n * The scheduler is created when `startWorkers()` initializes the\n * SchedulerWorker (guarded by `#shouldEnableScheduler()`).\n *\n * This is runtime plumbing (the cron tick loop). To create, list, pause,\n * resume, or delete schedules use `mastra.schedules` instead.\n *\n * @internal\n */\n get scheduler(): Scheduler | undefined {\n return this.#findSchedulerWorker()?.scheduler;\n }\n\n get datasets(): DatasetsManager {\n if (!this.#datasets) {\n this.#datasets = new DatasetsManager(this);\n }\n return this.#datasets;\n }\n\n /**\n * Gets the currently configured ID generator function.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * idGenerator: context =>\n * context?.idType === 'message' && context.threadId\n * ? `msg-${context.threadId}-${Date.now()}`\n * : `custom-${Date.now()}`\n * });\n * const generator = mastra.getIdGenerator();\n * console.log(generator?.({ idType: 'message', threadId: 'thread-123' })); // \\\"msg-thread-123-1234567890\\\"\n * ```\n */\n public getIdGenerator() {\n return this.#idGenerator;\n }\n\n /**\n * Gets the currently configured editor instance.\n * The editor is responsible for handling agent instantiation and configuration.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * editor: new MastraEditor({ logger })\n * });\n * const editor = mastra.getEditor();\n * ```\n */\n public getEditor() {\n return this.#editor;\n }\n\n /**\n * Gets a registered channel provider by its key.\n *\n * @example\n * ```typescript\n * import { SlackProvider } from '@mastra/slack';\n * const slack = mastra.getChannelProvider<SlackProvider>('slack');\n * ```\n */\n public getChannelProvider<T extends ChannelProvider = ChannelProvider>(key: string): T | undefined {\n return this.#channels?.[key] as T | undefined;\n }\n\n /**\n * Gets all registered channel providers.\n */\n public getChannelProviders(): Record<string, ChannelProvider> | undefined {\n return this.#channels;\n }\n\n /**\n * Shorthand getter for platform channels.\n * Usage: `mastra.channels.slack.connect(agentId)`\n */\n public get channels(): TChannels {\n return (this.#channels ?? {}) as TChannels;\n }\n\n /**\n * Canonical entrypoint for schedules — recurring agent or workflow runs\n * persisted as schedule rows discriminated by `target.type` (`'agent'` or\n * `'workflow'`). Use to create, list, update, pause/resume, manually fire,\n * or inspect trigger history for schedules across any agent or workflow.\n *\n * Lazily constructed. Operates against `getStorage()?.getStore('schedules')`.\n *\n * @example\n * ```ts\n * const schedule = await mastra.schedules.create({\n * agentId: 'pinger',\n * name: 'morning-checkin',\n * cron: '0 9 * * *',\n * prompt: 'good morning, anything to report?',\n * threadId: 't1',\n * resourceId: 'u1',\n * });\n * await mastra.schedules.list({ agentId: 'pinger' });\n * ```\n */\n public get schedules(): Schedules {\n this.#schedules ??= new Schedules(this as unknown as Mastra);\n return this.#schedules;\n }\n\n /**\n * Returns the schedule lifecycle hook bundle configured via\n * `new Mastra({ schedules: { ... } })`, if any. A single bundle runs for\n * every agent-schedule fire; hooks branch per agent via the `agentId` on\n * each context. Internal: consumed by the {@link AgentScheduleWorker} to\n * invoke `prepare`, `onFinish`, `onError`, and `onAbort` around\n * schedule-driven runs.\n *\n * @internal\n */\n __getScheduleHooks(): ScheduleHooks<Mastra> | undefined {\n return this.#schedulesConfig;\n }\n\n /**\n * Returns the global version overrides configured on this Mastra instance.\n * These are used as defaults when resolving sub-agent versions during delegation.\n */\n public getVersionOverrides(): VersionOverrides | undefined {\n return this.#versions;\n }\n\n /**\n * Returns the deployment environment name configured on this Mastra instance,\n * falling back to `process.env.NODE_ENV` when unset, or `undefined` if neither\n * is provided.\n *\n * Observability automatically reads this and attaches it to all signals so\n * consumers can filter by environment without passing\n * `tracingOptions.metadata.environment` on each call.\n */\n public getEnvironment(): string | undefined {\n return this.#environment;\n }\n\n public getToolPayloadTransform(): ToolPayloadTransformPolicy | undefined {\n return this.#toolPayloadTransform;\n }\n\n /**\n * Gets the stored agents cache\n * @internal\n */\n public getStoredAgentCache() {\n return this.#storedAgentsCache;\n }\n\n /**\n * Gets the stored scorers cache\n * @internal\n */\n public getStoredScorerCache() {\n return this.#storedScorersCache;\n }\n\n /**\n * Generates a unique identifier using the configured generator or defaults to `crypto.randomUUID()`.\n *\n * This method is used internally by Mastra for creating unique IDs for various entities\n * like workflow runs, agent conversations, and other resources that need unique identification.\n *\n * @param context - Optional context information about what type of ID is being generated\n * and where it's being requested from. This allows custom ID generators\n * to create deterministic IDs based on context.\n *\n * @throws {MastraError} When the custom ID generator returns an empty string\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const id = mastra.generateId();\n * console.log(id); // \"550e8400-e29b-41d4-a716-446655440000\"\n *\n * // With context for deterministic IDs\n * const messageId = mastra.generateId({\n * idType: 'message',\n * source: 'agent',\n * threadId: 'thread-123'\n * });\n * ```\n */\n public generateId(context?: IdGeneratorContext): string {\n if (this.#idGenerator) {\n const id = this.#idGenerator(context);\n if (!id) {\n const error = new MastraError({\n id: 'MASTRA_ID_GENERATOR_RETURNED_EMPTY_STRING',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'ID generator returned an empty string, which is not allowed',\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return id;\n }\n return randomUUID();\n }\n\n /**\n * Sets a custom ID generator function for creating unique identifiers.\n *\n * The ID generator function will be used by `generateId()` instead of the default\n * `crypto.randomUUID()`. This is useful for creating application-specific ID formats\n * or integrating with existing ID generation systems. The function receives\n * optional context about what is requesting the ID.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * mastra.setIdGenerator(context =>\n * context?.idType === 'run' && context.entityId\n * ? `run-${context.entityId}-${Date.now()}`\n * : `custom-${Date.now()}`\n * );\n * const id = mastra.generateId({ idType: 'run', entityId: 'agent-123' });\n * console.log(id); // \"run-agent-123-1234567890\"\n * ```\n */\n public setIdGenerator(idGenerator: MastraIdGenerator) {\n this.#idGenerator = idGenerator;\n }\n\n /**\n * Sets the server configuration for this Mastra instance.\n *\n * @param server - The server configuration object\n *\n * @example\n * ```typescript\n * mastra.setServer({ ...mastra.getServer(), auth: new MastraAuthWorkos() });\n * ```\n */\n public setServer(server: ServerConfig): void {\n this.#server = server;\n }\n\n /**\n * Sets the studio configuration for this Mastra instance.\n *\n * The studio configuration controls authentication and authorization for Studio UI,\n * separate from the server configuration. This enables dual auth patterns where\n * Studio users (e.g., internal team) use different auth than API consumers.\n *\n * @param studio - The studio configuration object\n *\n * @example\n * ```typescript\n * // Set studio auth separately from server auth\n * mastra.setStudio({\n * auth: new MastraAuthStudio(),\n * rbac: new MastraRBACStudio({ roleMapping: { admin: ['*'] } }),\n * });\n * ```\n */\n public setStudio(studio: StudioConfig): void {\n this.#studio = studio;\n }\n\n /**\n * Registers an exporter on the default observability instance.\n *\n * If the current observability is a no-op (user didn't configure any), it is\n * first replaced with the provided entrypoint and the instance is registered\n * as default. If a real observability entrypoint already exists, the exporter\n * is added directly to the existing default instance.\n *\n * @param exporter - The exporter to register (e.g. a MastraPlatformExporter)\n * @param instance - An ObservabilityInstance pre-configured with the exporter, used as default when bootstrapping\n * @param entrypoint - A real ObservabilityEntrypoint to bootstrap if the current one is a no-op\n */\n public registerExporter(\n exporter: ObservabilityExporter,\n instance: ObservabilityInstance,\n entrypoint: ObservabilityEntrypoint,\n ): void {\n if (this.#observability instanceof NoOpObservability) {\n this.#observability = entrypoint;\n this.#observability.setLogger({ logger: this.#logger });\n this.#observability.setMastraContext({ mastra: this });\n this.#observability.registerInstance('default', instance, true);\n }\n\n const defaultInstance = this.#observability.getDefaultInstance();\n if (defaultInstance?.registerExporter) {\n defaultInstance.registerExporter(exporter);\n }\n }\n\n /**\n * Creates a new Mastra instance with the provided configuration.\n *\n * The constructor initializes all the components specified in the config, sets up\n * internal systems like logging and observability, and registers components with each other.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * id: 'assistant',\n * name: 'Assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * },\n * storage: new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }),\n * logger: new PinoLogger({ name: 'MyApp' }),\n * observability: new Observability({\n * configs: { default: { serviceName: 'mastra', exporters: [new MastraStorageExporter()] } },\n * }),\n * });\n * ```\n */\n constructor(\n config?: Config<\n TAgents,\n TWorkflows,\n TVectors,\n TTTS,\n TLogger,\n TMCPServers,\n TScorers,\n TTools,\n TProcessors,\n TMemory,\n TChannels\n >,\n ) {\n // Register AsyncLocalStorage-backed context resolvers so that DualLogger\n // can correlate logs to the active span. Must happen before any agent runs.\n initContextStorage();\n\n // Server cache for temporary persistence and durable agent resumable streams\n this.#serverCache = config?.cache ?? new InMemoryServerCache();\n\n // Boot-time recovery policy for durable agent runs. Default is 'off' so\n // that an install can't silently re-run tools/LLM calls on restart; opt-in\n // via `recovery: { durableAgents: 'auto' }` matches the existing\n // `restartAllActiveWorkflowRuns` boot hook.\n this.#recoveryConfig = {\n durableAgents: config?.recovery?.durableAgents ?? 'off',\n };\n\n this.#editor = config?.editor;\n\n // Store global version overrides\n this.#versions = config?.versions;\n\n // Resolve deployment environment: explicit config wins, else fall back to\n // NODE_ENV. Leave undefined if neither is set rather than guessing.\n this.#environment = config?.environment ?? process.env.NODE_ENV;\n this.#toolPayloadTransform = normalizeToolPayloadTransformPolicy(\n config?.transform ?? (config as any)?.toolPayloadProjection,\n );\n\n if (config?.pubsub) {\n this.#pubsub = config.pubsub;\n } else {\n this.#pubsub = new EventEmitterPubSub();\n }\n\n this.#events = {};\n for (const topic in config?.events ?? {}) {\n if (!Array.isArray(config?.events?.[topic])) {\n this.#events[topic] = [config?.events?.[topic] as any];\n } else {\n this.#events[topic] = config?.events?.[topic] ?? [];\n }\n }\n\n // Initialize workers based on config.\n // MASTRA_WORKERS env var:\n // - \"false\": disables all event processing in this instance\n // - comma-separated names (e.g. \"scheduler,orchestration\"): only those\n // workers will be started by `startWorkers()` when called without an\n // explicit `name` argument. Construction still creates all workers so\n // a later explicit `startWorkers('foo')` still works.\n const rawWorkersEnv = process.env.MASTRA_WORKERS;\n let workersOption: MastraWorker[] | false | undefined;\n if (rawWorkersEnv === 'false') {\n workersOption = false;\n } else {\n workersOption = config?.workers;\n if (rawWorkersEnv && rawWorkersEnv !== 'false') {\n const names = rawWorkersEnv\n .split(',')\n .map(s => s.trim())\n .filter(Boolean);\n if (names.length > 0) {\n this.#workerFilter = new Set(names);\n }\n }\n }\n\n if (workersOption === false) {\n // Explicitly disabled — no event processing in this instance.\n // PubSub still exists for publishing events. Record the opt-out so\n // runtime triggers (e.g. schedules.create()) don't lazily inject\n // scheduler / agent-schedule workers behind the user's back.\n this.#workersDisabled = true;\n } else {\n // Auto-create default workers based on config.\n //\n // Skip OrchestrationWorker when the configured pubsub doesn't support\n // pull delivery (e.g. EventEmitter, GCP Pub/Sub push) — those transports\n // don't have a read loop to drive a worker, and Mastra wires\n // `handleWorkflowEvent` directly to the pubsub during startWorkers().\n const pubsubModes = this.#pubsub.supportedModes ?? ['pull'];\n const defaultWorkers: MastraWorker[] = [];\n if (pubsubModes.includes('pull')) {\n defaultWorkers.push(new OrchestrationWorker());\n }\n // SchedulerWorker is added lazily in startWorkers() rather than here\n // because workflows (and their schedule configs) are registered after\n // this block runs, so #hasScheduledWorkflow is not yet set.\n if (config?.backgroundTasks?.enabled) {\n defaultWorkers.push(new BackgroundTaskWorker(config.backgroundTasks));\n }\n // Merge custom workers with the defaults: a custom worker replaces a\n // default sharing its name (e.g. a custom OrchestrationWorker), and\n // duplicate names within the custom array fail loud.\n const customWorkers = workersOption ?? [];\n const customNames = new Set<string>();\n for (const w of customWorkers) {\n if (customNames.has(w.name)) {\n throw new Error(`Duplicate worker name \"${w.name}\" in the 'workers' option`);\n }\n customNames.add(w.name);\n }\n this.#workers = [...defaultWorkers.filter(w => !customNames.has(w.name)), ...customWorkers];\n for (const w of this.#workers) {\n w.__registerMastra(this);\n }\n }\n\n let logger: TLogger;\n if (config?.logger === false) {\n logger = noopLogger as unknown as TLogger;\n this.#loggerExplicit = true;\n } else {\n if (config?.logger) {\n logger = config.logger;\n this.#loggerExplicit = true;\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 // Default to an in-memory store when none is configured. The evented\n // workflow engine uses storage as the source of truth for cross-branch\n // coordination in parallel/foreach steps, so a missing store would cause\n // parallel branches to silently fail to aggregate. In-memory is the safe\n // default for `new Mastra({})` / tests; production callers always override.\n let storage: MastraCompositeStore;\n if (config?.storage) {\n storage = config.storage;\n this.#storageExplicit = true;\n } else {\n storage = new InMemoryStore();\n this.#logger?.warn(\n 'No `storage` configured on Mastra — falling back to an in-memory store. ' +\n 'In-memory storage is not durable: all data is lost on restart, and it is not safe for production. ' +\n 'Configure a persistent storage adapter (e.g. @mastra/libsql, @mastra/pg, @mastra/cloudflare).',\n );\n }\n storage = augmentWithInit(storage);\n\n // The evented workflow engine (used internally by the agentic loop) requires\n // `workflows` and `backgroundTasks` storage domains. When a user provides a\n // MastraCompositeStore with only specific domains (e.g. just `notifications`),\n // these infrastructure domains may be missing. Patch them in with lightweight\n // in-memory defaults so the engine works transparently without requiring users\n // to configure internal implementation details.\n if (storage.stores) {\n if (!storage.stores.workflows || !storage.stores.backgroundTasks) {\n const fallbackDb = new InMemoryDB();\n if (!storage.stores.workflows) {\n storage.stores.workflows = new WorkflowsInMemory({ db: fallbackDb });\n }\n if (!storage.stores.backgroundTasks) {\n storage.stores.backgroundTasks = new BackgroundTasksInMemory({ db: fallbackDb });\n }\n }\n }\n\n // Validate and assign observability instance\n if (config?.observability) {\n this.#observabilityExplicit = true;\n if (typeof config.observability.getDefaultInstance === 'function') {\n this.#observability = config.observability;\n // Set logger early\n this.#observability.setLogger({ logger: this.#logger });\n } else {\n this.#logger?.warn(\n 'Observability configuration error: Expected an Observability instance, but received a config object. ' +\n 'Import and instantiate: import { Observability, MastraStorageExporter } from \"@mastra/observability\"; ' +\n 'then pass: observability: new Observability({ configs: { default: { serviceName: \"mastra\", exporters: [new MastraStorageExporter()] } } }). ' +\n 'Observability has been disabled.',\n );\n this.#observability = new NoOpObservability();\n }\n } else {\n this.#observability = new NoOpObservability();\n }\n\n // Wrap the logger in a DualLogger so all existing this.logger.info(...) calls\n // also forward to loggerVNext (observability structured logging).\n // This is transparent — no call sites need to change.\n // Uses a lazy getter so loggerVNext is always resolved at call time\n // (observability may not be fully initialized yet at this point).\n const dualLogger = new DualLogger(this.#logger, () => this.loggerVNext);\n this.#logger = dualLogger as unknown as TLogger;\n\n this.#storage = storage;\n\n // Give storage adapters a back-pointer to this Mastra instance so they\n // can look up code-defined agents, editor config, etc. when needed\n // (e.g. filesystem code-mode snapshot filtering).\n storage?.__registerMastra?.(this as unknown as Parameters<NonNullable<typeof storage.__registerMastra>>[0]);\n\n // Register the editor after storage is assigned so code mode can overlay\n // filesystem-backed editor storage while preserving app storage domains.\n if (this.#editor && typeof this.#editor.registerWithMastra === 'function') {\n this.#editor.registerWithMastra(this);\n }\n\n // Kick off background license validation against the license server when\n // an enterprise license key is configured. Fire-and-forget: LicenseClient\n // caches the result, schedules revalidation, and fails open on network\n // errors, so this never blocks or throws during construction.\n if (process.env.MASTRA_LICENSE_KEY || process.env.MASTRA_EE_LICENSE) {\n LicenseClient.getInstance(this.#logger)\n .validate()\n .catch(() => {\n // Failures are logged and handled inside LicenseClient.\n });\n }\n\n this.#backgroundTaskConfig = config?.backgroundTasks;\n // Always create the background-task manager when background tasks are\n // enabled. When workers are disabled (`workers: false`) or when a\n // MASTRA_WORKERS filter is set that excludes 'backgroundTasks', the\n // manager runs in 'producer' mode: it can enqueue/dispatch tasks and\n // receive completion notifications via the fan-out result topic, but\n // does NOT join the worker consumer group — so it won't compete with\n // a dedicated BackgroundTaskWorker process for dispatch events.\n const bgWorkerFiltered = this.#workerFilter && !this.#workerFilter.has('backgroundTasks');\n this.#ensureBackgroundTaskManager(workersOption === false || bgWorkerFiltered ? 'producer' : undefined);\n\n this.#schedulerConfig = config?.scheduler;\n this.#notificationDispatchConfig = config?.notifications?.dispatch;\n this.#schedulesConfig = config?.schedules;\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, MastraModelGatewayInterface>;\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 (this.#notificationDispatchConfig?.enabled !== false) {\n const workflow = createNotificationDispatchWorkflow(this.#notificationDispatchConfig);\n this.addWorkflow(workflow, workflow.id);\n this.#hiddenWorkflowKeys.add(workflow.id);\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 = getGatewayId(gateway);\n // Check by logical ID to avoid duplicates when a user-registered gateway\n // exists under a different registry key but has the same gateway ID.\n const existingGateways = Object.values(this.#gateways as Record<string, MastraModelGatewayInterface>);\n const alreadyRegistered = existingGateways.some(\n existingGateway => existingGateway != null && getGatewayId(existingGateway) === key,\n );\n if (!alreadyRegistered) {\n (this.#gateways as Record<string, MastraModelGatewayInterface>)[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 this.#serverExplicit = true;\n }\n\n if (config?.studio) {\n this.#studio = config.studio;\n this.#studioExplicit = true;\n }\n\n // Register channels and merge their routes into server config\n if (config?.channels) {\n this.#channels = config.channels;\n const channelRoutes: ApiRoute[] = [];\n\n for (const [, channel] of Object.entries(config.channels)) {\n if (channel == null) continue;\n\n // Attach the channel to this Mastra instance\n if (channel.__attach) {\n channel.__attach(this);\n }\n\n // Collect routes from the channel\n const routes = channel.getRoutes();\n channelRoutes.push(...routes);\n }\n\n // Merge channel routes into server config\n if (channelRoutes.length > 0) {\n const existingRoutes = this.#server?.apiRoutes ?? [];\n this.#server = {\n ...this.#server,\n apiRoutes: [...existingRoutes, ...channelRoutes],\n };\n }\n }\n\n // Agents must be added after server config so that channel webhook routes\n // are appended to (not replaced by) the server config.\n if (config?.agents) {\n Object.entries(config.agents).forEach(([key, agent]) => {\n if (agent != null) {\n this.addAgent(agent, key);\n }\n });\n }\n\n // `harnesses` is the deprecated alias of `agentControllers`; merge both,\n // letting `agentControllers` win on key collisions.\n const agentControllerEntries = {\n ...(config?.harnesses ?? {}),\n ...(config?.agentControllers ?? {}),\n };\n for (const [key, agentController] of Object.entries(agentControllerEntries)) {\n this.#harnesses[key] = agentController;\n agentController.__registerMastra(this);\n\n // Set up AgentControllerChannels for manual adapter configurations,\n // mirroring the agent channels wiring in `addAgent`.\n const controllerChannels = agentController.getChannels();\n if (controllerChannels) {\n controllerChannels.__setLogger(this.#logger);\n const channelRoutes = controllerChannels.getWebhookRoutes();\n if (channelRoutes.length > 0) {\n this.#server = {\n ...this.#server,\n apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n };\n }\n controllerChannels.initialize(this).catch(err => {\n this.#logger?.error(`Failed to initialize channels for agent controller ${key}:`, err);\n });\n }\n }\n\n // `registerHook` adds to a module-level emitter that never drops handlers on\n // its own. Keep the reference so short-lived internal Mastras can release it\n // on teardown (see `__unregisterHooks`); otherwise their handler fires on\n // every scorer run for the lifetime of the process. Ephemeral instances\n // (standalone-Agent fallbacks) skip registration entirely: their hook can\n // never resolve a scorer, and the emitter would pin the instance against GC\n // for the process lifetime (#19404).\n if (!config?.__ephemeral) {\n this.#onScorerHook = createOnScorerHook(this);\n registerHook(AvailableHooks.ON_SCORER_RUN, this.#onScorerHook);\n }\n\n /*\n Initialize observability with Mastra context (after storage configured)\n */\n this.#observability.setMastraContext({ mastra: this });\n\n this.setLogger({ logger });\n\n // Initialize channels asynchronously (auto-provision apps, etc.)\n // This runs after all agents are registered so configs are available\n if (this.#channels) {\n void Promise.resolve().then(async () => {\n for (const [key, channel] of Object.entries(this.#channels ?? {})) {\n if (channel.initialize) {\n try {\n await channel.initialize();\n } catch (err) {\n console.error(`[Mastra] Failed to initialize channel \"${key}\":`, err);\n }\n }\n }\n });\n }\n }\n\n #ensureBackgroundTaskManager(modeOverride?: 'producer' | 'worker' | 'full'): void {\n if (!this.#backgroundTaskConfig?.enabled || !this.#storage || this.#backgroundTaskManager) {\n return;\n }\n\n // Derive the effective mode from the worker configuration when no\n // explicit override is given. Late call-sites (#maybeEnableBackgroundTasksForAgent,\n // setStorage) don't know the worker topology, so we derive it here to\n // ensure producer mode is consistently applied when workers are disabled\n // or the backgroundTasks worker is excluded by the MASTRA_WORKERS filter.\n const effectiveMode =\n modeOverride ??\n (this.#workersDisabled || (this.#workerFilter && !this.#workerFilter.has('backgroundTasks'))\n ? 'producer'\n : undefined);\n\n const managerConfig = effectiveMode\n ? { ...this.#backgroundTaskConfig, mode: effectiveMode }\n : this.#backgroundTaskConfig;\n const bgManager = new BackgroundTaskManager(managerConfig);\n bgManager.__registerMastra(this);\n this.#backgroundTaskManager = bgManager;\n\n // Wire statically-registered tools into the manager's name-keyed registry\n // so cross-process workers can resolve dispatched tasks. Tools added later\n // via `addTool()` are propagated through the same path.\n const tools = this.#tools as Record<string, ToolAction<any, any, any, any>> | undefined;\n if (tools) {\n for (const [name, tool] of Object.entries(tools)) {\n this.#registerToolWithBackgroundManager(name, tool);\n }\n }\n\n void bgManager.init(this.#pubsub).catch(error => {\n this.#logger?.error('Failed to initialize background task manager', error);\n });\n }\n\n /**\n * Build a `ToolExecutor` adapter for a Mastra-registered tool and stash it\n * on the background task manager's static registry. Skipped if the tool has\n * no `execute` (declarative-only tools, e.g. MCP descriptors).\n */\n #registerToolWithBackgroundManager(name: string, tool: ToolAction<any, any, any, any>): void {\n if (!this.#backgroundTaskManager) return;\n if (typeof tool.execute !== 'function') return;\n const execute = tool.execute.bind(tool);\n this.#backgroundTaskManager.registerStaticExecutor(name, {\n execute: async (args, options) => {\n // Cross-process workers don't have access to the producer's\n // request/workspace context. Statically-resolvable tools should\n // tolerate a minimal context (abortSignal only). Tools that need\n // closure-captured state must run in-process via TaskContext.\n return execute(\n args as any,\n {\n toolCallId: '',\n messages: [],\n abortSignal: options?.abortSignal,\n } as any,\n );\n },\n });\n }\n\n /**\n * Returns the flat list of declarative schedules sourced from currently\n * registered workflows. Single-schedule workflows yield one entry keyed by\n * `wf_<encoded(workflowId)>`. Array-form workflows yield one entry per array\n * entry keyed by `wf_<encoded(workflowId)>__<encoded(scheduleId)>` so the\n * prefix uniquely identifies \"all rows owned by this workflow's declarative\n * config\" even when ids contain `__` or other delimiter-like characters.\n */\n #collectDeclarativeSchedules(): Array<{\n scheduleId: string;\n workflowId: string;\n cfg: WorkflowScheduleConfig;\n }> {\n const out: Array<{ scheduleId: string; workflowId: string; cfg: WorkflowScheduleConfig }> = [];\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n for (const workflow of Object.values(workflows ?? {})) {\n const configs = collectWorkflowScheduleConfigs(workflow);\n if (configs.length === 0) continue;\n const isArrayForm = configs.length > 1 || (configs.length === 1 && configs[0]!.id !== undefined);\n for (const cfg of configs) {\n const scheduleId = isArrayForm\n ? declarativeScheduleRowId(workflow.id, cfg.id)\n : declarativeScheduleRowId(workflow.id);\n out.push({ scheduleId, workflowId: workflow.id, cfg });\n }\n }\n return out;\n }\n\n #shouldEnableScheduler(): boolean {\n // Honour an explicit `workers: false` opt-out — the user disabled all\n // event processing in this instance, so never auto-inject scheduler /\n // agent-schedule workers (even when scheduler.enabled is true or a\n // schedule is created at runtime). Standalone workers are expected to\n // run the scheduler separately.\n if (this.#workersDisabled) return false;\n if (this.#schedulerConfig?.enabled === false) return false;\n if (this.#schedulerConfig?.enabled === true) return true;\n return this.#hasScheduledWorkflow || this.#schedulerRequested;\n }\n\n /**\n * Find the SchedulerWorker from the workers list (if present).\n */\n #findSchedulerWorker(): SchedulerWorker | undefined {\n return this.#workers.find((w): w is SchedulerWorker => w.name === 'scheduler') as SchedulerWorker | undefined;\n }\n\n /**\n * Find the AgentScheduleWorker from the workers list (if present).\n */\n #findAgentScheduleWorker(): MastraWorker | undefined {\n return this.#workers.find(w => w.name === 'agent-schedule');\n }\n\n /**\n * Sync code-declared schedule configs to the database. Called by\n * SchedulerWorker during init and by addWorkflow() for late registrations.\n *\n * @internal — public so SchedulerWorker can call it, not part of the user API.\n */\n async registerDeclarativeSchedules(schedulesStore: SchedulesStorage): Promise<void> {\n const declared = this.#collectDeclarativeSchedules();\n const declaredIds = new Set(declared.map(d => d.scheduleId));\n\n // Group declared ids by workflow so we can detect orphans (rows that\n // start with `wf_<encoded(workflowId)>` but aren't in the current declared\n // set). Seed an empty entry for every registered workflow first so that\n // workflows which removed all their schedules across a redeploy still\n // have their old rows cleaned up.\n const declaredIdsByWorkflow = new Map<string, Set<string>>();\n const workflows = this.#workflows as Record<string, AnyWorkflow> | undefined;\n for (const workflow of Object.values(workflows ?? {})) {\n declaredIdsByWorkflow.set(workflow.id, new Set());\n }\n for (const { workflowId, scheduleId } of declared) {\n if (!declaredIdsByWorkflow.has(workflowId)) declaredIdsByWorkflow.set(workflowId, new Set());\n declaredIdsByWorkflow.get(workflowId)!.add(scheduleId);\n }\n\n for (const { scheduleId, workflowId, cfg } of declared) {\n try {\n const existing = await schedulesStore.getSchedule(scheduleId);\n const now = Date.now();\n const target: Schedule['target'] = {\n type: 'workflow',\n workflowId,\n inputData: cfg.inputData,\n initialState: cfg.initialState,\n requestContext: cfg.requestContext,\n };\n\n if (!existing) {\n await schedulesStore.createSchedule({\n id: scheduleId,\n target,\n cron: cfg.cron,\n timezone: cfg.timezone,\n status: 'active',\n nextFireAt: computeNextFireAt(cfg.cron, { timezone: cfg.timezone, after: now }),\n createdAt: now,\n updatedAt: now,\n metadata: cfg.metadata,\n });\n continue;\n }\n\n // Diff config fields and patch the existing row if anything changed.\n // We deliberately leave `status` alone — a row may have been paused\n // out-of-band via storage, and a redeploy shouldn't unpause it.\n const patch: ScheduleUpdate = {};\n const cronChanged = existing.cron !== cfg.cron;\n const timezoneChanged = (existing.timezone ?? undefined) !== (cfg.timezone ?? undefined);\n\n if (cronChanged) patch.cron = cfg.cron;\n if (timezoneChanged) patch.timezone = cfg.timezone;\n if (!targetsEqual(existing.target, target)) patch.target = target;\n if (!metadataEqual(existing.metadata, cfg.metadata)) patch.metadata = cfg.metadata;\n\n // Cron or timezone change invalidates the stored nextFireAt — recompute\n // from now so we don't fire on the old schedule.\n if (cronChanged || timezoneChanged) {\n patch.nextFireAt = computeNextFireAt(cfg.cron, { timezone: cfg.timezone, after: now });\n }\n\n if (Object.keys(patch).length > 0) {\n await schedulesStore.updateSchedule(scheduleId, patch);\n }\n } catch (error) {\n this.#logger?.error('Failed to register declarative schedule', { scheduleId, workflowId, error });\n }\n }\n\n // Orphan deletion: drop any Mastra-managed declarative schedule rows\n // (id starts with `wf_<workflowId>` or `wf_<workflowId>__`) that are no\n // longer declared in code. This covers two cases:\n // 1. A registered workflow's array-form entries shrunk across deploys.\n // 2. The owning workflow itself was deleted from code. Leaving these\n // rows behind would have the scheduler keep firing for a workflow\n // the processor can't resolve, producing infinite event-redelivery\n // loops (see WorkflowEventProcessor#dispatch).\n // User-created schedules (via the schedules API) don't use the `wf_`\n // prefix, so they're untouched.\n const allRows = await schedulesStore.listSchedules();\n for (const row of allRows) {\n if (declaredIds.has(row.id)) continue;\n if (!row.id.startsWith('wf_')) continue;\n const ownerWorkflowId = ownerWorkflowIdForRow(row.id, declaredIdsByWorkflow) ?? ownerWorkflowIdFromRowId(row.id);\n if (!ownerWorkflowId) continue;\n try {\n await schedulesStore.deleteSchedule(row.id);\n } catch (error) {\n this.#logger?.error('Failed to delete orphaned declarative schedule', {\n scheduleId: row.id,\n workflowId: ownerWorkflowId,\n error,\n });\n }\n }\n }\n\n /**\n * Auto-enables the background task manager when an agent with sub-agents is\n * registered. Sub-agent delegation runs in the background by default so the\n * parent stream stays responsive; that requires the manager to be available.\n * No-op when the user explicitly opted out via `backgroundTasks.enabled: false`.\n *\n * Eligible agents: any agent whose `agents` field is either a static record\n * with at least one entry OR a dynamic (function-based) resolver. Function\n * resolvers are evaluated per request, so we can't inspect their contents\n * here — but if the caller bothered to wire one up, we enable defensively\n * so those resolved sub-agents also dispatch in the background.\n */\n #maybeEnableBackgroundTasksForAgent(agent: Agent<any>): void {\n // Already running — nothing to do\n if (this.#backgroundTaskManager) return;\n\n // Explicit opt-out\n if (this.#backgroundTaskConfig?.enabled === false) return;\n\n if (!agent.__hasSubAgentsConfigured?.()) return;\n\n this.#backgroundTaskConfig = { ...(this.#backgroundTaskConfig ?? {}), enabled: true };\n this.#ensureBackgroundTaskManager();\n }\n\n /**\n * Retrieves a registered agent by its name.\n *\n * @template TAgentName - The specific agent name type from the registered agents\n * @throws {MastraError} When the agent with the specified name is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({\n * id: 'weather-agent',\n * name: 'weather-agent',\n * instructions: 'You provide weather information',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n * const agent = mastra.getAgent('weatherAgent');\n * const response = await agent.generate('What is the weather?');\n * ```\n */\n public getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName];\n public getAgent<TAgentName extends keyof TAgents>(\n name: TAgentName,\n version: { versionId: string } | { status?: 'draft' | 'published' },\n ): Promise<TAgents[TAgentName]>;\n public getAgent<TAgentName extends keyof TAgents>(\n name: TAgentName,\n version?: { versionId: string } | { status?: 'draft' | 'published' },\n ): TAgents[TAgentName] | Promise<TAgents[TAgentName]> {\n const agent = this.#agents?.[name];\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with name ${String(name)} not found`,\n details: {\n status: 404,\n agentName: String(name),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!version) {\n return this.#agents[name];\n }\n\n return this.resolveVersionedAgent(agent, version);\n }\n\n /**\n * Returns the `AgentChannels` instances for all registered agents and\n * agent controllers. Keys are agent / agent controller registration keys.\n * A controller's channels — also attached to its mode agents — are\n * reported once, under the controller's key.\n */\n public getChannels(): Record<string, AgentChannels> {\n const result: Record<string, AgentChannels> = {};\n // Collect controller channels first so mode agents carrying a\n // controller's channels instance aren't double-reported under agent\n // keys. (Identity match rather than `instanceof AgentControllerChannels`:\n // a value import of that class from here recreates the module cycle\n // documented at the top of this file.)\n const controllerEntries: Array<[string, AgentChannels]> = [];\n const controllerOwned = new Set<AgentChannels>();\n for (const [controllerKey, controller] of Object.entries(this.#harnesses ?? {})) {\n const controllerChannels = controller.getChannels();\n if (controllerChannels) {\n controllerEntries.push([controllerKey, controllerChannels]);\n controllerOwned.add(controllerChannels);\n }\n }\n for (const [agentKey, agent] of Object.entries(this.#agents ?? {})) {\n const agentChannels = agent.getChannels();\n if (agentChannels instanceof AgentChannels && !controllerOwned.has(agentChannels)) {\n result[agentKey] = agentChannels;\n }\n }\n for (const [controllerKey, controllerChannels] of controllerEntries) {\n if (result[controllerKey]) {\n this.#logger?.warn(\n `Channels key collision: an agent and an agent controller are both registered under '${controllerKey}'; reporting the controller's channels.`,\n );\n }\n result[controllerKey] = controllerChannels;\n }\n return result;\n }\n\n /**\n * Retrieves a registered agent by its unique ID.\n *\n * This method searches for an agent using its internal ID property. If no agent\n * is found with the given ID, it also attempts to find an agent using the ID as\n * a name.\n *\n * @throws {MastraError} When no agent is found with the specified ID\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * assistant: new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * instructions: 'You are a helpful assistant',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * const assistant = mastra.getAgent('assistant');\n * const sameAgent = mastra.getAgentById(assistant.id);\n * ```\n */\n public getAgentById<TAgentName extends keyof TAgents>(id: TAgents[TAgentName]['id']): TAgents[TAgentName];\n public getAgentById<TAgentName extends keyof TAgents>(\n id: TAgents[TAgentName]['id'],\n version: { versionId: string } | { status?: 'draft' | 'published' },\n ): Promise<TAgents[TAgentName]>;\n public getAgentById<TAgentName extends keyof TAgents>(\n id: TAgents[TAgentName]['id'],\n version?: { versionId: string } | { status?: 'draft' | 'published' },\n ): TAgents[TAgentName] | Promise<TAgents[TAgentName]> {\n let agent = Object.values(this.#agents).find(a => a.id === id);\n\n if (!agent) {\n try {\n agent = this.getAgent(id as keyof TAgents) as TAgents[TAgentName];\n } catch {\n // do nothing\n }\n }\n\n if (!agent) {\n const error = new MastraError({\n id: 'MASTRA_GET_AGENT_BY_AGENT_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with id ${String(id)} not found`,\n details: {\n status: 404,\n agentId: String(id),\n agents: Object.keys(this.#agents ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!version) {\n return agent as TAgents[TAgentName];\n }\n\n return this.resolveVersionedAgent(agent as TAgents[TAgentName], version);\n }\n\n /**\n * Resolve a versioned variant of an agent by applying stored overrides from the editor.\n *\n * Requires the editor package to be configured — throws\n * `MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP` if it is not.\n *\n * @param agent - The code-defined agent to resolve a version for.\n * @param version - Selects a version by ID or publication status.\n * @returns A forked agent instance with the stored overrides applied.\n */\n public async resolveVersionedAgent<TAgent extends Agent>(\n agent: TAgent,\n version: VersionSelector | { status?: 'draft' | 'published' },\n ): Promise<TAgent> {\n const editor = this.getEditor();\n\n if (!editor) {\n const error = new MastraError({\n id: 'MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Versioned agent lookup requires the editor package to be configured',\n details: {\n status: 400,\n agentId: agent.id,\n ...(version && 'versionId' in version ? { versionId: version.versionId } : {}),\n ...(version && 'status' in version && version.status ? { versionStatus: version.status } : {}),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return editor.agent.applyStoredOverrides(\n agent,\n 'versionId' in version ? version : { status: version.status ?? 'published' },\n ) as Promise<TAgent>;\n }\n\n /**\n * Returns all registered agents as a record keyed by their names.\n *\n * This method provides access to the complete registry of agents, allowing you to\n * iterate over them, check what agents are available, or perform bulk operations.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: {\n * weatherAgent: new Agent({ id: 'weather-agent', name: 'weather', model: 'openai/gpt-4o' }),\n * supportAgent: new Agent({ id: 'support-agent', name: 'support', model: 'openai/gpt-4o' })\n * }\n * });\n *\n * const allAgents = mastra.listAgents();\n * console.log(Object.keys(allAgents)); // ['weatherAgent', 'supportAgent']\n * ```\n */\n public listAgents() {\n return this.#agents;\n }\n\n /**\n * Get an AgentController hosted on this Mastra instance by its registration\n * key (the key it was registered under in `new Mastra({ agentControllers })`).\n * Returns `undefined` when none is registered under that key. Server route\n * handlers use this to create and drive sessions over HTTP.\n *\n * @example\n * ```typescript\n * const code = new AgentController({ id: 'code-controller', modes });\n * const mastra = new Mastra({ agentControllers: { code } });\n *\n * mastra.getAgentController('code'); // → the AgentController (by key)\n * ```\n */\n public getAgentController(key: string): AgentController<any> | undefined {\n return this.#harnesses[key];\n }\n\n /**\n * Get an AgentController hosted on this Mastra instance by its unique `id`\n * (the `id` passed to the `AgentController` constructor). Falls back to a\n * registration-key lookup when none matches by id, mirroring\n * {@link getAgentById}. Returns `undefined` when none is found.\n *\n * @example\n * ```typescript\n * const code = new AgentController({ id: 'code-controller', modes });\n * const mastra = new Mastra({ agentControllers: { code } });\n *\n * mastra.getAgentControllerById('code-controller'); // → by id\n * ```\n */\n public getAgentControllerById(id: string): AgentController<any> | undefined {\n return Object.values(this.#harnesses).find(controller => controller.id === id) ?? this.#harnesses[id];\n }\n\n /**\n * List all AgentControllers hosted on this Mastra instance, keyed by their\n * registration key.\n */\n public listAgentControllers(): Record<string, AgentController<any>> {\n return this.#harnesses;\n }\n\n /**\n * Get a Harness hosted on this Mastra instance by its registration key.\n *\n * @deprecated Use {@link Mastra.getAgentController} instead.\n */\n public getHarness(key: string): Harness<any> | undefined {\n return this.getAgentController(key);\n }\n\n /**\n * Get a Harness hosted on this Mastra instance by its unique `id`.\n *\n * @deprecated Use {@link Mastra.getAgentControllerById} instead.\n */\n public getHarnessById(id: string): Harness<any> | undefined {\n return this.getAgentControllerById(id);\n }\n\n /**\n * List all Harnesses hosted on this Mastra instance, keyed by their\n * registration key.\n *\n * @deprecated Use {@link Mastra.listAgentControllers} instead.\n */\n public listHarnesses(): Record<string, Harness<any>> {\n return this.listAgentControllers();\n }\n\n /**\n * Adds a new agent to the Mastra instance.\n *\n * This method allows dynamic registration of agents after the Mastra instance\n * has been created. The agent will be initialized with the current logger.\n *\n * @throws {MastraError} When an agent with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newAgent = new Agent({\n * id: 'chat-agent',\n * name: 'Chat Assistant',\n * model: 'openai/gpt-4o'\n * });\n * mastra.addAgent(newAgent); // Uses agent.id as key\n * // or\n * mastra.addAgent(newAgent, 'customKey'); // Uses custom key\n *\n * // Durable agents (e.g., InngestAgent) are also supported:\n * const durableAgent = createInngestAgent({ agent: newAgent, inngest });\n * mastra.addAgent(durableAgent); // Auto-registers required workflows\n * ```\n */\n public addAgent<A extends Agent | ToolLoopAgentLike | DurableAgentLike>(\n agent: A,\n key?: string,\n options?: { source?: DefinitionSource },\n ): void {\n if (!agent) {\n throw createUndefinedPrimitiveError('agent', agent, key);\n }\n\n // Auto-wrap regular Agents that opted in via AgentConfig.durable.\n // The wrapped agent then flows into the isDurableAgentLike branch below,\n // which handles __setMastra, workflow registration, and channel routes.\n //\n // Statically importing `createDurableAgent` here is safe because `agent.ts`\n // imports `Mastra` type-only, so there is no `agent → mastra` runtime edge\n // to close the init cycle. See the import note in `agent/agent.ts`.\n //\n // A standalone durable `Agent` satisfies `isDurableAgentLike` via a\n // self-referential `.agent` getter (see `Agent#agent`), so we must\n // discriminate against a real wrapper by checking `agent.agent !== agent`.\n // Real wrappers (e.g. `DurableAgent`, `InngestAgent`) point `.agent` at a\n // distinct inner `Agent`; the standalone placeholder points at itself.\n const isRealDurableWrapper = isDurableAgentLike(agent) && (agent as DurableAgentLike).agent !== (agent as unknown);\n if (!isRealDurableWrapper && (agent as Agent).durable) {\n const durableOption = (agent as Agent).durable;\n const opts = durableOption === true ? {} : { ...(durableOption as object) };\n agent = createDurableAgent({ agent: agent as Agent, ...opts }) as unknown as A;\n }\n\n // Handle durable agent wrappers (e.g., InngestAgent)\n // These wrap a regular Agent with execution engine-specific capabilities\n if (isDurableAgentLike(agent)) {\n const durableAgent = agent as DurableAgentLike;\n const underlyingAgent = durableAgent.agent;\n const agentKey = key || durableAgent.id;\n\n // Check if already registered\n const agents = this.#agents as Record<string, Agent<any>>;\n if (agents[agentKey]) {\n const logger = this.getLogger();\n logger.debug(`Agent with key ${agentKey} already exists. Skipping addition.`);\n return;\n }\n\n // Set the Mastra instance on the durable agent for observability\n durableAgent.__setMastra?.(this);\n\n // Propagate the definition source (e.g. 'fs') onto both the wrapper and\n // the underlying agent. The durable branch returns early below, so it\n // never reaches the shared `options?.source` handling.\n if (options?.source) {\n (durableAgent as unknown as Agent<any>).source = options.source;\n underlyingAgent.source = options.source;\n }\n\n // Initialize the underlying agent (needed for tools, memory, etc.)\n underlyingAgent.__setLogger(this.#logger);\n underlyingAgent.__registerMastra(this);\n underlyingAgent.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n\n // Store the durable wrapper in #agents (not the underlying agent)\n // This ensures getAgentById returns the wrapper so .stream() uses durable execution.\n // The cast is safe because DurableAgent extends Agent directly, and InngestAgent uses\n // a Proxy that forwards all Agent method calls to the underlying agent.\n agents[agentKey] = durableAgent as unknown as Agent<any>;\n\n // Register durable workflows if the wrapper provides them\n const durableWorkflows = durableAgent.getDurableWorkflows?.() ?? [];\n for (const workflow of durableWorkflows) {\n this.addWorkflow(workflow, workflow.id);\n }\n\n // 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 underlyingAgent\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 durable 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 (underlyingAgent.hasOwnWorkspace?.()) {\n Promise.resolve(underlyingAgent.getWorkspace?.())\n .then(workspace => {\n if (workspace) {\n this.addWorkspace(workspace, undefined, {\n source: 'agent',\n agentId: durableAgent.id ?? agentKey,\n agentName: durableAgent.name,\n });\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register workspace for durable agent ${agentKey}:`, err);\n });\n }\n\n // Register scorers from the underlying agent so durable runs can resolve\n // them via mastra.getScorer()/getScorerById() at workflow time.\n underlyingAgent\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 durable agent ${agentKey}:`, err);\n });\n\n // Register durable-agent-owned tools with the background task manager.\n // Namespaced as `agentId:toolName` to avoid cross-agent collisions.\n // Use agentKey (derived from durableAgent.id) rather than underlyingAgent.id\n // because the dispatch side uses the durable wrapper's identity.\n if (this.#backgroundTaskManager) {\n const durableAgentId = durableAgent.id ?? agentKey;\n Promise.resolve(underlyingAgent.listTools())\n .then(agentTools => {\n for (const [toolKey, tool] of Object.entries(agentTools || {})) {\n if (tool && typeof (tool as any).execute === 'function') {\n this.#registerToolWithBackgroundManager(\n `${durableAgentId}:${toolKey}`,\n tool as ToolAction<any, any, any, any>,\n );\n }\n }\n })\n .catch(err => {\n this.#logger?.debug(\n `Failed to register durable agent tools for background tasks (agent ${agentKey}):`,\n err,\n );\n });\n }\n\n // Set up AgentChannels for manual adapter configurations\n const agentChannelsInstance = underlyingAgent.getChannels();\n if (agentChannelsInstance) {\n agentChannelsInstance.__setLogger(this.#logger);\n const channelRoutes = agentChannelsInstance.getWebhookRoutes();\n if (channelRoutes.length > 0) {\n this.#server = {\n ...this.#server,\n apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n };\n }\n agentChannelsInstance.initialize(this).catch(err => {\n this.#logger?.error(`Failed to initialize channels for durable agent ${agentKey}:`, err);\n });\n }\n\n return;\n }\n\n let mastraAgent: Agent<any, any, any>;\n if (isToolLoopAgentLike(agent)) {\n // Pass the config key as the name if the ToolLoopAgent doesn't have an id\n mastraAgent = toolLoopAgentToMastraAgent(agent, { fallbackName: key });\n } else {\n mastraAgent = agent as Agent;\n }\n const agentKey = key || mastraAgent.id;\n const agents = this.#agents as Record<string, Agent<any>>;\n if (agents[agentKey]) {\n return;\n }\n\n // Initialize the agent\n mastraAgent.__setLogger(this.#logger);\n mastraAgent.__registerMastra(this);\n mastraAgent.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n agents: agents,\n tts: this.#tts,\n vectors: this.#vectors,\n });\n\n // Set the source if provided\n if (options?.source) {\n mastraAgent.source = options.source;\n }\n\n agents[agentKey] = mastraAgent;\n\n // Register configured processor workflows from the agent\n // Use .then() to handle async resolution without blocking the constructor\n // This excludes memory-derived processors to avoid triggering memory factory functions\n mastraAgent\n .getConfiguredProcessorWorkflows()\n .then(processorWorkflows => {\n for (const workflow of processorWorkflows) {\n this.addWorkflow(workflow, workflow.id);\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register processor workflows for agent ${agentKey}:`, err);\n });\n\n // Register agent workspace in the workspaces registry for direct lookup.\n // Dynamic workspace functions may return undefined without request context — that's fine,\n // the if (workspace) guard below will skip registration and they'll register lazily later.\n if (mastraAgent.hasOwnWorkspace?.()) {\n Promise.resolve(mastraAgent.getWorkspace?.())\n .then(workspace => {\n if (workspace) {\n this.addWorkspace(workspace, undefined, {\n source: 'agent',\n agentId: mastraAgent.id ?? agentKey,\n agentName: mastraAgent.name,\n });\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register workspace for agent ${agentKey}:`, err);\n });\n }\n\n // Register scorers from the agent to the Mastra instance\n // This makes agent-level scorers discoverable via mastra.getScorer()/getScorerById()\n mastraAgent\n .listScorers()\n .then(scorers => {\n for (const [, entry] of Object.entries(scorers || {})) {\n this.addScorer(entry.scorer, undefined, { source: 'code' });\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register scorers from agent ${agentKey}:`, err);\n });\n\n // Register agent-owned tools with the background task manager's static\n // executor registry so cross-process workers can resolve dispatched tasks\n // for tools that are only attached to an agent (not top-level on Mastra).\n // Keys are namespaced as `agentId:toolName` to avoid cross-agent collisions\n // when multiple agents define tools with the same config key.\n // Dynamic (function-based) tools are resolved lazily and cannot be\n // eagerly registered — only static tool records are wired here.\n if (this.#backgroundTaskManager) {\n const agentId = mastraAgent.id ?? agentKey;\n Promise.resolve(mastraAgent.listTools())\n .then(agentTools => {\n for (const [toolKey, tool] of Object.entries(agentTools || {})) {\n if (tool && typeof (tool as any).execute === 'function') {\n this.#registerToolWithBackgroundManager(`${agentId}:${toolKey}`, tool as ToolAction<any, any, any, any>);\n }\n }\n })\n .catch(err => {\n this.#logger?.debug(`Failed to register agent tools for background tasks (agent ${agentKey}):`, err);\n });\n }\n\n // Set up AgentChannels for manual adapter configurations\n const agentChannelsInstance = mastraAgent.getChannels();\n if (agentChannelsInstance) {\n agentChannelsInstance.__setLogger(this.#logger);\n const channelRoutes = agentChannelsInstance.getWebhookRoutes();\n if (channelRoutes.length > 0) {\n this.#server = {\n ...this.#server,\n apiRoutes: [...(this.#server?.apiRoutes ?? []), ...channelRoutes],\n };\n }\n agentChannelsInstance.initialize(this).catch(err => {\n this.#logger?.error(`Failed to initialize channels for agent ${agentKey}:`, err);\n });\n }\n }\n\n /**\n * Registers a map of file-system routed agents (discovered from\n * `agents/<name>/` directories) into this Mastra instance.\n *\n * Code-registered agents win on name collisions: if an agent with the same\n * key already exists, the file-system agent is skipped and a warning is\n * logged. Otherwise each agent is added via {@link addAgent} with\n * `source: 'fs'`.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsAgents(fsAgents: Record<string, Agent | ToolLoopAgentLike | DurableAgentLike>): void {\n if (!fsAgents) {\n return;\n }\n\n const agents = this.#agents as Record<string, Agent<any>>;\n for (const [key, agent] of Object.entries(fsAgents)) {\n if (agent == null) {\n continue;\n }\n if (agents[key]) {\n this.getLogger().warn(\n `File-system routed agent \"${key}\" conflicts with a code-registered agent of the same name. Keeping the code-registered agent.`,\n );\n continue;\n }\n this.addAgent(agent, key, { source: 'fs' });\n }\n }\n\n /**\n * Registers a map of file-system routed workflows (discovered from\n * `workflows/*.ts` files) into this Mastra instance.\n *\n * Code-registered workflows win on name collisions: if a workflow with the\n * same key already exists, the file-system workflow is skipped and a warning\n * is logged. Otherwise each workflow is added via {@link addWorkflow} with\n * its key.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsWorkflows(fsWorkflows: Record<string, AnyWorkflow>): void {\n if (!fsWorkflows) {\n return;\n }\n\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n for (const [key, workflow] of Object.entries(fsWorkflows)) {\n if (workflow == null) {\n continue;\n }\n if (workflows[key]) {\n this.getLogger().warn(\n `File-system routed workflow \"${key}\" conflicts with a code-registered workflow of the same name. Keeping the code-registered workflow.`,\n );\n continue;\n }\n this.addWorkflow(workflow, key);\n }\n }\n\n /**\n * Registers a file-system routed logger (discovered from `logger.ts`) into\n * this Mastra instance.\n *\n * Code-registered loggers win: if the user already passed `logger` to the\n * `new Mastra({logger})` constructor (including `logger: false`), the\n * file-system logger is skipped and a warning is logged. Otherwise the\n * fs-provided logger replaces the default ConsoleLogger via {@link setLogger}.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsLogger(fsLogger: TLogger): void {\n if (!fsLogger) {\n return;\n }\n\n if (this.#loggerExplicit) {\n this.getLogger().warn(\n `File-system routed logger conflicts with a code-registered logger. Keeping the code-registered logger.`,\n );\n return;\n }\n\n this.setLogger({ logger: fsLogger });\n }\n\n /**\n * Registers a file-system routed storage instance (discovered from\n * `storage.ts`) into this Mastra instance.\n *\n * Code-registered storage wins: if the user already passed `storage` to the\n * `new Mastra({storage})` constructor, the file-system storage is skipped\n * and a warning is logged. Otherwise the fs-provided storage replaces the\n * default InMemoryStore via {@link setStorage}.\n *\n * Intended to be called by the bundler/dev generated entry, not by user code.\n *\n * @internal\n */\n public __registerFsStorage(fsStorage: MastraCompositeStore): void {\n if (!fsStorage) {\n return;\n }\n\n if (this.#storageExplicit) {\n this.getLogger().warn(\n `File-system routed storage conflicts with a code-registered storage. Keeping the code-registered storage.`,\n );\n return;\n }\n\n this.setStorage(fsStorage);\n }\n\n /**\n * Registers a file-system routed observability instance (discovered from\n * `observability.ts`) into this Mastra instance.\n *\n * Code-registered observability wins: if the user already passed\n * `observability` to the `new Mastra({observability})` constructor, the\n * file-system instance is skipped with a warning.\n *\n * @internal\n */\n public __registerFsObservability(fsObservability: ObservabilityEntrypoint): void {\n if (!fsObservability) {\n return;\n }\n\n if (this.#observabilityExplicit) {\n this.getLogger().warn(\n `File-system routed observability conflicts with a code-registered observability. Keeping the code-registered observability.`,\n );\n return;\n }\n\n if (typeof fsObservability.getDefaultInstance !== 'function') {\n this.getLogger().warn(\n `File-system routed observability.ts did not export a valid ObservabilityEntrypoint. Ignoring.`,\n );\n return;\n }\n\n this.#observability = fsObservability;\n // Pass the raw logger (not the DualLogger) to observability to avoid\n // circular forwarding, mirroring setLogger().\n const rawLogger = this.#logger instanceof DualLogger ? this.#logger.baseLogger : this.#logger;\n this.#observability.setLogger({ logger: rawLogger as any });\n this.#observability.setMastraContext({ mastra: this as any });\n }\n\n /**\n * Registers a file-system routed server config (discovered from\n * `server.ts`) into this Mastra instance.\n *\n * Code-registered server config wins on collision.\n *\n * @internal\n */\n public __registerFsServer(fsServer: ServerConfig): void {\n if (!fsServer) {\n return;\n }\n\n if (this.#serverExplicit) {\n this.getLogger().warn(\n `File-system routed server config conflicts with a code-registered server config. Keeping the code-registered server config.`,\n );\n return;\n }\n\n // Preserve apiRoutes accumulated during construction (e.g. channel\n // webhook routes) — they live on #server even when the user never\n // passed a server config explicitly.\n const existingRoutes = this.#server?.apiRoutes ?? [];\n const fsRoutes = fsServer.apiRoutes ?? [];\n const mergedRoutes = [...existingRoutes, ...fsRoutes];\n this.setServer({\n ...fsServer,\n ...(mergedRoutes.length > 0 ? { apiRoutes: mergedRoutes } : {}),\n });\n }\n\n /**\n * Registers a file-system routed studio config (discovered from\n * `studio.ts`) into this Mastra instance.\n *\n * Code-registered studio config wins on collision.\n *\n * @internal\n */\n public __registerFsStudio(fsStudio: StudioConfig): void {\n if (!fsStudio) {\n return;\n }\n\n if (this.#studioExplicit) {\n this.getLogger().warn(\n `File-system routed studio config conflicts with a code-registered studio config. Keeping the code-registered studio config.`,\n );\n return;\n }\n\n this.setStudio(fsStudio);\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 * Removes a registered workspace by its ID.\n *\n * When `destroy` is true, the workspace is destroyed before it is removed from\n * the registry. If destruction fails, the workspace remains registered and the\n * error is rethrown.\n *\n * @example\n * ```typescript\n * await mastra.removeWorkspace('workspace-123', { destroy: true });\n * ```\n */\n public async removeWorkspace(id: string, options?: { destroy?: boolean }): Promise<boolean> {\n const entry = this.#workspaces[id];\n if (!entry) {\n return false;\n }\n\n if (options?.destroy) {\n await entry.workspace.destroy();\n }\n\n delete this.#workspaces[id];\n\n if (this.#workspace === entry.workspace) {\n this.#workspace = undefined;\n }\n\n return true;\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 /**\n * Register a workflow under an internal-only registry.\n *\n * - Without `runId`: stored at the bare `${id}` slot. Used by single-instance\n * internal workflows (background tasks, score-traces) that are looked up\n * without a runId.\n * - With `runId`: stored *only* at `${id}:${runId}`. Concurrent or nested\n * invocations that share a workflow id (e.g. a parent and a sub-agent both\n * registering their `agentic-loop`) each get their own closure-bound\n * instance keyed by run, and the bare `${id}` slot is never overwritten by\n * a run-scoped registration — so a run-scoped lookup can never resolve a\n * *different* run's instance via an id scan.\n */\n __registerInternalWorkflow(workflow: AnyWorkflow, runId?: string) {\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n });\n if (runId) {\n const key = `${workflow.id}:${runId}`;\n const isNewRegistration = !this.#internalMastraWorkflows[key];\n this.#internalMastraWorkflows[key] = workflow;\n this.#runScopedWorkflowTimestamps.set(key, { registeredAt: Date.now(), runId });\n // Pair the registration with a runScope. Multiple workflows can share a\n // runId (parent + nested); we refcount so the scope outlives the first\n // unregister and dies with the last.\n if (isNewRegistration) {\n this.#runScopeRefcounts.set(runId, (this.#runScopeRefcounts.get(runId) ?? 0) + 1);\n if (!this.#runScopes.has(runId)) {\n this.#runScopes.set(runId, createRunScope());\n }\n }\n this.#sweepStaleRunScopedWorkflows();\n } else {\n this.#internalMastraWorkflows[workflow.id] = workflow;\n }\n }\n\n /**\n * Remove a runId-scoped registration. The unscoped `${id}` entry is left intact\n * so single-instance callers (background tasks, score-traces) continue to resolve.\n *\n * Decrements the refcount for the runScope tied to this runId; when the\n * count hits zero the scope is dropped along with every reference it held.\n */\n __unregisterInternalWorkflow(id: string, runId: string) {\n const key = `${id}:${runId}`;\n const wasRegistered = !!this.#internalMastraWorkflows[key];\n delete this.#internalMastraWorkflows[key];\n this.#runScopedWorkflowTimestamps.delete(key);\n if (wasRegistered) {\n this.#releaseRunScope(runId);\n }\n }\n\n /**\n * Get the existing runScope for a runId without creating one.\n * Returns undefined when no internal workflow has been registered against\n * the runId — callers should treat this as the run not yet being bootstrapped.\n */\n __getRunScope(runId: string): RunScope | undefined {\n return this.#runScopes.get(runId);\n }\n\n /**\n * Idempotently allocate a runScope for a runId. Used by call sites (like\n * `loop()`) that need to populate the scope *before* the internal workflow\n * registration lands. The scope is held until the matching internal-workflow\n * registration is released or the TTL sweep evicts it.\n *\n * Bumps the refcount so the scope cannot be freed before the caller is done\n * with it; callers MUST pair this with `__releaseRunScope(runId)`.\n */\n __createRunScope(runId: string): RunScope {\n let scope = this.#runScopes.get(runId);\n if (!scope) {\n scope = createRunScope();\n this.#runScopes.set(runId, scope);\n }\n this.#runScopeRefcounts.set(runId, (this.#runScopeRefcounts.get(runId) ?? 0) + 1);\n return scope;\n }\n\n /**\n * Decrement the runScope refcount; drops the scope when the count reaches\n * zero. Public so callers that called `__createRunScope` directly (e.g.,\n * `loop()` hydration) can release their hold without unregistering a\n * workflow.\n */\n __releaseRunScope(runId: string): void {\n this.#releaseRunScope(runId);\n }\n\n #releaseRunScope(runId: string): void {\n const next = (this.#runScopeRefcounts.get(runId) ?? 0) - 1;\n if (next <= 0) {\n this.#runScopeRefcounts.delete(runId);\n this.#runScopes.delete(runId);\n } else {\n this.#runScopeRefcounts.set(runId, next);\n }\n }\n\n __hasInternalWorkflow(id: string, runId?: string): boolean {\n if (runId) {\n // Only the exact run-scoped entry or the genuinely-unscoped slot — never\n // another run's `${id}:${otherRunId}` registration.\n return !!this.#internalMastraWorkflows[`${id}:${runId}`] || !!this.#internalMastraWorkflows[id];\n }\n return !!this.#internalMastraWorkflows[id];\n }\n\n /**\n * Returns `true` when this Mastra instance can resolve the workflow\n * identified by `workflowId` + `runId`. Mirrors the resolution order in\n * the WEP's `#dispatch` — internal registry → nested (parentWorkflow\n * present) → public registry — without side-effects.\n *\n * Used by the push-subscription guard in {@link startWorkers} to drop\n * cross-process events for internal workflows that belong to another\n * process.\n */\n #ownsWorkflow(workflowId: string, runId: string, parentWorkflow: unknown): boolean {\n // 1. Internal registry (run-scoped execution-workflow, agentic-loop, etc.)\n if (this.__hasInternalWorkflow(workflowId, runId)) return true;\n // 2. Nested workflow — walk up the parentWorkflow chain to the root and\n // verify that the root workflow is owned by this instance. Without this\n // check, cross-process subscribers would process foreign nested events\n // (the parentWorkflow field is truthy on both processes) and publish\n // spurious workflow.fail events that kill the correct owner's run.\n if (parentWorkflow) {\n let root = parentWorkflow as { workflowId?: string; runId?: string; parentWorkflow?: unknown };\n while (root.parentWorkflow) {\n root = root.parentWorkflow as typeof root;\n }\n const rootId = root.workflowId as string | undefined;\n const rootRunId = root.runId as string | undefined;\n if (rootId && rootRunId) {\n return this.#ownsWorkflow(rootId, rootRunId, undefined);\n }\n // Malformed chain — fall through to public registry check below.\n }\n // 3. Public workflow registry — direct lookup to avoid telemetry noise\n // from getWorkflowById() on the expected \"foreign workflow\" path.\n const workflows = this.#workflows as Record<string, AnyWorkflow> | undefined;\n if (workflows?.[workflowId]) return true;\n return Object.values(workflows ?? {}).some(w => w.id === workflowId);\n }\n\n __getInternalWorkflow(id: string, runId?: string): AnyWorkflow {\n const workflow = runId\n ? (this.#internalMastraWorkflows[`${id}:${runId}`] ?? this.#internalMastraWorkflows[id])\n : this.#internalMastraWorkflows[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 * @internal Records the tracing context for an evented workflow run so the\n * event processor can nest step spans under the run's parent span. The\n * `currentSpan` is non-serializable, so it is held here rather than passed\n * through the engine's pubsub events.\n */\n __registerRunTracingContext(runId: string, tracingContext: TracingContext) {\n this.#runTracingContexts.set(runId, tracingContext);\n }\n\n /** @internal Returns the tracing context recorded for an evented workflow run. */\n __getRunTracingContext(runId: string): TracingContext | undefined {\n return this.#runTracingContexts.get(runId);\n }\n\n /** @internal Clears the tracing context once an evented workflow run finishes. */\n __unregisterRunTracingContext(runId: string) {\n this.#runTracingContexts.delete(runId);\n }\n\n /**\n * Lazily evict run-scoped internal workflow entries that have exceeded\n * {@link Mastra.INTERNAL_WORKFLOW_TTL_MS}. Called on every new run-scoped\n * registration so cleanup is proportional to activity — zero overhead when\n * the system is idle.\n */\n #sweepStaleRunScopedWorkflows() {\n const now = Date.now();\n for (const [key, entry] of this.#runScopedWorkflowTimestamps) {\n if (now - entry.registeredAt > Mastra.INTERNAL_WORKFLOW_TTL_MS) {\n delete this.#internalMastraWorkflows[key];\n this.#runScopedWorkflowTimestamps.delete(key);\n // Release the matching scope using the runId we stored at registration\n // time — never parse it back out of the composite key, since callers\n // can pass runIds that contain ':'.\n this.#releaseRunScope(entry.runId);\n // Surface the eviction so operators can investigate long-suspended\n // runs that never resumed. The refcounted lifecycle in\n // `__createRunScope`/`__releaseRunScope` covers the happy path; this\n // branch only fires when a registration was abandoned past the TTL.\n this.#logger.warn('Evicted stale run-scoped workflow after TTL expired', {\n runId: entry.runId,\n ageMs: now - entry.registeredAt,\n ttlMs: Mastra.INTERNAL_WORKFLOW_TTL_MS,\n });\n }\n }\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 const activeRunsByWorkflow = await Promise.all(\n defaultEngineWorkflows.map(workflow => workflow.listActiveWorkflowRuns()),\n );\n\n const allRuns = activeRunsByWorkflow.flatMap(activeRuns => activeRuns.runs);\n const allTotal = activeRunsByWorkflow.reduce((total, activeRuns) => total + activeRuns.total, 0);\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 * The resolved boot-time recovery configuration for this Mastra instance.\n * See {@link Config.recovery}.\n */\n get recoveryConfig(): MastraRecoveryConfig {\n return this.#recoveryConfig;\n }\n\n /**\n * Re-drive every orphaned RUNNING durable-agent run across every registered\n * `DurableAgent`. Delegates to `DurableAgent.recoverActiveRuns()` on each\n * agent that supports it (default-engine durable agents only — Inngest and\n * other externally-executed durable wrappers run their own recovery).\n *\n * Intended to be called once on server boot, after\n * `restartAllActiveWorkflowRuns()`. The deployer wires this up automatically\n * when `recovery.durableAgents` is set to `'auto'` in the Mastra config; you\n * can also call it directly if you need finer control (e.g. running it in a\n * cron, or gating it behind a leader election).\n *\n * Requires persistent storage — with an in-memory store there is nothing to\n * recover after a process restart, so this is a no-op and returns zeroed\n * counts.\n */\n public async recoverAllDurableAgents(): Promise<{\n agents: number;\n recovered: number;\n succeeded: number;\n failed: number;\n }> {\n if (!this.#storage) {\n this.#logger.debug('Cannot recover durable agents. Mastra storage is not initialized');\n return { agents: 0, recovered: 0, succeeded: 0, failed: 0 };\n }\n\n const durableAgents: DurableAgentLike[] = [];\n for (const agent of Object.values(this.#agents ?? {})) {\n if (agent && isDurableAgentLike(agent)) {\n durableAgents.push(agent);\n }\n }\n\n if (durableAgents.length === 0) {\n return { agents: 0, recovered: 0, succeeded: 0, failed: 0 };\n }\n\n this.#logger.debug(\n `Recovering active durable-agent runs across ${durableAgents.length} agent${durableAgents.length > 1 ? 's' : ''}`,\n );\n\n let recovered = 0;\n let succeeded = 0;\n let failed = 0;\n\n for (const agent of durableAgents) {\n try {\n const result = await agent.recoverActiveRuns();\n recovered += result.recovered.length;\n succeeded += result.succeeded;\n failed += result.failed;\n } catch (error) {\n this.#logger.error('Failed to recover active runs for durable agent', {\n agentId: agent.id,\n error,\n });\n }\n }\n\n return { agents: durableAgents.length, recovered, succeeded, failed };\n }\n\n /**\n * Returns all registered scorers as a record keyed by their IDs.\n *\n * @example Listing all scorers\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer, RelevanceScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer(),\n * accuracy: new AccuracyScorer(),\n * relevance: new RelevanceScorer()\n * }\n * });\n *\n * const allScorers = mastra.listScorers();\n * console.log(Object.keys(allScorers)); // ['helpfulness', 'accuracy', 'relevance']\n *\n * // Check scorer configurations\n * for (const [id, scorer] of Object.entries(allScorers)) {\n * console.log(`Scorer ${id}:`, scorer.id, scorer.name, scorer.description);\n * }\n * ```\n */\n public listScorers() {\n return this.#scorers;\n }\n\n /**\n * Adds a new scorer to the Mastra instance.\n *\n * This method allows dynamic registration of scorers after the Mastra instance\n * has been created.\n *\n * If a scorer with the same key already exists, this method leaves the existing\n * scorer registered and returns.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newScorer = new MastraScorer({\n * id: 'quality-scorer',\n * name: 'Quality Scorer'\n * });\n * mastra.addScorer(newScorer); // Uses scorer.id as key\n * // or\n * mastra.addScorer(newScorer, 'customKey'); // Uses custom key\n * ```\n */\n public addScorer<S extends MastraScorer<any, any, any, any>>(\n scorer: S,\n key?: string,\n options?: { source?: DefinitionSource },\n ): void {\n if (!scorer) {\n throw createUndefinedPrimitiveError('scorer', scorer, key);\n }\n const scorerKey = key || scorer.id;\n const scorers = this.#scorers as Record<string, MastraScorer<any, any, any, any>>;\n if (scorers[scorerKey]) {\n return;\n }\n\n // Register Mastra instance with scorer to enable custom gateway access\n scorer.__registerMastra(this);\n\n // Set the source if provided\n if (options?.source) {\n scorer.source = options.source;\n }\n\n scorers[scorerKey] = scorer;\n }\n\n /**\n * Retrieves a registered scorer by its key.\n *\n * @template TScorerKey - The specific scorer key type from the registered scorers\n * @throws {MastraError} When the scorer with the specified key is not found\n *\n * @example Getting and using a scorer\n * ```typescript\n * import { HelpfulnessScorer, AccuracyScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * helpfulness: new HelpfulnessScorer({\n * model: 'openai/gpt-4o',\n * criteria: 'Rate how helpful this response is'\n * }),\n * accuracy: new AccuracyScorer({\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Get a specific scorer\n * const helpfulnessScorer = mastra.getScorer('helpfulness');\n * const score = await helpfulnessScorer.score({\n * input: 'How do I reset my password?',\n * output: 'You can reset your password by clicking the forgot password link.',\n * expected: 'Detailed password reset instructions'\n * });\n *\n * console.log('Helpfulness score:', score);\n * ```\n */\n public getScorer<TScorerKey extends keyof TScorers>(key: TScorerKey): TScorers[TScorerKey] {\n const scorer = this.#scorers?.[key];\n if (!scorer) {\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with ${String(key)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return scorer;\n }\n\n /**\n * Retrieves a registered scorer by its name.\n *\n * This method searches through all registered scorers to find one with the specified name.\n * Unlike `getScorer()` which uses the registration key, this method uses the scorer's\n * internal name property.\n *\n * @throws {MastraError} When no scorer is found with the specified name\n *\n * @example Finding a scorer by name\n * ```typescript\n * import { HelpfulnessScorer } from '@mastra/scorers';\n *\n * const mastra = new Mastra({\n * scorers: {\n * myHelpfulnessScorer: new HelpfulnessScorer({\n * name: 'helpfulness-evaluator',\n * model: 'openai/gpt-5'\n * })\n * }\n * });\n *\n * // Find scorer by its internal name, not the registration key\n * const scorer = mastra.getScorerById('helpfulness-evaluator');\n * const score = await scorer.score({\n * input: 'question',\n * output: 'answer'\n * });\n * ```\n */\n public getScorerById<TScorerName extends keyof TScorers>(id: TScorers[TScorerName]['id']): TScorers[TScorerName] {\n for (const [_key, value] of Object.entries(this.#scorers ?? {})) {\n if (value.id === id || value?.name === id) {\n return value as TScorers[TScorerName];\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_SCORER_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Scorer with id ${String(id)} not found`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Removes a scorer from the Mastra instance by its key or ID.\n *\n * @param keyOrId - The scorer key or ID to remove\n * @returns true if a scorer was removed, false if no scorer was found\n */\n public removeScorer(keyOrId: string): boolean {\n const scorers = this.#scorers as Record<string, MastraScorer<any, any, any, any>> | undefined;\n if (!scorers) return false;\n\n // Try direct key lookup first\n if (scorers[keyOrId]) {\n const scorerId = scorers[keyOrId]?.id;\n delete scorers[keyOrId];\n // Clear from stored scorers cache to prevent stale data\n if (scorerId) {\n this.#storedScorersCache.delete(scorerId);\n }\n return true;\n }\n\n // Try finding by ID or name\n const key = Object.keys(scorers).find(k => scorers[k]?.id === keyOrId || scorers[k]?.name === keyOrId);\n if (key) {\n const scorerId = scorers[key]?.id;\n delete scorers[key];\n // Clear from stored scorers cache to prevent stale data\n if (scorerId) {\n this.#storedScorersCache.delete(scorerId);\n }\n return true;\n }\n\n return false;\n }\n\n // =========================================================================\n // Prompt Blocks\n // =========================================================================\n\n /**\n * Returns all registered prompt blocks.\n */\n public listPromptBlocks(): Record<string, StorageResolvedPromptBlockType> {\n return this.#promptBlocks;\n }\n\n /**\n * Registers a prompt block in the Mastra instance's runtime registry.\n *\n * @param promptBlock - The resolved prompt block to register\n * @param key - Optional registration key (defaults to promptBlock.id)\n */\n public addPromptBlock(promptBlock: StorageResolvedPromptBlockType, key?: string): void {\n const blockKey = key || promptBlock.id;\n if (this.#promptBlocks[blockKey]) {\n return;\n }\n this.#promptBlocks[blockKey] = promptBlock;\n }\n\n /**\n * Retrieves a registered prompt block by its key.\n *\n * @throws {MastraError} When the prompt block with the specified key is not found\n */\n public getPromptBlock(key: string): StorageResolvedPromptBlockType {\n const block = this.#promptBlocks[key];\n if (!block) {\n throw new MastraError({\n id: 'MASTRA_GET_PROMPT_BLOCK_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Prompt block with key ${key} not found`,\n });\n }\n return block;\n }\n\n /**\n * Retrieves a registered prompt block by its ID.\n *\n * @throws {MastraError} When no prompt block is found with the specified ID\n */\n public getPromptBlockById(id: string): StorageResolvedPromptBlockType {\n for (const [, block] of Object.entries(this.#promptBlocks)) {\n if (block.id === id) {\n return block;\n }\n }\n\n throw new MastraError({\n id: 'MASTRA_GET_PROMPT_BLOCK_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Prompt block with id ${id} not found`,\n });\n }\n\n /**\n * Removes a prompt block from the Mastra instance by its key or ID.\n *\n * @param keyOrId - The prompt block key or ID to remove\n * @returns true if a prompt block was removed, false if not found\n */\n public removePromptBlock(keyOrId: string): boolean {\n if (this.#promptBlocks[keyOrId]) {\n delete this.#promptBlocks[keyOrId];\n return true;\n }\n\n const key = Object.keys(this.#promptBlocks).find(k => this.#promptBlocks[k]?.id === keyOrId);\n if (key) {\n delete this.#promptBlocks[key];\n return true;\n }\n\n return false;\n }\n\n /**\n * Retrieves a specific tool by registration key.\n *\n * @throws {MastraError} When the specified tool is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool,\n * weather: weatherTool\n * }\n * });\n *\n * const tool = mastra.getTool('calculator');\n * ```\n */\n public getTool<TToolName extends keyof TTools>(name: TToolName): TTools[TToolName] {\n if (!this.#tools || !this.#tools[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_TOOL_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with name ${String(name)} not found`,\n details: {\n status: 404,\n toolName: String(name),\n tools: Object.keys(this.#tools ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#tools[name];\n }\n\n /**\n * Retrieves a specific tool by its ID.\n *\n * @throws {MastraError} When the specified tool is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool\n * }\n * });\n *\n * const tool = mastra.getToolById('calculator-tool-id');\n * ```\n */\n public getToolById<TToolName extends keyof TTools>(id: TTools[TToolName]['id']): TTools[TToolName] {\n const allTools = this.#tools;\n\n if (!allTools) {\n throw new MastraError({\n id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with id ${id} not found`,\n });\n }\n // First try to find by internal ID\n for (const tool of Object.values(allTools)) {\n if (tool.id === id) {\n return tool as TTools[TToolName];\n }\n }\n\n // Fallback to searching by registration key\n const toolByKey = allTools[id];\n if (toolByKey) {\n return toolByKey as TTools[TToolName];\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_TOOL_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Tool with id ${id} not found`,\n details: {\n status: 404,\n toolId: String(id),\n tools: Object.keys(allTools).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Lists all configured tools.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tools: {\n * calculator: calculatorTool,\n * weather: weatherTool\n * }\n * });\n *\n * const tools = mastra.listTools();\n * Object.entries(tools || {}).forEach(([name, tool]) => {\n * console.log(`Tool \"${name}\":`, tool.id);\n * });\n * ```\n */\n public listTools(): TTools | undefined {\n return this.#tools;\n }\n\n /**\n * Adds a new tool to the Mastra instance.\n *\n * This method allows dynamic registration of tools after the Mastra instance\n * has been created.\n *\n * @throws {MastraError} When a tool with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newTool = createTool({\n * id: 'calculator-tool',\n * description: 'Performs calculations'\n * });\n * mastra.addTool(newTool); // Uses tool.id as key\n * // or\n * mastra.addTool(newTool, 'customKey'); // Uses custom key\n * ```\n */\n public addTool<T extends ToolAction<any, any, any, any>>(tool: T, key?: string): void {\n if (!tool) {\n throw createUndefinedPrimitiveError('tool', tool, key);\n }\n const toolKey = key || tool.id;\n const tools = this.#tools as Record<string, ToolAction<any, any, any, any>>;\n if (tools[toolKey]) {\n return;\n }\n\n tools[toolKey] = tool;\n\n // If the background-task manager has already initialized, register the\n // newly-added tool with its static registry so cross-process workers can\n // resolve dispatches for it. If init hasn't happened yet, the registry\n // will be populated wholesale in #ensureBackgroundTaskManager().\n if (this.#backgroundTaskManager) {\n this.#registerToolWithBackgroundManager(toolKey, tool);\n }\n }\n\n /**\n * Removes a tool from the Mastra instance by its registration key.\n *\n * Also unregisters the tool's static executor from the background task\n * manager, if one was registered.\n *\n * @returns `true` if a tool was removed, `false` if no tool was registered under the key\n *\n * @example\n * ```typescript\n * mastra.removeTool('calculator-tool');\n * ```\n */\n public removeTool(key: string): boolean {\n const tools = this.#tools as Record<string, ToolAction<any, any, any, any>>;\n if (!tools[key]) {\n return false;\n }\n delete tools[key];\n this.#backgroundTaskManager?.unregisterStaticExecutor(key);\n return true;\n }\n\n /**\n * Retrieves a specific processor by registration key.\n *\n * @throws {MastraError} When the specified processor is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor,\n * transformer: transformerProcessor\n * }\n * });\n *\n * const processor = mastra.getProcessor('validator');\n * ```\n */\n public getProcessor<TProcessorName extends keyof TProcessors>(name: TProcessorName): TProcessors[TProcessorName] {\n if (!this.#processors || !this.#processors[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_NAME_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with name ${String(name)} not found`,\n details: {\n status: 404,\n processorName: String(name),\n processors: Object.keys(this.#processors ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#processors[name];\n }\n\n /**\n * Retrieves a specific processor by its ID.\n *\n * @throws {MastraError} When the specified processor is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor\n * }\n * });\n *\n * const processor = mastra.getProcessorById('validator-processor-id');\n * ```\n */\n public getProcessorById<TProcessorName extends keyof TProcessors>(\n id: TProcessors[TProcessorName]['id'],\n ): TProcessors[TProcessorName] {\n const allProcessors = this.#processors;\n\n if (!allProcessors) {\n throw new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with id ${id} not found`,\n });\n }\n\n // First try to find by internal ID\n for (const processor of Object.values(allProcessors)) {\n if (processor.id === id) {\n return processor as TProcessors[TProcessorName];\n }\n }\n\n // Fallback to searching by registration key\n const processorByKey = allProcessors[id];\n if (processorByKey) {\n return processorByKey as TProcessors[TProcessorName];\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Processor with id ${id} not found`,\n details: {\n status: 404,\n processorId: String(id),\n processors: Object.keys(allProcessors).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Lists all configured processors.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * processors: {\n * validator: validatorProcessor,\n * transformer: transformerProcessor\n * }\n * });\n *\n * const processors = mastra.listProcessors();\n * Object.entries(processors || {}).forEach(([name, processor]) => {\n * console.log(`Processor \"${name}\":`, processor.id);\n * });\n * ```\n */\n public listProcessors(): TProcessors | undefined {\n return this.#processors;\n }\n\n /**\n * Adds a new processor to the Mastra instance.\n *\n * This method allows dynamic registration of processors after the Mastra instance\n * has been created.\n *\n * @throws {MastraError} When a processor with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newProcessor = {\n * id: 'text-processor',\n * processInput: async (messages) => messages\n * };\n * mastra.addProcessor(newProcessor); // Uses processor.id as key\n * // or\n * mastra.addProcessor(newProcessor, 'customKey'); // Uses custom key\n * ```\n */\n public addProcessor<P extends Processor>(processor: P, key?: string): void {\n if (!processor) {\n throw createUndefinedPrimitiveError('processor', processor, key);\n }\n const processorKey = key || processor.id;\n const processors = this.#processors as Record<string, Processor>;\n if (processors[processorKey]) {\n return;\n }\n\n // Register Mastra with the processor if it supports it\n if (typeof processor.__registerMastra === 'function') {\n processor.__registerMastra(this);\n }\n\n processors[processorKey] = processor;\n }\n\n /**\n * Registers a processor configuration with agent context.\n * This tracks which agents use which processors with what configuration.\n *\n * @param processor - The processor instance\n * @param agentId - The ID of the agent that uses this processor\n * @param type - Whether this is an input or output processor\n */\n public addProcessorConfiguration(processor: Processor, agentId: string, type: 'input' | 'output'): void {\n const processorId = processor.id;\n if (!this.#processorConfigurations.has(processorId)) {\n this.#processorConfigurations.set(processorId, []);\n }\n const configs = this.#processorConfigurations.get(processorId)!;\n\n // Check if this exact configuration already exists\n const exists = configs.some(c => c.agentId === agentId && c.type === type);\n if (!exists) {\n configs.push({ processor, agentId, type });\n }\n }\n\n /**\n * Gets all processor configurations for a specific processor ID.\n *\n * @param processorId - The ID of the processor\n * @returns Array of configurations with agent context\n */\n public getProcessorConfigurations(\n processorId: string,\n ): Array<{ processor: Processor; agentId: string; type: 'input' | 'output' }> {\n return this.#processorConfigurations.get(processorId) || [];\n }\n\n /**\n * Gets all processor configurations.\n *\n * @returns Map of processor IDs to their configurations\n */\n public listProcessorConfigurations(): Map<\n string,\n Array<{ processor: Processor; agentId: string; type: 'input' | 'output' }>\n > {\n return this.#processorConfigurations;\n }\n\n /**\n * Retrieves a registered memory instance by its registration key.\n *\n * @throws {MastraError} When the memory instance with the specified key is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * memory: {\n * chat: new Memory({ storage })\n * }\n * });\n *\n * const chatMemory = mastra.getMemory('chat');\n * ```\n */\n public getMemory<TMemoryName extends keyof TMemory>(name: TMemoryName): TMemory[TMemoryName] {\n if (!this.#memory || !this.#memory[name]) {\n const error = new MastraError({\n id: 'MASTRA_GET_MEMORY_BY_KEY_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Memory with key ${String(name)} not found`,\n details: {\n status: 404,\n memoryKey: String(name),\n memory: Object.keys(this.#memory ?? {}).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return this.#memory[name];\n }\n\n /**\n * Retrieves a registered memory instance by its ID.\n *\n * Searches through all registered memory instances and returns the one whose ID matches.\n *\n * @throws {MastraError} When no memory instance with the specified ID is found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * memory: {\n * chat: new Memory({ id: 'chat-memory', storage })\n * }\n * });\n *\n * const memory = mastra.getMemoryById('chat-memory');\n * ```\n */\n public getMemoryById(id: string): MastraMemory {\n const allMemory = this.#memory;\n if (allMemory) {\n for (const [, memory] of Object.entries(allMemory)) {\n if (memory.id === id) {\n return memory;\n }\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_MEMORY_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Memory with id ${id} not found`,\n details: {\n status: 404,\n memoryId: id,\n availableIds: Object.values(allMemory ?? {})\n .map(m => m.id)\n .join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Returns all registered memory instances as a record keyed by their names.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * memory: {\n * chat: new Memory({ storage }),\n * longTerm: new Memory({ storage })\n * }\n * });\n *\n * const allMemory = mastra.listMemory();\n * console.log(Object.keys(allMemory)); // ['chat', 'longTerm']\n * ```\n */\n public listMemory(): TMemory | undefined {\n return this.#memory;\n }\n\n /**\n * Adds a new memory instance to the Mastra instance.\n *\n * This method allows dynamic registration of memory instances after the Mastra instance\n * has been created.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const chatMemory = new Memory({\n * id: 'chat-memory',\n * storage: mastra.getStorage()\n * });\n * mastra.addMemory(chatMemory); // Uses memory.id as key\n * // or\n * mastra.addMemory(chatMemory, 'customKey'); // Uses custom key\n * ```\n */\n public addMemory<M extends MastraMemory>(memory: M, key?: string): void {\n if (!memory) {\n throw createUndefinedPrimitiveError('memory', memory, key);\n }\n const memoryKey = key || memory.id;\n const memoryRegistry = this.#memory as Record<string, MastraMemory>;\n if (memoryRegistry[memoryKey]) {\n return;\n }\n\n memory.__registerMastra(this);\n if (!memory.hasOwnStorage) {\n const storage = this.getStorage();\n if (storage) {\n memory.setStorage(storage);\n }\n }\n\n memoryRegistry[memoryKey] = memory;\n }\n\n /**\n * Returns all registered workflows as a record keyed by their IDs.\n *\n * @example Listing all workflows\n * ```typescript\n * const mastra = new Mastra({\n * workflows: {\n * dataProcessor: createWorkflow({...}).commit(),\n * emailSender: createWorkflow({...}).commit(),\n * reportGenerator: createWorkflow({...}).commit()\n * }\n * });\n *\n * const allWorkflows = mastra.listWorkflows();\n * console.log(Object.keys(allWorkflows)); // ['dataProcessor', 'emailSender', 'reportGenerator']\n *\n * // Execute all workflows with sample data\n * for (const [id, workflow] of Object.entries(allWorkflows)) {\n * console.log(`Workflow ${id}:`, workflow.name);\n * // const result = await workflow.execute(sampleData);\n * }\n * ```\n */\n public listWorkflows(props: { serialized?: boolean } = {}): Record<string, Workflow> {\n const workflows = Object.fromEntries(\n Object.entries(this.#workflows).filter(([key]) => !this.#hiddenWorkflowKeys.has(key)),\n ) as Record<string, Workflow>;\n\n if (props.serialized) {\n return Object.entries(workflows).reduce((acc, [k, v]) => {\n return {\n ...acc,\n [k]: { name: v.name },\n };\n }, {});\n }\n return workflows;\n }\n\n /**\n * Adds a new workflow to the Mastra instance.\n *\n * This method allows dynamic registration of workflows after the Mastra instance\n * has been created. The workflow will be initialized with Mastra and primitives.\n *\n * @throws {MastraError} When a workflow with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newWorkflow = createWorkflow({\n * id: 'data-pipeline',\n * name: 'Data Pipeline'\n * }).commit();\n * mastra.addWorkflow(newWorkflow); // Uses workflow.id as key\n * // or\n * mastra.addWorkflow(newWorkflow, 'customKey'); // Uses custom key\n * ```\n */\n public addWorkflow(workflow: AnyWorkflow, key?: string): void {\n if (!workflow) {\n throw createUndefinedPrimitiveError('workflow', workflow, key);\n }\n const workflowKey = key || workflow.id;\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n if (workflows[workflowKey]) {\n return;\n }\n\n // Note on schedules: a workflow declaring a `schedule` is auto-promoted to\n // the evented engine by the `createWorkflow` factory. We don't reject default-\n // engine workflows that happen to carry schedule configs — those would only\n // exist if a user constructed `Workflow` directly, in which case they've\n // explicitly opted out of the factory's promotion behavior and we trust them.\n const scheduleConfigs = collectWorkflowScheduleConfigs(workflow);\n const hasSchedule = scheduleConfigs.length > 0;\n\n // Initialize the workflow with Mastra and primitives\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n });\n if (!workflow.committed) {\n workflow.commit();\n }\n workflows[workflowKey] = workflow;\n\n this.registerStaticWorkflowScorers(workflow);\n\n // If a schedule is declared, mark the flag and register into the\n // running scheduler worker (if already started).\n if (hasSchedule) {\n this.#hasScheduledWorkflow = true;\n const worker = this.#findSchedulerWorker();\n if (worker?.scheduler) {\n void (async () => {\n try {\n const schedulesStore = await this.#storage?.getStore('schedules');\n if (!schedulesStore) return;\n await this.registerDeclarativeSchedules(schedulesStore);\n } catch (error) {\n this.#logger?.error('Failed to register declarative schedule for workflow', {\n workflowId: workflow.id,\n error,\n });\n }\n })();\n }\n // If the worker doesn't exist yet (workers not started), schedules\n // will be registered when SchedulerWorker.init() runs.\n }\n }\n\n /**\n * Signal that a schedule has been registered imperatively at runtime\n * (e.g. `mastra.schedules.create()` after `startWorkers()`). Flips the\n * scheduler-requested flag and, if workers are already running,\n * lazily injects + starts both the scheduler and agent-schedule workers.\n *\n * @internal\n */\n async __ensureScheduleRuntimeReady(): Promise<void> {\n this.#schedulerRequested = true;\n if (this.#workersStarted) {\n await this.#ensureSchedulingWorkersStarted();\n }\n }\n\n /**\n * Signal that a deferred notification exists and the dispatcher schedule is\n * needed. Lazily upserts the dispatcher schedule row (imperative, non-`wf_`\n * id so declarative orphan-cleanup leaves it alone) and requests the\n * scheduler — mirroring `__ensureScheduleRuntimeReady()`. Idle apps that\n * never defer a notification never start the scheduler (see #18864).\n *\n * @internal\n */\n async __ensureNotificationDispatchReady(): Promise<void> {\n if (this.#notificationDispatchReady) return;\n if (this.#notificationDispatchConfig?.enabled === false) return;\n if (this.#workersDisabled) return;\n if (this.#schedulerConfig?.enabled === false) return;\n if (!this.#storage) return;\n\n try {\n const schedulesStore = await this.#storage.getStore('schedules');\n if (!schedulesStore) return;\n\n const desired = buildNotificationDispatchSchedule(this.#notificationDispatchConfig);\n const existing = await schedulesStore.getSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n if (!existing) {\n try {\n await schedulesStore.createSchedule(desired);\n } catch (err) {\n // Another instance may have created the row concurrently — only\n // rethrow if it's still missing.\n const raced = await schedulesStore.getSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n if (!raced) throw err;\n }\n } else {\n // Patch the row if the dispatch config changed across deploys.\n const patch: ScheduleUpdate = {};\n if (existing.cron !== desired.cron) {\n patch.cron = desired.cron;\n patch.nextFireAt = desired.nextFireAt;\n }\n if (!targetsEqual(existing.target, desired.target)) patch.target = desired.target;\n if (Object.keys(patch).length > 0) {\n await schedulesStore.updateSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID, patch);\n }\n }\n } catch (err) {\n // Leave #notificationDispatchReady unset so the next deferred\n // notification retries the upsert.\n this.#logger?.warn?.('Failed to ensure notification dispatch schedule', err as any);\n return;\n }\n\n this.#notificationDispatchReady = true;\n this.#schedulerRequested = true;\n if (this.#workersStarted) {\n await this.#ensureSchedulingWorkersStarted();\n }\n }\n\n /**\n * Lazily inject and start the SchedulerWorker (and AgentScheduleWorker when\n * needed) after `startWorkers()` has already run. Used by features that\n * surface a need for the scheduler at runtime (e.g.\n * `mastra.schedules.create()`). No-op when the scheduler is disabled, no\n * storage is configured, or the workers are already present.\n *\n * @internal\n */\n async #ensureSchedulingWorkersStarted(): Promise<void> {\n // Memoize the in-flight startup so concurrent callers can't both pass the\n // worker-existence checks and start duplicate workers (which would\n // double-subscribe to the scheduling topics on push-based pubsubs).\n if (!this.#schedulingWorkersStartPromise) {\n this.#schedulingWorkersStartPromise = this.#startSchedulingWorkers().finally(() => {\n this.#schedulingWorkersStartPromise = undefined;\n });\n }\n await this.#schedulingWorkersStartPromise;\n }\n\n async #startSchedulingWorkers(): Promise<void> {\n if (!this.#shouldEnableScheduler()) return;\n if (!this.#storage) return;\n\n const deps: WorkerDeps = {\n pubsub: this.#pubsub,\n storage: this.#storage,\n logger: this.#logger as unknown as IMastraLogger,\n mastra: this,\n };\n\n if (!this.#findSchedulerWorker()) {\n const sw = new SchedulerWorker(this.#schedulerConfig);\n sw.__registerMastra(this);\n this.#workers.push(sw);\n await sw.init(deps);\n await sw.start();\n }\n\n if (!this.#findAgentScheduleWorker()) {\n const { AgentScheduleWorker } = await import('../schedules/worker');\n const asw = new AgentScheduleWorker();\n asw.__registerMastra(this);\n this.#workers.push(asw);\n await asw.init(deps);\n await asw.start();\n }\n }\n\n /**\n * Detect agent-schedule rows in storage on boot. Used by\n * `#shouldEnableScheduler` to flip the scheduler-requested flag when\n * imperative agent schedules persisted from a previous process exist —\n * without this, a fresh boot with only DB-side agent schedules would skip\n * starting the scheduler and agent-schedule workers entirely.\n *\n * @internal\n */\n async #detectExistingAgentSchedules(): Promise<void> {\n if (this.#schedulerRequested) return;\n if (!this.#storage) return;\n try {\n const schedulesStore = await this.#storage.getStore('schedules');\n if (!schedulesStore) return;\n const existing = await schedulesStore.listSchedules({ ownerType: 'agent' });\n if (existing.length === 0) return;\n this.#schedulerRequested = true;\n } catch (err) {\n this.#logger?.warn?.('Failed to detect existing agent schedules on boot', err as any);\n }\n }\n\n /**\n * Detect the lazily-created notification dispatcher schedule row on boot.\n * A previous process upserts the row via `__ensureNotificationDispatchReady()`\n * when a deferred notification is created; a fresh boot must then start the\n * scheduler so pending deferred notifications still get dispatched.\n * Mirrors `#detectExistingAgentSchedules`.\n *\n * @internal\n */\n async #detectExistingNotificationDispatch(): Promise<void> {\n if (this.#schedulerRequested) return;\n if (this.#notificationDispatchConfig?.enabled === false) return;\n if (!this.#storage) return;\n try {\n const schedulesStore = await this.#storage.getStore('schedules');\n if (!schedulesStore) return;\n const existing = await schedulesStore.getSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n if (!existing) return;\n this.#schedulerRequested = true;\n } catch (err) {\n this.#logger?.warn?.('Failed to detect existing notification dispatch schedule on boot', err as any);\n }\n }\n\n private registerStaticWorkflowScorers(workflow: AnyWorkflow): void {\n for (const step of Object.values(workflow.steps ?? {})) {\n const scorers = step.scorers;\n if (!scorers || typeof scorers === 'function') {\n continue;\n }\n\n for (const [, entry] of Object.entries(scorers)) {\n this.addScorer(entry.scorer, undefined, { source: 'code' });\n }\n }\n }\n\n /**\n * Sets the storage provider for the Mastra instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n *\n * // Set PostgreSQL storage\n * mastra.setStorage(new PostgresStore({\n * connectionString: process.env.DATABASE_URL\n * }));\n *\n * // Now agents can use memory with the storage\n * const agent = new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * memory: new Memory({ storage: mastra.getStorage() })\n * });\n * ```\n */\n public setStorage(storage: MastraCompositeStore) {\n this.#storage = augmentWithInit(storage);\n this.#storage?.__registerMastra?.(this as unknown as Parameters<NonNullable<typeof storage.__registerMastra>>[0]);\n this.#ensureBackgroundTaskManager();\n // If storage was attached after construction, the SchedulerWorker\n // will pick it up when startWorkers() is called.\n }\n\n public setLogger({ logger }: { logger: TLogger }) {\n // Wrap the new logger in a DualLogger to maintain dual-write to loggerVNext\n const dualLogger = new DualLogger(logger, () => this.loggerVNext);\n this.#logger = dualLogger as unknown as TLogger;\n\n if (this.#agents) {\n Object.keys(this.#agents).forEach(key => {\n this.#agents?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#deployer) {\n this.#deployer.__setLogger(this.#logger);\n }\n\n if (this.#tts) {\n Object.keys(this.#tts).forEach(key => {\n this.#tts?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#storage) {\n this.#storage.__setLogger(this.#logger);\n }\n\n if (this.#vectors) {\n Object.keys(this.#vectors).forEach(key => {\n this.#vectors?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#mcpServers) {\n Object.keys(this.#mcpServers).forEach(key => {\n this.#mcpServers?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#workflows) {\n Object.keys(this.#workflows).forEach(key => {\n this.#workflows?.[key]?.__setLogger(this.#logger);\n });\n }\n\n if (this.#serverAdapter) {\n this.#serverAdapter.__setLogger(this.#logger);\n }\n\n if (this.#workspace) {\n this.#workspace.__setLogger(this.#logger);\n }\n\n if (this.#memory) {\n Object.keys(this.#memory).forEach(key => {\n this.#memory?.[key]?.__setLogger(this.#logger);\n });\n }\n\n // Pass the raw logger (not the DualLogger) to observability to avoid circular forwarding\n this.#observability.setLogger({ logger });\n }\n\n /**\n * Gets all registered text-to-speech (TTS) providers.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * tts: {\n * openai: new OpenAITTS({\n * apiKey: process.env.OPENAI_API_KEY,\n * voice: 'alloy'\n * })\n * }\n * });\n *\n * const ttsProviders = mastra.getTTS();\n * const openaiTTS = ttsProviders?.openai;\n * if (openaiTTS) {\n * const audioBuffer = await openaiTTS.synthesize('Hello, world!');\n * }\n * ```\n */\n public getTTS() {\n return this.#tts;\n }\n\n /**\n * Gets the currently configured logger instance.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * logger: new PinoLogger({\n * name: 'MyApp',\n * level: 'info'\n * })\n * });\n *\n * const logger = mastra.getLogger();\n * logger.info('Application started');\n * logger.error('An error occurred', { error: 'details' });\n * ```\n */\n public getLogger() {\n return this.#logger;\n }\n\n /**\n * Gets the currently configured storage provider.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./data.db' })\n * });\n *\n * // Use the storage in agent memory\n * const agent = new Agent({\n * id: 'assistant',\n * name: 'assistant',\n * memory: new Memory({\n * storage: mastra.getStorage()\n * })\n * });\n * ```\n */\n public getStorage() {\n return this.#storage;\n }\n\n get observability(): ObservabilityEntrypoint {\n return this.#observability;\n }\n\n /**\n * Structured logging API for observability.\n * Logs emitted via this API will not have trace correlation when used outside a span.\n * Use for startup logs, background jobs, or other non-traced scenarios.\n *\n * Note: For the infrastructure logger (IMastraLogger), use getLogger() instead.\n */\n get loggerVNext(): LoggerContext {\n return this.#observability.getDefaultInstance()?.getLoggerContext?.() ?? noOpLoggerContext;\n }\n\n /**\n * Direct metrics API for use outside trace context.\n * Metrics emitted via this API will not have auto correlation or cost context from spans.\n * Use for background jobs, startup metrics, or other non-traced scenarios.\n */\n get metrics(): MetricsContext {\n return this.#observability.getDefaultInstance()?.getMetricsContext?.() ?? noOpMetricsContext;\n }\n\n public getServerMiddleware() {\n return this.#serverMiddleware;\n }\n\n public getServerCache() {\n return this.#serverCache;\n }\n\n public setServerMiddleware(serverMiddleware: Middleware | Middleware[]) {\n if (typeof serverMiddleware === 'function') {\n this.#serverMiddleware = [\n {\n handler: serverMiddleware,\n path: '/api/*',\n },\n ];\n return;\n }\n\n if (!Array.isArray(serverMiddleware)) {\n const error = new MastraError({\n id: 'MASTRA_SET_SERVER_MIDDLEWARE_INVALID_TYPE',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Invalid middleware: expected a function or array, received ${typeof serverMiddleware}`,\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n this.#serverMiddleware = serverMiddleware.map(m => {\n if (typeof m === 'function') {\n return {\n handler: m,\n path: '/api/*',\n };\n }\n return {\n handler: m.handler,\n path: m.path || '/api/*',\n };\n });\n }\n\n public getServer() {\n return this.#server;\n }\n\n /**\n * Gets the Studio-specific authentication and authorization configuration.\n *\n * @returns The studio config, or undefined if not configured\n *\n * @example\n * ```typescript\n * const studioConfig = mastra.getStudio();\n * if (studioConfig?.auth) {\n * // Studio has separate auth configured\n * }\n * ```\n */\n public getStudio() {\n return this.#studio;\n }\n\n /**\n * Sets the server adapter for this Mastra instance.\n *\n * The server adapter provides access to the underlying server app (e.g., Hono, Express)\n * and allows users to call routes directly via `app.fetch()` instead of making HTTP requests.\n *\n * This is typically called by `createHonoServer` or similar factory functions during\n * server initialization.\n *\n * @param adapter - The server adapter instance (e.g., MastraServer from @mastra/hono or @mastra/express)\n *\n * @example\n * ```typescript\n * const app = new Hono();\n * const adapter = new MastraServer({ app, mastra });\n * mastra.setMastraServer(adapter);\n * ```\n */\n public setMastraServer(adapter: MastraServerBase): void {\n if (this.#serverAdapter) {\n this.#logger?.debug(\n 'Replacing existing server adapter. Only one adapter should be registered per Mastra instance.',\n );\n }\n this.#serverAdapter = adapter;\n // Inject the logger into the adapter\n if (this.#logger) {\n adapter.__setLogger(this.#logger);\n }\n }\n\n /**\n * Gets the server adapter for this Mastra instance.\n *\n * @returns The server adapter, or undefined if not set\n *\n * @example\n * ```typescript\n * const adapter = mastra.getMastraServer();\n * if (adapter) {\n * const app = adapter.getApp<Hono>();\n * }\n * ```\n */\n public getMastraServer(): MastraServerBase | undefined {\n return this.#serverAdapter;\n }\n\n /**\n * Gets the server app from the server adapter.\n *\n * This is a convenience method that calls `getMastraServer()?.getApp<T>()`.\n * Use this to access the underlying server framework's app instance (e.g., Hono, Express)\n * for direct operations like calling routes via `app.fetch()`.\n *\n * @template T - The expected type of the app (e.g., Hono, Express Application)\n * @returns The server app, or undefined if no adapter is set\n *\n * @example\n * ```typescript\n * // After createHonoServer() is called:\n * const app = mastra.getServerApp<Hono>();\n *\n * // Call routes directly without HTTP overhead\n * const response = await app?.fetch(new Request('http://localhost/health'));\n * const data = await response?.json();\n * ```\n */\n public getServerApp<T = unknown>(): T | undefined {\n return this.#serverAdapter?.getApp<T>();\n }\n\n public getBundlerConfig() {\n return this.#bundler;\n }\n\n public async listLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n transportId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_LIST_LOGS_BY_RUN_ID_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger?.listLogsByRunId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_BY_RUN_ID_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not configured or does not support listLogsByRunId operation',\n details: {\n runId,\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n return await this.#logger.listLogsByRunId({\n runId,\n transportId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n });\n }\n\n public async listLogs(\n transportId: string,\n params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n },\n ) {\n if (!transportId) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_MISSING_TRANSPORT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Transport ID is required',\n details: {\n transportId,\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n if (!this.#logger) {\n const error = new MastraError({\n id: 'MASTRA_GET_LOGS_LOGGER_NOT_CONFIGURED',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.SYSTEM,\n text: 'Logger is not set',\n details: {\n transportId,\n },\n });\n throw error;\n }\n\n return await this.#logger.listLogs(transportId, params);\n }\n\n /**\n * Gets all registered Model Context Protocol (MCP) server instances.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const mcpServers = mastra.getMCPServers();\n * if (mcpServers) {\n * const fsServer = mcpServers.filesystem;\n * const tools = await fsServer.listTools();\n * }\n * ```\n */\n public listMCPServers(): Record<string, MCPServerBase> | undefined {\n return this.#mcpServers;\n }\n\n /**\n * Adds a new MCP server to the Mastra instance.\n *\n * This method allows dynamic registration of MCP servers after the Mastra instance\n * has been created. The server will be initialized with ID, Mastra instance, and logger.\n *\n * @throws {MastraError} When an MCP server with the same key already exists\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newServer = new FileSystemMCPServer({\n * rootPath: '/data'\n * });\n * mastra.addMCPServer(newServer); // Uses server.id as key\n * // or\n * mastra.addMCPServer(newServer, 'customKey'); // Uses custom key\n * ```\n */\n public addMCPServer<M extends MCPServerBase>(server: M, key?: string): void {\n if (!server) {\n throw createUndefinedPrimitiveError('mcp-server', server, key);\n }\n // If a key is provided, try to set it as the ID\n // The setId method will only update if the ID wasn't explicitly set by the user\n if (key) {\n server.setId(key);\n }\n\n // Now resolve the ID after potentially setting it\n const resolvedId = server.id;\n if (!resolvedId) {\n const error = new MastraError({\n id: 'MASTRA_ADD_MCP_SERVER_MISSING_ID',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'MCP server must expose an id or be registered under one',\n details: { status: 400 },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n const serverKey = key ?? resolvedId;\n const servers = this.#mcpServers as Record<string, MCPServerBase>;\n if (servers[serverKey]) {\n return;\n }\n\n // Initialize the server\n server.__registerMastra(this);\n server.__setLogger(this.getLogger());\n servers[serverKey] = server;\n }\n\n /**\n * Retrieves a specific MCP server instance by registration key.\n *\n * @throws {MastraError} When the specified MCP server is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({...})\n * }\n * });\n *\n * const fsServer = mastra.getMCPServer('filesystem');\n * const tools = await fsServer.listTools();\n * ```\n */\n public getMCPServer<TMCPServerName extends keyof TMCPServers>(\n name: TMCPServerName,\n ): TMCPServers[TMCPServerName] | undefined {\n if (!this.#mcpServers || !this.#mcpServers[name]) {\n this.#logger?.debug(`MCP server with name ${String(name)} not found`);\n return undefined as TMCPServers[TMCPServerName] | undefined;\n }\n return this.#mcpServers[name];\n }\n\n /**\n * Retrieves a specific Model Context Protocol (MCP) server instance by its logical ID.\n *\n * This method searches for an MCP server using its logical ID. If a version is specified,\n * it returns the exact version match. If no version is provided, it returns the server\n * with the most recent release date.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * mcpServers: {\n * filesystem: new FileSystemMCPServer({\n * id: 'fs-server',\n * version: '1.0.0',\n * rootPath: '/app/data'\n * })\n * }\n * });\n *\n * const fsServer = mastra.getMCPServerById('fs-server');\n * if (fsServer) {\n * const tools = await fsServer.listTools();\n * }\n * ```\n */\n public getMCPServerById<TMCPServerName extends keyof TMCPServers>(\n serverId: TMCPServers[TMCPServerName]['id'],\n version?: string,\n ): TMCPServers[TMCPServerName] | undefined {\n if (!this.#mcpServers) {\n return undefined;\n }\n\n const allRegisteredServers = Object.values(this.#mcpServers || {});\n\n const matchingLogicalIdServers = allRegisteredServers.filter(server => server.id === serverId);\n\n if (matchingLogicalIdServers.length === 0) {\n this.#logger?.debug(`No MCP servers found with logical ID: ${serverId}`);\n return undefined;\n }\n\n if (version) {\n const specificVersionServer = matchingLogicalIdServers.find(server => server.version === version);\n if (!specificVersionServer) {\n this.#logger?.debug(`MCP server with logical ID '${serverId}' found, but not version '${version}'.`);\n }\n return specificVersionServer as TMCPServers[TMCPServerName] | undefined;\n } else {\n // No version specified, find the one with the most recent releaseDate\n if (matchingLogicalIdServers.length === 1) {\n return matchingLogicalIdServers[0] as TMCPServers[TMCPServerName];\n }\n\n matchingLogicalIdServers.sort((a, b) => {\n // Ensure releaseDate exists and is a string before creating a Date object\n const dateAVal = a.releaseDate && typeof a.releaseDate === 'string' ? new Date(a.releaseDate).getTime() : NaN;\n const dateBVal = b.releaseDate && typeof b.releaseDate === 'string' ? new Date(b.releaseDate).getTime() : NaN;\n\n if (isNaN(dateAVal) && isNaN(dateBVal)) return 0;\n if (isNaN(dateAVal)) return 1; // Treat invalid/missing dates as older\n if (isNaN(dateBVal)) return -1; // Treat invalid/missing dates as older\n\n return dateBVal - dateAVal; // Sorts in descending order of time (latest first)\n });\n\n // After sorting, the first element should be the latest if its date is valid\n if (matchingLogicalIdServers.length > 0) {\n const latestServer = matchingLogicalIdServers[0];\n if (\n latestServer &&\n latestServer.releaseDate &&\n typeof latestServer.releaseDate === 'string' &&\n !isNaN(new Date(latestServer.releaseDate).getTime())\n ) {\n return latestServer as TMCPServers[TMCPServerName];\n }\n }\n this.#logger?.warn(\n `Could not determine the latest server for logical ID '${serverId}' due to invalid or missing release dates, or no servers left after filtering.`,\n );\n return undefined;\n }\n }\n\n public async addTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.subscribe(topic, listener);\n }\n\n public async removeTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.unsubscribe(topic, listener);\n }\n\n /**\n * Process a single workflow event. Shared entry point used by:\n * - pull-mode workers (OrchestrationWorker)\n * - in-process push pubsubs (EventEmitterPubSub) wired during startWorkers()\n * - HTTP push delivered to `POST /api/workers/events`\n *\n * Returns `{ ok: true }` on success; the caller should ack/return 2xx.\n * Returns `{ ok: false, retry: true }` on transient failure; the caller\n * should nack/return 5xx so the broker retries.\n */\n public async handleWorkflowEvent(event: Event): Promise<{ ok: true } | { ok: false; retry: boolean }> {\n if (!this.#workflowEventProcessor) {\n this.#workflowEventProcessor = new WorkflowEventProcessor({ mastra: this });\n }\n return this.#workflowEventProcessor.handle(event);\n }\n\n /**\n * Initialize and start workers. If `name` is provided, starts only\n * that worker. Otherwise starts all registered workers and subscribes\n * user-defined event listeners.\n */\n public async startWorkers(name?: string): Promise<void> {\n // Initialize storage before any read so adapters that open/create their\n // stores in init() are ready. The scheduler warm-up tick also persists a\n // workflow snapshot on start(), which can race a lazy init() that creates\n // `mastra_workflow_snapshot` (\"no such table\" on SQL stores, see #17905).\n // init() is idempotent and a no-op when disabled.\n if (this.#storage) {\n await this.#storage.init();\n }\n\n // Flip the scheduler-requested flag if any agent-schedule rows\n // exist in storage from a previous boot. Without this, a process\n // that boots with only DB-side agent schedules (no in-code declarative\n // schedules and no imperative `schedules.create()` calls yet) would\n // skip injecting the scheduler + agent-schedule workers entirely. This\n // reads the schedules store, so it must run after storage.init() above.\n if (!name) {\n await this.#detectExistingAgentSchedules();\n // Same idea for the notification dispatcher: a previous process may\n // have lazily created the dispatcher schedule row because deferred\n // notifications were in play.\n await this.#detectExistingNotificationDispatch();\n }\n\n // Lazily inject the SchedulerWorker + AgentScheduleWorker if the\n // scheduler should be enabled and they're not already registered.\n // This runs after all workflows have been registered (unlike the\n // constructor's default-workers block), so #hasScheduledWorkflow is\n // accurate.\n if (!name && this.#shouldEnableScheduler() && this.#storage) {\n if (!this.#findSchedulerWorker()) {\n const sw = new SchedulerWorker(this.#schedulerConfig);\n sw.__registerMastra(this);\n this.#workers.push(sw);\n }\n if (!this.#findAgentScheduleWorker()) {\n const { AgentScheduleWorker } = await import('../schedules/worker');\n const asw = new AgentScheduleWorker();\n asw.__registerMastra(this);\n this.#workers.push(asw);\n }\n }\n\n const deps: WorkerDeps = {\n pubsub: this.#pubsub,\n storage: this.#storage!,\n logger: this.#logger as unknown as IMastraLogger,\n mastra: this,\n };\n\n let targets: MastraWorker[];\n if (name) {\n targets = this.#workers.filter(w => w.name === name);\n if (targets.length === 0) {\n throw new Error(`Worker \"${name}\" not found. Available: ${this.#workers.map(w => w.name).join(', ')}`);\n }\n } else if (this.#workerFilter) {\n targets = this.#workers.filter(w => this.#workerFilter!.has(w.name));\n if (targets.length === 0) {\n this.#logger?.warn?.(\n `MASTRA_WORKERS=${[...this.#workerFilter].join(',')} did not match any registered workers (have: ${this.#workers.map(w => w.name).join(', ')})`,\n );\n }\n } else {\n targets = this.#workers;\n }\n\n // When explicitly starting the backgroundTasks worker (e.g.\n // `startWorkers('backgroundTasks')`), upgrade a producer-mode manager to\n // full mode so the worker can subscribe to dispatch events. Without this,\n // a manager created at construction time as 'producer' (because\n // MASTRA_WORKERS excluded backgroundTasks) would be reused by the worker\n // but never subscribe to the dispatch topic.\n if (\n name === 'backgroundTasks' &&\n this.#backgroundTaskManager &&\n this.#backgroundTaskManager.config.mode === 'producer'\n ) {\n await this.#backgroundTaskManager.shutdown();\n this.#backgroundTaskManager = undefined;\n this.#ensureBackgroundTaskManager('full');\n }\n\n for (const worker of targets) {\n await worker.init(deps);\n await worker.start();\n }\n\n // For push-mode pubsubs (e.g. EventEmitterPubSub) there is no\n // OrchestrationWorker pulling events — wire handleWorkflowEvent directly\n // to the pubsub so workflow events still get processed in-process.\n if (!name) {\n await this.#wirePushWorkflowSubscription();\n }\n\n // Subscribe user-defined event listeners (non-workflow topics, or legacy inline WEP)\n // Only when starting all workers (not when targeting a specific one).\n // Idempotent: skip pairs we've already subscribed.\n if (!name) {\n for (const topic in this.#events) {\n if (!this.#events[topic]) {\n continue;\n }\n\n const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];\n for (const listener of listeners) {\n const alreadySubscribed = this.#userEventSubscriptions.some(\n sub => sub.topic === topic && sub.cb === listener,\n );\n if (alreadySubscribed) continue;\n await this.#pubsub.subscribe(topic, listener);\n this.#userEventSubscriptions.push({ topic, cb: listener });\n }\n }\n }\n\n // Track that the boot path has executed at least once so subsequent\n // runtime signals (e.g. `mastra.schedules.create()`) know whether they need\n // to lazily inject + start additional workers themselves.\n this.#workersStarted = true;\n }\n\n /**\n * Wire `handleWorkflowEvent` directly to the pubsub when it is push-only\n * (no pull mode for an OrchestrationWorker to drive). Idempotent — no-op\n * when the pubsub supports pull or the subscription already exists.\n * Shared by `startWorkers()` and `__ensureExecutionWorkersStarted()`.\n */\n async #wirePushWorkflowSubscription(): Promise<void> {\n const modes = this.#pubsub.supportedModes ?? ['pull'];\n const pushOnly = modes.includes('push') && !modes.includes('pull');\n if (pushOnly && !this.#pushSubscription) {\n const cb: EventCallback = (event, ack, nack) => {\n // In cross-process push environments (e.g. UnixSocketPubSub),\n // every subscriber receives every event — including events for\n // internal workflows registered on a different process. Skip\n // events whose workflow exists in neither the internal nor the\n // public registry so only the owning process handles them.\n // Without this guard the WEP would publish workflow.fail,\n // propagating through workflows-finish and erroneously\n // terminating the correct process's run.\n const data = event.data as Record<string, unknown> | undefined;\n const wfId = data?.workflowId as string | undefined;\n const rId = data?.runId as string | undefined;\n if (wfId && rId && !this.#ownsWorkflow(wfId, rId, data?.parentWorkflow)) {\n if (ack) {\n void ack().catch(err => this.#logger?.error?.('Error acking skipped workflow event', err));\n }\n return;\n }\n\n void this.handleWorkflowEvent(event)\n .then(result => {\n if (result.ok) {\n if (ack) {\n return ack().catch(err =>\n this.#logger?.error?.('Error acking workflow event in push subscription', err),\n );\n }\n return;\n }\n // Non-ok result: ask the transport to redeliver (nack) when the\n // handle layer says retry. The WEP tracks per-event delivery\n // attempts and eventually returns `retry: false` to break the\n // loop and surface a terminal workflow.fail. For terminal\n // failures we ack so the event is dropped from the transport.\n if (result.retry) {\n if (nack) {\n return nack().catch(err =>\n this.#logger?.error?.('Error nacking workflow event in push subscription', err),\n );\n }\n // Transport does not support nack. Do NOT ack — acking a\n // retryable failure would drop the event and silently lose\n // the workflow run. Log and let the transport's own delivery\n // semantics decide (most non-ack transports redeliver until\n // explicitly acked).\n this.#logger?.error?.('Retryable workflow event cannot be requeued because nack is unavailable', {\n type: event.type,\n runId: event.runId,\n });\n return;\n }\n if (ack) {\n return ack().catch(err =>\n this.#logger?.error?.('Error acking terminal workflow event in push subscription', err),\n );\n }\n })\n .catch(err => this.#logger?.error?.('Unhandled error in workflow event push subscription', err));\n };\n await this.#pubsub.subscribe('workflows', cb);\n this.#pushSubscription = { topic: 'workflows', cb };\n }\n }\n\n /**\n * Ensure the execution-side machinery — the `orchestration` and\n * `backgroundTasks` workers, plus the push-mode workflow subscription —\n * is running. Called lazily by {@link BackgroundTaskManager} when a task\n * is dispatched or resumed, so background tasks execute in \"library mode\"\n * where nothing ever calls `startWorkers()` (no server, no `mastra dev`;\n * see #19339).\n *\n * Deliberately narrower than `startWorkers()`: it never injects or starts\n * the scheduler/agent-schedule workers and never subscribes user event\n * listeners — dispatching a background task must not boot cron machinery\n * as a side effect.\n *\n * Honors the same opt-outs as the rest of the worker lifecycle:\n * `workers: false` / `MASTRA_WORKERS=false` (standalone-worker topologies\n * run their own worker processes, so this instance must not start local\n * ones) and the `MASTRA_WORKERS` name filter.\n *\n * The fast path is its own `#executionWorkersStarted` flag, NOT\n * `#workersStarted` — the latter is set by any `startWorkers(name)` call,\n * including partial named starts (e.g. `startWorkers('backgroundTasks')`)\n * that never start the orchestration worker or push wiring, which would\n * leave dispatched tasks stuck again. The pass itself is idempotent\n * (per-worker `isRunning` checks, idempotent push wiring), so running it\n * once after a full `startWorkers()` boot is a cheap no-op.\n *\n * @internal\n */\n async __ensureExecutionWorkersStarted(): Promise<void> {\n if (this.#executionWorkersStarted) return;\n if (this.#workersDisabled) return;\n // Memoize the in-flight startup so concurrent first dispatches on a cold\n // instance share one start instead of racing worker.init()/start().\n // Cleared on settle so a dispatch after stopWorkers() can start again.\n if (!this.#executionWorkersStartPromise) {\n this.#executionWorkersStartPromise = this.#startExecutionWorkers().finally(() => {\n this.#executionWorkersStartPromise = undefined;\n });\n }\n await this.#executionWorkersStartPromise;\n }\n\n async #startExecutionWorkers(): Promise<void> {\n // Storage init is memoized (see augmentWithInit) — cheap when already run.\n if (this.#storage) {\n await this.#storage.init();\n }\n\n const deps: WorkerDeps = {\n pubsub: this.#pubsub,\n storage: this.#storage!,\n logger: this.#logger as unknown as IMastraLogger,\n mastra: this,\n };\n\n for (const worker of this.#workers) {\n if (worker.name !== 'orchestration' && worker.name !== 'backgroundTasks') continue;\n if (this.#workerFilter && !this.#workerFilter.has(worker.name)) continue;\n if (worker.isRunning) continue;\n await worker.init(deps);\n await worker.start();\n }\n\n await this.#wirePushWorkflowSubscription();\n this.#executionWorkersStarted = true;\n }\n\n /**\n * Stop all running workers and unsubscribe event listeners.\n */\n public async stopWorkers(): Promise<void> {\n // A background-task dispatch may have kicked off a lazy execution-worker\n // start (`__ensureExecutionWorkersStarted`) that is still in flight. Wait\n // for it so the teardown below covers what it started — otherwise the\n // start finishes after this method returns, leaving workers running and\n // subscriptions wired behind a \"stopped\" instance. Failures are already\n // logged by the start path; here they just mean there is less to stop.\n while (this.#executionWorkersStartPromise) {\n await this.#executionWorkersStartPromise.catch(() => {});\n }\n\n // Stop registered workers in reverse order\n for (const worker of [...this.#workers].reverse()) {\n if (worker.isRunning) {\n await worker.stop();\n }\n }\n\n // Tear down the in-process push subscription wired during startWorkers().\n if (this.#pushSubscription) {\n await this.#pubsub.unsubscribe(this.#pushSubscription.topic, this.#pushSubscription.cb);\n this.#pushSubscription = undefined;\n }\n\n // Unsubscribe only the (topic, listener) pairs we actually registered in\n // startWorkers() — keeps stopWorkers() symmetric with startWorkers() and\n // avoids unsubscribing listeners that startWorkers never owned.\n for (const { topic, cb } of this.#userEventSubscriptions) {\n await this.#pubsub.unsubscribe(topic, cb);\n }\n this.#userEventSubscriptions = [];\n\n await this.#pubsub.flush();\n this.#workersStarted = false;\n this.#executionWorkersStarted = false;\n }\n\n /**\n * Release the module-level hooks this instance registered in its constructor.\n * The scorer hook is added to a shared emitter that never drops handlers on\n * its own, so short-lived internal/ephemeral Mastras must call this on teardown\n * or their handler keeps firing (and failing to resolve the scorer) on every\n * scorer run for the rest of the process. Idempotent.\n * @internal\n */\n __unregisterHooks(): void {\n if (this.#onScorerHook) {\n deregisterHook(AvailableHooks.ON_SCORER_RUN, this.#onScorerHook);\n this.#onScorerHook = undefined;\n }\n }\n\n /**\n * @deprecated Use {@link Mastra.startWorkers} instead. Will be removed in a\n * future release.\n */\n public async startEventEngine(name?: string): Promise<void> {\n return this.startWorkers(name);\n }\n\n /**\n * @deprecated Use {@link Mastra.stopWorkers} instead. Will be removed in a\n * future release.\n */\n public async stopEventEngine(): Promise<void> {\n return this.stopWorkers();\n }\n\n /**\n * Retrieves a registered gateway by its key.\n *\n * @throws {MastraError} When the gateway with the specified key is not found\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * gateways: {\n * myGateway: new CustomGateway()\n * }\n * });\n *\n * const gateway = mastra.getGateway('myGateway');\n * ```\n */\n public getGateway(key: string): MastraModelGatewayInterface {\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): MastraModelGatewayInterface {\n const gateways = this.#gateways ?? {};\n for (const gateway of Object.values(gateways)) {\n if (getGatewayId(gateway) === 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 => getGatewayId(g))\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 registration keys.\n *\n * Gateways can be plain objects that satisfy `MastraModelGatewayInterface` or\n * classes that extend `MastraModelGateway`.\n *\n * @example\n * ```typescript\n * import { createOpenAICompatible } from '@ai-sdk/openai-compatible-v6';\n * import { MastraModelGateway, type MastraModelGatewayInterface } from '@mastra/core/llm';\n *\n * const plainGateway: MastraModelGatewayInterface = {\n * id: 'plain-gateway',\n * name: 'Plain Gateway',\n * async fetchProviders() { return {}; },\n * buildUrl() { return undefined; },\n * async getApiKey() { return ''; },\n * resolveLanguageModel(args) { return createOpenAICompatible({ name: args.providerId, apiKey: args.apiKey }).chatModel(args.modelId); },\n * };\n *\n * class ClassGateway extends MastraModelGateway {\n * readonly id = 'class-gateway';\n * readonly name = 'Class Gateway';\n * // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.\n * }\n *\n * const mastra = new Mastra({\n * gateways: {\n * plain: plainGateway,\n * class: new ClassGateway(),\n * },\n * });\n *\n * const allGateways = mastra.listGateways();\n * console.log(Object.keys(allGateways ?? {})); // ['plain', 'class']\n * ```\n */\n public listGateways(): Record<string, MastraModelGatewayInterface> | 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 will be used as the key.\n *\n * @example Plain object gateway\n * ```typescript\n * import type { MastraModelGatewayInterface } from '@mastra/core/llm';\n *\n * const customGateway: MastraModelGatewayInterface = {\n * id: 'custom-gateway-v1',\n * name: 'Custom Gateway',\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-gateway-v1',\n * },\n * };\n * },\n * buildUrl() {\n * return 'https://api.myprovider.com/v1';\n * },\n * async getApiKey() {\n * return process.env.MY_API_KEY || '';\n * },\n * async resolveLanguageModel({ modelId, providerId, apiKey }) {\n * const provider = createOpenAICompatible({\n * name: providerId,\n * apiKey,\n * baseURL: this.buildUrl(),\n * supportsStructuredOutputs: true,\n * });\n * return provider.chatModel(modelId);\n * },\n * };\n *\n * const mastra = new Mastra();\n * mastra.addGateway(customGateway);\n * ```\n *\n * @example Convenience base class\n * ```typescript\n * import { MastraModelGateway } from '@mastra/core/llm';\n *\n * class CustomGateway extends MastraModelGateway {\n * readonly id = 'custom-gateway-v1';\n * readonly name = 'Custom Gateway';\n *\n * // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.\n * }\n *\n * mastra.addGateway(new CustomGateway(), 'customKey');\n * ```\n */\n public addGateway(gateway: MastraModelGatewayInterface, key?: string): void {\n if (!gateway) {\n throw createUndefinedPrimitiveError('gateway', gateway, key);\n }\n const gatewayKey = key || getGatewayId(gateway);\n const gateways = this.#gateways as Record<string, MastraModelGatewayInterface>;\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 * - registered workspaces (sandbox processes, filesystem handles, LSP, browser)\n * - All registered components and their resources\n *\n * It's important to call this method when your application is shutting down\n * to ensure proper cleanup and prevent resource leaks.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra({\n * agents: { myAgent },\n * workflows: { myWorkflow }\n * });\n *\n * // Graceful shutdown on SIGINT\n * process.on('SIGINT', async () => {\n * await mastra.shutdown();\n * process.exit(0);\n * });\n * ```\n */\n async shutdown(): Promise<void> {\n // SchedulerWorker is stopped as part of stopWorkers().\n await this.stopWorkers();\n\n const workspaceIds = Object.keys(this.#workspaces);\n const teardownResults = await Promise.allSettled(\n workspaceIds.map(id => this.removeWorkspace(id, { destroy: true })),\n );\n teardownResults.forEach((result, index) => {\n if (result.status === 'rejected') {\n this.#logger?.error('Failed to destroy workspace during shutdown', {\n workspaceId: workspaceIds[index],\n error: result.reason,\n });\n }\n });\n\n // Tear down hosted Harnesses (interval handlers, workspaces) before closing storage,\n // since teardown may still flush to the shared store.\n const harnessKeys = Object.keys(this.#harnesses);\n const harnessTeardown = await Promise.allSettled(harnessKeys.map(key => this.#harnesses[key]!.destroy()));\n harnessTeardown.forEach((result, index) => {\n if (result.status === 'rejected') {\n this.#logger?.error('Failed to destroy harness during shutdown', {\n harnessKey: harnessKeys[index],\n error: result.reason,\n });\n }\n });\n\n // Close storage to release OS file handles (critical on Windows: open WAL/shm\n // handles cause EBUSY when callers try to fs.rm the storage dir after shutdown).\n if (this.#storage?.close) {\n await this.#storage.close();\n }\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\n// Publish the constructor so `Agent`'s ephemeral-Mastra path can build one\n// without a static `agent → mastra` runtime import (which would re-create the\n// init cycle documented in `agent/agent.ts`). Runs once, after the class above\n// is initialized. See `./mastra-ctor-holder`.\n__registerMastraCtor(Mastra);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAa,oCAAoC;;;;;;;AAQjD,MAAa,wCAAwC;AAErD,MAAa,qCAAqC;AAUlD,SAAgB,6BAA6B,OAAsB;CACjE,MAAM,MAAM,QAAQ,IAAI,KAAK,KAAK,oBAAI,IAAI,KAAK;CAC/C,IAAI,OAAO,MAAM,IAAI,QAAQ,CAAC,GAC5B,MAAM,IAAI,MAAM,uCAAuC,OAAO;CAEhE,OAAO;AACT;;;;;;;AAQA,SAAgB,kCAAkC,EAChD,OAAO,oCACP,YAAA,QAC+C,CAAC,GAAa;CAC7D,MAAM,MAAM,KAAK,IAAI;CACrB,OAAO;EACL,IAAI;EACJ,QAAQ;GACN,MAAM;GACN,YAAY;GACZ,WAAW,EAAE,OAAO,UAAU;EAChC;EACA;EACA,QAAQ;EACR,YAAY,kBAAkB,MAAM,EAAE,OAAO,IAAI,CAAC;EAClD,WAAW;EACX,WAAW;EACX,UAAU;GAAE,UAAU;GAAM,SAAS;EAAgB;CACvD;AACF;AAEA,SAAgB,mCAAmC,EACjD,YAAA,QACwD,CAAC,GAAG;CAC5D,MAAM,eAAe,WAAW;EAC9B,IAAI;EACJ,aAAa,EAAE,OAAO;GACpB,KAAK,EAAE,OAAO,CAAC,CAAC,SAAS;GACzB,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;EAC7B,CAAC;EACD,cAAc,EAAE,OAAO;GACrB,WAAW,EAAE,OAAO;GACpB,QAAQ,EAAE,OAAO;EACnB,CAAC;EACD,SAAS,OAAO,EAAE,WAAW,aAAa;GACxC,MAAM,UAAU,MAA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