@mastra/core
Version:
1 lines • 462 kB
Source Map (JSON)
{"version":3,"file":"mastra-DGIYMiih.cjs","names":["computeNextFireAt","createStep","z","dispatchDueNotifications","createWorkflow","fsAgentScheduleRowId","parseFsAgentScheduleRowId","computeNextFire","MastraError","ErrorDomain","ErrorCategory","createConcurrencyLimiter","readPositiveIntEnv","isRunLocalTopic","agentThreadStreamRuntime","DatasetsManager","Schedules","NoOpObservability","InMemoryServerCache","normalizeConcurrency","normalizeToolPayloadTransformPolicy","EventEmitterPubSub","OrchestrationWorker","BackgroundTaskWorker","noopLogger","LogLevel","ConsoleLogger","InMemoryStore","getStorageSource","augmentWithInit","InMemoryDB","WorkflowsInMemory","BackgroundTasksInMemory","defaultGateways","getGatewayId","createOnScorerHook","BackgroundTaskManager","computeScheduleDefinitionHash","toEpochMs","computeNextFire","AgentChannels","isDurableAgentLike","isToolLoopAgentLike","toolLoopAgentToMastraAgent","createRunScope","createNestedRunParentStatusLookup","nestedRunParentOf","nestedRunRecoveryAction","cancelNestedRun","nestedRunStatusOf","WORKFLOW_RUN_LEASE_TTL_MS","runOutsideRunFenceScope","renewWorkflowLease","repeatAfterSettled","runWithConcurrency","toJsonSchemaOrUndefined","normalizeWorkflowBuilderDefinition","collectNestedWorkflowIds","rehydrateWorkflow","SchedulerWorker","isAdaptableLogger","isObservabilityExportSuppressed","resolveCurrentSpan","DualLogger","createExportSuppressedLogger","noOpLoggerContext","noOpMetricsContext","WorkflowEventProcessor","assertDrainTimeout","waitMs","isDurableAgentExecutionDetached","getActiveDurableAgentWorkflowExecutions","abandonDurableAgentExecutions","__registerMastraCtor"],"sources":["../src/notifications/workflow.ts","../src/schedules/row-diff.ts","../src/mastra/fs-agent-schedules.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';\nimport type { NotificationsStorage } from './storage';\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\n/**\n * The dispatcher ticks once a minute, has a single non-suspending step, and is\n * never resumed — no code path consumes its snapshot. Opting out of snapshot\n * persistence entirely keeps `mastra_workflow_snapshot` from growing by one\n * dead row per minute forever (issue #20254).\n */\nconst NOTIFICATION_DISPATCH_SHOULD_PERSIST_SNAPSHOT = () => false;\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\n/**\n * Upper bound passed as `now` to find every pending record with a due time,\n * however far ahead. Year 9999 stays inside every adapter's timestamp range.\n */\nconst FAR_FUTURE = new Date('9999-12-31T23:59:59.999Z');\n\n/**\n * True when some pending notification has a `deliverAt` or `summaryAt`, i.e.\n * the dispatcher still has work now or later. Records without a due time are\n * never picked up by a dispatch pass, so they don't count.\n */\nexport async function hasPendingDeferredNotifications(storage: NotificationsStorage): Promise<boolean> {\n const pending = await storage.listDueNotifications({ now: FAR_FUTURE, limit: 1 });\n return pending.length > 0;\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 // Stop the once-a-minute cron when nothing is left to deliver, so an\n // idle app stops polling storage. The next deferral re-arms it.\n await mastra.__releaseNotificationDispatchIfIdle();\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 options: {\n shouldPersistSnapshot: NOTIFICATION_DISPATCH_SHOULD_PERSIST_SNAPSHOT,\n },\n })\n .then(dispatchStep)\n .commit();\n}\n","import type { Schedule } from '../storage/domains/schedules/base';\n\n/**\n * Comparators for deciding whether a stored schedule row still matches what\n * code declares. Shared by both declarative sync paths — workflow schedules\n * (`createWorkflow({ schedule })`) and file-based agent schedules — so the two\n * cannot drift on what counts as \"unchanged\" and start rewriting rows on every\n * boot.\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 */\nexport function 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/** See {@link targetsEqual}. Same approach for free-form metadata. */\nexport function metadataEqual(\n a: Record<string, unknown> | null | undefined,\n b: Record<string, unknown> | undefined,\n): 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 * Boot-time sync between the schedules a file-based agent declares on disk\n * (`agents/<id>/schedules/`) and the rows in schedule storage.\n *\n * Kept out of `mastra/index.ts` because none of it needs Mastra's private\n * state: it is a function of the registered agent map, the schedules store, and\n * a logger. `Mastra` keeps only the wiring — when to run this, and where the\n * store comes from.\n */\nimport type { Agent } from '../agent';\nimport type { IMastraLogger } from '../logger';\nimport { FS_AGENT_SCHEDULE_PREFIX, fsAgentScheduleRowId, parseFsAgentScheduleRowId } from '../schedules/define';\nimport type { AgentScheduleDefinition, AgentScheduleHandler, DeclaredAgentSchedule } from '../schedules/define';\nimport { metadataEqual, targetsEqual } from '../schedules/row-diff';\nimport type { Schedule, ScheduleUpdate, SchedulesStorage } from '../storage/domains/schedules/base';\nimport { computeNextFire } from '../workflows/scheduler/cron';\n\n/**\n * Mastra's registered agent map: registration key to agent. The key is not the\n * agent's `id` — schedules key off `agent.id`, because that is what the worker\n * resolves against at fire time.\n */\nexport type RegisteredAgents = Record<string, Agent<any>>;\n\n/** One declared schedule resolved to the storage row it owns. */\nexport interface ResolvedFsAgentSchedule {\n scheduleId: string;\n agentId: string;\n key: string;\n definition: AgentScheduleDefinition;\n}\n\n/**\n * Two agents registered under different keys can still share an `id`, which\n * would map their schedules onto one row. The collector keeps the first and\n * reports the rest here so the caller can log once, at sync time, rather than\n * on every lookup.\n */\nexport interface FsAgentScheduleCollection {\n schedules: ResolvedFsAgentSchedule[];\n duplicates: Array<{ agentId: string; key: string }>;\n}\n\n/**\n * Reads the file-based schedules declared on a registered agent.\n *\n * Wrappers around an inner `Agent` (durable execution) delegate this\n * explicitly — see `DurableAgent.getDeclaredSchedules` — so there is nothing to\n * unwrap here. The optional call covers registrable shapes that are not\n * `Agent`s at all (`ToolLoopAgentLike`).\n */\nexport function declaredSchedulesOf(agent: unknown): DeclaredAgentSchedule[] {\n return (agent as { getDeclaredSchedules?: () => DeclaredAgentSchedule[] } | null)?.getDeclaredSchedules?.() ?? [];\n}\n\n/** True when any registered agent declares schedules on disk. */\nexport function hasFsAgentSchedule(agents: RegisteredAgents | undefined): boolean {\n return Object.values(agents ?? {}).some(agent => declaredSchedulesOf(agent).length > 0);\n}\n\n/**\n * Collect every declared schedule across the registered agents, keyed by\n * `fsa_<encoded(agentId)>__<encoded(key)>` so the prefix uniquely identifies\n * \"all rows owned by this agent's schedules/ directory\" even when ids contain\n * delimiter-like characters.\n *\n * Pure: duplicates are returned rather than logged, so callers that run per\n * fire don't re-emit the same warning forever.\n */\nexport function collectFsAgentSchedules(agents: RegisteredAgents | undefined): FsAgentScheduleCollection {\n const schedules: ResolvedFsAgentSchedule[] = [];\n const duplicates: Array<{ agentId: string; key: string }> = [];\n const seen = new Set<string>();\n\n for (const agent of Object.values(agents ?? {})) {\n // `agent.id` (not the registration key) is what `getAgentById` matches on,\n // and that's how the schedule worker resolves the target at fire time.\n for (const { key, definition } of declaredSchedulesOf(agent)) {\n const scheduleId = fsAgentScheduleRowId(agent.id, key);\n if (seen.has(scheduleId)) {\n duplicates.push({ agentId: agent.id, key });\n continue;\n }\n seen.add(scheduleId);\n schedules.push({ scheduleId, agentId: agent.id, key, definition });\n }\n }\n\n return { schedules, duplicates };\n}\n\n/**\n * Resolve the handler for a handler-mode file-based schedule. Handlers are\n * functions and therefore cannot be persisted on the JSON schedule row, so the\n * agent-schedule worker looks them up in-process by row id at fire time.\n *\n * The row id already encodes the agent and the key, so this decodes it and\n * reads that one agent rather than rebuilding the whole cross-agent collection\n * on every fire. When two agents share an id the first wins, matching\n * {@link collectFsAgentSchedules}.\n */\nexport function findFsAgentScheduleHandler<TMastra>(\n agents: RegisteredAgents | undefined,\n scheduleId: string,\n): AgentScheduleHandler<TMastra> | undefined {\n const parsed = parseFsAgentScheduleRowId(scheduleId);\n if (!parsed) return undefined;\n\n // `find`, not a filter: the first agent with this id owns the row, matching\n // how the collector resolves a duplicate id.\n const owner = Object.values(agents ?? {}).find(agent => agent.id === parsed.agentId);\n const declared = declaredSchedulesOf(owner).find(entry => entry.key === parsed.key);\n const handler = declared?.definition.handler;\n\n return typeof handler === 'function' ? (handler as AgentScheduleHandler<TMastra>) : undefined;\n}\n\n/** Build the storage `target` for a declared schedule. */\nfunction buildTarget(agentId: string, definition: AgentScheduleDefinition): Schedule['target'] {\n // Handler-mode schedules carry no stored prompt: the handler computes the\n // fire's parameters in-process at trigger time. Undefined fields drop out on\n // serialization, so they need no conditional spreads.\n return {\n type: 'agent',\n agentId,\n prompt: definition.prompt ?? '',\n name: definition.name,\n threadId: definition.threadId,\n resourceId: definition.resourceId,\n signalType: definition.signalType,\n tagName: definition.tagName,\n attributes: definition.attributes,\n providerOptions: definition.providerOptions,\n ifActive: definition.ifActive,\n ifIdle: definition.ifIdle,\n };\n}\n\nexport interface SyncFsAgentSchedulesOptions {\n agents: RegisteredAgents | undefined;\n store: SchedulesStorage;\n logger?: IMastraLogger;\n /**\n * Rows already read by the caller, reused for both the upsert diff and the\n * orphan sweep instead of a second `listSchedules()` pass.\n */\n knownRows?: Schedule[];\n}\n\n/**\n * Sync schedules declared by file-based agents' `schedules/` directories into\n * schedule storage.\n *\n * Mirrors the declarative workflow sync: upsert declared rows, diff the config\n * fields and patch what changed, leave `status` alone so an out-of-band pause\n * survives a redeploy, and delete orphaned `fsa_` rows that code no longer\n * declares. Rows created imperatively through `mastra.schedules.create(...)`\n * use the `agent_` prefix and are never touched here.\n */\nexport async function syncFsAgentSchedules({\n agents,\n store,\n logger,\n knownRows,\n}: SyncFsAgentSchedulesOptions): Promise<void> {\n const { schedules: declared, duplicates } = collectFsAgentSchedules(agents);\n\n for (const { agentId, key } of duplicates) {\n logger?.warn(\n `Duplicate schedule \"${key}\" for agent id \"${agentId}\": two registered agents share that id. Keeping the first and ignoring the rest.`,\n );\n }\n\n const declaredIds = new Set(declared.map(d => d.scheduleId));\n\n // One read for both the upsert diff and the orphan sweep, instead of a\n // `getSchedule` round-trip per declared schedule on every boot.\n const allRows = knownRows ?? (await store.listSchedules());\n const rowsById = new Map(allRows.map(row => [row.id, row]));\n\n for (const { scheduleId, agentId, key, definition } of declared) {\n try {\n const now = Date.now();\n const target = buildTarget(agentId, definition);\n const existing = rowsById.get(scheduleId);\n\n // A declared cadence can outlive its final occurrence (e.g. a year-pinned\n // cron that has already passed). Register the row as `completed` rather\n // than skipping it, so boot stays self-consistent.\n const computeTiming = () => {\n const next = computeNextFire({ cron: definition.cron, timezone: definition.timezone, nextFireAt: now }, now);\n return {\n nextFireAt: next.nextFireAt,\n status: next.completed ? 'completed' : (definition.status ?? 'active'),\n } as const;\n };\n\n if (!existing) {\n const timing = computeTiming();\n await store.createSchedule({\n id: scheduleId,\n target,\n cron: definition.cron,\n timezone: definition.timezone,\n status: timing.status,\n nextFireAt: timing.nextFireAt,\n createdAt: now,\n updatedAt: now,\n metadata: definition.metadata,\n ownerType: 'agent',\n ownerId: agentId,\n });\n continue;\n }\n\n const patch: ScheduleUpdate = {};\n const cronChanged = existing.cron !== definition.cron;\n const timezoneChanged = (existing.timezone ?? undefined) !== (definition.timezone ?? undefined);\n\n if (cronChanged) patch.cron = definition.cron;\n if (timezoneChanged) patch.timezone = definition.timezone;\n if (!targetsEqual(existing.target, target)) patch.target = target;\n if (!metadataEqual(existing.metadata, definition.metadata)) patch.metadata = definition.metadata;\n\n // Cron or timezone change invalidates the stored nextFireAt — recompute\n // from now so we don't fire on the old schedule. An exhausted cadence\n // completes the row; a live one re-arms a completed row.\n if (cronChanged || timezoneChanged) {\n const timing = computeTiming();\n patch.nextFireAt = timing.nextFireAt;\n if (timing.status === 'completed') patch.status = 'completed';\n else if (existing.status === 'completed') patch.status = 'active';\n }\n\n if (Object.keys(patch).length > 0) {\n await store.updateSchedule(scheduleId, patch);\n }\n } catch (error) {\n logger?.error('Failed to register file-based agent schedule', { scheduleId, agentId, key, error });\n }\n }\n\n // Orphan deletion: drop `fsa_` rows whose owning agent is registered here but\n // no longer declares that schedule — a file deleted or renamed.\n //\n // Scoped to agents registered in THIS process on purpose. A process holding\n // only a subset of the agents (a standalone worker, a partial registry after\n // a failed import) must not delete another agent's schedules. Rows whose\n // agent is gone from the project entirely are already self-healing: the\n // agent-schedule worker deletes a row when it can't resolve the target\n // (`agent-missing` → `selfClean`), so nothing is left firing forever.\n const registeredAgentIds = new Set(Object.values(agents ?? {}).map(a => a.id));\n for (const row of allRows) {\n if (declaredIds.has(row.id)) continue;\n if (!row.id.startsWith(FS_AGENT_SCHEDULE_PREFIX)) continue;\n const ownerAgentId = parseFsAgentScheduleRowId(row.id)?.agentId;\n if (!ownerAgentId || !registeredAgentIds.has(ownerAgentId)) continue;\n try {\n await store.deleteSchedule(row.id);\n } catch (error) {\n logger?.error('Failed to delete orphaned file-based agent schedule', {\n scheduleId: row.id,\n agentId: ownerAgentId,\n error,\n });\n }\n }\n}\n","import type { Agent } from '../agent';\nimport {\n abandonDurableAgentExecutions,\n getActiveDurableAgentWorkflowExecutions,\n isDurableAgentExecutionDetached,\n} from '../agent/durable/run-registry';\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';\nimport { InMemoryServerCache } from '../cache';\nimport type { MastraServerCache } from '../cache';\nimport { AgentChannels } from '../channels';\nimport type { ChannelProvider, ChannelsResolver } from '../channels';\nimport type { Classifier, ClassifierQuestions } from '../classifier';\nimport { DatasetsManager } from '../datasets/manager.js';\nimport type { IDeployer } 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 { isRunLocalTopic } from '../events/topics';\nimport type { Event, EventCallback } from '../events/types';\nimport type { Harness } from '../harness';\nimport { AvailableHooks, deregisterHook, registerHook } from '../hooks';\nimport type { Knowledge } from '../knowledge';\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 {\n LogLevel,\n noopLogger,\n ConsoleLogger,\n DualLogger,\n isAdaptableLogger,\n resolveTraceFields,\n isObservabilityExportSuppressed,\n createExportSuppressedLogger,\n} from '../logger';\nimport type { IMastraLogger, LoggerAdapterOptions } from '../logger';\nimport type { MCPServerBase } from '../mcp';\nimport type { MastraMemory } from '../memory';\nimport type { NotificationDispatchConfig } from '../notifications/workflow';\nimport {\n buildNotificationDispatchSchedule,\n createNotificationDispatchWorkflow,\n hasPendingDeferredNotifications,\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 { resolveCurrentSpan } from '../observability/utils';\nimport type { Processor } from '../processors';\nimport type { AgentScheduleHandler } from '../schedules/define';\nimport { metadataEqual, targetsEqual } from '../schedules/row-diff';\nimport { Schedules } from '../schedules/schedules';\nimport type { SchedulesConfig, ScheduleHooks } from '../schedules/types';\nimport type { MastraServerBase } from '../server/base';\nimport type { ApiRoute, Middleware, ServerConfig, ServerConfigInput, StudioConfig } from '../server/types';\nimport type { SignalProvider } from '../signals/signal-provider';\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 type { WorkflowsStorage } from '../storage/domains/workflows/base';\nimport { WorkflowsInMemory } from '../storage/domains/workflows/inmemory';\nimport { runOutsideRunFenceScope } from '../storage/run-fencing';\nimport type { RunFence, RunOwnershipRecord } from '../storage/run-fencing';\nimport { augmentWithInit, getStorageSource } from '../storage/storageWithInit';\nimport type { StorageResolvedPromptBlockType, WorkflowRun } from '../storage/types';\nimport { trackFeatureUsage } from '../telemetry/feature-telemetry';\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 { readPositiveIntEnv } from '../utils';\nimport { waitMs } from '../utils/test-waits';\nimport type { MastraVector } from '../vector';\nimport { OrchestrationWorker, SchedulerWorker, BackgroundTaskWorker } from '../worker';\nimport type { MastraWorker, WorkerDeps, WorkerStopOptions } from '../worker';\nimport { assertDrainTimeout } from '../worker/drain-timeout';\nimport type { AnyWorkflow, Workflow } from '../workflows';\nimport { normalizeWorkflowBuilderDefinition } from '../workflows/builder';\nimport type { WorkflowBuilderDefinitionInput } from '../workflows/builder';\nimport type { DynamicWorkflowGraph, WorkflowRegistryIndex, WorkflowRegistrySchemas } from '../workflows/dynamic';\nimport {\n assertValidDynamicWorkflow,\n collectNestedWorkflowIds,\n rehydrateWorkflow,\n toJsonSchemaOrUndefined,\n} from '../workflows/dynamic';\nimport { WorkflowEventProcessor } from '../workflows/evented/workflow-event-processor';\nimport {\n cancelNestedRun,\n createNestedRunParentStatusLookup,\n nestedRunParentOf,\n nestedRunRecoveryAction,\n nestedRunStatusOf,\n} from '../workflows/nested-run-recovery';\nimport { renewWorkflowLease, repeatAfterSettled, WORKFLOW_RUN_LEASE_TTL_MS } from '../workflows/run-ownership';\nimport { computeScheduleDefinitionHash } from '../workflows/scheduler';\nimport type { WorkflowScheduleConfig, SchedulerConfig, Scheduler } from '../workflows/scheduler';\nimport { computeNextFire, toEpochMs } from '../workflows/scheduler/cron';\nimport type { WorkflowRunStatus } from '../workflows/types';\nimport type { AnyWorkspace, RegisteredWorkspace, Workspace } from '../workspace';\nimport {\n declaredSchedulesOf,\n findFsAgentScheduleHandler,\n hasFsAgentSchedule,\n syncFsAgentSchedules,\n} from './fs-agent-schedules';\nimport { createOnScorerHook } from './hooks';\nimport { __registerMastraCtor } from './mastra-ctor-holder';\nimport type { RunScope } from './run-scope';\nimport { createRunScope } from './run-scope';\nimport type { ConcurrencyLimiter } from './run-with-concurrency';\nimport {\n DEFAULT_RESTART_CONCURRENCY,\n createConcurrencyLimiter,\n normalizeConcurrency,\n runWithConcurrency,\n} from './run-with-concurrency';\nimport type { VersionOverrides, VersionSelector } from './types';\n\nfunction normalizeApiRoutes(routes: NonNullable<ServerConfigInput['apiRoutes']>): ApiRoute[] {\n return routes.flatMap(route => (Array.isArray(route) ? route : [route]));\n}\n\nfunction normalizeServerConfig({ apiRoutes, ...server }: ServerConfigInput): ServerConfig {\n return apiRoutes ? { ...server, apiRoutes: normalizeApiRoutes(apiRoutes) } : server;\n}\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 | 'classifier'\n | 'workflow'\n | 'mcp-server'\n | 'gateway'\n | 'memory'\n | 'knowledge'\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 * Whether the Mastra scheduler fires this workflow's declared schedules.\n * Only the default and evented engines are dispatched by it; other engines\n * (Inngest, Temporal) own their scheduling natively.\n */\nfunction runsOnMastraScheduler(workflow: unknown): boolean {\n const engineType = (workflow as { engineType?: string }).engineType;\n return engineType === 'default' || engineType === 'evented';\n}\n\n/**\n * Reads the declarative schedule configs off a workflow, regardless of its\n * engine. Supports both the `getScheduleConfigs(): WorkflowScheduleConfig[]`\n * accessor and a legacy `getScheduleConfig(): WorkflowScheduleConfig | undefined`\n * fallback used in tests that inject a fake getter.\n */\nfunction readWorkflowScheduleConfigs(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 * The declarative schedule configs the Mastra scheduler should register for a\n * workflow. Empty for engines the scheduler does not dispatch.\n */\nfunction collectWorkflowScheduleConfigs(workflow: unknown): WorkflowScheduleConfig[] {\n return runsOnMastraScheduler(workflow) ? readWorkflowScheduleConfigs(workflow) : [];\n}\n\n/**\n * Whether `runId` names a scheduler-spawned run whose workflow events stay in the publishing\n * process: `sched_wf_<workflowId>_<timestamp>` for declarative schedules, or the notification\n * dispatcher's row. These ticks fire on every instance independently, so the `mastra.pubsub`\n * proxy publishes their events `localOnly`, and a broker never holds them.\n */\nfunction isProcessLocalScheduledRunId(runId: string | undefined): boolean {\n if (!runId) {\n return false;\n }\n\n return runId.startsWith('sched_wf_') || runId.startsWith(`sched_${NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID}_`);\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 encodeDeclarativeScheduleId(id: string): string {\n return encodeURIComponent(id).replaceAll('_', '%5F');\n}\n\nfunction declarativeScheduleRowId(workflowId: string, scheduleId?: string): string {\n const encodedWorkflow = encodeDeclarativeScheduleId(workflowId);\n if (scheduleId === undefined) return `wf_${encodedWorkflow}`;\n return `wf_${encodedWorkflow}__${encodeDeclarativeScheduleId(scheduleId)}`;\n}\n\nfunction legacyDeclarativeScheduleRowId(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, workflowIds: Iterable<string>): string | undefined {\n for (const workflowId of workflowIds) {\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/**\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 TClassifiers extends Record<string, Classifier<any>> = Record<string, Classifier<any>>,\n TKnowledge extends Record<string, Knowledge> = Record<string, Knowledge>,\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 * How the configured logger integrates with Mastra observability.\n *\n * - `correlation` — inject `trace_id`/`span_id` into the logger's native\n * records (stdout, transports) when a span is active. Requires a logger\n * that supports adapters (e.g. `ConsoleLogger`, `PinoLogger`). Default: true.\n * - `export` — export log records to Mastra observability storage/exporters.\n * Set to false to keep trace-correlated stdout without shipping logs.\n * Default: true.\n */\n loggerOptions?: Partial<LoggerAdapterOptions>;\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?: IDeployer;\n\n /**\n * Server configuration for HTTP endpoints and middleware.\n */\n server?: ServerConfigInput;\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 * Classifiers return typed fixed-option decisions from evaluation models.\n * Registered classifiers can be retrieved with getClassifier() or getClassifierById().\n */\n classifiers?: TClassifiers;\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 * Knowledge instances registered by stable application key.\n */\n knowledge?: TKnowledge;\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 // Listeners receive only the event. Acknowledgement is handled for them:\n // the delivery is acked once the listener resolves and nacked if it throws.\n [topic: string]: ((event: Event) => Promise<void> | void) | ((event: Event) => Promise<void> | 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, when schedule rows exist in storage, when a schedule is\n * created at runtime (in this process or — via the shared pubsub — in\n * another), or when `scheduler.enabled` is true. Apps that never schedule\n * anything never poll storage. It requires a storage adapter implementing\n * 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 * Accepts either a static provider record or a {@link ChannelsResolver} —\n * a callable that returns the current provider map. With a resolver, routes\n * for every possible channel are mounted up front (via\n * `resolver.getRoutes()`) and the live provider set is re-resolved at\n * runtime, so channels added or removed in an external system of record\n * (e.g. the Mastra platform) take effect without redeploying.\n *\n * @example\n * ```typescript\n * import { SlackProvider } from '@mastra/slack';\n *\n * // Static record\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 * // Live resolver (platform-managed connections)\n * import { channels } from '@mastra/connect';\n *\n * new Mastra({\n * channels: await channels({ projectId }),\n * });\n * ```\n */\n channels?: TChannels | ChannelsResolver<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, resolves to `'development'` for `mastra dev` runs (detected via\n * `MASTRA_DEV`), then falls back to `process.env.NODE_ENV`. If none of these\n * are set the field 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 * `workflows` controls whether the server calls\n * {@link Mastra.restartAllActiveWorkflowRuns} on boot and whether\n * `startWorkers()` starts the workflow recovery loop. Set it to `'off'` to\n * skip both (no storage queries), for example when several replicas share\n * one database and you recover runs another way. `workflowConcurrency` caps\n * how many runs recovery restarts at once, `workflowGraceMs` sets how long a\n * default-engine run must have stopped before it does, and\n * `workflowScanIntervalMs` how often the loop looks.\n *\n * `durableAgents` controls whether the deployer will automatically call\n * {@link Mastra.recoverAllDurableAgents} for every registered `DurableAgent`\n * when the server starts (concurrently with `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 a run another replica\n * still drives is skipped, and recovered once that replica's claim lapses.\n *\n * @default { workflows: 'auto', workflowConcurrency: 5, workflowGraceMs: 2000, workflowScanIntervalMs: 60000, 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 * Restart RUNNING/WAITING workflow runs found in storage on server boot,\n * and run the workflow recovery loop on instances that call `startWorkers()`.\n * @default 'auto'\n */\n workflows?: 'auto' | 'off';\n /**\n * Maximum number of workflow runs restarted at the same time by\n * {@link Mastra.restartAllActiveWorkflowRuns} and the recovery loop. Use\n * `Infinity` for no limit. A restarted run holds its slot until it finishes.\n * @default 5\n */\n workflowConcurrency?: number;\n /**\n * How long a RUNNING/WAITING default-engine run must show no sign of life\n * before recovery restarts it: no instance holds the run's lease, and neither\n * the run nor that lease changed for this long. A run skipped as live or in\n * its grace period is looked at again by the recovery loop's next pass.\n *\n * Evented runs don't use it. On a pubsub whose broker redelivers unacked\n * messages (see `PubSub.redeliversUnacked`) the broker recovers them; on any\n * other pubsub they are restarted at once.\n * @default 2000\n */\n workflowGraceMs?: number;\n /**\n * How often the workflow recovery loop looks for default-engine runs whose\n * instance stopped. Each wait is up to a fifth shorter or longer, so\n * instances that booted together don't look at once, and is shortened when\n * a run the last pass saw comes out of its grace period sooner. Capped at\n * 2^31 - 1 ms. One instance at a time runs the passes; see\n * {@link Mastra.startWorkers}.\n * @default 60000\n */\n workflowScanIntervalMs?: number;\n /**\n * Auto-recover orphaned RUNNING durable agent runs on server boot.\n * @default 'off'\n */\n durableAgents?: 'auto' | 'off';\n}\n\nexport interface WorkersConfigSection {\n enabled: boolean;\n [key: string]: unknown;\n}\n\nexport interface WorkersConfig {\n version: 1;\n orchestration: WorkersConfigSection;\n scheduler: WorkersConfigSection;\n backgroundTasks: WorkersConfigSection;\n custom: string[];\n}\n\nfunction serializableWorkerConfig<T extends object>(config: T | undefined): Record<string, unknown> {\n return JSON.parse(JSON.stringify(config ?? {})) as Record<string, unknown>;\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 */\n// Tracks which Mastra instance last attached observability to a logger, so\n// sharing one logger instance across multiple Mastras warns instead of\n// silently re-targeting the export (weak: never pins loggers or Mastras).\n// Keyed on the logger's attachment identity (`__observabilityAttachmentKey`,\n// e.g. PinoLogger's family-shared ref cell) so attaching a child of an\n// already-wired family also warns; falls back to the instance itself.\nconst attachedLoggerOwners = new WeakMap<object, unknown>();\n\n/**\n * Pubsub topic used to tell every process running the default worker set that\n * a schedule now exists and the scheduler tick loop should start. Lets a\n * standalone worker that booted with an empty schedules table discover\n * schedules created later by the API process without continuously polling storage.\n */\nconst SCHEDULER_WAKE_TOPIC = 'scheduler';\nconst SCHEDULER_WAKE_EVENT = 'scheduler.wake';\n// Default budget shutdown() gives in-flight evented workflow runs (and\n// stopWorkers() gives in-flight push events) before tearing down pubsub.\n// Mirrors BackgroundTaskManager's grace period and the deployer's\n// `server.drainTimeout` default.\nconst DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS = 5_000;\n// A thread run still executing at shutdown is aborted and gets at least this long to wind down before its thread is\n// handed back, even when the drain budget is already spent. A tool call already executing may still finish after.\nconst SHUTDOWN_THREAD_RUN_ABORT_GRACE_MIN_MS = 500;\n// Spreads re-checks of durable-agent runs other instances still drove at boot,\n// so replicas that skipped the same run don't all try it at the same instant.\nconst DURABLE_RECOVERY_RECHECK_JITTER_MS = 5_000;\n// A re-check that throws (e.g. storage briefly unavailable) is retried after\n// this delay, doubling per consecutive failure, up to\n// DURABLE_RECOVERY_RECHECK_MAX_RETRIES times.\nconst DURABLE_RECOVERY_RECHECK_RETRY_BASE_MS = 30_000;\nconst DURABLE_RECOVERY_RECHECK_MAX_RETRIES = 5;\nconst DURABLE_RECOVERY_ATTEMPT_TIMEOUT_MS = 30_000;\n// Default `recovery.workflowGraceMs`, the same for every pubsub. The rule applies only to default-engine\n// runs, which have no broker message in flight to wait for: the grace covers the short gaps where such a\n// run is `running` without a live lease (between a status write and its claim, or a nested resume handing\n// its parent's lease over) and clock skew between the store and the app. Evented runs between two\n// messages are what needed a longer grace, and the pass no longer applies the rule to them.\nconst DEFAULT_WORKFLOW_GRACE_MS = 2_000;\n// The longest delay `setTimeout` honours.\nconst MAX_TIMER_DELAY_MS = 2 ** 31 - 1;\n// The active runs whose leases one `getRunOwnerships` call reads during a recovery pass.\nconst RECOVERY_OWNERSHIP_BATCH_SIZE = 100;\n// How many `listWorkflowRuns` calls the recovery passes of one instance make at once, all passes together.\nconst RECOVERY_LISTING_CONCURRENCY = 5;\n// The statuses of the runs a recovery pass looks at.\nconst ACTIVE_RUN_STATUSES: readonly WorkflowRunStatus[] = ['running', 'waiting'];\nconst DEFAULT_WORKFLOW_SCAN_INTERVAL_MS = 60_000;\n// A run the last pass found in its grace period moves the next pass up, but never closer than this,\n// so runs that keep coming due at once can't turn the loop into a busy one.\nconst MIN_WORKFLOW_SCAN_DELAY_MS = 1_000;\n// The run-owners row whose holder runs the recovery loop's passes. No run ID starts with `::`.\nconst RECOVERY_LEADER_KEY = '::recovery-leader';\n\n/** `recovery.workflowGraceMs` as configured, or `fallback` when it is unset or not a finite non-negative number. */\nfunction normalizeGraceMs(graceMs: number | undefined, fallback: number): number {\n if (typeof graceMs !== 'number' || !Number.isFinite(graceMs) || graceMs < 0) {\n return fallback;\n }\n\n return graceMs;\n}\n\n/** `recovery.workflowScanIntervalMs` as configured, capped at the longest timer delay; the default when unset or not positive. */\nfunction normalizeScanIntervalMs(intervalMs: number | undefined): number {\n if (typeof intervalMs !== 'number' || Number.isNaN(intervalMs) || intervalMs <= 0) {\n return DEFAULT_WORKFLOW_SCAN_INTERVAL_MS;\n }\n\n return Math.min(intervalMs, MAX_TIMER_DELAY_MS);\n}\n\n/**\n * How long the recovery loop waits for its next pass: the scan interval, give or take a fifth, or\n * less when `dueAt`, the end of the grace period of a run the last pass left alone, comes first.\n * The wait for `dueAt` is at least {@link MIN_WORKFLOW_SCAN_DELAY_MS} and up to a fifth longer, as\n * a check made before `dueAt` would find the run still in its grace period.\n */\nfunction nextWorkflowScanDelay(intervalMs: number, dueAt: number | undefined): number {\n const interval = intervalMs * (0.8 + Math.random() * 0.4);\n const untilDue =\n dueAt === undefined\n ? Infinity\n : Math.max(MIN_WORKFLOW_SCAN_DELAY_MS, dueAt - Date.now()) * (1 + Math.random() * 0.2);\n return Math.min(interval, untilDue, MAX_TIMER_DELAY_MS);\n}\n\n/**\n * The engine whose runs one recovery pass looks at. Default-engine passes run on the recovery leader;\n * evented runs are restarted only by an explicit `restartAllActiveWorkflowRuns()` call.\n */\ntype RecoveryEngine = 'default' | 'evented';\n\n/** An active run a recovery pass listed, with the registered workflow it belongs to. */\ninterface RecoveryCandidate {\n workflow: AnyWorkflow;\n run: WorkflowRun;\n}\n\n/** A recovery pass that handed out every restart it picked. */\ninterface RecoveryPass {\n /** The earliest time a run the pass left in its grace period, and not live, becomes due. */\n earliestDueAt?: number;\n /** Settles once every restart the pass handed out settled; never rejects. */\n settled: Promise<void>;\n}\n\n/** Whether the recovery rule restarts a run now, or when it should look at it again. */\ntype RecoveryVerdict = { restart: true } | { restart: false; live: boolean; dueAt: number };\n\n/** Identifies a run across the workflows of one recovery pass. */\nfunction recoveryRunKey(workflowName: string, runId: string): string {\n return JSON.stringify([workflowName, runId]);\n}\n\n/**\n * The recovery rule for a default-engine run. It is restarted when its run\n * lease is not live and `graceMs` passed since the later of the lease's last\n * expiry and the run's last write. Otherwise `dueAt` is when that could next\n * be true.\n *\n * A released or missing lease carries no expiry, so the run's own last write\n * anchors the grace then.\n */\nfunction recoveryVerdict({\n owner,\n updatedAt,\n graceMs,\n now,\n}: {\n owner: RunOwnershipRecord | undefined;\n updatedAt: Date | string | number | undefined;\n graceMs: number;\n now: number;\n}): RecoveryVerdict {\n const lastWrite = updatedAt === undefined ? NaN : new Date(updatedAt).getTime();\n const anchor = Math.max(\n // A store that lost the timestamp leaves only the lease to go by.\n Number.isNaN(lastWrite) ? -Infinity : lastWrite,\n owner?.leaseExpiresAt?.getTime() ?? -Infinity,\n );\n const dueAt = anchor + graceMs;\n const live = owner?.live === true;\n\n if (live || now < dueAt) {\n return { restart: false, live, dueAt };\n }\n\n return { restart: true };\n}\n\n/**\n * Whether runs of `workflow` hold a run lease while they execute, which the recovery rule reads.\n * Evented runs hold none: their steps run wherever the pubsub delivers each event.\n */\nfunction usesRunLease(workflow: AnyWorkflow): boolean {\n return workflow.engineType === 'default';\n}\n\n/**\n * Whether boot-time recovery restarts runs of `workflow`. Processor workflows only run inside an\n * agent call, so a lone restart has nothing to resume.\n */\nfunction isRecoveryRestartable(workflow: AnyWorkflow): boolean {\n return (\n (workflow.engineType === 'default' || workflow.engineType === 'evented') &&\n workflow.options?.autoRestartActiveRuns !== false &&\n workflow.type !== 'processor'\n );\n}\n\n/**\n * Registers and coordinates agents, workflows, storage, and other Mastra services.\n *\n * @example\n * `yourAgent` is an agent you have already configured.\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n *\n * const mastra = new Mastra({\n * agents: { assistant: yourAgent },\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/core/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Mastra documentation](https://mastra.ai/reference/core/mastra-class)\n * if packaged docs are unavailable.\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 TClassifiers extends Record<string, Classifier<any>> = Record<string, Classifier<any>>,\n TKnowledge extends Record<string, Knowledge> = Record<string, Knowledge>,\n> {\n #vectors?: TVectors;\n #agents: TAgents;\n #toolLoopRegistrations = new WeakMap<ToolLoopAgentLike, Map<string, Agent<any>>>();\n #logger: TLogger;\n #loggerAdapterOptions: LoggerAdapterOptions = { correlation: true, export: true };\n #wiredLoggers = new WeakSet<IMastraLogger>();\n #fallbackWrappers = new WeakMap<IMastraLogger, DualLogger>();\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?: IDeployer;\n #serverMiddleware: Array<{\n handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;\n path: string;\n }> = [];\n\n #storage?: MastraCompositeStore;\n #storageSource?: MastraCompositeStore;\n #storageExplicit = false;\n #storageFallbackWarningPending = false;\n #recoveryConfig: MastraRecoveryConfig = {\n workflows: 'auto',\n workflowConcurrency: DEFAULT_RESTART_CONCURRENCY,\n workflowGraceMs: DEFAULT_WORKFLOW_GRACE_MS,\n workflowScanIntervalMs: DEFAULT_WORKFLOW_SCAN_INTERVAL_MS,\n durableAgents: 'off',\n };\n #durableRecoveryRechecks = new Map<string, ReturnType<typeof setTimeout>>();\n #durableRecoveryRechecksInFlight = new Set<Promise<unknown>>();\n #shuttingDown = false;\n /** The default-engine recovery pass in flight; see `#recoverStoppedRuns`. */\n #recoveryPass?: Promise<RecoveryPass>;\n /** Stops the recovery loop `startWorkers()` started; unset while none runs. */\n #stopWorkflowRecoveryLoop?: () => void;\n /** The recovery leader row while this instance holds it; see `#leadWorkflowRecovery`. */\n #recoveryLeader?: { store: WorkflowsStorage; fence: RunFence; stopRenewing: () => void };\n /** A tick's claim of the recovery leader row in flight, which `#releaseRecoveryLeader()` waits for. */\n #recoveryLeaderClaim?: Promise<boolean>;\n /** Runs the restarts of every recovery pass, `recovery.workflowConcurrency` at a time. */\n #recoveryRestarts!: ConcurrencyLimiter;\n // Shared by every recovery pass, so overlapping scans don't take every connection of the store's pool\n // and hold up this process's other reads.\n #recoveryListings = createConcurrencyLimiter(RECOVERY_LISTING_CONCURRENCY);\n /** The runs a recovery pass handed to `#recoveryRestarts` whose restart has not settled. */\n #queuedRecoveryRestarts = new Set<string>();\n /** The runs whose last recovery restart threw, by the engine whose pass restarts them. */\n #failedRecoveryRestarts: Record<RecoveryEngine, Set<string>> = { default: new Set(), evented: new Set() };\n #scorers?: TScorers;\n #classifiers?: TClassifiers;\n #tools?: TTools;\n #processors?: TProcessors;\n #processorConfigurations: Map<\n string,\n Array<{ processor: Processor; agentId: string; type: 'input' | 'output'; source?: DefinitionSource }>\n > = new Map();\n #memory?: TMemory;\n #knowledge: TKnowledge;\n #workspace?: Workspace;\n #workspaces: Record<string, RegisteredWorkspace> = {};\n #server?: ServerConfig;\n #serverExplicit = false;\n #signalProviderRouteOwners = new WeakMap<ApiRoute, SignalProvider>();\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 /**\n * Ids of persisted dynamic workflow definitions that failed to rehydrate at\n * boot. Their declarative `wf_*` schedule rows are exempt from orphan\n * deletion — the workflow still exists in storage, so its schedules aren't\n * orphans; deleting them would silently lose the user's schedules.\n */\n #failedDynamicWorkflowIds = new Set<string>();\n /**\n * Set while a file-based agent schedule sync is queued, so registering a\n * batch of agents after startup triggers one sweep rather than one per agent.\n */\n #fsScheduleSyncPending = false;\n /** Set once file-based agent usage has been reported for this Mastra instance. */\n #fsAgentUsageTracked = false;\n /**\n * Set when an agent registers while a sweep is already in flight. That sweep\n * may have read the agent map before the agent landed, so it runs one more\n * pass instead of dropping the registration.\n */\n #fsScheduleSyncRerun = false;\n #gateways?: Record<string, MastraModelGatewayInterface>;\n #channels?: TChannels;\n /** Live channel-provider source; when set, `#channels` holds the latest resolved snapshot. */\n #channelsResolver?: ChannelsResolver<TChannels>;\n /** In-flight resolver invocation, shared so concurrent `resolveChannels()` calls coalesce. */\n #channelsResolvePromise?: Promise<TChannels>;\n /** Providers already attached/initialized, so resolver refreshes touch each instance once. */\n #attachedChannelProviders = new WeakSet<ChannelProvider>();\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 requested the\n * scheduler in this process, so later deferrals only verify the row.\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 // handleWorkflowEvent() calls started by the push subscription that have not\n // settled yet. stopWorkers() waits for these (bounded) after unsubscribing so\n // a step mid-execution is not abandoned by teardown.\n #inFlightPushEvents = new Set<Promise<unknown>>();\n // Result promises of evented workflow runs started through this instance\n // (see EventedExecutionEngine.execute). shutdown() drains these before it\n // tears down the pubsub subscriptions they need in order to make progress.\n #activeEventedRuns = new Set<Promise<unknown>>();\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: EventCallback;\n }> = [];\n // Callback subscribed to SCHEDULER_WAKE_TOPIC while the scheduler is not\n // running, so another process creating a schedule can start it here.\n // Removed once the scheduler starts and in stopWorkers().\n #schedulerWakeSubscription?: EventCallback;\n\n #events: {\n [topic: string]: ((event: Event) => Promise<void> | void)[];\n } = {};\n #internalMastraWorkflows: Record<string, AnyWorkflow> = {};\n // Unscoped internal workflow ids that every process registers identically\n // (e.g. the evented durable-agent loop), so any process's workers can run\n // them. The pubsub proxy never tags their events `localOnly`.\n #distributedInternalWorkflowIds = new Set<string>();\n // Workflow ids already warned about for a `localOnly` start with no local\n // consumer, so the warning fires once per id rather than per event.\n #warnedStrandedLocalWorkflowIds = new Set<string>();\n // Tracks last-activity timestamps for run-scoped internal workflows so a lazy\n // TTL sweep can evict entries from abandoned suspended runs that were never\n // resumed. The timestamp is refreshed every time the run resolves its own\n // registration, so the TTL bounds *idle* time rather than total run duration —\n // a run that legitimately executes for hours is never swept out from under\n // itself. Unscoped (singleton) entries are not tracked — they live forever.\n #runScopedWorkflowTimestamps: Map<string, { lastActivityAt: 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 idle for longer than this TTL (ms) are evicted\n // during the lazy sweep that runs on each new registration. Reads the shared\n // `MASTRA_SUSPENDED_RUN_TTL_MS` so this registry and the agent thread-stream\n // runtime expire a suspended run's state on one bound; production keeps the 30\n // minute default.\n static readonly INTERNAL_WORKFLOW_TTL_MS = readPositiveIntEnv('MASTRA_SUSPENDED_RUN_TTL_MS', 30 * 60 * 1000);\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 = (guarded = false) => {\n if (wfId && rId && self.#isProcessLocalInternalWorkflow(wfId, rId, topic, guarded)) 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.#isProcessLocalInternalWorkflow(pwfId, prId, topic, guarded)) return true;\n parent = parent.parentWorkflow as typeof parent;\n depth++;\n }\n // Scheduler-spawned background workflows: events are only\n // meaningful to the publishing process.\n return isProcessLocalScheduledRunId(rId);\n };\n if (isOwnedHere()) {\n if (topic === 'workflows' && !isOwnedHere(true)) {\n return Promise.resolve(self.getStorage()?.getStore('workflows')).then(store =>\n target.publish(topic, event, { localOnly: !store?.supportsWorkflowStepGuards() }),\n );\n }\n // A local-only start in a process that consumes no workflow\n // events (e.g. `MASTRA_WORKERS=false`) is dropped by the\n // transport. Say so instead of hanging silently.\n if (\n topic === 'workflows' &&\n !self.__hasLocalWorkflowExecution() &&\n !self.#warnedStrandedLocalWorkflowIds.has(wfId ?? '')\n ) {\n self.#warnedStrandedLocalWorkflowIds.add(wfId ?? '');\n self\n .getLogger()\n ?.warn(\n `Workflow event \"${event.type}\" for workflow \"${wfId}\" (run \"${rId}\") is local to this process, ` +\n `but this process has no running workflow workers, so the event will not be processed. ` +\n `Start workers in this process (mastra.startWorkers()) to run it.`,\n );\n }\n return target.publish(topic, event, { localOnly: true });\n }\n } else if (isRunLocalTopic(topic)) {\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 /** Returns a serializable snapshot of this instance's active worker configuration. */\n getWorkerConfig(): WorkersConfig {\n const runningWorkerNames = new Set(this.#workers.filter(worker => worker.isRunning).map(worker => worker.name));\n\n return {\n version: 1,\n orchestration: { enabled: runningWorkerNames.has('orchestration') },\n scheduler: {\n ...serializableWorkerConfig(this.#schedulerConfig),\n enabled: runningWorkerNames.has('scheduler'),\n },\n backgroundTasks: {\n ...serializableWorkerConfig(this.#backgroundTaskConfig),\n enabled: runningWorkerNames.has('backgroundTasks'),\n },\n custom: [...runningWorkerNames]\n .filter(name => !['orchestration', 'scheduler', 'backgroundTasks'].includes(name))\n .sort(),\n };\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 * It is created when worker startup detects scheduling work, or lazily when\n * a schedule is created after boot.\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 * When channels were configured with a {@link ChannelsResolver}, this\n * returns the latest resolved snapshot (possibly `undefined` before the\n * first resolution completes). Use {@link resolveChannels} to get the\n * current provider map.\n */\n public getChannelProviders(): Record<string, ChannelProvider> | undefined {\n return this.#channels;\n }\n\n /**\n * Resolves the current channel provider map.\n *\n * For a static `channels` record this returns it directly. For a\n * {@link ChannelsResolver} it invokes the resolver (the resolver owns\n * freshness via its own cache/TTL), attaches and initializes any providers\n * not seen before, and updates the synchronous snapshot served by\n * {@link getChannelProviders} / {@link channels}.\n *\n * Server handlers that act on channels (webhooks, connect/disconnect,\n * listings) should await this instead of reading the snapshot so\n * connections added after boot are picked up.\n */\n public async resolveChannels(): Promise<Record<string, ChannelProvider>> {\n const resolver = this.#channelsResolver;\n if (!resolver) {\n return this.#channels ?? {};\n }\n if (this.#channelsResolvePromise) {\n return this.#channelsResolvePromise;\n }\n const promise = (async () => {\n const resolved = await resolver({ mastra: this as unknown as Mastra });\n for (const [key, provider] of Object.entries<ChannelProvider>(resolved)) {\n if (provider == null || this.#attachedChannelProviders.has(provider)) continue;\n this.#attachedChannelProviders.add(provider);\n provider.__attach?.(this as unknown as Mastra);\n if (provider.initialize) {\n // Fire-and-forget, matching the static-config init path: resolution\n // consumers shouldn't block on installation restores.\n void provider.initialize().catch(err => {\n this.#logger?.error(`[Mastra] Failed to initialize channel \"${key}\":`, err);\n });\n }\n }\n this.#channels = resolved;\n return resolved;\n })().finally(() => {\n this.#channelsResolvePromise = undefined;\n });\n this.#channelsResolvePromise = promise;\n return promise;\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 * When unset, resolves to `'development'` for `mastra dev` runs (detected via\n * `MASTRA_DEV`), then falls back to `process.env.NODE_ENV`, or `undefined` if\n * none are 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 globalThis.crypto.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: ServerConfigInput): void {\n this.#server = normalizeServerConfig(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.#observabilitySafeLogger() as unknown as TLogger });\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 TClassifiers,\n TKnowledge\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 workflows: config?.recovery?.workflows ?? 'auto',\n workflowConcurrency: normalizeConcurrency(config?.recovery?.workflowConcurrency),\n workflowGraceMs: normalizeGraceMs(config?.recovery?.workflowGraceMs, DEFAULT_WORKFLOW_GRACE_MS),\n workflowScanIntervalMs: normalizeScanIntervalMs(config?.recovery?.workflowScanIntervalMs),\n durableAgents: config?.recovery?.durableAgents ?? 'off',\n };\n this.#recoveryRestarts = createConcurrencyLimiter(this.#recoveryConfig.workflowConcurrency);\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. `mastra dev` spawns\n // its server with NODE_ENV=production so dependencies run in production\n // mode, but flags the run with MASTRA_DEV — treat that as development so\n // Studio telemetry isn't tagged as production. Otherwise fall back to\n // NODE_ENV, leaving undefined if unset rather than guessing.\n this.#environment =\n config?.environment ?? (process.env.MASTRA_DEV === 'true' ? 'development' : 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() once scheduling work exists.\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 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.#storageFallbackWarningPending = true;\n queueMicrotask(() => {\n if (!this.#storageFallbackWarningPending) {\n return;\n }\n\n this.#storageFallbackWarningPending = false;\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). See https://mastra.ai/docs/storage',\n );\n });\n }\n this.#storageSource = getStorageSource(storage);\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 (export-suppressed so observability's own logs\n // never feed back into observability export once wiring completes)\n this.#observability.setLogger({ logger: this.#observabilitySafeLogger() as unknown as TLogger });\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 // Wire the logger into observability so all existing this.logger.info(...)\n // calls get trace correlation and/or export. Adaptable loggers (ConsoleLogger,\n // PinoLogger) are attached in place — trace fields land in their native\n // records. Other loggers fall back to the deprecated DualLogger wrapper.\n this.#loggerAdapterOptions = {\n correlation: config?.loggerOptions?.correlation ?? true,\n export: config?.loggerOptions?.export ?? true,\n };\n this.#logger = this.#wireLoggerObservability(this.#logger);\n\n // Initialize primitive registries before registering storage or editor integrations.\n // Those integrations can call back into Mastra during construction (for example,\n // an editor can replace storage), so registry-dependent methods must already be safe.\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.#classifiers = {} as TClassifiers;\n this.#tools = {} as TTools;\n this.#processors = {} as TProcessors;\n this.#memory = {} as TMemory;\n this.#knowledge = {} as TKnowledge;\n this.#workflows = {} as TWorkflows;\n this.#gateways = {} as Record<string, MastraModelGatewayInterface>;\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 // 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?.classifiers) {\n Object.entries(config.classifiers).forEach(([key, classifier]) => {\n if (classifier != null) {\n this.addClassifier(classifier, 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?.knowledge) {\n Object.entries(config.knowledge).forEach(([key, knowledge]) => {\n if (knowledge != null) {\n this.addKnowledge(knowledge, 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 = normalizeServerConfig(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 const channelRoutes: ApiRoute[] = [];\n\n if (typeof config.channels === 'function') {\n // Live resolver (e.g. `channels()` from @mastra/connect): routes for\n // every possible channel mount up front; provider instances late-bind\n // via `resolveChannels()` so connections added or removed at runtime\n // take effect without a restart.\n this.#channelsResolver = config.channels;\n channelRoutes.push(...config.channels.getRoutes());\n } else {\n this.#channels = config.channels;\n\n for (const [, channel] of Object.entries<ChannelProvider>(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\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 // Warm the first channels resolution so webhook routes have live\n // providers before the first inbound request. Non-fatal: any\n // resolveChannels() call retries.\n if (this.#channelsResolver) {\n void this.resolveChannels().catch(err => {\n this.#logger?.warn(`[Mastra] Initial channels resolution failed (will retry on next access):`, err);\n });\n }\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 legacyScheduleId: string;\n workflowId: string;\n cfg: WorkflowScheduleConfig;\n }> {\n const out: Array<{\n scheduleId: string;\n legacyScheduleId: string;\n workflowId: string;\n cfg: WorkflowScheduleConfig;\n }> = [];\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 const legacyScheduleId = isArrayForm\n ? legacyDeclarativeScheduleRowId(workflow.id, cfg.id)\n : legacyDeclarativeScheduleRowId(workflow.id);\n out.push({ scheduleId, legacyScheduleId, workflowId: workflow.id, cfg });\n }\n }\n return out;\n }\n\n /**\n * Resolve the handler for a handler-mode file-based schedule. Handlers are\n * functions and therefore cannot be persisted on the JSON schedule row, so\n * the agent-schedule worker looks them up in-process by row id at fire time.\n *\n * @internal — public so the agent-schedule worker can call it.\n */\n __getFsAgentScheduleHandler(scheduleId: string): AgentScheduleHandler<Mastra> | undefined {\n return findFsAgentScheduleHandler<Mastra>(this.#agents as Record<string, Agent<any>>, scheduleId);\n }\n\n /**\n * True when the app opted out of the scheduler for the whole instance,\n * either with `workers: false` or with `scheduler: { enabled: false }`.\n *\n * `workers: false` disables all event processing in this instance, so never\n * auto-inject scheduler / agent-schedule workers (even when a schedule is\n * created at runtime). Standalone workers run the scheduler separately.\n *\n * Nothing can start the scheduler while this is true, so callers must also\n * skip the storage reads that only exist to request it (see #20550).\n */\n #schedulerDisabled(): boolean {\n return this.#workersDisabled || this.#schedulerConfig?.enabled === false;\n }\n\n #shouldEnableScheduler(): boolean {\n if (this.#schedulerDisabled()) return false;\n if (this.#schedulerConfig?.enabled === true) return true;\n return (\n this.#hasScheduledWorkflow ||\n this.#schedulerRequested ||\n hasFsAgentSchedule(this.#agents as Record<string, Agent<any>>)\n );\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 allRows = await schedulesStore.listSchedules();\n const rowsById = new Map(allRows.map(row => [row.id, row]));\n const declared = this.#collectDeclarativeSchedules().map(entry => {\n const legacyRow = rowsById.get(entry.legacyScheduleId);\n if (\n entry.legacyScheduleId !== entry.scheduleId &&\n legacyRow?.target.type === 'workflow' &&\n legacyRow.target.workflowId === entry.workflowId\n ) {\n return { ...entry, scheduleId: entry.legacyScheduleId };\n }\n return entry;\n });\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 // `#workflows` is keyed by registration key, which may differ from\n // `workflow.id` — index by id for the definition-hash lookup below.\n const workflowsById = new Map<string, AnyWorkflow>();\n for (const workflow of Object.values(workflows ?? {})) {\n declaredIdsByWorkflow.set(workflow.id, new Set());\n workflowsById.set(workflow.id, workflow);\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 = rowsById.get(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 // Stamp the current build's step-graph hash so the scheduler can\n // refuse to claim this row from an instance whose local workflow\n // definition differs (stale-build fencing, #19169). `targetsEqual`\n // below picks up hash changes and rewrites the row on redeploy.\n const definitionHash = computeScheduleDefinitionHash(workflowsById.get(workflowId)?.serializedStepGraph);\n if (definitionHash) target.definitionHash = definitionHash;\n\n const runAt = cfg.runAt !== undefined ? toEpochMs(cfg.runAt) : undefined;\n const endAt = cfg.endAt !== undefined ? toEpochMs(cfg.endAt) : undefined;\n const cron = cfg.cron ?? '';\n // A one-off whose `runAt` has already passed is recorded as completed\n // rather than fired, so a fresh deploy never runs a stale one-off. A\n // declarative cadence can outlive its final occurrence (e.g. a\n // year-pinned cron that has already passed): that row is registered as\n // `completed` rather than skipped, so the deployment stays\n // self-consistent instead of retrying a doomed write on every boot.\n const computeTiming = (): { nextFireAt: number; status: 'active' | 'completed' } => {\n if (runAt !== undefined) return { nextFireAt: runAt, status: runAt > now ? 'active' : 'completed' };\n const next = computeNextFire({ cron, timezone: cfg.timezone, endAt, nextFireAt: now }, now);\n return { nextFireAt: next.nextFireAt, status: next.completed ? 'completed' : 'active' };\n };\n\n if (!existing) {\n const timing = computeTiming();\n await schedulesStore.createSchedule({\n id: scheduleId,\n target,\n cron,\n timezone: cfg.timezone,\n ...(runAt !== undefined ? { runAt } : {}),\n ...(endAt !== undefined ? { endAt } : {}),\n status: timing.status,\n nextFireAt: timing.nextFireAt,\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. A\n // recomputed cadence is the exception: it re-arms a completed row when\n // it has future occurrences, and completes it when it does not.\n const patch: ScheduleUpdate = {};\n const cronChanged = existing.cron !== cron;\n const timezoneChanged = (existing.timezone ?? undefined) !== (cfg.timezone ?? undefined);\n const runAtChanged = (existing.runAt ?? undefined) !== runAt;\n const endAtChanged = (existing.endAt ?? undefined) !== endAt;\n\n if (cronChanged) patch.cron = cron;\n if (timezoneChanged) patch.timezone = cfg.timezone;\n // Adapters clear the column when the key is present but undefined.\n if (runAtChanged) patch.runAt = runAt;\n if (endAtChanged) patch.endAt = endAt;\n if (!targetsEqual(existing.target, target)) patch.target = target;\n if (!metadataEqual(existing.metadata, cfg.metadata)) patch.metadata = cfg.metadata;\n\n // Any timing change invalidates the stored nextFireAt — recompute from\n // now so we don't fire on the old schedule, and re-arm or complete the\n // row per the recomputed cadence.\n if (cronChanged || timezoneChanged || runAtChanged || endAtChanged) {\n const timing = computeTiming();\n patch.nextFireAt = timing.nextFireAt;\n if (timing.status === 'completed') patch.status = 'completed';\n else if (existing.status === 'completed') patch.status = 'active';\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 for (const row of allRows) {\n if (declaredIds.has(row.id)) continue;\n if (!row.id.startsWith('wf_')) continue;\n // A dynamic workflow that failed to rehydrate is not deleted — keep its\n // schedule rows so a later successful boot picks them back up. Match by\n // generated row-id prefix (not by decoding the row id): workflow ids may\n // themselves contain `__`, which `encodeURIComponent` doesn't escape, so\n // decoding the segment before the first `__` can recover the wrong id.\n const targetWorkflowId = row.target.type === 'workflow' ? row.target.workflowId : undefined;\n const failedOwnerId =\n targetWorkflowId && this.#failedDynamicWorkflowIds.has(targetWorkflowId)\n ? targetWorkflowId\n : ownerWorkflowIdForRow(row.id, this.#failedDynamicWorkflowIds);\n if (failedOwnerId !== undefined) {\n this.#logger?.warn?.(\n `Keeping declarative schedule \"${row.id}\": dynamic workflow \"${failedOwnerId}\" failed to load this boot.`,\n );\n continue;\n }\n const ownerWorkflowId =\n targetWorkflowId ??\n ownerWorkflowIdForRow(row.id, declaredIdsByWorkflow.keys()) ??\n 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 await this.#registerFsAgentSchedules(schedulesStore, allRows);\n\n // A running scheduler sleeps until its earliest fire; re-arm it for rows\n // registered after it started. No-op before it starts.\n this.#findSchedulerWorker()?.scheduler?.wake();\n }\n\n /**\n * Sync schedules declared by file-based agents' `schedules/` directories into\n * schedule storage. Runs as part of {@link registerDeclarativeSchedules}, so\n * it happens on scheduler init and on late agent registration.\n *\n * The sync itself lives in `mastra/fs-agent-schedules.ts` — it needs only the\n * agent map, the store and a logger, so keeping it out of this file keeps the\n * upsert/diff/sweep policy readable on its own. Row equality goes through the\n * same `schedules/row-diff` comparators as the workflow sync above.\n */\n async #registerFsAgentSchedules(schedulesStore: SchedulesStorage, knownRows?: Schedule[]): Promise<void> {\n await syncFsAgentSchedules({\n agents: this.#agents as Record<string, Agent<any>>,\n store: schedulesStore,\n logger: this.#logger as IMastraLogger | undefined,\n knownRows,\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 * Looking up a specific `versionId` requires the editor package to be\n * configured — throws `MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP` if\n * it is not. A `status` selector is a default rather than a request for a\n * specific stored version (the server stamps one on every agent request), so\n * without the editor there are no stored versions and the code-defined agent\n * is returned as-is.\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 The code-defined agent for a status selector without an editor, otherwise a forked\n * 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 && !('versionId' in version)) {\n return agent;\n }\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 const resolved = (await editor.agent.applyStoredOverrides(\n agent,\n 'versionId' in version ? version : { status: version.status ?? 'published' },\n )) as TAgent;\n\n // Mark forks so Agent#execute doesn't try to re-resolve the version and recurse\n if (resolved !== agent) {\n resolved.__markStoredVersionApplied();\n }\n\n return resolved;\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 * Re-registering the same instance under the same key is a no-op. Rehydrating\n * a stored agent under an existing stored-agent key also leaves the original\n * registration unchanged.\n *\n * @throws {MastraError} When a different agent with the same key already exists,\n * except when both registrations have source 'stored'\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * const newAgent = new Agent({\n * id: 'chat-agent',\n * name: 'Chat Assistant',\n * model: 'openai/gpt-4o'\n * });\n * mastra.addAgent(newAgent); // Uses agent.id as key\n * // or\n * mastra.addAgent(newAgent, 'customKey'); // Uses custom key\n *\n * // Durable agents (e.g., InngestAgent) are also supported:\n * const durableAgent = createInngestAgent({ agent: newAgent, inngest });\n * mastra.addAgent(durableAgent); // Auto-registers required workflows\n * ```\n */\n public addAgent<A extends Agent | ToolLoopAgentLike | DurableAgentLike>(\n agent: A,\n key?: string,\n options?: { source?: DefinitionSource },\n ): void {\n if (!agent) {\n throw createUndefinedPrimitiveError('agent', agent, key);\n }\n\n // Handle durable agent wrappers (e.g., InngestAgent)\n // These wrap a regular Agent with execution engine-specific capabilities\n if (isDurableAgentLike(agent)) {\n const durableAgent = agent as DurableAgentLike;\n const underlyingAgent = durableAgent.agent;\n const agentKey = key || durableAgent.id;\n\n // Only re-registering the same wrapper is idempotent.\n const agents = this.#agents as Record<string, Agent<any>>;\n if (agents[agentKey]) {\n if (Object.is(agents[agentKey], durableAgent)) {\n return;\n }\n throw new MastraError({\n id: 'MASTRA_ADD_AGENT_DUPLICATE_KEY',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with key ${agentKey} already exists`,\n details: { status: 409, key: agentKey },\n });\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 // Hide the agent's backing loop workflow from listWorkflows() — it is\n // internal execution plumbing, not a user-runnable workflow. Identity\n // guard: addWorkflow() no-ops on key collision, so a user workflow\n // pre-registered under the same id must stay visible.\n if ((this.#workflows as Record<string, unknown>)[workflow.id] === workflow) {\n this.#hiddenWorkflowKeys.add(workflow.id);\n }\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 agentSource: underlyingAgent.source,\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 this.#registerSignalProviderRoutes(underlyingAgent);\n this.#syncLateRegisteredAgentSchedules(underlyingAgent);\n\n return;\n }\n\n let mastraAgent: Agent<any, any, any>;\n const toolLoopInput = isToolLoopAgentLike(agent) ? agent : undefined;\n if (toolLoopInput) {\n // Pass the config key as the name if the ToolLoopAgent doesn't have an id\n mastraAgent = toolLoopAgentToMastraAgent(toolLoopInput, { 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 if (\n agents[agentKey] === mastraAgent ||\n (toolLoopInput && this.#toolLoopRegistrations.get(toolLoopInput)?.get(agentKey) === agents[agentKey]) ||\n (agents[agentKey].source === 'stored' && options?.source === 'stored')\n ) {\n return;\n }\n throw new MastraError({\n id: 'MASTRA_ADD_AGENT_DUPLICATE_KEY',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Agent with key ${agentKey} already exists`,\n details: { status: 409, key: agentKey },\n });\n }\n\n // Set the source first: registering the agent records it on the agent's processor configurations\n if (options?.source) {\n mastraAgent.source = options.source;\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 agents[agentKey] = mastraAgent;\n if (toolLoopInput) {\n let registrations = this.#toolLoopRegistrations.get(toolLoopInput);\n if (!registrations) {\n registrations = new Map();\n this.#toolLoopRegistrations.set(toolLoopInput, registrations);\n }\n registrations.set(agentKey, mastraAgent);\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 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 agentSource: mastraAgent.source,\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 this.#registerSignalProviderRoutes(mastraAgent);\n this.#syncLateRegisteredAgentSchedules(mastraAgent);\n }\n\n /**\n * Merge routes from the agent's signal providers into `server.apiRoutes`.\n * Skips routes whose method and path are already registered, so a provider\n * shared by several agents only mounts its routes once and existing routes\n * win. Logs a warning when a route is skipped because something other than\n * the same provider already holds that method and path.\n */\n #registerSignalProviderRoutes(agent: Agent<any, any, any>): void {\n const existingRoutes = this.#server?.apiRoutes ?? [];\n const newRoutes: ApiRoute[] = [];\n\n for (const provider of agent.listSignalProviders?.() ?? []) {\n for (const route of provider.getRoutes?.() ?? []) {\n const registered = [...existingRoutes, ...newRoutes].find(\n existing => existing.path === route.path && existing.method === route.method,\n );\n if (!registered) {\n newRoutes.push(route);\n this.#signalProviderRouteOwners.set(route, provider);\n continue;\n }\n if (this.#signalProviderRouteOwners.get(registered) !== provider) {\n this.getLogger().warn(\n `Signal provider \"${provider.id}\" on agent \"${agent.id}\" declares ${route.method} ${route.path}, but that route is already registered. Skipping the provider route.`,\n );\n }\n }\n }\n\n if (newRoutes.length > 0) {\n this.#server = { ...this.#server, apiRoutes: [...existingRoutes, ...newRoutes] };\n }\n }\n\n /**\n * Remove routes added by a removed agent's signal providers, unless another\n * registered agent still uses the same provider instance.\n */\n #unregisterSignalProviderRoutes(removedAgent: Agent<any, any, any> | undefined): void {\n const routes = this.#server?.apiRoutes;\n const removedProviders = new Set(this.#listAgentSignalProviders(removedAgent));\n if (!routes || removedProviders.size === 0) return;\n\n const providersInUse = new Set(\n Object.values(this.#agents as Record<string, Agent<any, any, any>>).flatMap(agent =>\n this.#listAgentSignalProviders(agent),\n ),\n );\n const keptRoutes = routes.filter(route => {\n const provider = this.#signalProviderRouteOwners.get(route);\n return !provider || !removedProviders.has(provider) || providersInUse.has(provider);\n });\n\n if (keptRoutes.length !== routes.length) {\n this.#server = { ...this.#server, apiRoutes: keptRoutes };\n }\n }\n\n #listAgentSignalProviders(agent: Agent<any, any, any> | undefined): SignalProvider[] {\n const target = agent && isDurableAgentLike(agent) ? (agent as DurableAgentLike).agent : agent;\n return target?.listSignalProviders?.() ?? [];\n }\n\n /**\n * Push an agent's declared schedules into an already-running scheduler.\n *\n * Agents registered before `startWorkers()` are picked up by\n * `SchedulerWorker.init()`, which calls {@link registerDeclarativeSchedules}.\n * An agent added afterwards would otherwise never have its rows written, so\n * mirror what `addWorkflow` does for declarative workflow schedules.\n *\n * The sync covers every registered agent, so registering a batch (e.g.\n * `__registerFsAgents`) coalesces into a single sweep instead of one full\n * `listSchedules()` pass per agent.\n */\n #syncLateRegisteredAgentSchedules(agent: Agent<any>): void {\n if (declaredSchedulesOf(agent).length === 0) return;\n\n const worker = this.#findSchedulerWorker();\n // SchedulerWorker.init() syncs these when the scheduler starts.\n if (!worker?.scheduler) return;\n\n // A sweep is already in flight. It may already have read the agent map, so\n // ask it to run once more rather than dropping this registration — but do\n // not start a second sweep, which would race the first on `createSchedule`\n // for the same row.\n if (this.#fsScheduleSyncPending) {\n this.#fsScheduleSyncRerun = true;\n return;\n }\n this.#fsScheduleSyncPending = true;\n\n void (async () => {\n try {\n do {\n this.#fsScheduleSyncRerun = false;\n // Yield first so agents registered in the same synchronous batch are\n // all present before the sweep computes what is declared.\n await Promise.resolve();\n const schedulesStore = await this.#storage?.getStore('schedules');\n if (!schedulesStore) return;\n await this.registerDeclarativeSchedules(schedulesStore);\n } while (this.#fsScheduleSyncRerun);\n } catch (error) {\n this.#logger?.error('Failed to register schedules for late-registered agent', {\n agentId: agent.id,\n error,\n });\n } finally {\n this.#fsScheduleSyncPending = false;\n this.#fsScheduleSyncRerun = false;\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 let registeredCount = 0;\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 registeredCount++;\n }\n\n if (registeredCount > 0 && !this.#fsAgentUsageTracked) {\n this.#fsAgentUsageTracked = true;\n trackFeatureUsage('file_based_agents', { fs_agent_count: registeredCount });\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 an export-suppressed view of the logger to observability so its\n // internal logs never feed back into observability export.\n this.#observability.setLogger({ logger: this.#observabilitySafeLogger() 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 // File-system routes win over signal provider routes on the same method and path.\n const fsRoutes = fsServer.apiRoutes ?? [];\n const existingRoutes = (this.#server?.apiRoutes ?? []).filter(route => {\n const provider = this.#signalProviderRouteOwners.get(route);\n if (!provider) return true;\n const overridden = fsRoutes.some(fsRoute => fsRoute.path === route.path && fsRoute.method === route.method);\n if (overridden) {\n this.getLogger().warn(\n `Signal provider \"${provider.id}\" route ${route.method} ${route.path} is overridden by a file-system route.`,\n );\n }\n return !overridden;\n });\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 /** Drops an agent's processor configurations; registering the agent again re-adds them. */\n #removeProcessorConfigurations(agentId: string): void {\n for (const [processorId, configs] of this.#processorConfigurations) {\n const remaining = configs.filter(c => c.agentId !== agentId);\n if (remaining.length === 0) {\n this.#processorConfigurations.delete(processorId);\n } else if (remaining.length !== configs.length) {\n this.#processorConfigurations.set(processorId, remaining);\n }\n }\n }\n\n /**\n * Removes an agent from the Mastra instance by its key or ID.\n * Used when stored agents are updated/deleted to allow fresh data to be loaded.\n *\n * @param keyOrId - The agent key or ID to remove\n * @returns true if an agent was removed, false if no agent was found\n *\n * @example\n * ```typescript\n * // Remove by key\n * mastra.removeAgent('myAgent');\n *\n * // Remove by ID\n * mastra.removeAgent('agent-123');\n * ```\n */\n public removeAgent(keyOrId: string): boolean {\n const agents = this.#agents as Record<string, Agent<any>>;\n\n // Try direct key lookup first\n if (agents[keyOrId]) {\n const removedAgent = agents[keyOrId];\n const agentId = removedAgent?.id;\n delete agents[keyOrId];\n this.#unregisterSignalProviderRoutes(removedAgent);\n // Clear from stored agents cache to prevent stale data\n if (agentId) {\n this.#storedAgentsCache.delete(agentId);\n this.#removeProcessorConfigurations(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 removedAgent = agents[key];\n const agentId = removedAgent?.id;\n delete agents[key];\n this.#unregisterSignalProviderRoutes(removedAgent);\n // Clear from stored agents cache to prevent stale data\n if (agentId) {\n this.#storedAgentsCache.delete(agentId);\n this.#removeProcessorConfigurations(agentId);\n }\n return true;\n }\n\n // An agent attached to Mastra without being registered (a sub-agent) still registers processor configurations.\n this.#removeProcessorConfigurations(keyOrId);\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; agentSource?: DefinitionSource },\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 ...(source === 'agent' && metadata?.agentSource ? { agentSource: metadata.agentSource } : {}),\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 * Track an in-flight evented workflow run owned by this instance so\n * {@link shutdown} can let it settle before tearing down pubsub. Returns a\n * release function the caller must invoke once the run has settled.\n *\n * @internal\n */\n __trackEventedRun(execution: Promise<unknown>): () => void {\n // Tracking must never turn a run's rejection into an unhandledRejection;\n // the caller still observes the original promise.\n execution.catch(() => {});\n this.#activeEventedRuns.add(execution);\n return () => {\n this.#activeEventedRuns.delete(execution);\n };\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 * Pass `{ distributed: true }` (unscoped only) when every process registers\n * the workflow identically, so any process's workers can execute its runs.\n * Its events then travel through the shared pubsub instead of being kept\n * local to the publishing process.\n */\n __registerInternalWorkflow(workflow: AnyWorkflow, runId?: string, options?: { distributed?: boolean }) {\n workflow.__markInternal();\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, { lastActivityAt: 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 if (options?.distributed) {\n this.#distributedInternalWorkflowIds.add(workflow.id);\n } else {\n this.#distributedInternalWorkflowIds.delete(workflow.id);\n }\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 /**\n * Whether this process consumes workflow-execution events itself, i.e.\n * whether a `workflow.start` published here would be handled here.\n *\n * True when a local OrchestrationWorker is pulling the `workflows` topic,\n * or when a push-only pubsub has `handleWorkflowEvent` wired directly\n * (`#wirePushWorkflowSubscription`).\n *\n * The scheduler uses this to keep a scheduled fire on the instance that\n * claimed it (#19169). Scheduler and execution workers start through\n * separate paths (`#startSchedulingWorkers` / `#startExecutionWorkers`),\n * so a scheduler-only process is a supported topology and must keep\n * publishing to the shared topic instead of stranding the fire locally.\n *\n * @internal\n */\n __hasLocalWorkflowExecution(): boolean {\n if (this.#pushSubscription) return true;\n const orchestration = this.#workers.find(w => w.name === 'orchestration');\n return !!orchestration?.isRunning;\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 if (this.#internalMastraWorkflows[`${id}:${runId}`]) {\n this.#touchRunScopedWorkflow(id, runId);\n return true;\n }\n return !!this.#internalMastraWorkflows[id];\n }\n return !!this.#internalMastraWorkflows[id];\n }\n\n /**\n * Whether this internal workflow event must stay in this process. A\n * run-scoped registration always qualifies; an unscoped one does unless it\n * was registered `distributed`. A distributed workflow's `workflows` events\n * stay local on stores without atomic occurrence guards. Guarded stores\n * allow workers to publish reclaimable continuations through the broker.\n * Its `workflows-finish` events always cross, since\n * the process waiting for the result may not be the one that ran it.\n */\n #isProcessLocalInternalWorkflow(id: string, runId: string, topic: string, guarded: boolean): boolean {\n if (!this.__hasInternalWorkflow(id, runId)) return false;\n if (this.#internalMastraWorkflows[`${id}:${runId}`]) return true;\n if (!this.#distributedInternalWorkflowIds.has(id)) return true;\n return topic === 'workflows' && !guarded && this.__hasLocalWorkflowExecution();\n }\n\n /**\n * Mark a run-scoped registration as active so the lazy TTL sweep measures\n * idle time rather than total run duration. Only refreshes an entry that\n * already exists at the exact `${id}:${runId}` key — resolving the bare\n * unscoped `${id}` slot says nothing about a run's liveness, and this must\n * never create an entry.\n */\n #touchRunScopedWorkflow(id: string, runId: string) {\n const entry = this.#runScopedWorkflowTimestamps.get(`${id}:${runId}`);\n if (entry) {\n entry.lastActivityAt = Date.now();\n }\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 let workflow: AnyWorkflow | undefined;\n if (runId) {\n workflow = this.#internalMastraWorkflows[`${id}:${runId}`];\n if (workflow) {\n this.#touchRunScopedWorkflow(id, runId);\n } else {\n workflow = this.#internalMastraWorkflows[id];\n }\n } else {\n workflow = this.#internalMastraWorkflows[id];\n }\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 been *idle*\n * longer than {@link Mastra.INTERNAL_WORKFLOW_TTL_MS}. Called on every new\n * run-scoped registration so cleanup is proportional to activity — zero\n * overhead when the system is idle.\n *\n * Idleness, not age: every lookup a run makes against its own registration\n * refreshes `lastActivityAt` (see `#touchRunScopedWorkflow`), so a run that\n * executes for longer than the TTL is never evicted mid-flight. Only a run\n * that has stopped touching its registration — suspended and never resumed,\n * or abandoned — ages out. This matches how the agent thread-stream runtime\n * treats the shared `MASTRA_SUSPENDED_RUN_TTL_MS` bound, which only expires\n * records that are actually parked.\n */\n #sweepStaleRunScopedWorkflows() {\n const now = Date.now();\n for (const [key, entry] of this.#runScopedWorkflowTimestamps) {\n if (now - entry.lastActivityAt > 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 went idle past the TTL.\n this.#logger.warn('Evicted stale run-scoped workflow after TTL expired', {\n runId: entry.runId,\n idleMs: now - entry.lastActivityAt,\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 /**\n * Every RUNNING/WAITING run of the workflows recovery restarts, with full snapshots, read in one\n * call per workflow and status. `restartAllActiveWorkflowRuns()` lists summaries instead.\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 const activeRunsByWorkflow = await Promise.all(\n this.#restartableWorkflows().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 /**\n * The workflows whose active runs the recovery sweep restarts (see {@link isRecoveryRestartable}).\n * Filtered before listing, so opted-out workflows cost no storage queries.\n */\n #restartableWorkflows(): AnyWorkflow[] {\n return Object.values(this.#workflows).filter(workflow => isRecoveryRestartable(workflow));\n }\n\n /**\n * Whether the pubsub's broker recovers run `runId` of `workflow`, so recovery never lists, reads\n * or restarts it: an evented run whose events reach a broker that redelivers a dead worker's\n * unacked message to another worker. A scheduled run whose events stay in the publishing process\n * (see {@link isProcessLocalScheduledRunId}) has no message at the broker, so it is not one.\n */\n #brokerOwnsRun(workflow: AnyWorkflow, runId: string): boolean {\n return (\n workflow.engineType === 'evented' &&\n this.#pubsub.__rawBus().redeliversUnacked &&\n !isProcessLocalScheduledRunId(runId)\n );\n }\n\n /**\n * Restarts the RUNNING/WAITING runs of the registered workflows that no process runs any more,\n * `recovery.workflowConcurrency` at a time (default 5).\n *\n * A default-engine run counts as stopped once no instance holds its run lease and\n * `recovery.workflowGraceMs` passed since it or its lease last changed. A run still live or in\n * its grace period is left to the recovery loop (see {@link Mastra.startWorkers}); this call\n * doesn't look at it again. Without run fencing in the store, every active default-engine run is\n * restarted.\n *\n * An evented run on a pubsub whose broker redelivers unacked messages\n * (`PubSub.redeliversUnacked`) is left to the broker and never read, except a scheduled run\n * whose events stay in the process. Every other evented run is restarted at once, by this call\n * only: the recovery loop never restarts evented runs.\n *\n * Resolves once every restart its pass queued finished. Runs an earlier pass already queued are\n * skipped and not awaited. A call made while a default-engine pass is still handing out restarts\n * joins it. Failures are logged per run and never reject. Once `shutdown()` starts, no further\n * runs are restarted.\n */\n public async restartAllActiveWorkflowRuns(): Promise<void> {\n let workflowsStore: WorkflowsStorage | undefined;\n try {\n workflowsStore = await this.#storage?.getStore('workflows');\n } catch (error) {\n this.#logger.error('Failed to recover stopped workflow runs', { error });\n return;\n }\n\n if (!workflowsStore) {\n this.#logger.debug('Cannot restart active workflow runs. Mastra storage is not initialized');\n return;\n }\n\n const runFencing = await this.#supportsRunFencing(workflowsStore);\n const passes = await Promise.all([\n // Tracked, as the shared default-engine pass is, so shutdown() waits while it reads the store.\n this.#trackDurableRecovery(this.#runRecoveryPass({ workflowsStore, runFencing, engine: 'evented' })),\n // Never gated on the recovery leader: the leader lists only the workflows it registers, and a\n // restarted run executes where it is restarted, so each booting instance restarts its own.\n this.#recoverStoppedRuns(workflowsStore, runFencing),\n ]);\n await Promise.all(passes.map(pass => pass.settled));\n }\n\n /** The default-engine recovery pass still handing out restarts, which overlapping callers share, or a new one. */\n #recoverStoppedRuns(workflowsStore: WorkflowsStorage, runFencing: boolean): Promise<RecoveryPass> {\n if (!this.#recoveryPass) {\n const pass = this.#runRecoveryPass({ workflowsStore, runFencing, engine: 'default' });\n this.#recoveryPass = pass;\n // `#runRecoveryPass` never rejects. A pass that already ended must not clear a newer one.\n void pass.finally(() => {\n if (this.#recoveryPass === pass) {\n this.#recoveryPass = undefined;\n }\n });\n }\n\n return this.#recoveryPass;\n }\n\n /**\n * One recovery pass over the run summaries of `engine`'s workflows and their run leases (see\n * {@link recoveryVerdict}); never rejects.\n */\n async #runRecoveryPass({\n workflowsStore,\n runFencing,\n engine,\n }: {\n workflowsStore: WorkflowsStorage;\n runFencing: boolean;\n engine: RecoveryEngine;\n }): Promise<RecoveryPass> {\n const restarts: Promise<void>[] = [];\n const failedRestarts = this.#failedRecoveryRestarts[engine];\n let earliestDueAt: number | undefined;\n try {\n const listed = await this.#listActiveRunSummaries(workflowsStore, engine);\n // A failed run that is no longer active cannot fail again, so it is forgotten.\n const listedKeys = new Set(listed.map(({ run }) => recoveryRunKey(run.workflowName, run.runId)));\n for (const key of failedRestarts) {\n if (!listedKeys.has(key)) {\n failedRestarts.delete(key);\n }\n }\n\n const candidates = await this.#recoveryCandidates(workflowsStore, listed);\n const graceMs = this.#workflowGraceMs();\n\n for (let start = 0; start < candidates.length; start += RECOVERY_OWNERSHIP_BATCH_SIZE) {\n if (this.#shuttingDown) {\n break;\n }\n\n // A run an earlier pass handed out and that is still queued or running here is that pass's to restart.\n const batch = candidates\n .slice(start, start + RECOVERY_OWNERSHIP_BATCH_SIZE)\n .filter(({ run }) => !this.#queuedRecoveryRestarts.has(recoveryRunKey(run.workflowName, run.runId)));\n const leased = runFencing ? batch.filter(({ workflow }) => usesRunLease(workflow)) : [];\n const owners = leased.length > 0 ? await this.#readRunOwners(workflowsStore, leased) : undefined;\n const now = Date.now();\n\n for (const candidate of batch) {\n if (this.#shuttingDown) {\n break;\n }\n\n const { workflow, run } = candidate;\n let verdict: RecoveryVerdict;\n if (!runFencing || !usesRunLease(workflow)) {\n // Nothing tells a live run from a stopped one: without run fencing, and for an evented run, which\n // holds no run lease. Such a run is restarted at once, as before the recovery rule existed.\n verdict = { restart: true };\n } else if (!owners) {\n // The leases could not be read: the next pass looks again. Counted as live, so a broken read does\n // not bring that pass forward.\n verdict = { restart: false, live: true, dueAt: now + graceMs };\n } else {\n verdict = recoveryVerdict({ owner: owners.get(run.runId), updatedAt: run.updatedAt, graceMs, now });\n }\n\n if (verdict.restart) {\n // Queued without waiting for a slot, so long restarts never hold up the pass.\n const key = recoveryRunKey(run.workflowName, run.runId);\n const restart = this.#queueRecoveryRestart({ workflow, run, workflowsStore, runFencing }).then(\n () => void failedRestarts.delete(key),\n error => {\n // Every pass retries a run whose restart throws, so only its first failure is an error.\n const context = { workflow: workflow.id, runId: run.runId, error };\n if (failedRestarts.has(key)) {\n this.#logger.debug('Failed to restart workflow run again', context);\n } else {\n failedRestarts.add(key);\n this.#logger.error('Failed to restart workflow run', context);\n }\n },\n );\n restarts.push(restart);\n continue;\n }\n\n // A run left in its grace period moves the recovery loop's next pass up. A live run doesn't: its\n // lease is renewed while it runs, so its due time keeps moving, and the loop's interval bounds how\n // long a run whose process dies waits past it.\n if (!verdict.live) {\n earliestDueAt = Math.min(earliestDueAt ?? Infinity, verdict.dueAt);\n }\n }\n }\n } catch (error) {\n this.#logger.error('Failed to recover stopped workflow runs', { error });\n }\n\n // Each restart logs its own failure and never rejects.\n return { earliestDueAt, settled: Promise.all(restarts).then(() => {}) };\n }\n\n /**\n * Restarts a run the recovery pass picked once `#recoveryRestarts` has a free slot, and rejects when\n * the restart fails. The run counts as queued meanwhile, so recovery leaves it to this restart, and a\n * run that is already queued resolves at once without a second restart.\n *\n * A default-engine run's verdict is from a lease read before the run was queued. While it waited for a\n * slot, another instance can have restarted the run and stopped again; `restart()` alone would not see\n * that, as it ignores the grace period. So the lease is read once more first.\n */\n #queueRecoveryRestart({\n workflow,\n run,\n workflowsStore,\n runFencing,\n }: {\n workflow: AnyWorkflow;\n run: WorkflowRun;\n workflowsStore: WorkflowsStorage;\n runFencing: boolean;\n }): Promise<void> {\n const restartIfStopped = async () => {\n if (this.#shuttingDown) {\n return;\n }\n\n if (runFencing && usesRunLease(workflow)) {\n let owners: Map<string, RunOwnershipRecord>;\n try {\n owners = await workflowsStore.getRunOwnerships({ runIds: [run.runId] });\n } catch (error) {\n // As for a failed batch read: the next pass looks again.\n this.#logger.warn('Failed to read workflow run lease before restarting', {\n workflow: workflow.id,\n runId: run.runId,\n error,\n });\n return;\n }\n\n const verdict = recoveryVerdict({\n owner: owners.get(run.runId),\n updatedAt: run.updatedAt,\n graceMs: this.#workflowGraceMs(),\n now: Date.now(),\n });\n if (!verdict.restart) {\n return;\n }\n }\n\n await this.#restartWorkflowRun(workflow, run.runId);\n };\n\n // Checked here, right before the add: a pass checks before its lease read, and another pass can queue\n // the run during that read.\n const key = recoveryRunKey(run.workflowName, run.runId);\n if (this.#queuedRecoveryRestarts.has(key)) {\n return Promise.resolve();\n }\n\n this.#queuedRecoveryRestarts.add(key);\n return this.#recoveryRestarts\n .run(() => this.#trackDurableRecovery(restartIfStopped()))\n .finally(() => this.#queuedRecoveryRestarts.delete(key));\n }\n\n /** The grace period of the recovery rule (`recovery.workflowGraceMs`). */\n #workflowGraceMs(): number {\n return this.#recoveryConfig.workflowGraceMs ?? DEFAULT_WORKFLOW_GRACE_MS;\n }\n\n /**\n * Whether the pass can read run leases. A failed probe counts as no, which restarts every active\n * run as a store without leases does: `restart()` probes again and refuses a run another process\n * still holds.\n */\n async #supportsRunFencing(workflowsStore: WorkflowsStorage): Promise<boolean> {\n try {\n return await workflowsStore.supportsRunFencing();\n } catch (error) {\n this.#logger.warn('Failed to check run fencing support before restarting workflow runs', { error });\n return false;\n }\n }\n\n /**\n * Every RUNNING/WAITING run of the restartable workflows on `engine` that recovery may restart, as\n * summaries without step results. Runs the broker recovers (see `#brokerOwnsRun`) are left out.\n */\n async #listActiveRunSummaries(\n workflowsStore: WorkflowsStorage,\n engine: RecoveryEngine,\n ): Promise<RecoveryCandidate[]> {\n const redelivers = this.#pubsub.__rawBus().redeliversUnacked;\n const workflows = this.#restartableWorkflows().filter(workflow => workflow.engineType === engine);\n const listed = await Promise.all(\n workflows.map(async workflow => {\n // On a redelivering broker the only evented runs recovery restarts are scheduled ones, and only a\n // workflow with declarative schedules has those. The other evented workflows cost no listing.\n if (workflow.engineType === 'evented' && redelivers && collectWorkflowScheduleConfigs(workflow).length === 0) {\n return [];\n }\n\n try {\n // A run that moved from one status to the other between the two reads is listed under both.\n const runs = new Map<string, WorkflowRun>();\n for (const status of ACTIVE_RUN_STATUSES) {\n const { runs: listedRuns } = await this.#recoveryListings.run(() =>\n workflowsStore.listWorkflowRuns({ workflowName: workflow.id, status, perPage: false, summary: true }),\n );\n for (const run of listedRuns) {\n if (!runs.has(run.runId) && !this.#brokerOwnsRun(workflow, run.runId)) {\n runs.set(run.runId, run);\n }\n }\n }\n\n return [...runs.values()].map(run => ({ workflow, run }));\n } catch (error) {\n // A store error while listing one workflow's runs must not leave the other workflows unrecovered.\n this.#logger.error('Failed to list active workflow runs for recovery', { workflow: workflow.id, error });\n return [];\n }\n }),\n );\n\n return listed.flat();\n }\n\n /** The listed runs the recovery rule applies to, after nested runs are left to or canceled by their parents. */\n async #recoveryCandidates(\n workflowsStore: WorkflowsStorage,\n listed: RecoveryCandidate[],\n ): Promise<RecoveryCandidate[]> {\n const activeRuns = new Set(listed.map(({ run }) => recoveryRunKey(run.workflowName, run.runId)));\n // One lookup per parent per pass: a crashed foreach leaves one nested run per item, all under the same parent.\n const parentStatusOf = createNestedRunParentStatusLookup({ store: workflowsStore });\n const candidates: RecoveryCandidate[] = [];\n\n for (const candidate of listed) {\n const { run } = candidate;\n const parent = nestedRunParentOf(run.snapshot);\n if (!parent) {\n candidates.push(candidate);\n continue;\n }\n\n // The active parent's recovery re-drives it; restarting it as well would run it twice. This needs every\n // workflow listed first, since the parent can belong to a workflow listed after it.\n if (activeRuns.has(recoveryRunKey(parent.workflowName, parent.runId))) {\n continue;\n }\n\n // A nested run is collected by its parent's step, so the parent's stored status decides what\n // restarting it standalone would do: run it twice while the parent drives it, or re-run the\n // item after the parent already finished it. A pass lists one engine's runs, so a registered\n // default-engine workflow nested in an evented parent costs this lookup, once per parent per\n // pass, and is skipped while that parent runs.\n try {\n const parentStatus = await parentStatusOf(parent);\n const recovery = nestedRunRecoveryAction(parentStatus);\n if (recovery === 'restart') {\n candidates.push(candidate);\n } else if (recovery === 'cancel') {\n await cancelNestedRun({\n store: workflowsStore,\n workflowName: run.workflowName,\n runId: run.runId,\n expectedStatus: nestedRunStatusOf(run.snapshot),\n logger: this.#logger,\n });\n } else {\n // Nothing is wrong here: the parent can still drive this run. Logged because a nested\n // run left waiting on a parent that never restarts is otherwise only visible in the\n // nested workflow's own active runs.\n this.#logger.debug('Left a nested workflow run for its parent to drive', {\n workflow: run.workflowName,\n runId: run.runId,\n parentWorkflow: parent.workflowName,\n parentRunId: parent.runId,\n parentStatus,\n });\n }\n } catch (error) {\n // One nested run's lookup must not stop the pass, or unrelated runs go unrecovered.\n this.#logger.error('Failed to recover nested workflow run', {\n workflow: run.workflowName,\n runId: run.runId,\n error,\n });\n }\n }\n\n return candidates;\n }\n\n /** The run leases of one batch of default-engine runs, read in one call; `undefined` when the read fails. */\n async #readRunOwners(\n workflowsStore: WorkflowsStorage,\n batch: RecoveryCandidate[],\n ): Promise<Map<string, RunOwnershipRecord> | undefined> {\n try {\n return await workflowsStore.getRunOwnerships({ runIds: batch.map(({ run }) => run.runId) });\n } catch (error) {\n this.#logger.warn('Failed to read workflow run leases before restarting', { runs: batch.length, error });\n return undefined;\n }\n }\n\n /**\n * Restarts one run the recovery pass picked. When another process won a default-engine run in\n * the meantime, `restart()` refuses with `WORKFLOW_RESTART_RUN_OWNED` and the run is left to the\n * recovery loop's next pass. Other failures reject, for the caller to log or retry. The restart\n * holds its slot until the run ends.\n */\n async #restartWorkflowRun(workflow: AnyWorkflow, runId: string): Promise<void> {\n // The reads before it can outlast the start of shutdown.\n if (this.#shuttingDown) {\n return;\n }\n\n const run = await workflow.createRun({ runId });\n try {\n await run.restart();\n } catch (error) {\n if (!(error instanceof MastraError && error.id === 'WORKFLOW_RESTART_RUN_OWNED')) {\n throw error;\n }\n\n this.#logger.debug('Skipped restarting workflow run owned by a live process', { workflow: workflow.id, runId });\n return;\n }\n\n this.#logger.debug('Restarted workflow run', { workflow: workflow.id, runId });\n }\n\n /**\n * Whether this instance is the recovery leader: it holds the `::recovery-leader` run-owners row,\n * or takes it now when no other instance holds it live. A taken row is renewed until\n * `#releaseRecoveryLeader()`, so the leader keeps it across passes; when this instance dies the\n * row lapses after the lease TTL and the next instance to try takes it. Only the loop's ticks call\n * this, one at a time. Rejects when the store fails the claim.\n */\n #leadWorkflowRecovery(workflowsStore: WorkflowsStorage): Promise<boolean> {\n if (this.#recoveryLeader) {\n return Promise.resolve(true);\n }\n\n this.#recoveryLeaderClaim = this.#claimRecoveryLeader(workflowsStore).finally(() => {\n this.#recoveryLeaderClaim = undefined;\n });\n return this.#recoveryLeaderClaim;\n }\n\n /** One non-forced claim of the recovery leader row; see `#leadWorkflowRecovery`. */\n async #claimRecoveryLeader(workflowsStore: WorkflowsStorage): Promise<boolean> {\n const claim = await workflowsStore.claimRunOwnership({\n runId: RECOVERY_LEADER_KEY,\n ownerId: crypto.randomUUID(),\n leaseMs: WORKFLOW_RUN_LEASE_TTL_MS,\n force: false,\n });\n if (!claim.acquired) {\n return false;\n }\n\n const fence: RunFence = {\n runId: RECOVERY_LEADER_KEY,\n generation: claim.record.generation,\n ownerId: claim.record.ownerId,\n };\n const leader = { store: workflowsStore, fence, stopRenewing: () => {} };\n // The renewals outlive the call that claimed, which may run inside a durable run; they must not carry its fence.\n leader.stopRenewing = runOutsideRunFenceScope(() =>\n renewWorkflowLease({\n store: workflowsStore,\n fence,\n onLost: owner => {\n if (this.#recoveryLeader === leader) {\n this.#recoveryLeader = undefined;\n }\n\n this.#logger.warn('Lost the workflow recovery leader lease; another instance may lead recovery now', {\n owner: owner?.ownerId,\n });\n },\n onError: error => this.#logger.warn('Failed to renew the workflow recovery leader lease', { error }),\n }),\n );\n this.#recoveryLeader = leader;\n return true;\n }\n\n /** Hands the recovery leader row back, if this instance holds it, so another instance can take it at once. */\n async #releaseRecoveryLeader(): Promise<void> {\n // A claim in flight could otherwise take the row after this release and keep renewing it.\n await this.#recoveryLeaderClaim?.catch(() => {});\n const leader = this.#recoveryLeader;\n if (!leader) {\n return;\n }\n\n this.#recoveryLeader = undefined;\n leader.stopRenewing();\n try {\n await leader.store.releaseRunOwnership(leader.fence);\n } catch (error) {\n this.#logger.warn('Failed to release the workflow recovery leader lease', { error });\n }\n }\n\n /**\n * Starts the recovery loop unless it runs, recovery is off, or this instance has no storage or\n * workers; the caller checks that this instance handles workflow events.\n *\n * Each tick tries to lead (see `#leadWorkflowRecovery`); only the leader runs a pass, over\n * default-engine runs only. The first tick runs now; a `restartAllActiveWorkflowRuns()` call made\n * while this instance's pass runs, such as the server's at boot, joins it. Each later tick runs a scan\n * interval after the previous one handed out its restarts, or sooner when a run that pass found\n * in its grace period comes due first (see {@link nextWorkflowScanDelay}). The loop stops for\n * good on a store without run fencing, where nothing tells a live run from a stopped one.\n */\n #startWorkflowRecoveryLoop(): void {\n if (\n this.#stopWorkflowRecoveryLoop ||\n this.#recoveryConfig.workflows === 'off' ||\n !this.#storage ||\n this.#workersDisabled\n ) {\n return;\n }\n\n let stopChain: (() => void) | undefined;\n const stop = () => {\n stopChain?.();\n if (this.#stopWorkflowRecoveryLoop === stop) {\n this.#stopWorkflowRecoveryLoop = undefined;\n }\n };\n this.#stopWorkflowRecoveryLoop = stop;\n\n let dueAt: number | undefined;\n // Never rejects, as `repeatAfterSettled` requires.\n const tick = async () => {\n dueAt = undefined;\n // With no default-engine workflow to recover there is nothing to lead: no claim, and no lease renewals.\n // Checked per tick, as workflows can be added after startWorkers().\n if (!this.#restartableWorkflows().some(usesRunLease)) {\n return;\n }\n\n try {\n const workflowsStore = await this.#storage?.getStore('workflows');\n if (!workflowsStore) {\n return;\n }\n\n // A failed probe throws and skips the tick: some stores (MongoDB) fail it until one succeeds.\n if (!(await workflowsStore.supportsRunFencing())) {\n stop();\n return;\n }\n\n // A stopWorkers() during the awaits above already released the row: a claim now would hold it for good.\n if (this.#stopWorkflowRecoveryLoop !== stop) {\n return;\n }\n\n if (!(await this.#leadWorkflowRecovery(workflowsStore))) {\n return;\n }\n\n // Stopped during the claim, which the release waited for: the row is handed back, so no pass either.\n if (this.#stopWorkflowRecoveryLoop !== stop) {\n return;\n }\n\n // shutdown() waits for this pass and for each restart it hands out; the tick waits only for the handing\n // out, so a long restart never holds up the next pass.\n const pass = await this.#recoverStoppedRuns(workflowsStore, true);\n dueAt = pass.earliestDueAt;\n } catch (error) {\n this.#logger.warn('Workflow recovery loop skipped a pass', { error });\n }\n };\n\n // Started from startWorkers(), which may run inside a durable run; the passes must not carry its write fence.\n stopChain = runOutsideRunFenceScope(() =>\n repeatAfterSettled(tick, () => nextWorkflowScanDelay(this.#recoveryConfig.workflowScanIntervalMs!, dueAt), {\n immediately: true,\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 * True once `shutdown()` has started. Durable agents use it to checkpoint\n * in-flight runs so they can be recovered after the process exits.\n * @internal\n */\n get __shuttingDown(): boolean {\n return this.#shuttingDown;\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, concurrently with\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 * Runs another instance still drives are skipped, not taken over, and\n * counted in `skipped`. Each is re-checked once that instance's claim could\n * have lapsed, so a run whose instance crashed is recovered without another\n * call. `shutdown()` cancels pending re-checks.\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 skipped: 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, skipped: 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, skipped: 0 };\n }\n\n this.#logger.debug(\n `Recovering active durable-agent runs across ${durableAgents.length} agent${durableAgents.length > 1 ? 's' : ''}`,\n );\n\n return this.#trackDurableRecovery(\n (async () => {\n let recovered = 0;\n let succeeded = 0;\n let failed = 0;\n let skipped = 0;\n\n await runWithConcurrency(durableAgents, DEFAULT_RESTART_CONCURRENCY, async agent => {\n if (this.#shuttingDown) return;\n try {\n const result = await agent.recoverActiveRuns();\n for (const run of result.recovered) {\n if (run.status === 'skipped') {\n skipped++;\n this.#scheduleDurableRecoveryRecheck(agent, run);\n } else {\n recovered++;\n }\n }\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, skipped };\n })(),\n );\n }\n\n #trackDurableRecovery<T>(promise: Promise<T>): Promise<T> {\n this.#durableRecoveryRechecksInFlight.add(promise);\n const remove = () => this.#durableRecoveryRechecksInFlight.delete(promise);\n void promise.then(remove, remove);\n return promise;\n }\n\n /** @internal Bound waiting, not execution; shutdown must still drain the original attempt. */\n __awaitDurableRecoveryAttempt<T>(promise: Promise<T>, description: string): Promise<{ value: T } | undefined> {\n return this.#awaitBounded(\n this.#trackDurableRecovery(promise).then(value => ({ value })),\n DURABLE_RECOVERY_ATTEMPT_TIMEOUT_MS,\n description,\n `Durable recovery timed out after ${DURABLE_RECOVERY_ATTEMPT_TIMEOUT_MS}ms waiting for ${description}; the attempt continues in the background`,\n );\n }\n\n /**\n * Re-check skipped runs after a foreign claim could have lapsed or a\n * recovery wait timed out. Timed-out originals keep their ownership and\n * defer rechecks until settlement without starting duplicate executions.\n * A re-check that throws is retried with backoff; `failures` counts the\n * consecutive ones.\n */\n #scheduleDurableRecoveryRecheck(\n agent: DurableAgentLike,\n run: { runId: string; retryAt?: number },\n failures = 0,\n ): void {\n if (run.retryAt === undefined || this.#shuttingDown) return;\n const key = JSON.stringify([agent.id, run.runId]);\n clearTimeout(this.#durableRecoveryRechecks.get(key));\n const delay = Math.max(0, run.retryAt - Date.now()) + Math.random() * DURABLE_RECOVERY_RECHECK_JITTER_MS;\n const timer = setTimeout(() => {\n this.#durableRecoveryRechecks.delete(key);\n const recheck = agent\n .recoverActiveRuns({ runId: run.runId })\n .then(result => {\n for (const next of result.recovered) {\n if (next.status === 'skipped') this.#scheduleDurableRecoveryRecheck(agent, next);\n }\n })\n .catch(error => {\n const context = { agentId: agent.id, runId: run.runId, error };\n if (failures >= DURABLE_RECOVERY_RECHECK_MAX_RETRIES) {\n this.#logger.error(\n 'Failed to re-check durable agent run for recovery; leaving it for the next boot or a manual recover()',\n context,\n );\n return;\n }\n this.#logger.warn('Failed to re-check durable agent run for recovery; retrying', context);\n this.#scheduleDurableRecoveryRecheck(\n agent,\n { runId: run.runId, retryAt: Date.now() + DURABLE_RECOVERY_RECHECK_RETRY_BASE_MS * 2 ** failures },\n failures + 1,\n );\n })\n .finally(() => this.#durableRecoveryRechecksInFlight.delete(recheck));\n this.#durableRecoveryRechecksInFlight.add(recheck);\n }, delay);\n timer.unref?.();\n this.#durableRecoveryRechecks.set(key, timer);\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 // Classifiers\n // =========================================================================\n\n /**\n * Returns all registered classifiers keyed by their registration key.\n */\n public listClassifiers() {\n return this.#classifiers;\n }\n\n /**\n * Adds a classifier to the Mastra instance.\n *\n * If a classifier with the same key already exists, this method leaves the existing\n * classifier registered and returns.\n *\n * @example\n * ```typescript\n * const mastra = new Mastra();\n * mastra.addClassifier(new Classifier({ id: 'safety', model })); // Uses classifier.id as key\n * mastra.addClassifier(new Classifier({ id: 'safety', model }), 'customKey');\n * ```\n */\n public addClassifier<C extends Classifier<any>>(classifier: C, key?: string): void {\n if (!classifier) {\n throw createUndefinedPrimitiveError('classifier', classifier, key);\n }\n const classifierKey = key || classifier.id;\n const classifiers = this.#classifiers as Record<string, Classifier<any>>;\n if (classifiers[classifierKey]) {\n return;\n }\n\n classifier.__registerMastra(this);\n classifiers[classifierKey] = classifier;\n }\n\n /**\n * Retrieves a registered classifier by its registration key.\n *\n * @throws {MastraError} When the classifier with the specified key is not found\n */\n public getClassifier<TClassifierKey extends keyof TClassifiers>(key: TClassifierKey): TClassifiers[TClassifierKey] {\n const classifier = this.#classifiers?.[key];\n if (!classifier) {\n const error = new MastraError({\n id: 'MASTRA_GET_CLASSIFIER_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Classifier with ${String(key)} not found`,\n details: { status: 404 },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return classifier;\n }\n\n /**\n * Retrieves a registered classifier by its `id`, falling back to the registration key.\n *\n * @throws {MastraError} When no classifier is found with the specified id\n */\n public getClassifierById<TClassifierKey extends keyof TClassifiers>(\n id: TClassifiers[TClassifierKey]['id'],\n ): TClassifiers[TClassifierKey] {\n for (const [key, value] of Object.entries(this.#classifiers ?? {})) {\n if (value.id === id || key === id) {\n return value as TClassifiers[TClassifierKey];\n }\n }\n\n const error = new MastraError({\n id: 'MASTRA_GET_CLASSIFIER_BY_ID_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Classifier with id ${String(id)} not found`,\n details: { status: 404 },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n\n /**\n * Removes a classifier from the Mastra instance by its key or id.\n *\n * @returns true if a classifier was removed, false if no classifier was found\n */\n public removeClassifier(keyOrId: string): boolean {\n const classifiers = this.#classifiers as Record<string, Classifier<any>> | undefined;\n if (!classifiers) return false;\n\n if (classifiers[keyOrId]) {\n delete classifiers[keyOrId];\n return true;\n }\n\n const key = Object.keys(classifiers).find(k => classifiers[k]?.id === keyOrId);\n if (key) {\n delete classifiers[key];\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 * If a tool with the same key already exists, this method leaves the existing\n * tool registered and returns without an error. The new tool is not added.\n *\n * @throws {MastraError} When the tool is undefined\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 // Register Mastra with every processor instance, even when another processor already uses its key.\n if (typeof processor.__registerMastra === 'function') {\n processor.__registerMastra(this);\n }\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 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 * @param source - Where the agent is defined. Configurations of stored agents stay marked as stored, so they can\n * be told apart from code agents' configurations after the stored agent is gone.\n */\n public addProcessorConfiguration(\n processor: Processor,\n agentId: string,\n type: 'input' | 'output',\n source?: DefinitionSource,\n ): 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 existing = configs.find(c => c.agentId === agentId && c.type === type);\n if (!existing) {\n configs.push({ processor, agentId, type, ...(source && { source }) });\n } else if (source === 'stored') {\n existing.source = 'stored';\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'; source?: DefinitionSource }> {\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'; source?: DefinitionSource }>\n > {\n return this.#processorConfigurations;\n }\n\n /** Retrieves a registered Knowledge instance by its application key. */\n public getKnowledge<TKnowledgeKey extends keyof TKnowledge>(key: TKnowledgeKey): TKnowledge[TKnowledgeKey] {\n const knowledge = this.#knowledge[key];\n if (!knowledge) {\n const error = new MastraError({\n id: 'MASTRA_GET_KNOWLEDGE_BY_KEY_NOT_FOUND',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Knowledge with key ${String(key)} not found`,\n details: {\n status: 404,\n knowledgeKey: String(key),\n availableKeys: Object.keys(this.#knowledge).join(', '),\n },\n });\n this.#logger?.trackException(error);\n throw error;\n }\n return knowledge;\n }\n\n /** Returns all registered Knowledge instances keyed by application key. */\n public listKnowledge(): TKnowledge {\n // A copy, so callers cannot swap an entry past addKnowledge()'s shared-backend check.\n return { ...this.#knowledge };\n }\n\n /** Registers a Knowledge instance without initializing its storage. */\n public addKnowledge<K extends Knowledge>(knowledge: K, key?: string): void {\n if (!knowledge) {\n throw createUndefinedPrimitiveError('knowledge', knowledge, key);\n }\n\n const knowledgeKey = key ?? knowledge.id;\n const registry = this.#knowledge as Record<string, Knowledge>;\n if (registry[knowledgeKey]) {\n throw new MastraError({\n id: 'MASTRA_ADD_KNOWLEDGE_DUPLICATE_KEY',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: `Knowledge with key ${knowledgeKey} is already registered`,\n details: { status: 409, knowledgeKey },\n });\n }\n if (\n Object.values(registry).some(\n instance =>\n (!knowledge.hasOwnStorage && !instance.hasOwnStorage) ||\n knowledge.__sharesStorageWith(instance) ||\n (!knowledge.hasOwnStorage &&\n this.#storageSource !== undefined &&\n instance.__usesStorage(this.#storageSource)),\n )\n ) {\n throw new MastraError({\n id: 'MASTRA_ADD_KNOWLEDGE_SHARED_STORAGE',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Knowledge instances cannot share a storage backend. Configure separate storage on named instances to preserve isolation.',\n details: { status: 409, knowledgeKey },\n });\n }\n\n knowledge.__setLogger(this.#logger);\n knowledge.__registerMastra(this);\n if (!knowledge.hasOwnStorage && this.#storage) {\n knowledge.setStorage(this.#storage, this.#storageSource);\n }\n registry[knowledgeKey] = knowledge;\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 * Removes a workflow from the Mastra instance by its key or ID.\n * Used when dynamic workflows are updated/deleted so subsequent saves can\n * re-register the same id cleanly.\n *\n * Note: this only clears the live in-process registration. In-flight runs\n * are unaffected (they capture stepFlow at start time). Static workflow\n * scorers stay registered (matching removeAgent/removeTool behavior).\n *\n * @param keyOrId - The workflow key or ID to remove\n * @returns true if a workflow was removed, false if no workflow was found\n *\n * @example\n * ```typescript\n * // Remove by key\n * mastra.removeWorkflow('myWorkflow');\n *\n * // Remove by ID\n * mastra.removeWorkflow('workflow-123');\n * ```\n */\n public removeWorkflow(keyOrId: string): boolean {\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n\n if (workflows[keyOrId]) {\n delete workflows[keyOrId];\n this.#hiddenWorkflowKeys.delete(keyOrId);\n return true;\n }\n\n const key = Object.keys(workflows).find(k => workflows[k]?.id === keyOrId);\n if (key) {\n delete workflows[key];\n this.#hiddenWorkflowKeys.delete(key);\n return true;\n }\n\n return false;\n }\n\n /**\n * Returns how a workflow was registered — `'code'` for statically declared\n * or `addWorkflow()`-added workflows, `'dynamic'` for anything added via\n * `addDynamicWorkflow()` (either at boot or through the HTTP/SDK surface).\n * Returns `undefined` if no workflow is registered under that key/id.\n *\n * Reads `workflow.origin`, which is set to `'dynamic'` by `rehydrateWorkflow`\n * at construction time and defaults to `'code'` otherwise. Used by the HTTP\n * layer to surface a visual distinction (e.g. a \"Dynamic\" badge in Studio).\n */\n public getWorkflowOrigin(keyOrId: string): 'code' | 'dynamic' | undefined {\n const workflows = this.#workflows as Record<string, AnyWorkflow>;\n const workflow = workflows[keyOrId] ?? Object.values(workflows).find(wf => wf?.id === keyOrId);\n return workflow?.origin;\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 // The Mastra scheduler only dispatches default and evented workflows. A\n // `schedule` on any other engine is ignored so it can't double-fire next\n // to that engine's own scheduling.\n const hasSchedule = collectWorkflowScheduleConfigs(workflow).length > 0;\n if (!runsOnMastraScheduler(workflow) && readWorkflowScheduleConfigs(workflow).length > 0) {\n this.#logger?.warn(\n `Workflow \"${workflow.id}\" declares \\`schedule\\` but runs on the ${workflow.engineType} engine; the Mastra scheduler only fires default and evented workflows. Use the engine's native scheduling (Inngest \\`cron\\`).`,\n { workflowId: workflow.id, engineType: workflow.engineType },\n );\n }\n\n // Initialize the workflow with Mastra and primitives\n workflow.__registerMastra(this);\n workflow.__registerPrimitives({\n logger: this.getLogger(),\n storage: this.getStorage(),\n });\n if (!workflow.committed) {\n workflow.commit();\n }\n workflows[workflowKey] = workflow;\n\n 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 // SchedulerWorker.init() registers this schedule when the scheduler starts.\n }\n }\n\n #replaceDynamicWorkflow(workflow: AnyWorkflow, key: string): void {\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\n (this.#workflows as Record<string, AnyWorkflow>)[key] = workflow;\n this.#hiddenWorkflowKeys.delete(key);\n this.registerStaticWorkflowScorers(workflow);\n if (collectWorkflowScheduleConfigs(workflow).length > 0) {\n this.#hasScheduledWorkflow = true;\n }\n // Declarative schedule (re-)registration happens in addDynamicWorkflows()\n // after definition persistence succeeds, so a persistence failure can't\n // leave schedule rows reflecting a rolled-back registry.\n }\n\n /**\n * Flattens this instance's registries into the index the dynamic-workflow\n * validation core resolves references and schemas against. Registered keys\n * and canonical ids both count as valid references. Schemas are converted\n * best-effort — an unconvertible schema degrades to \"unknown\", never to a\n * false incompatibility. Agents stay presence-only: their `{ prompt }`\n * input default lives in schema-flow itself.\n */\n #buildWorkflowRegistryIndex(): WorkflowRegistryIndex {\n const agents: Record<string, WorkflowRegistrySchemas> = {};\n for (const [key, agent] of Object.entries(this.listAgents() ?? {})) {\n agents[key] = {};\n agents[agent.id] = {};\n }\n const tools: Record<string, WorkflowRegistrySchemas> = {};\n for (const [key, tool] of Object.entries(this.listTools() ?? {})) {\n const schemas: WorkflowRegistrySchemas = {\n inputSchema: toJsonSchemaOrUndefined(tool.inputSchema),\n outputSchema: toJsonSchemaOrUndefined(tool.outputSchema),\n };\n tools[key] = schemas;\n tools[tool.id] = schemas;\n }\n const classifiers: NonNullable<WorkflowRegistryIndex['classifiers']> = {};\n const refusedAnswerDescription =\n \"When the model refuses the question, the answer is { type: 'refusal' } with no choice, score, probability, or probabilities.\";\n for (const [key, classifier] of Object.entries(this.listClassifiers() ?? {})) {\n const questions = classifier.questions\n ? Object.fromEntries(\n Object.entries(classifier.questions as ClassifierQuestions).map(([questionId, question]) => [\n questionId,\n question.type === 'choice'\n ? { type: 'choice' as const, choices: Object.keys(question.criteria) }\n : question.type === 'score'\n ? { type: 'score' as const, min: 0, max: question.criteria.length - 1 }\n : { type: 'boolean' as const },\n ]),\n )\n : undefined;\n // A decision model may refuse any question. A refused answer is `{ type: 'refusal' }`\n // with no payload fields, so only `type` is required.\n const answerProperties = questions\n ? Object.fromEntries(\n Object.entries(questions).map(([questionId, question]) => [\n questionId,\n question.type === 'choice'\n ? {\n type: 'object',\n properties: {\n type: { type: 'string', enum: ['choice', 'refusal'] },\n choice: { type: 'string', enum: question.choices },\n probabilities: {\n type: 'object',\n properties: Object.fromEntries(question.choices.map(choice => [choice, { type: 'number' }])),\n additionalProperties: false,\n },\n },\n required: ['type'],\n description: refusedAnswerDescription,\n }\n : question.type === 'score'\n ? {\n type: 'object',\n properties: {\n type: { type: 'string', enum: ['score', 'refusal'] },\n score: { type: 'number', minimum: question.min, maximum: question.max },\n probabilities: {\n type: 'object',\n properties: Object.fromEntries(\n Array.from({ length: question.max - question.min + 1 }, (_, index) => [\n String(question.min + index),\n { type: 'number' },\n ]),\n ),\n additionalProperties: false,\n },\n },\n required: ['type'],\n description: refusedAnswerDescription,\n }\n : {\n type: 'object',\n properties: {\n type: { type: 'string', enum: ['boolean', 'refusal'] },\n probability: { type: 'number', minimum: 0, maximum: 1 },\n },\n required: ['type'],\n description: refusedAnswerDescription,\n },\n ]),\n )\n : {};\n const schemas = {\n inputSchema: {},\n outputSchema: {\n type: 'object',\n properties: {\n answers: { type: 'object', properties: answerProperties, required: Object.keys(answerProperties) },\n usage: { type: 'object' },\n },\n required: ['answers', 'usage'],\n },\n questions,\n };\n classifiers[key] = schemas;\n classifiers[classifier.id] = schemas;\n }\n const workflows: Record<string, WorkflowRegistrySchemas> = {};\n for (const [key, workflow] of Object.entries(this.#workflows as Record<string, AnyWorkflow>)) {\n const schemas: WorkflowRegistrySchemas = {\n inputSchema: toJsonSchemaOrUndefined(workflow.inputSchema),\n outputSchema: toJsonSchemaOrUndefined(workflow.outputSchema),\n };\n workflows[key] = schemas;\n workflows[workflow.id] = schemas;\n }\n return { agents, tools, classifiers, workflows };\n }\n\n /**\n * Persist a static workflow definition to storage and live-register it on\n * this Mastra instance so it becomes immediately runnable. The same path is\n * used by `loadDynamicWorkflows()` at boot to re-materialize previously saved\n * workflows.\n *\n * @example\n * ```typescript\n * await mastra.addDynamicWorkflow({\n * id: 'cli-weather-v1',\n * inputSchema: { type: 'object', properties: { location: { type: 'string' } }, required: ['location'] },\n * outputSchema: { type: 'object', properties: { report: { type: 'string' } }, required: ['report'] },\n * graph: [...],\n * });\n *\n * const run = await mastra.getWorkflow('cli-weather-v1').createRun();\n * await run.start({ inputData: { location: 'Helsinki' } });\n * ```\n */\n public async addDynamicWorkflow(def: DynamicWorkflowGraph | WorkflowBuilderDefinitionInput): Promise<void> {\n await this.addDynamicWorkflows([def]);\n }\n\n /**\n * Persist and live-register a set of dynamic workflow definitions that depend\n * on each other — typically a root workflow plus the helper workflows it\n * nests, none of which exist yet.\n *\n * The bundle is validated as a unit: references resolve against this\n * instance's registries UNION the bundle's own ids, so a root may nest a\n * helper being introduced in the same call. Members are then hydrated in\n * dependency order, since hydration resolves nested workflows through the\n * live registry.\n *\n * Failure semantics — a rejected bundle registers nothing:\n * - Duplicate ids, invalid members, and dependency cycles are all detected\n * before anything is mutated.\n * - If hydration or persistence fails partway, the in-memory registry is\n * restored to its prior state.\n * - Storage writes happen last. A storage-level failure mid-bundle is the\n * one residual window where rows can be partially written; the registry is\n * still rolled back, and the orphaned rows are inert until the next boot.\n *\n * `addDynamicWorkflow()` is the single-member case.\n *\n * @example\n * ```typescript\n * await mastra.addDynamicWorkflows([\n * { id: 'lookup-first-customer', ... }, // helper — order is derived, not assumed\n * { id: 'parallel-customer-lookup', ... }, // root, nests the helper above\n * ]);\n * ```\n */\n public async addDynamicWorkflows(\n defs: readonly (DynamicWorkflowGraph | WorkflowBuilderDefinitionInput)[],\n ): Promise<void> {\n if (defs.length === 0) return;\n\n const seen = new Set<string>();\n for (const def of defs) {\n if (seen.has(def.id)) {\n throw new Error(\n `Dynamic workflow bundle contains more than one definition with id \"${def.id}\". Ids must be unique within a bundle.`,\n );\n }\n seen.add(def.id);\n }\n\n // Save-path is strict (boot-time load is lenient — see #loadDynamicWorkflows).\n // Normalization coerces the wire shape; one validation call per member\n // covers structure, JSON-Schema keywords, references, and schema-flow.\n const members = defs.map(def => ({\n normalized: normalizeWorkflowBuilderDefinition({\n id: def.id,\n description: def.description,\n metadata: def.metadata,\n inputSchema: def.inputSchema,\n outputSchema: def.outputSchema,\n stateSchema: def.stateSchema,\n requestContextSchema: def.requestContextSchema,\n graph: def.graph,\n schedule: def.schedule,\n }),\n }));\n\n // Members may nest each other, so the index every member validates against\n // is the live registries plus the bundle itself — not the registry alone.\n const index = this.#buildWorkflowRegistryIndex();\n const bundleIds = new Set(members.map(member => member.normalized.id));\n for (const { normalized } of members) {\n (index.workflows ??= {})[normalized.id] = {\n inputSchema: normalized.inputSchema,\n outputSchema: normalized.outputSchema,\n } as WorkflowRegistrySchemas;\n }\n for (const { normalized } of members) {\n assertValidDynamicWorkflow(normalized, index);\n }\n\n // Hydration resolves nested workflows through the live registry, so a\n // member cannot be hydrated before the bundle members it nests.\n const ordered: typeof members = [];\n const remaining = new Map(members.map(member => [member.normalized.id, member] as const));\n const hydrated = new Set<string>();\n let progress = true;\n while (remaining.size > 0 && progress) {\n progress = false;\n for (const [id, member] of Array.from(remaining)) {\n const pending = Array.from(collectNestedWorkflowIds(member.normalized.graph)).filter(\n dependency => dependency !== id && bundleIds.has(dependency) && !hydrated.has(dependency),\n );\n if (pending.length > 0) continue;\n remaining.delete(id);\n hydrated.add(id);\n ordered.push(member);\n progress = true;\n }\n }\n if (remaining.size > 0) {\n throw new Error(\n `Dynamic workflow bundle has a circular nested-workflow dependency among: ${Array.from(remaining.keys())\n .sort()\n .join(', ')}.`,\n );\n }\n\n // Snapshot the registry slots this bundle will overwrite so a failure\n // anywhere below leaves the instance exactly as it was found.\n const registry = this.#workflows as Record<string, AnyWorkflow>;\n const priorWorkflows = new Map<string, AnyWorkflow | undefined>();\n const priorHiddenKeys = new Set<string>();\n for (const { normalized } of ordered) {\n priorWorkflows.set(normalized.id, registry[normalized.id]);\n if (this.#hiddenWorkflowKeys.has(normalized.id)) priorHiddenKeys.add(normalized.id);\n }\n const restoreRegistry = () => {\n for (const [id, prior] of priorWorkflows) {\n if (prior) registry[id] = prior;\n else delete registry[id];\n if (priorHiddenKeys.has(id)) this.#hiddenWorkflowKeys.add(id);\n }\n };\n\n try {\n for (const { normalized } of ordered) {\n const { workflow } = await rehydrateWorkflow(normalized, this);\n this.#replaceDynamicWorkflow(workflow as AnyWorkflow, normalized.id);\n }\n\n const store = await this.#storage?.getStore('workflowDefinitions');\n if (store) {\n for (const { normalized } of ordered) {\n await store.upsert({\n id: normalized.id,\n description: normalized.description,\n metadata: normalized.metadata,\n inputSchema: normalized.inputSchema,\n outputSchema: normalized.outputSchema,\n stateSchema: normalized.stateSchema,\n requestContextSchema: normalized.requestContextSchema,\n graph: normalized.graph,\n schedule: normalized.schedule,\n });\n }\n }\n } catch (error) {\n restoreRegistry();\n throw error;\n }\n\n // Synchronize declarative schedules only after every registry replacement\n // and definition upsert has succeeded. Run for every replacement — a\n // replacement that dropped its schedules must still sweep the old wf_*\n // rows. A sync failure is logged, not thrown: the registry and persisted\n // definitions are already consistent, and the next boot re-syncs.\n const worker = this.#findSchedulerWorker();\n if (worker?.scheduler) {\n try {\n const schedulesStore = await this.#storage?.getStore('schedules');\n if (schedulesStore) {\n await this.registerDeclarativeSchedules(schedulesStore);\n }\n } catch (error) {\n this.#logger?.error('Failed to synchronize declarative schedules after dynamic workflow registration', {\n workflowIds: ordered.map(({ normalized }) => normalized.id),\n error,\n });\n }\n }\n }\n\n /**\n * Load any previously persisted workflow definitions from storage and\n * live-register each one. Called by `startWorkers()` after storage init.\n * Bad rows are logged and skipped — one corrupt definition shouldn't sink\n * the rest.\n * @internal\n */\n async #loadDynamicWorkflows(): Promise<void> {\n const store = await this.#storage?.getStore('workflowDefinitions');\n if (!store) return;\n\n const { definitions } = await store.list({ status: 'active' });\n this.#failedDynamicWorkflowIds.clear();\n\n // Code-registered workflows win; storage is additive.\n const pending = definitions.filter(d => !(this.#workflows as Record<string, AnyWorkflow>)[d.id]);\n\n const pendingIds = new Set(pending.map(d => d.id));\n const deps = new Map<string, Set<string>>();\n for (const def of pending) {\n const all = collectNestedWorkflowIds(def.graph);\n const pendingDeps = new Set<string>();\n for (const id of all) if (pendingIds.has(id) && id !== def.id) pendingDeps.add(id);\n deps.set(def.id, pendingDeps);\n }\n\n // Hydrate in dependency order; anything left after the loop is a cycle.\n const remaining = new Map(pending.map(d => [d.id, d] as const));\n const loaded = new Set<string>();\n let progress = true;\n while (remaining.size > 0 && progress) {\n progress = false;\n for (const [id, def] of Array.from(remaining)) {\n const unresolved = Array.from(deps.get(id) ?? []).filter(d => !loaded.has(d));\n if (unresolved.length > 0) continue;\n remaining.delete(id);\n progress = true;\n try {\n const { workflow } = await rehydrateWorkflow(\n {\n id: def.id,\n description: def.description,\n metadata: def.metadata,\n inputSchema: def.inputSchema as Record<string, any>,\n outputSchema: def.outputSchema as Record<string, any>,\n stateSchema: def.stateSchema as Record<string, any> | undefined,\n requestContextSchema: def.requestContextSchema as Record<string, any> | undefined,\n graph: def.graph,\n schedule: def.schedule,\n },\n this,\n // Lenient at boot (save path is strict): degrade to z.any() + warn.\n {\n onUnsupportedSchema: 'warn',\n onUnsupported: message => this.#logger?.warn?.(`Dynamic workflow \"${def.id}\": ${message}`),\n },\n );\n this.addWorkflow(workflow as AnyWorkflow, def.id);\n loaded.add(def.id);\n } catch (error) {\n this.#failedDynamicWorkflowIds.add(def.id);\n this.#logger?.error?.(`Failed to load dynamic workflow \"${def.id}\"`, { error });\n }\n }\n }\n if (remaining.size > 0) {\n for (const id of remaining.keys()) this.#failedDynamicWorkflowIds.add(id);\n const stuck = Array.from(remaining.keys()).join(', ');\n this.#logger?.error?.(\n `Failed to load dynamic workflows (cycle or unresolved nested-workflow reference): ${stuck}`,\n );\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 * Publish a best-effort cross-process wake after the schedule row is durable.\n * This also runs in producer-only (`workers: false`) processes.\n *\n * @internal\n */\n async __publishSchedulerWake(scheduleId: string): Promise<void> {\n try {\n await this.#pubsub.publish(SCHEDULER_WAKE_TOPIC, { type: SCHEDULER_WAKE_EVENT, runId: scheduleId, data: {} });\n } catch (err) {\n this.#logger?.warn?.('Failed to publish scheduler wake event', err as any);\n }\n }\n\n /** Subscribe for cross-process scheduler wakes. Idempotent. */\n async #wireSchedulerWakeSubscription(): Promise<void> {\n if (this.#schedulerWakeSubscription) return;\n const cb: EventCallback = async (event, ack, nack) => {\n try {\n // Persistent backends require every delivery, including unknown event\n // types, to be settled.\n if (event.type !== SCHEDULER_WAKE_EVENT) {\n await ack?.();\n return;\n }\n this.#schedulerRequested = true;\n // Mid-boot (subscribed before the worker start loop ran) the flag is\n // enough: `startWorkers()` re-checks it before returning. Injecting\n // here would race that loop and start the scheduler twice.\n if (this.#workersStarted) {\n await this.#ensureSchedulingWorkersStarted();\n // A running scheduler sleeps until its earliest fire; the new or\n // changed schedule may be due sooner.\n this.#findSchedulerWorker()?.scheduler?.wake();\n }\n await ack?.();\n } catch (err) {\n await nack?.();\n // Some PubSub backends invoke callbacks without observing returned\n // promise rejections, so log after nacking instead of rethrowing.\n this.#logger?.warn?.('Failed to start scheduling workers from wake event', err as any);\n }\n };\n this.#schedulerWakeSubscription = cb;\n try {\n // Wake events are transient hints; the awaited boot probe below is the\n // durable recovery path. Starting from latest avoids replaying retained\n // wakes and starting the scheduler when no schedule rows remain. The\n // subscription stays wired while the scheduler runs, to re-arm it.\n await this.#pubsub.subscribe(SCHEDULER_WAKE_TOPIC, cb, { startFrom: 'latest' });\n } catch (err) {\n // Allow a later startWorkers() call to retry a transient subscribe error.\n if (this.#schedulerWakeSubscription === cb) {\n this.#schedulerWakeSubscription = undefined;\n }\n throw err;\n }\n }\n\n async #unwireSchedulerWakeSubscription(): Promise<void> {\n const cb = this.#schedulerWakeSubscription;\n if (!cb) return;\n this.#schedulerWakeSubscription = undefined;\n await this.#pubsub.unsubscribe(SCHEDULER_WAKE_TOPIC, cb);\n }\n\n /**\n * One-shot boot probe for persisted agent, workflow, or notification-dispatch\n * schedules. Runtime discovery uses the wake subscription instead.\n */\n async #detectPersistedSchedulerWork(): Promise<void> {\n if (!this.#storage) return;\n try {\n const schedulesStore = await this.#storage.getStore('schedules');\n if (!schedulesStore) return;\n\n const rows = await schedulesStore.listSchedules();\n let hasWork = rows.some(row => row.id !== NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n // A leftover dispatcher row is only work while deferred notifications\n // are pending. Otherwise its once-a-minute cron would keep the scheduler\n // polling storage forever, and nothing would consume it when dispatch\n // has since been disabled.\n const dispatchEnabled = this.#notificationDispatchConfig?.enabled !== false;\n if (!hasWork && dispatchEnabled && rows.some(row => row.id === NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID)) {\n const notifications = await this.#storage.getStore('notifications');\n hasWork = notifications ? await hasPendingDeferredNotifications(notifications) : false;\n }\n if (hasWork) this.#schedulerRequested = true;\n } catch (err) {\n this.#logger?.warn?.('Failed to detect persisted scheduler work on boot', err as any);\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()`. This also supports\n * processes that publish notifications without running workers locally.\n *\n * The row is read on every call rather than memoized: the dispatcher deletes\n * it once nothing is pending (`__releaseNotificationDispatchIfIdle()`),\n * possibly from another process, and the next deferral must re-arm it.\n *\n * @internal\n */\n async __ensureNotificationDispatchReady(): Promise<void> {\n if (this.#notificationDispatchConfig?.enabled === false) return;\n if (!this.#storage) return;\n\n let created = false;\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 created = true;\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 // The next deferred notification retries the upsert.\n this.#logger?.warn?.('Failed to ensure notification dispatch schedule', err as any);\n return;\n }\n\n // Request the scheduler once per process, and wake schedulers everywhere\n // whenever the row is (re)created.\n if (this.#notificationDispatchReady && !created) return;\n this.#notificationDispatchReady = true;\n this.#schedulerRequested = true;\n if (this.#workersStarted) {\n await this.#ensureSchedulingWorkersStarted();\n }\n await this.__publishSchedulerWake(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n }\n\n /**\n * Called by the dispatcher after each pass. When no deferred notification is\n * pending, deletes the dispatcher schedule row so its cron stops firing and\n * an idle app stops polling storage. The next deferral re-creates it.\n *\n * @internal\n */\n async __releaseNotificationDispatchIfIdle(): Promise<void> {\n if (!this.#storage) return;\n try {\n const [schedulesStore, notifications] = await Promise.all([\n this.#storage.getStore('schedules'),\n this.#storage.getStore('notifications'),\n ]);\n if (!schedulesStore || !notifications) return;\n if (await hasPendingDeferredNotifications(notifications)) return;\n\n await schedulesStore.deleteSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);\n this.#notificationDispatchReady = false;\n\n // A deferral elsewhere may have written its record and seen the row\n // just before the delete. It won't re-create the row, so re-check after\n // deleting and re-arm on its behalf.\n if (await hasPendingDeferredNotifications(notifications)) {\n await this.__ensureNotificationDispatchReady();\n }\n } catch (err) {\n // Leaving the row in place only costs extra dispatch passes.\n this.#logger?.warn?.('Failed to release idle notification dispatch schedule', err as any);\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.#workerFilter && !this.#workerFilter.has('scheduler')) return;\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 let schedulerWorker = this.#findSchedulerWorker();\n if (!schedulerWorker) {\n schedulerWorker = new SchedulerWorker(this.#schedulerConfig);\n schedulerWorker.__registerMastra(this);\n this.#workers.push(schedulerWorker);\n }\n if (!schedulerWorker.isRunning) {\n await schedulerWorker.init(deps);\n await schedulerWorker.start();\n }\n\n const agentScheduleSelected = !this.#workerFilter || this.#workerFilter.has('agent-schedule');\n if (agentScheduleSelected) {\n let agentScheduleWorker = this.#findAgentScheduleWorker();\n if (!agentScheduleWorker) {\n const { AgentScheduleWorker } = await import('../schedules/worker');\n agentScheduleWorker = new AgentScheduleWorker();\n agentScheduleWorker.__registerMastra(this);\n this.#workers.push(agentScheduleWorker);\n }\n if (!agentScheduleWorker.isRunning) {\n await agentScheduleWorker.init(deps);\n await agentScheduleWorker.start();\n }\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 const knowledgeInstances = Object.values(this.#knowledge);\n if (\n knowledgeInstances.some(instance => !instance.hasOwnStorage) &&\n knowledgeInstances.some(instance => instance.hasOwnStorage && instance.__usesStorage(storage))\n ) {\n throw new MastraError({\n id: 'MASTRA_SET_STORAGE_KNOWLEDGE_CONFLICT',\n domain: ErrorDomain.MASTRA,\n category: ErrorCategory.USER,\n text: 'Cannot set Mastra storage because a named Knowledge instance already uses that backend.',\n details: { status: 409 },\n });\n }\n\n this.#storageFallbackWarningPending = false;\n this.#storageSource = getStorageSource(storage);\n this.#storage = augmentWithInit(storage);\n this.#storage?.__registerMastra?.(this as unknown as Parameters<NonNullable<typeof storage.__registerMastra>>[0]);\n // Storage attached after construction must log through this instance's logger too.\n this.#storage.__setLogger(this.#logger);\n for (const knowledge of Object.values(this.#knowledge)) {\n if (!knowledge.hasOwnStorage) {\n knowledge.setStorage(this.#storage, this.#storageSource);\n }\n }\n this.#ensureBackgroundTaskManager();\n // If storage was attached after construction, the SchedulerWorker\n // will pick it up when startWorkers() is called.\n }\n\n /**\n * Wire a logger into observability. Adaptable loggers get trace\n * correlation + export attached in place (native record path); other\n * loggers are wrapped in the deprecated DualLogger fallback.\n */\n #wireLoggerObservability(logger: TLogger): TLogger {\n const inner = logger as unknown as IMastraLogger;\n\n if (isAdaptableLogger(inner)) {\n // Idempotent: the constructor and setLogger() may both wire the same\n // logger instance — attach only once.\n if (this.#wiredLoggers.has(inner)) return logger;\n this.#wiredLoggers.add(inner);\n // __attachObservability mutates the logger instance: sharing one logger\n // across Mastra instances means the last attach wins — earlier\n // instances' logs export to the newest Mastra's observability (and the\n // logger holds a strong reference to it). Surface this instead of\n // silently clobbering.\n const ownershipKey = inner.__observabilityAttachmentKey?.() ?? inner;\n const previousOwner = attachedLoggerOwners.get(ownershipKey);\n // Only warn when export is active: re-attaching clobbers the export\n // target only when loggerOptions.export is enabled. With export disabled\n // there is nothing to clobber, so the warning would be a false positive.\n if (previousOwner && previousOwner !== this && this.#loggerAdapterOptions.export) {\n try {\n inner.warn(\n 'This logger instance is already wired to another Mastra instance; re-attaching. ' +\n 'Its observability export now targets the newest Mastra. ' +\n 'Create a separate logger per Mastra instance to keep exports isolated.',\n );\n } catch {\n // A throwing logger must not break Mastra construction.\n }\n }\n attachedLoggerOwners.set(ownershipKey, this);\n inner.__attachObservability({\n resolveTraceFields,\n getLogSink: () => {\n if (!this.#loggerAdapterOptions.export || isObservabilityExportSuppressed()) return undefined;\n // Prefer the span-correlated logger context; fall back to the\n // global one so non-span logs are still exported (uncorrelated).\n const span = resolveCurrentSpan();\n const correlated = span?.observabilityInstance?.getLoggerContext?.(span);\n // Resolve the real logger context directly (not `loggerVNext`,\n // which falls back to a truthy no-op) so adapters skip record\n // derivation entirely when observability is not configured.\n return correlated ?? this.#observability.getDefaultInstance()?.getLoggerContext?.();\n },\n options: this.#loggerAdapterOptions,\n });\n return logger;\n }\n\n // Already wrapped (e.g. setLogger() re-invoked with the wired logger, or\n // another Mastra instance's wrapper passed in). Rewire the underlying\n // logger for this instance so exports target this instance's\n // observability; for our own wrapper this is idempotent via\n // #fallbackWrappers.\n if (inner instanceof DualLogger) {\n return this.#wireLoggerObservability(inner.baseLogger as unknown as TLogger);\n }\n\n // Idempotent: the constructor wires the logger and then setLogger() is\n // called with the same unwrapped instance — reuse the existing wrapper\n // so the deprecation notice fires only once per logger instance.\n const existing = this.#fallbackWrappers.get(inner);\n if (existing) return existing as unknown as TLogger;\n\n // Deprecated fallback: dual-write wrapper. Native records (stdout) do\n // not receive trace correlation on this path.\n try {\n inner.debug?.(\n 'Configured logger does not support observability adapters; falling back to DualLogger (deprecated). ' +\n 'Implement __attachObservability() on your logger to get trace-correlated stdout.',\n );\n } catch {\n // A throwing logger must not break Mastra construction.\n }\n // Resolve the real logger context directly (not `loggerVNext`, which\n // falls back to a truthy no-op) so the fallback skips record derivation\n // entirely when observability is not configured.\n const wrapper = new DualLogger(\n inner,\n this.#loggerAdapterOptions.export\n ? () => this.#observability.getDefaultInstance()?.getLoggerContext?.()\n : undefined,\n );\n this.#fallbackWrappers.set(inner, wrapper);\n return wrapper as unknown as TLogger;\n }\n\n public setLogger({ logger }: { logger: TLogger }) {\n this.#logger = this.#wireLoggerObservability(logger);\n\n if (this.#agents) {\n Object.keys(this.#agents).forEach(key => {\n this.#agents?.[key]?.__setLogger(this.#logger);\n this.#agents?.[key]?.getChannels()?.__setLogger(this.#logger);\n });\n }\n\n Object.values(this.#harnesses ?? {}).forEach(controller => controller.getChannels()?.__setLogger(this.#logger));\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 Object.values(this.#knowledge).forEach(knowledge => knowledge.__setLogger(this.#logger));\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 an export-suppressed view of the logger to observability so its\n // internal logs never feed back into observability export.\n this.#observability.setLogger({ logger: this.#observabilitySafeLogger() as unknown as TLogger });\n }\n\n /**\n * A view of the current logger safe to hand to observability internals:\n * unwraps the DualLogger fallback and suppresses observability export.\n */\n #observabilitySafeLogger(): IMastraLogger {\n const inner =\n this.#logger instanceof DualLogger ? this.#logger.baseLogger : (this.#logger as unknown as IMastraLogger);\n return createExportSuppressedLogger(inner);\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 }\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 * Wrap a user-provided topic listener so the delivery is acknowledged once\n * the listener resolves. User listeners take only the event, so nothing\n * would ever call `ack` for them — and on a durable transport (Redis\n * consumer groups) an unacknowledged delivery stays pending for the life of\n * the subscription. A throwing listener nacks instead so the transport can\n * redeliver rather than assume success.\n *\n * The wrapper is memoized per listener so `removeTopicListener` can\n * unsubscribe the exact callback `addTopicListener` registered.\n */\n #ackingTopicListeners = new WeakMap<(event: any) => Promise<void> | void, EventCallback>();\n\n #ackingTopicListener(listener: (event: any) => Promise<void> | void): EventCallback {\n const existing = this.#ackingTopicListeners.get(listener);\n if (existing) return existing;\n const wrapped: EventCallback = async (event, ack, nack) => {\n try {\n await listener(event);\n } catch (err) {\n this.#logger?.error?.('Error in topic listener; nacking event', {\n eventType: event.type,\n err: err instanceof Error ? err.message : err,\n });\n await nack?.();\n return;\n }\n await ack?.();\n };\n this.#ackingTopicListeners.set(listener, wrapped);\n return wrapped;\n }\n\n public async addTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.subscribe(topic, this.#ackingTopicListener(listener));\n }\n\n public async removeTopicListener(topic: string, listener: (event: any) => Promise<void>) {\n await this.#pubsub.unsubscribe(topic, this.#ackingTopicListener(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 * When the orchestration worker is among them, this also starts the\n * workflow recovery loop (unless `recovery.workflows` is `'off'`): every\n * `recovery.workflowScanIntervalMs` it restarts default-engine runs whose\n * instance stopped, by the rule of {@link Mastra.restartAllActiveWorkflowRuns}.\n * Instances sharing a store elect one leader through a run lease; the others'\n * ticks only try to take that role, which they get once the leader's\n * `stopWorkers()` releases it or its lease lapses. The leader's loop looks\n * only at the workflows it registers, and the runs it restarts execute on\n * it. The loop never restarts evented runs, and doesn't run on a store\n * without run fencing.\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 // Skip the boot probe when it cannot affect startup. Besides avoiding an\n // unnecessary query, this preserves request-scoped storage behavior from\n // #20550.\n const schedulerSelected =\n !this.#schedulerDisabled() && (!this.#workerFilter || this.#workerFilter.has('scheduler'));\n const schedulerForcedByFilter = schedulerSelected && (this.#workerFilter?.has('scheduler') ?? false);\n\n // Subscribe before probing so a schedule committed during boot cannot fall\n // between the probe and subscription.\n if (!name && schedulerSelected && this.#storage && !this.#findSchedulerWorker()?.isRunning) {\n try {\n await this.#wireSchedulerWakeSubscription();\n } catch (err) {\n // The wake subscription is a cross-process hint; the boot probe and\n // `scheduler.enabled` remain the durable paths. Don't let a pubsub\n // failure on this one topic keep every other worker from starting.\n this.#logger?.warn?.(\n 'Failed to subscribe to scheduler wake events; scheduler will not wake on demand',\n err as any,\n );\n }\n }\n\n if (!name && schedulerSelected && !this.#schedulerRequested && !schedulerForcedByFilter) {\n await this.#detectPersistedSchedulerWork();\n }\n\n // Do not create the polling worker until work exists. An explicit\n // MASTRA_WORKERS=scheduler filter remains an unconditional opt-in for\n // dedicated scheduler processes.\n if (!name && (this.#shouldEnableScheduler() || schedulerForcedByFilter) && this.#storage) {\n if (!this.#findSchedulerWorker()) {\n // A filter-selected scheduler is dedicated: keep it polling like an\n // explicitly enabled one, since it may share no pubsub with producers.\n const sw = new SchedulerWorker(\n schedulerForcedByFilter ? { ...this.#schedulerConfig, enabled: true } : this.#schedulerConfig,\n );\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 // Rehydrate persisted workflow definitions (after storage.init() above).\n if (this.#storage) {\n await this.#loadDynamicWorkflows();\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 cb = this.#ackingTopicListener(listener);\n const alreadySubscribed = this.#userEventSubscriptions.some(sub => sub.topic === topic && sub.cb === cb);\n if (alreadySubscribed) continue;\n await this.#pubsub.subscribe(topic, cb);\n this.#userEventSubscriptions.push({ topic, cb });\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 // A wake event (or a local `schedules.create()`) that landed while this\n // method was running only flipped the request flag, because injecting\n // workers mid-boot would race the start loop above. Honor it now.\n if (!name && this.#schedulerRequested && !this.#findSchedulerWorker()) {\n await this.#ensureSchedulingWorkersStarted();\n }\n\n // An instance that handles workflow events can restart a stopped run, so it runs the recovery loop.\n const handlesWorkflowEvents = name\n ? name === 'orchestration'\n : !this.#workerFilter || this.#workerFilter.has('orchestration');\n if (handlesWorkflowEvents) {\n this.#startWorkflowRecoveryLoop();\n }\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 const inFlight = 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 this.#inFlightPushEvents.add(inFlight);\n void inFlight.finally(() => this.#inFlightPushEvents.delete(inFlight));\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 // Lazy startup can be triggered from inside a durable run. The workers'\n // timers and subscriptions outlive it and must not carry its write fence.\n this.#executionWorkersStartPromise = runOutsideRunFenceScope(() => 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 * Workflow events already being processed are given up to\n * `options.drainTimeout` milliseconds (default 5000) to finish before the\n * pubsub is flushed.\n */\n public async stopWorkers(options?: WorkerStopOptions): Promise<void> {\n const drainTimeout = assertDrainTimeout(\n options?.drainTimeout ?? waitMs(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS, 50),\n 'stopWorkers',\n );\n // One deadline for the whole call. Each worker's transport drain and the\n // push-event drain below typically wait on the same stuck step, so giving\n // each phase the full budget would multiply the worst-case stop time.\n const deadline = Date.now() + drainTimeout;\n const remaining = () => Math.max(0, deadline - Date.now());\n // Block new lazy starts immediately. Runtime signals that arrive during\n // teardown still set their request flags, so a later startWorkers() can\n // honor them, but they must not resurrect workers behind a stopped instance.\n this.#workersStarted = false;\n // Released first, so another instance can lead recovery while this one drains.\n this.#stopWorkflowRecoveryLoop?.();\n await this.#releaseRecoveryLeader();\n\n // A runtime signal may have kicked off a lazy worker start that is still in\n // flight. Wait for it so the teardown below covers what it started —\n // otherwise the start can finish after this method returns, leaving workers\n // running and subscriptions wired behind a \"stopped\" instance. Failures are\n // already logged by the start paths; here they just mean there is less to\n // stop.\n while (this.#schedulingWorkersStartPromise) {\n await this.#schedulingWorkersStartPromise.catch(() => {});\n }\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({ drainTimeout: remaining() });\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 // Events already handed to handleWorkflowEvent() keep running after the\n // unsubscribe; wait for them so a step mid-execution finishes (or publishes\n // its next event) before pubsub is flushed and storage closed.\n if (this.#inFlightPushEvents.size > 0) {\n await this.#awaitBounded(\n Promise.allSettled([...this.#inFlightPushEvents]),\n remaining(),\n `${this.#inFlightPushEvents.size} in-flight workflow event(s)`,\n );\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 await this.#unwireSchedulerWakeSubscription();\n\n await this.#pubsub.flush();\n this.#executionWorkersStarted = false;\n // Workers are gone again, so a stranded workflow event should warn again.\n this.#warnedStrandedLocalWorkflowIds.clear();\n }\n\n /**\n * Hand back the thread runs this Mastra still holds once its durable executions are abandoned: announce each run's\n * end, stop its lease renewal and release its thread lease, so another process can take the thread right away.\n */\n async #shutdownThreadRuns(deadline: number): Promise<void> {\n // Agents can carry their own pubsub; thread runs live in a separate runtime state per pubsub.\n const pubsubs = new Set<PubSub | undefined>([this.pubsub]);\n for (const agent of Object.values(this.#agents as Record<string, Agent<any>>)) {\n if (typeof agent?.getPubSub === 'function') pubsubs.add(agent.getPubSub());\n }\n const abortGraceMs = Math.max(SHUTDOWN_THREAD_RUN_ABORT_GRACE_MIN_MS, deadline - Date.now());\n const executesElsewhere = (runId: string) => isDurableAgentExecutionDetached(this, runId);\n const results = await this.#awaitBounded(\n Promise.allSettled(\n [...pubsubs].map(pubsub =>\n agentThreadStreamRuntime.shutdown(pubsub, this, { abortGraceMs, executesElsewhere }),\n ),\n ),\n abortGraceMs + 1_000,\n 'thread run handback',\n );\n results?.forEach(result => {\n if (result.status === 'rejected') {\n this.#logger?.error('Handing back thread runs failed during shutdown', { error: result.reason });\n }\n });\n }\n\n /**\n * Await an already-started promise for at most `timeoutMs`. Returns its value\n * when it settles in time, or `undefined` after logging a warning when the\n * budget is exhausted — the work keeps running in the background so teardown\n * stays best-effort but bounded.\n */\n async #awaitBounded<T>(\n promise: Promise<T>,\n timeoutMs: number,\n description: string,\n timeoutMessage = `Shutdown drain timed out after ${timeoutMs}ms; abandoning ${description}`,\n ): Promise<T | undefined> {\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n try {\n const outcome = await Promise.race([\n promise.then(value => ({ timedOut: false as const, value })),\n new Promise<{ timedOut: true }>(resolve => {\n timeoutHandle = setTimeout(() => resolve({ timedOut: true }), timeoutMs);\n }),\n ]);\n if (outcome.timedOut) {\n this.#logger?.warn(timeoutMessage);\n return undefined;\n }\n return outcome.value;\n } finally {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n }\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 * In-flight evented workflow runs (including durable agent runs) started\n * through this instance are given up to `drainTimeout` milliseconds\n * (default 5000) to reach a terminal or suspended state before workers and\n * pubsub subscriptions are torn down. Runs that do not settle within the\n * window are abandoned with a warning. Durable agent runs using the default\n * snapshot policy persist a `running` checkpoint at each step boundary they\n * reach during the drain. An abandoned durable agent run then stops without\n * writing and is released. It can be recovered only if a checkpoint was\n * persisted.\n *\n * Agent thread runs this instance still holds are then handed back. A run\n * still executing is aborted so it starts no further steps, and other\n * processes watching its thread see it end; its partial response is not\n * saved. A run parked on a tool approval or suspension stays parked and\n * resumable. Either way the thread lease is released right away instead of\n * at expiry, so another process can use the thread immediately. Release is\n * best-effort: if an aborted run doesn't stop in time (for example, a tool\n * call that ignores the abort), or the lease backend doesn't answer or\n * fails the release, the lease is kept until it expires. Handing runs back can take up to about 1.5 seconds past\n * `drainTimeout`.\n */\n async shutdown(options?: { drainTimeout?: number }): Promise<void> {\n const drainTimeout = assertDrainTimeout(\n options?.drainTimeout ?? waitMs(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS, 50),\n 'shutdown',\n );\n\n // `drainTimeout` is a single deadline shared by every drain in this method\n // (evented runs here, then worker transports and push events inside\n // stopWorkers()). They all end up waiting on the same in-flight steps, so a\n // stuck step must only be charged once — the deployer's shutdown deadline\n // is sized as `drainTimeout + fixed teardown`, and stacking would break it.\n const deadline = Date.now() + drainTimeout;\n\n // A pending durable-agent recovery re-check must not start a run while the\n // instance drains. One already under way may still be claiming its run, so\n // the drain below waits for it like a run: what it claims is then drained\n // or abandoned, not left claimed until the claim expires.\n this.#shuttingDown = true;\n this.#durableRecoveryRechecks.forEach(timer => clearTimeout(timer));\n this.#durableRecoveryRechecks.clear();\n // A pass in flight is drained below; stopWorkers() releases the recovery leader row after it.\n this.#stopWorkflowRecoveryLoop?.();\n\n // The scorer hook lives on a process-global emitter. Release it before any\n // awaited teardown so even a later cleanup failure cannot retain this\n // Mastra instance and its full component graph.\n this.__unregisterHooks();\n\n // Evented workflow runs (plain and durable-agent) only progress while the\n // `workflows` subscriptions below are alive, so let them settle first.\n // Durable workflows may also still be persisting their next terminal or\n // suspended snapshot; storage stays open until after this drain either way.\n // Workers stay up during this drain, so a run can still be started while\n // we wait (an in-flight request handler, a scheduler tick, a step that\n // starts another run). Re-snapshot until nothing is left or the deadline\n // passes rather than gating new runs, which would turn those callers into\n // errors mid-shutdown.\n // Each promise is awaited at most once: the durable-agent registry can keep\n // returning a settled execution, which would otherwise spin this loop.\n const awaited = new Set<Promise<unknown>>();\n for (;;) {\n const pendingRuns = [\n ...this.#activeEventedRuns,\n ...getActiveDurableAgentWorkflowExecutions(this),\n ...this.#durableRecoveryRechecksInFlight,\n // A recovery pass still reading the store, for example a boot pass when a deploy stops the instance.\n ...(this.#recoveryPass ? [this.#recoveryPass] : []),\n ].filter(run => !awaited.has(run));\n if (pendingRuns.length === 0) break;\n pendingRuns.forEach(run => awaited.add(run));\n const drained = await this.#awaitBounded(\n Promise.allSettled(pendingRuns),\n Math.max(0, deadline - Date.now()),\n `${pendingRuns.length} in-flight evented workflow run(s)`,\n );\n if (!drained) break;\n drained.forEach(result => {\n if (result.status === 'rejected') {\n this.#logger?.error('Evented workflow run failed during shutdown', {\n error: result.reason,\n });\n }\n });\n }\n\n // A durable-agent execution still running now would keep its run claimed\n // until the claim expires. Stop it without writing and release the run, so\n // the next boot recovers it right away. Storage must still be open.\n await abandonDurableAgentExecutions(this);\n\n // Hand back the thread runs this instance still holds: announce each run's end to observers in other\n // processes and release its thread lease, so the thread is free right away instead of after the lease\n // lapses. Pubsub must still be open.\n await this.#shutdownThreadRuns(deadline);\n // The shared BackgroundTaskWorker deliberately delegates manager ownership\n // to Mastra. Stop the manager while workers, pubsub, and storage are still\n // available so it can abort active tasks, preserve retry recovery, and\n // remove its subscriptions.\n if (this.#backgroundTaskManager) {\n await this.#backgroundTaskManager.shutdown({ deadline });\n }\n\n // SchedulerWorker is stopped as part of stopWorkers().\n await this.stopWorkers({ drainTimeout: Math.max(0, deadline - Date.now()) });\n\n // Stop — don't destroy — registered workspaces. Remote sandboxes\n // suspend/pause and stay resumable across process restarts, and\n // LocalSandbox.stop() kills its background processes, so nothing leaks.\n // Callers that want a full teardown destroy workspaces explicitly via\n // removeWorkspace(id, { destroy: true }) or workspace.destroy().\n const workspaceIds = Object.keys(this.#workspaces);\n const teardownResults = await Promise.allSettled(\n workspaceIds.map(async id => {\n const entry = this.#workspaces[id];\n if (!entry) return;\n await entry.workspace.stop();\n await this.removeWorkspace(id);\n }),\n );\n teardownResults.forEach((result, index) => {\n if (result.status === 'rejected') {\n this.#logger?.error('Failed to tear down 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 // Workers and runs are stopped, so nothing publishes anymore. Close transports\n // that hold connections (e.g. Redis) so they don't keep the process alive.\n const pubsub = this.#pubsub as PubSub & { close?: () => Promise<void> };\n if (typeof pubsub.close === 'function') {\n try {\n await pubsub.close();\n } catch (error) {\n this.#logger?.error('Failed to close pubsub during shutdown', { error });\n }\n }\n\n // Flush observability exporters while their storage is still open.\n await this.#observability.shutdown();\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\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,MAAa,oCAAoC;;;;;;;AAQjD,MAAa,wCAAwC;AAErD,MAAa,qCAAqC;;;;;;;AASlD,MAAM,sDAAsD;;;;;AAa5D,MAAM,6BAAa,IAAI,KAAK,0BAA0B;;;;;;AAOtD,eAAsB,gCAAgC,SAAiD;CAErG,QAAO,MADe,QAAQ,qBAAqB;EAAE,KAAK;EAAY,OAAO;CAAE,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