UNPKG

@mastra/core

Version:
6,237 lines • 232 kB
import { Bu as createConcurrencyLimiter, Cl as nestedRunParentOf, Dl as renewWorkflowLease, El as WORKFLOW_RUN_LEASE_TTL_MS, Gc as AgentChannels, Gi as BackgroundTasksInMemory, Gt as getStorageSource, Hu as runWithConcurrency, Mo as __registerMastraCtor, Ol as repeatAfterSettled, Sl as createNestedRunParentStatusLookup, Tl as nestedRunStatusOf, Vu as normalizeConcurrency, Wt as augmentWithInit, _t as createWorkflow, ai as InMemoryStore, bt as computeScheduleDefinitionHash, gd as runOutsideRunFenceScope, gt as createStep, hu as waitMs, mu as assertDrainTimeout, qu as isDurableAgentLike, r as abandonDurableAgentExecutions, rl as createOnScorerHook, s as getActiveDurableAgentWorkflowExecutions, si as WorkflowsInMemory, u as isDurableAgentExecutionDetached, v as agentThreadStreamRuntime, vt as WorkflowEventProcessor, wi as dispatchDueNotifications, wl as nestedRunRecoveryAction, xl as cancelNestedRun } from "./run-registry-Ca8idv6o.js";
import { s as BackgroundTaskManager } from "./background-tasks-CChqE9Qy.js";
import { t as InMemoryServerCache } from "./inmemory-BDD0w8gx.js";
import { t as DatasetsManager } from "./manager-DHcGDPph.js";
import { i as MastraError, n as ErrorDomain, t as ErrorCategory } from "./error-oh2DLsP2.js";
import { g as EventEmitterPubSub, u as isRunLocalTopic } from "./output-helpers-D4II19No.js";
import { a as registerHook, r as deregisterHook } from "./hooks-Bth8Cjpj.js";
import { LicenseClient } from "./license/index.js";
import { p as getGatewayId } from "./netlify-WYnWTeMp.js";
import { l as defaultGateways } from "./llm-vu4qB_Xw.js";
import { l as isAdaptableLogger, n as LogLevel, t as ConsoleLogger, u as noopLogger } from "./logger-BwbmRqfc.js";
import { DualLogger, createExportSuppressedLogger, isObservabilityExportSuppressed, resolveTraceFields } from "./logger/index.js";
import { c as fsAgentScheduleRowId, d as computeNextFireAt, f as toEpochMs, l as parseFsAgentScheduleRowId, t as Schedules, u as computeNextFire } from "./schedules-CGkeqNro.js";
import { C as NoOpObservability, T as noOpMetricsContext, w as noOpLoggerContext } from "./observability-D3dpuDDk.js";
import { initContextStorage } from "./observability/context-storage.js";
import { f as resolveCurrentSpan } from "./utils-DU_pU5SK.js";
import { r as InMemoryDB } from "./source-DRqDgbCv.js";
import { r as trackFeatureUsage } from "./feature-telemetry-DdR8J_5o.js";
import { r as isToolLoopAgentLike, t as toolLoopAgentToMastraAgent } from "./tool-loop-agent-JLED__vL.js";
import { r as normalizeToolPayloadTransformPolicy } from "./payload-transform-Dj3HUeD4.js";
import { v as readPositiveIntEnv } from "./utils-Dpa2BH2v.js";
import { i as OrchestrationWorker, n as BackgroundTaskWorker, r as SchedulerWorker } from "./worker-Dz7t0AMX.js";
import { n as normalizeWorkflowBuilderDefinition } from "./builder-BITivu1w.js";
import { d as toJsonSchemaOrUndefined, p as collectNestedWorkflowIds, t as assertValidDynamicWorkflow } from "./validate-CfgsbSxQ.js";
import { t as rehydrateWorkflow } from "./rehydrate-DzumSyB6.js";
import { wn as createRunScope } from "./stream-sJ8FGaH9.js";
import { z } from "zod/v4";
// src/notifications/workflow.ts
const NOTIFICATION_DISPATCH_WORKFLOW_ID = "__mastra_notification_dispatcher";
/**
* Schedule row id for the lazily-created dispatcher schedule. Deliberately
* NOT `wf_`-prefixed: `registerDeclarativeSchedules` orphan-cleanup deletes
* `wf_`-prefixed rows that are no longer declared in code, and this row is
* created imperatively (like heartbeat rows) on first deferred notification.
*/
const NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID = "__mastra_notification_dispatch";
const NOTIFICATION_DISPATCH_DEFAULT_CRON = "*/1 * * * *";
/**
* The dispatcher ticks once a minute, has a single non-suspending step, and is
* never resumed — no code path consumes its snapshot. Opting out of snapshot
* persistence entirely keeps `mastra_workflow_snapshot` from growing by one
* dead row per minute forever (issue #20254).
*/
const NOTIFICATION_DISPATCH_SHOULD_PERSIST_SNAPSHOT = () => false;
/**
* Upper bound passed as `now` to find every pending record with a due time,
* however far ahead. Year 9999 stays inside every adapter's timestamp range.
*/
const FAR_FUTURE = /* @__PURE__ */ new Date("9999-12-31T23:59:59.999Z");
/**
* True when some pending notification has a `deliverAt` or `summaryAt`, i.e.
* the dispatcher still has work now or later. Records without a due time are
* never picked up by a dispatch pass, so they don't count.
*/
async function hasPendingDeferredNotifications(storage) {
	return (await storage.listDueNotifications({
		now: FAR_FUTURE,
		limit: 1
	})).length > 0;
}
function parseNotificationDispatchNow(input) {
	const now = input ? new Date(input) : /* @__PURE__ */ new Date();
	if (Number.isNaN(now.getTime())) throw new Error(`Invalid notification dispatch time: ${input}`);
	return now;
}
/**
* Builds the imperative schedule row that drives the notification dispatcher.
* Created lazily by `Mastra.__ensureNotificationDispatchReady()` on the first
* deferred notification, rather than declared on the workflow, so idle apps
* never start the scheduler.
*/
function buildNotificationDispatchSchedule({ cron = NOTIFICATION_DISPATCH_DEFAULT_CRON, batchSize = 100 } = {}) {
	const now = Date.now();
	return {
		id: NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID,
		target: {
			type: "workflow",
			workflowId: NOTIFICATION_DISPATCH_WORKFLOW_ID,
			inputData: { limit: batchSize }
		},
		cron,
		status: "active",
		nextFireAt: computeNextFireAt(cron, { after: now }),
		createdAt: now,
		updatedAt: now,
		metadata: {
			internal: true,
			feature: "notifications"
		}
	};
}
function createNotificationDispatchWorkflow({ batchSize = 100 } = {}) {
	const dispatchStep = createStep({
		id: "dispatch-due-notifications",
		inputSchema: z.object({
			now: z.string().optional(),
			limit: z.number().optional()
		}),
		outputSchema: z.object({
			delivered: z.number(),
			failed: z.number()
		}),
		execute: async ({ inputData, mastra }) => {
			const storage = await mastra.getStorage()?.getStore("notifications");
			if (!storage) return {
				delivered: 0,
				failed: 0
			};
			const now = parseNotificationDispatchNow(inputData.now);
			const result = await dispatchDueNotifications({
				mastra,
				storage,
				now,
				limit: inputData.limit ?? batchSize
			});
			await mastra.__releaseNotificationDispatchIfIdle();
			return {
				delivered: result.delivered.length,
				failed: result.failed.length
			};
		}
	});
	return createWorkflow({
		id: NOTIFICATION_DISPATCH_WORKFLOW_ID,
		inputSchema: z.object({
			now: z.string().optional(),
			limit: z.number().optional()
		}),
		outputSchema: z.object({
			delivered: z.number(),
			failed: z.number()
		}),
		options: { shouldPersistSnapshot: NOTIFICATION_DISPATCH_SHOULD_PERSIST_SNAPSHOT }
	}).then(dispatchStep).commit();
}
// src/schedules/row-diff.ts
/**
* Comparators for deciding whether a stored schedule row still matches what
* code declares. Shared by both declarative sync paths — workflow schedules
* (`createWorkflow({ schedule })`) and file-based agent schedules — so the two
* cannot drift on what counts as "unchanged" and start rewriting rows on every
* boot.
*/
/**
* Stable JSON-shape comparison for two `Schedule.target` values. Uses
* JSON.stringify because targets are plain JSON-serializable objects (the
* storage layer round-trips them through the same encoding). Covers the
* `inputData` / `initialState` / `requestContext` payload fields that we
* want to detect changes on across redeploys.
*/
function targetsEqual(a, b) {
	if (a === b) return true;
	if (!a) return false;
	return JSON.stringify(a) === JSON.stringify(b);
}
/** See {@link targetsEqual}. Same approach for free-form metadata. */
function metadataEqual(a, b) {
	const aNorm = a ?? void 0;
	const bNorm = b ?? void 0;
	if (aNorm === bNorm) return true;
	if (!aNorm || !bNorm) return false;
	return JSON.stringify(aNorm) === JSON.stringify(bNorm);
}
// src/mastra/fs-agent-schedules.ts
/**
* Reads the file-based schedules declared on a registered agent.
*
* Wrappers around an inner `Agent` (durable execution) delegate this
* explicitly — see `DurableAgent.getDeclaredSchedules` — so there is nothing to
* unwrap here. The optional call covers registrable shapes that are not
* `Agent`s at all (`ToolLoopAgentLike`).
*/
function declaredSchedulesOf(agent) {
	return agent?.getDeclaredSchedules?.() ?? [];
}
/** True when any registered agent declares schedules on disk. */
function hasFsAgentSchedule(agents) {
	return Object.values(agents ?? {}).some((agent) => declaredSchedulesOf(agent).length > 0);
}
/**
* Collect every declared schedule across the registered agents, keyed by
* `fsa_<encoded(agentId)>__<encoded(key)>` so the prefix uniquely identifies
* "all rows owned by this agent's schedules/ directory" even when ids contain
* delimiter-like characters.
*
* Pure: duplicates are returned rather than logged, so callers that run per
* fire don't re-emit the same warning forever.
*/
function collectFsAgentSchedules(agents) {
	const schedules = [];
	const duplicates = [];
	const seen = /* @__PURE__ */ new Set();
	for (const agent of Object.values(agents ?? {})) for (const { key, definition } of declaredSchedulesOf(agent)) {
		const scheduleId = fsAgentScheduleRowId(agent.id, key);
		if (seen.has(scheduleId)) {
			duplicates.push({
				agentId: agent.id,
				key
			});
			continue;
		}
		seen.add(scheduleId);
		schedules.push({
			scheduleId,
			agentId: agent.id,
			key,
			definition
		});
	}
	return {
		schedules,
		duplicates
	};
}
/**
* Resolve the handler for a handler-mode file-based schedule. Handlers are
* functions and therefore cannot be persisted on the JSON schedule row, so the
* agent-schedule worker looks them up in-process by row id at fire time.
*
* The row id already encodes the agent and the key, so this decodes it and
* reads that one agent rather than rebuilding the whole cross-agent collection
* on every fire. When two agents share an id the first wins, matching
* {@link collectFsAgentSchedules}.
*/
function findFsAgentScheduleHandler(agents, scheduleId) {
	const parsed = parseFsAgentScheduleRowId(scheduleId);
	if (!parsed) return void 0;
	const handler = declaredSchedulesOf(Object.values(agents ?? {}).find((agent) => agent.id === parsed.agentId)).find((entry) => entry.key === parsed.key)?.definition.handler;
	return typeof handler === "function" ? handler : void 0;
}
/** Build the storage `target` for a declared schedule. */
function buildTarget(agentId, definition) {
	return {
		type: "agent",
		agentId,
		prompt: definition.prompt ?? "",
		name: definition.name,
		threadId: definition.threadId,
		resourceId: definition.resourceId,
		signalType: definition.signalType,
		tagName: definition.tagName,
		attributes: definition.attributes,
		providerOptions: definition.providerOptions,
		ifActive: definition.ifActive,
		ifIdle: definition.ifIdle
	};
}
/**
* Sync schedules declared by file-based agents' `schedules/` directories into
* schedule storage.
*
* Mirrors the declarative workflow sync: upsert declared rows, diff the config
* fields and patch what changed, leave `status` alone so an out-of-band pause
* survives a redeploy, and delete orphaned `fsa_` rows that code no longer
* declares. Rows created imperatively through `mastra.schedules.create(...)`
* use the `agent_` prefix and are never touched here.
*/
async function syncFsAgentSchedules({ agents, store, logger, knownRows }) {
	const { schedules: declared, duplicates } = collectFsAgentSchedules(agents);
	for (const { agentId, key } of duplicates) logger?.warn(`Duplicate schedule "${key}" for agent id "${agentId}": two registered agents share that id. Keeping the first and ignoring the rest.`);
	const declaredIds = new Set(declared.map((d) => d.scheduleId));
	const allRows = knownRows ?? await store.listSchedules();
	const rowsById = new Map(allRows.map((row) => [row.id, row]));
	for (const { scheduleId, agentId, key, definition } of declared) try {
		const now = Date.now();
		const target = buildTarget(agentId, definition);
		const existing = rowsById.get(scheduleId);
		const computeTiming = () => {
			const next = computeNextFire({
				cron: definition.cron,
				timezone: definition.timezone,
				nextFireAt: now
			}, now);
			return {
				nextFireAt: next.nextFireAt,
				status: next.completed ? "completed" : definition.status ?? "active"
			};
		};
		if (!existing) {
			const timing = computeTiming();
			await store.createSchedule({
				id: scheduleId,
				target,
				cron: definition.cron,
				timezone: definition.timezone,
				status: timing.status,
				nextFireAt: timing.nextFireAt,
				createdAt: now,
				updatedAt: now,
				metadata: definition.metadata,
				ownerType: "agent",
				ownerId: agentId
			});
			continue;
		}
		const patch = {};
		const cronChanged = existing.cron !== definition.cron;
		const timezoneChanged = (existing.timezone ?? void 0) !== (definition.timezone ?? void 0);
		if (cronChanged) patch.cron = definition.cron;
		if (timezoneChanged) patch.timezone = definition.timezone;
		if (!targetsEqual(existing.target, target)) patch.target = target;
		if (!metadataEqual(existing.metadata, definition.metadata)) patch.metadata = definition.metadata;
		if (cronChanged || timezoneChanged) {
			const timing = computeTiming();
			patch.nextFireAt = timing.nextFireAt;
			if (timing.status === "completed") patch.status = "completed";
			else if (existing.status === "completed") patch.status = "active";
		}
		if (Object.keys(patch).length > 0) await store.updateSchedule(scheduleId, patch);
	} catch (error) {
		logger?.error("Failed to register file-based agent schedule", {
			scheduleId,
			agentId,
			key,
			error
		});
	}
	const registeredAgentIds = new Set(Object.values(agents ?? {}).map((a) => a.id));
	for (const row of allRows) {
		if (declaredIds.has(row.id)) continue;
		if (!row.id.startsWith("fsa_")) continue;
		const ownerAgentId = parseFsAgentScheduleRowId(row.id)?.agentId;
		if (!ownerAgentId || !registeredAgentIds.has(ownerAgentId)) continue;
		try {
			await store.deleteSchedule(row.id);
		} catch (error) {
			logger?.error("Failed to delete orphaned file-based agent schedule", {
				scheduleId: row.id,
				agentId: ownerAgentId,
				error
			});
		}
	}
}
// src/mastra/index.ts
function normalizeApiRoutes(routes) {
	return routes.flatMap((route) => Array.isArray(route) ? route : [route]);
}
function normalizeServerConfig({ apiRoutes, ...server }) {
	return apiRoutes ? {
		...server,
		apiRoutes: normalizeApiRoutes(apiRoutes)
	} : server;
}
/**
* Creates an error for when a null/undefined value is passed to an add* method.
* This commonly occurs when config is spread ({ ...config }) and the original
* object had getters or non-enumerable properties.
*/
function createUndefinedPrimitiveError(type, value, key) {
	const typeLabel = type === "mcp-server" ? "MCP server" : type;
	const errorId = `MASTRA_ADD_${type.toUpperCase().replace("-", "_")}_UNDEFINED`;
	return new MastraError({
		id: errorId,
		domain: ErrorDomain.MASTRA,
		category: ErrorCategory.USER,
		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.`,
		details: {
			status: 400,
			...key && { key }
		}
	});
}
/**
* Whether the Mastra scheduler fires this workflow's declared schedules.
* Only the default and evented engines are dispatched by it; other engines
* (Inngest, Temporal) own their scheduling natively.
*/
function runsOnMastraScheduler(workflow) {
	const engineType = workflow.engineType;
	return engineType === "default" || engineType === "evented";
}
/**
* Reads the declarative schedule configs off a workflow, regardless of its
* engine. Supports both the `getScheduleConfigs(): WorkflowScheduleConfig[]`
* accessor and a legacy `getScheduleConfig(): WorkflowScheduleConfig | undefined`
* fallback used in tests that inject a fake getter.
*/
function readWorkflowScheduleConfigs(workflow) {
	const w = workflow;
	if (typeof w.getScheduleConfigs === "function") return w.getScheduleConfigs() ?? [];
	if (typeof w.getScheduleConfig === "function") {
		const cfg = w.getScheduleConfig();
		if (!cfg) return [];
		return Array.isArray(cfg) ? cfg : [cfg];
	}
	return [];
}
/**
* The declarative schedule configs the Mastra scheduler should register for a
* workflow. Empty for engines the scheduler does not dispatch.
*/
function collectWorkflowScheduleConfigs(workflow) {
	return runsOnMastraScheduler(workflow) ? readWorkflowScheduleConfigs(workflow) : [];
}
/**
* Whether `runId` names a scheduler-spawned run whose workflow events stay in the publishing
* process: `sched_wf_<workflowId>_<timestamp>` for declarative schedules, or the notification
* dispatcher's row. These ticks fire on every instance independently, so the `mastra.pubsub`
* proxy publishes their events `localOnly`, and a broker never holds them.
*/
function isProcessLocalScheduledRunId(runId) {
	if (!runId) return false;
	return runId.startsWith("sched_wf_") || runId.startsWith(`sched___mastra_notification_dispatch_`);
}
/**
* Builds the storage row id for a declarative schedule. Workflow and schedule
* ids are URL-encoded so delimiters in user-supplied ids cannot collide
* across workflows (e.g. `foo__bar` single vs `foo` array-entry `bar`).
*/
function encodeDeclarativeScheduleId(id) {
	return encodeURIComponent(id).replaceAll("_", "%5F");
}
function declarativeScheduleRowId(workflowId, scheduleId) {
	const encodedWorkflow = encodeDeclarativeScheduleId(workflowId);
	if (scheduleId === void 0) return `wf_${encodedWorkflow}`;
	return `wf_${encodedWorkflow}__${encodeDeclarativeScheduleId(scheduleId)}`;
}
function legacyDeclarativeScheduleRowId(workflowId, scheduleId) {
	const encodedWorkflow = encodeURIComponent(workflowId);
	if (scheduleId === void 0) return `wf_${encodedWorkflow}`;
	return `wf_${encodedWorkflow}__${encodeURIComponent(scheduleId)}`;
}
/**
* Determines whether a stored schedule row id belongs to one of the registered
* workflows. Returns the owning workflow id when the row id either equals
* `wf_<encoded(workflowId)>` (single-schedule form) or starts with
* `wf_<encoded(workflowId)>__` (array form). Returns undefined when no
* registered workflow owns the row.
*/
function ownerWorkflowIdForRow(rowId, workflowIds) {
	for (const workflowId of workflowIds) {
		const prefix = `wf_${encodeURIComponent(workflowId)}`;
		if (rowId === prefix || rowId.startsWith(`${prefix}__`)) return workflowId;
	}
}
/**
* Decodes the owning workflow id directly from a `wf_<encoded>` /
* `wf_<encoded>__<...>` row id without needing the workflow to be in the
* current registry. Used to identify rows whose workflow has been deleted
* from code so we can clean them up on startup.
*/
function ownerWorkflowIdFromRowId(rowId) {
	if (!rowId.startsWith("wf_")) return void 0;
	const rest = rowId.slice(3);
	const sep = rest.indexOf("__");
	const encoded = sep === -1 ? rest : rest.slice(0, sep);
	if (!encoded) return void 0;
	try {
		return decodeURIComponent(encoded);
	} catch {
		return;
	}
}
function serializableWorkerConfig(config) {
	return JSON.parse(JSON.stringify(config ?? {}));
}
/**
* The central orchestrator for Mastra applications, managing agents, workflows, storage, logging, observability, and more.
*
* The `Mastra` class serves as the main entry point and registry for all components in a Mastra application.
* It coordinates the interaction between agents, workflows, storage systems, and other services.

* @template TAgents - Record of agent instances keyed by their names
* @template TWorkflows - Record of modern workflow instances
* @template TVectors - Record of vector store instances for semantic search and RAG
* @template TTTS - Record of text-to-speech provider instances
* @template TLogger - Logger implementation type for application logging
* @template TVNextNetworks - Record of next-generation agent network instances
* @template TMCPServers - Record of Model Context Protocol server instances
* @template TScorers - Record of evaluation scorer instances for measuring AI performance
*
* @example
* ```typescript
* const mastra = new Mastra({
*   agents: {
*     weatherAgent: new Agent({
*       id: 'weather-agent',
*       name: 'Weather Agent',
*       instructions: 'You provide weather information',
*       model: 'openai/gpt-5',
*       tools: [getWeatherTool]
*     })
*   },
*   workflows: { dataWorkflow },
*   storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:' }),
*   logger: new PinoLogger({ name: 'MyApp' })
* });
* ```
*/
const attachedLoggerOwners = /* @__PURE__ */ new WeakMap();
/**
* Pubsub topic used to tell every process running the default worker set that
* a schedule now exists and the scheduler tick loop should start. Lets a
* standalone worker that booted with an empty schedules table discover
* schedules created later by the API process without continuously polling storage.
*/
const SCHEDULER_WAKE_TOPIC = "scheduler";
const SCHEDULER_WAKE_EVENT = "scheduler.wake";
const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS = 5e3;
const SHUTDOWN_THREAD_RUN_ABORT_GRACE_MIN_MS = 500;
const DURABLE_RECOVERY_RECHECK_JITTER_MS = 5e3;
const DURABLE_RECOVERY_RECHECK_RETRY_BASE_MS = 3e4;
const DURABLE_RECOVERY_RECHECK_MAX_RETRIES = 5;
const DURABLE_RECOVERY_ATTEMPT_TIMEOUT_MS = 3e4;
const DEFAULT_WORKFLOW_GRACE_MS = 2e3;
const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
const RECOVERY_OWNERSHIP_BATCH_SIZE = 100;
const RECOVERY_LISTING_CONCURRENCY = 5;
const ACTIVE_RUN_STATUSES = ["running", "waiting"];
const DEFAULT_WORKFLOW_SCAN_INTERVAL_MS = 6e4;
const MIN_WORKFLOW_SCAN_DELAY_MS = 1e3;
const RECOVERY_LEADER_KEY = "::recovery-leader";
/** `recovery.workflowGraceMs` as configured, or `fallback` when it is unset or not a finite non-negative number. */
function normalizeGraceMs(graceMs, fallback) {
	if (typeof graceMs !== "number" || !Number.isFinite(graceMs) || graceMs < 0) return fallback;
	return graceMs;
}
/** `recovery.workflowScanIntervalMs` as configured, capped at the longest timer delay; the default when unset or not positive. */
function normalizeScanIntervalMs(intervalMs) {
	if (typeof intervalMs !== "number" || Number.isNaN(intervalMs) || intervalMs <= 0) return DEFAULT_WORKFLOW_SCAN_INTERVAL_MS;
	return Math.min(intervalMs, MAX_TIMER_DELAY_MS);
}
/**
* How long the recovery loop waits for its next pass: the scan interval, give or take a fifth, or
* less when `dueAt`, the end of the grace period of a run the last pass left alone, comes first.
* The wait for `dueAt` is at least {@link MIN_WORKFLOW_SCAN_DELAY_MS} and up to a fifth longer, as
* a check made before `dueAt` would find the run still in its grace period.
*/
function nextWorkflowScanDelay(intervalMs, dueAt) {
	const interval = intervalMs * (.8 + Math.random() * .4);
	const untilDue = dueAt === void 0 ? Infinity : Math.max(MIN_WORKFLOW_SCAN_DELAY_MS, dueAt - Date.now()) * (1 + Math.random() * .2);
	return Math.min(interval, untilDue, MAX_TIMER_DELAY_MS);
}
/** Identifies a run across the workflows of one recovery pass. */
function recoveryRunKey(workflowName, runId) {
	return JSON.stringify([workflowName, runId]);
}
/**
* The recovery rule for a default-engine run. It is restarted when its run
* lease is not live and `graceMs` passed since the later of the lease's last
* expiry and the run's last write. Otherwise `dueAt` is when that could next
* be true.
*
* A released or missing lease carries no expiry, so the run's own last write
* anchors the grace then.
*/
function recoveryVerdict({ owner, updatedAt, graceMs, now }) {
	const lastWrite = updatedAt === void 0 ? NaN : new Date(updatedAt).getTime();
	const dueAt = Math.max(Number.isNaN(lastWrite) ? -Infinity : lastWrite, owner?.leaseExpiresAt?.getTime() ?? -Infinity) + graceMs;
	const live = owner?.live === true;
	if (live || now < dueAt) return {
		restart: false,
		live,
		dueAt
	};
	return { restart: true };
}
/**
* Whether runs of `workflow` hold a run lease while they execute, which the recovery rule reads.
* Evented runs hold none: their steps run wherever the pubsub delivers each event.
*/
function usesRunLease(workflow) {
	return workflow.engineType === "default";
}
/**
* Whether boot-time recovery restarts runs of `workflow`. Processor workflows only run inside an
* agent call, so a lone restart has nothing to resume.
*/
function isRecoveryRestartable(workflow) {
	return (workflow.engineType === "default" || workflow.engineType === "evented") && workflow.options?.autoRestartActiveRuns !== false && workflow.type !== "processor";
}
/**
* Registers and coordinates agents, workflows, storage, and other Mastra services.
*
* @example
* `yourAgent` is an agent you have already configured.
* ```typescript
* import { Mastra } from '@mastra/core/mastra';
*
* const mastra = new Mastra({
*   agents: { assistant: yourAgent },
* });
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Mastra documentation](https://mastra.ai/reference/core/mastra-class)
* if packaged docs are unavailable.
*/
var Mastra = class Mastra {
	#vectors;
	#agents;
	#toolLoopRegistrations = /* @__PURE__ */ new WeakMap();
	#logger;
	#loggerAdapterOptions = {
		correlation: true,
		export: true
	};
	#wiredLoggers = /* @__PURE__ */ new WeakSet();
	#fallbackWrappers = /* @__PURE__ */ new WeakMap();
	#loggerExplicit = false;
	#workflows;
	#harnesses = {};
	#hiddenWorkflowKeys = /* @__PURE__ */ new Set();
	#observability;
	#observabilityExplicit = false;
	#onScorerHook;
	#tts;
	#deployer;
	#serverMiddleware = [];
	#storage;
	#storageSource;
	#storageExplicit = false;
	#storageFallbackWarningPending = false;
	#recoveryConfig = {
		workflows: "auto",
		workflowConcurrency: 5,
		workflowGraceMs: DEFAULT_WORKFLOW_GRACE_MS,
		workflowScanIntervalMs: DEFAULT_WORKFLOW_SCAN_INTERVAL_MS,
		durableAgents: "off"
	};
	#durableRecoveryRechecks = /* @__PURE__ */ new Map();
	#durableRecoveryRechecksInFlight = /* @__PURE__ */ new Set();
	#shuttingDown = false;
	/** The default-engine recovery pass in flight; see `#recoverStoppedRuns`. */
	#recoveryPass;
	/** Stops the recovery loop `startWorkers()` started; unset while none runs. */
	#stopWorkflowRecoveryLoop;
	/** The recovery leader row while this instance holds it; see `#leadWorkflowRecovery`. */
	#recoveryLeader;
	/** A tick's claim of the recovery leader row in flight, which `#releaseRecoveryLeader()` waits for. */
	#recoveryLeaderClaim;
	/** Runs the restarts of every recovery pass, `recovery.workflowConcurrency` at a time. */
	#recoveryRestarts;
	#recoveryListings = createConcurrencyLimiter(RECOVERY_LISTING_CONCURRENCY);
	/** The runs a recovery pass handed to `#recoveryRestarts` whose restart has not settled. */
	#queuedRecoveryRestarts = /* @__PURE__ */ new Set();
	/** The runs whose last recovery restart threw, by the engine whose pass restarts them. */
	#failedRecoveryRestarts = {
		default: /* @__PURE__ */ new Set(),
		evented: /* @__PURE__ */ new Set()
	};
	#scorers;
	#classifiers;
	#tools;
	#processors;
	#processorConfigurations = /* @__PURE__ */ new Map();
	#memory;
	#knowledge;
	#workspace;
	#workspaces = {};
	#server;
	#serverExplicit = false;
	#signalProviderRouteOwners = /* @__PURE__ */ new WeakMap();
	#studio;
	#studioExplicit = false;
	#serverAdapter;
	#mcpServers;
	#bundler;
	#idGenerator;
	#pubsub;
	#backgroundTaskConfig;
	#backgroundTaskManager;
	#schedulerConfig;
	#notificationDispatchConfig;
	/**
	* Tracks whether any registered workflow has declared a `schedule` config.
	* Used as a fast short-circuit so users without scheduled workflows pay
	* zero cost beyond a boolean check.
	*/
	#hasScheduledWorkflow = false;
	/**
	* Ids of persisted dynamic workflow definitions that failed to rehydrate at
	* boot. Their declarative `wf_*` schedule rows are exempt from orphan
	* deletion — the workflow still exists in storage, so its schedules aren't
	* orphans; deleting them would silently lose the user's schedules.
	*/
	#failedDynamicWorkflowIds = /* @__PURE__ */ new Set();
	/**
	* Set while a file-based agent schedule sync is queued, so registering a
	* batch of agents after startup triggers one sweep rather than one per agent.
	*/
	#fsScheduleSyncPending = false;
	/** Set once file-based agent usage has been reported for this Mastra instance. */
	#fsAgentUsageTracked = false;
	/**
	* Set when an agent registers while a sweep is already in flight. That sweep
	* may have read the agent map before the agent landed, so it runs one more
	* pass instead of dropping the registration.
	*/
	#fsScheduleSyncRerun = false;
	#gateways;
	#channels;
	/** Live channel-provider source; when set, `#channels` holds the latest resolved snapshot. */
	#channelsResolver;
	/** In-flight resolver invocation, shared so concurrent `resolveChannels()` calls coalesce. */
	#channelsResolvePromise;
	/** Providers already attached/initialized, so resolver refreshes touch each instance once. */
	#attachedChannelProviders = /* @__PURE__ */ new WeakSet();
	#schedules;
	#schedulesConfig;
	#environment;
	#toolPayloadTransform;
	#workers = [];
	#workerFilter;
	/**
	* Set when the user (or `MASTRA_WORKERS=false`) explicitly disabled all event
	* processing in this instance via `workers: false`. Gates lazy scheduler /
	* agent-schedule worker injection so runtime triggers (e.g.
	* `schedules.create()`) don't resurrect workers the user opted out of.
	*/
	#workersDisabled = false;
	/**
	* Tracks whether `startWorkers()` has already run. Used to decide whether
	* lazy scheduler injection (e.g. from `mastra.schedules.create()` after boot)
	* needs to also `init`/`start` the worker, or whether the normal
	* `startWorkers()` path will pick it up.
	*/
	#workersStarted = false;
	/**
	* Set when something has signalled that the scheduler is needed at runtime
	* (e.g. an agent schedule was registered via `__ensureScheduleRuntimeReady()`).
	* Causes `#shouldEnableScheduler()` to return `true` even when there are no
	* declarative scheduled workflows, unless the user explicitly set
	* `scheduler: { enabled: false }`.
	*/
	#schedulerRequested = false;
	/**
	* Set once `__ensureNotificationDispatchReady()` has requested the
	* scheduler in this process, so later deferrals only verify the row.
	*/
	#notificationDispatchReady = false;
	/**
	* In-flight promise for `#ensureSchedulingWorkersStarted()`. Serializes
	* concurrent startup requests so two callers can't both pass the
	* worker-existence checks and double-subscribe to the scheduling topics.
	*/
	#schedulingWorkersStartPromise;
	/**
	* In-flight promise for `__ensureExecutionWorkersStarted()`. Serializes
	* concurrent lazy startups triggered by background-task dispatches so two
	* first dispatches on a cold instance can't both init/start the same
	* workers.
	*/
	#executionWorkersStartPromise;
	/**
	* Fast path for `__ensureExecutionWorkersStarted()`. Set once the execution
	* workers + push wiring are confirmed running; reset by `stopWorkers()`.
	* Kept separate from `#workersStarted`, which partial `startWorkers(name)`
	* calls also set without starting the workflow consumer.
	*/
	#executionWorkersStarted = false;
	#workflowEventProcessor;
	#pushSubscription;
	#inFlightPushEvents = /* @__PURE__ */ new Set();
	#activeEventedRuns = /* @__PURE__ */ new Set();
	#userEventSubscriptions = [];
	#schedulerWakeSubscription;
	#events = {};
	#internalMastraWorkflows = {};
	#distributedInternalWorkflowIds = /* @__PURE__ */ new Set();
	#warnedStrandedLocalWorkflowIds = /* @__PURE__ */ new Set();
	#runScopedWorkflowTimestamps = /* @__PURE__ */ new Map();
	#runScopes = /* @__PURE__ */ new Map();
	#runScopeRefcounts = /* @__PURE__ */ new Map();
	static INTERNAL_WORKFLOW_TTL_MS = readPositiveIntEnv("MASTRA_SUSPENDED_RUN_TTL_MS", 18e5);
	#runTracingContexts = /* @__PURE__ */ new Map();
	#serverCache;
	#storedAgentsCache = /* @__PURE__ */ new Map();
	#storedScorersCache = /* @__PURE__ */ new Map();
	#promptBlocks = {};
	#editor;
	#datasets;
	#versions;
	#pubsubProxy;
	get pubsub() {
		if (!this.#pubsubProxy) {
			const raw = this.#pubsub;
			const self = this;
			this.#pubsubProxy = new Proxy(raw, { get(target, prop, _receiver) {
				if (prop === "publish") return function publish(topic, event) {
					if (topic === "workflows" || topic === "workflows-finish") {
						const data = event.data;
						const wfId = data?.workflowId;
						const rId = data?.runId;
						const isOwnedHere = (guarded = false) => {
							if (wfId && rId && self.#isProcessLocalInternalWorkflow(wfId, rId, topic, guarded)) return true;
							let parent = data?.parentWorkflow;
							let depth = 0;
							while (parent && depth < 16) {
								const pwfId = parent.workflowId;
								const prId = parent.runId;
								if (pwfId && prId && self.#isProcessLocalInternalWorkflow(pwfId, prId, topic, guarded)) return true;
								parent = parent.parentWorkflow;
								depth++;
							}
							return isProcessLocalScheduledRunId(rId);
						};
						if (isOwnedHere()) {
							if (topic === "workflows" && !isOwnedHere(true)) return Promise.resolve(self.getStorage()?.getStore("workflows")).then((store) => target.publish(topic, event, { localOnly: !store?.supportsWorkflowStepGuards() }));
							if (topic === "workflows" && !self.__hasLocalWorkflowExecution() && !self.#warnedStrandedLocalWorkflowIds.has(wfId ?? "")) {
								self.#warnedStrandedLocalWorkflowIds.add(wfId ?? "");
								self.getLogger()?.warn(`Workflow event "${event.type}" for workflow "${wfId}" (run "${rId}") is local to this process, but this process has no running workflow workers, so the event will not be processed. Start workers in this process (mastra.startWorkers()) to run it.`);
							}
							return target.publish(topic, event, { localOnly: true });
						}
					} else if (isRunLocalTopic(topic)) return target.publish(topic, event, { localOnly: true });
					return target.publish(topic, event);
				};
				const val = Reflect.get(target, prop, target);
				if (typeof val === "function") return val.bind(target);
				return val;
			} });
		}
		return this.#pubsubProxy;
	}
	get agentThreadStreamRuntime() {
		return agentThreadStreamRuntime;
	}
	get workers() {
		return this.#workers;
	}
	getWorker(name) {
		return this.#workers.find((w) => w.name === name);
	}
	/** Returns a serializable snapshot of this instance's active worker configuration. */
	getWorkerConfig() {
		const runningWorkerNames = new Set(this.#workers.filter((worker) => worker.isRunning).map((worker) => worker.name));
		return {
			version: 1,
			orchestration: { enabled: runningWorkerNames.has("orchestration") },
			scheduler: {
				...serializableWorkerConfig(this.#schedulerConfig),
				enabled: runningWorkerNames.has("scheduler")
			},
			backgroundTasks: {
				...serializableWorkerConfig(this.#backgroundTaskConfig),
				enabled: runningWorkerNames.has("backgroundTasks")
			},
			custom: [...runningWorkerNames].filter((name) => ![
				"orchestration",
				"scheduler",
				"backgroundTasks"
			].includes(name)).sort()
		};
	}
	get backgroundTaskManager() {
		return this.#backgroundTaskManager;
	}
	/**
	* Returns the workflow scheduler owned by the SchedulerWorker,
	* or undefined if the scheduler is not enabled / not yet started.
	*
	* It is created when worker startup detects scheduling work, or lazily when
	* a schedule is created after boot.
	*
	* This is runtime plumbing (the cron tick loop). To create, list, pause,
	* resume, or delete schedules use `mastra.schedules` instead.
	*
	* @internal
	*/
	get scheduler() {
		return this.#findSchedulerWorker()?.scheduler;
	}
	get datasets() {
		if (!this.#datasets) this.#datasets = new DatasetsManager(this);
		return this.#datasets;
	}
	/**
	* Gets the currently configured ID generator function.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   idGenerator: context =>
	*     context?.idType === 'message' && context.threadId
	*       ? `msg-${context.threadId}-${Date.now()}`
	*       : `custom-${Date.now()}`
	* });
	* const generator = mastra.getIdGenerator();
	* console.log(generator?.({ idType: 'message', threadId: 'thread-123' })); // \"msg-thread-123-1234567890\"
	* ```
	*/
	getIdGenerator() {
		return this.#idGenerator;
	}
	/**
	* Gets the currently configured editor instance.
	* The editor is responsible for handling agent instantiation and configuration.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   editor: new MastraEditor({ logger })
	* });
	* const editor = mastra.getEditor();
	* ```
	*/
	getEditor() {
		return this.#editor;
	}
	/**
	* Gets a registered channel provider by its key.
	*
	* @example
	* ```typescript
	* import { SlackProvider } from '@mastra/slack';
	* const slack = mastra.getChannelProvider<SlackProvider>('slack');
	* ```
	*/
	getChannelProvider(key) {
		return this.#channels?.[key];
	}
	/**
	* Gets all registered channel providers.
	*
	* When channels were configured with a {@link ChannelsResolver}, this
	* returns the latest resolved snapshot (possibly `undefined` before the
	* first resolution completes). Use {@link resolveChannels} to get the
	* current provider map.
	*/
	getChannelProviders() {
		return this.#channels;
	}
	/**
	* Resolves the current channel provider map.
	*
	* For a static `channels` record this returns it directly. For a
	* {@link ChannelsResolver} it invokes the resolver (the resolver owns
	* freshness via its own cache/TTL), attaches and initializes any providers
	* not seen before, and updates the synchronous snapshot served by
	* {@link getChannelProviders} / {@link channels}.
	*
	* Server handlers that act on channels (webhooks, connect/disconnect,
	* listings) should await this instead of reading the snapshot so
	* connections added after boot are picked up.
	*/
	async resolveChannels() {
		const resolver = this.#channelsResolver;
		if (!resolver) return this.#channels ?? {};
		if (this.#channelsResolvePromise) return this.#channelsResolvePromise;
		const promise = (async () => {
			const resolved = await resolver({ mastra: this });
			for (const [key, provider] of Object.entries(resolved)) {
				if (provider == null || this.#attachedChannelProviders.has(provider)) continue;
				this.#attachedChannelProviders.add(provider);
				provider.__attach?.(this);
				if (provider.initialize) provider.initialize().catch((err) => {
					this.#logger?.error(`[Mastra] Failed to initialize channel "${key}":`, err);
				});
			}
			this.#channels = resolved;
			return resolved;
		})().finally(() => {
			this.#channelsResolvePromise = void 0;
		});
		this.#channelsResolvePromise = promise;
		return promise;
	}
	/**
	* Shorthand getter for platform channels.
	* Usage: `mastra.channels.slack.connect(agentId)`
	*/
	get channels() {
		return this.#channels ?? {};
	}
	/**
	* Canonical entrypoint for schedules — recurring agent or workflow runs
	* persisted as schedule rows discriminated by `target.type` (`'agent'` or
	* `'workflow'`). Use to create, list, update, pause/resume, manually fire,
	* or inspect trigger history for schedules across any agent or workflow.
	*
	* Lazily constructed. Operates against `getStorage()?.getStore('schedules')`.
	*
	* @example
	* ```ts
	* const schedule = await mastra.schedules.create({
	*   agentId: 'pinger',
	*   name: 'morning-checkin',
	*   cron: '0 9 * * *',
	*   prompt: 'good morning, anything to report?',
	*   threadId: 't1',
	*   resourceId: 'u1',
	* });
	* await mastra.schedules.list({ agentId: 'pinger' });
	* ```
	*/
	get schedules() {
		this.#schedules ??= new Schedules(this);
		return this.#schedules;
	}
	/**
	* Returns the schedule lifecycle hook bundle configured via
	* `new Mastra({ schedules: { ... } })`, if any. A single bundle runs for
	* every agent-schedule fire; hooks branch per agent via the `agentId` on
	* each context. Internal: consumed by the {@link AgentScheduleWorker} to
	* invoke `prepare`, `onFinish`, `onError`, and `onAbort` around
	* schedule-driven runs.
	*
	* @internal
	*/
	__getScheduleHooks() {
		return this.#schedulesConfig;
	}
	/**
	* Returns the global version overrides configured on this Mastra instance.
	* These are used as defaults when resolving sub-agent versions during delegation.
	*/
	getVersionOverrides() {
		return this.#versions;
	}
	/**
	* Returns the deployment environment name configured on this Mastra instance.
	* When unset, resolves to `'development'` for `mastra dev` runs (detected via
	* `MASTRA_DEV`), then falls back to `process.env.NODE_ENV`, or `undefined` if
	* none are provided.
	*
	* Observability automatically reads this and attaches it to all signals so
	* consumers can filter by environment without passing
	* `tracingOptions.metadata.environment` on each call.
	*/
	getEnvironment() {
		return this.#environment;
	}
	getToolPayloadTransform() {
		return this.#toolPayloadTransform;
	}
	/**
	* Gets the stored agents cache
	* @internal
	*/
	getStoredAgentCache() {
		return this.#storedAgentsCache;
	}
	/**
	* Gets the stored scorers cache
	* @internal
	*/
	getStoredScorerCache() {
		return this.#storedScorersCache;
	}
	/**
	* Generates a unique identifier using the configured generator or defaults to `crypto.randomUUID()`.
	*
	* This method is used internally by Mastra for creating unique IDs for various entities
	* like workflow runs, agent conversations, and other resources that need unique identification.
	*
	* @param context - Optional context information about what type of ID is being generated
	*                  and where it's being requested from. This allows custom ID generators
	*                  to create deterministic IDs based on context.
	*
	* @throws {MastraError} When the custom ID generator returns an empty string
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const id = mastra.generateId();
	* console.log(id); // "550e8400-e29b-41d4-a716-446655440000"
	*
	* // With context for deterministic IDs
	* const messageId = mastra.generateId({
	*   idType: 'message',
	*   source: 'agent',
	*   threadId: 'thread-123'
	* });
	* ```
	*/
	generateId(context) {
		if (this.#idGenerator) {
			const id = this.#idGenerator(context);
			if (!id) {
				const error = new MastraError({
					id: "MASTRA_ID_GENERATOR_RETURNED_EMPTY_STRING",
					domain: ErrorDomain.MASTRA,
					category: ErrorCategory.USER,
					text: "ID generator returned an empty string, which is not allowed"
				});
				this.#logger?.trackException(error);
				throw error;
			}
			return id;
		}
		return globalThis.crypto.randomUUID();
	}
	/**
	* Sets a custom ID generator function for creating unique identifiers.
	*
	* The ID generator function will be used by `generateId()` instead of the default
	* `crypto.randomUUID()`. This is useful for creating application-specific ID formats
	* or integrating with existing ID generation systems. The function receives
	* optional context about what is requesting the ID.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* mastra.setIdGenerator(context =>
	*   context?.idType === 'run' && context.entityId
	*     ? `run-${context.entityId}-${Date.now()}`
	*     : `custom-${Date.now()}`
	* );
	* const id = mastra.generateId({ idType: 'run', entityId: 'agent-123' });
	* console.log(id); // "run-agent-123-1234567890"
	* ```
	*/
	setIdGenerator(idGenerator) {
		this.#idGenerator = idGenerator;
	}
	/**
	* Sets the server configuration for this Mastra instance.
	*
	* @param server - The server configuration object
	*
	* @example
	* ```typescript
	* mastra.setServer({ ...mastra.getServer(), auth: new MastraAuthWorkos() });
	* ```
	*/
	setServer(server) {
		this.#server = normalizeServerConfig(server);
	}
	/**
	* Sets the studio configuration for this Mastra instance.
	*
	* The studio configuration controls authentication and authorization for Studio UI,
	* separate from the server configuration. This enables dual auth patterns where
	* Studio users (e.g., internal team) use different auth than API consumers.
	*
	* @param studio - The studio configuration object
	*
	* @example
	* ```typescript
	* // Set studio auth separately from server auth
	* mastra.setStudio({
	*   auth: new MastraAuthStudio(),
	*   rbac: new MastraRBACStudio({ roleMapping: { admin: ['*'] } }),
	* });
	* ```
	*/
	setStudio(studio) {
		this.#studio = studio;
	}
	/**
	* Registers an exporter on the default observability instance.
	*
	* If the current observability is a no-op (user didn't configure any), it is
	* first replaced with the provided entrypoint and the instance is registered
	* as default. If a real observability entrypoint already exists, the exporter
	* is added directly to the existing default instance.
	*
	* @param exporter - The exporter to register (e.g. a MastraPlatformExporter)
	* @param instance - An ObservabilityInstance pre-configured with the exporter, used as default when bootstrapping
	* @param entrypoint - A real ObservabilityEntrypoint to bootstrap if the current one is a no-op
	*/
	registerExporter(exporter, instance, entrypoint) {
		if (this.#observability instanceof NoOpObservability) {
			this.#observability = entrypoint;
			this.#observability.setLogger({ logger: this.#observabilitySafeLogger() });
			this.#observability.setMastraContext({ mastra: this });
			this.#observability.registerInstance("default", instance, true);
		}
		const defaultInstance = this.#observability.getDefaultInstance();
		if (defaultInstance?.registerExporter) defaultInstance.registerExporter(exporter);
	}
	/**
	* Creates a new Mastra instance with the provided configuration.
	*
	* The constructor initializes all the components specified in the config, sets up
	* internal systems like logging and observability, and registers components with each other.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   agents: {
	*     assistant: new Agent({
	*       id: 'assistant',
	*       name: 'Assistant',
	*       instructions: 'You are a helpful assistant',
	*       model: 'openai/gpt-5'
	*     })
	*   },
	*   storage: new PostgresStore({
	*     connectionString: process.env.DATABASE_URL
	*   }),
	*   logger: new PinoLogger({ name: 'MyApp' }),
	*   observability: new Observability({
	*     configs: { default: { serviceName: 'mastra', exporters: [new MastraStorageExporter()] } },
	*   }),
	* });
	* ```
	*/
	constructor(config) {
		initContextStorage();
		this.#serverCache = config?.cache ?? new InMemoryServerCache();
		this.#recoveryConfig = {
			workflows: config?.recovery?.workflows ?? "auto",
			workflowConcurrency: normalizeConcurrency(config?.recovery?.workflowConcurrency),
			workflowGraceMs: normalizeGraceMs(config?.recovery?.workflowGraceMs, DEFAULT_WORKFLOW_GRACE_MS),
			workflowScanIntervalMs: normalizeScanIntervalMs(config?.recovery?.workflowScanIntervalMs),
			durableAgents: config?.recovery?.durableAgents ?? "off"
		};
		this.#recoveryRestarts = createConcurrencyLimiter(this.#recoveryConfig.workflowConcurrency);
		this.#editor = config?.editor;
		this.#versions = config?.versions;
		this.#environment = config?.environment ?? (process.env.MASTRA_DEV === "true" ? "development" : process.env.NODE_ENV);
		this.#toolPayloadTransform = normalizeToolPayloadTransformPolicy(config?.transform ?? config?.toolPayloadProjection);
		if (config?.pubsub) this.#pubsub = config.pubsub;
		else this.#pubsub = new EventEmitterPubSub();
		this.#events = {};
		for (const topic in config?.events ?? {}) if (!Array.isArray(config?.events?.[topic])) this.#events[topic] = [config?.events?.[topic]];
		else this.#events[topic] = config?.events?.[topic] ?? [];
		const rawWorkersEnv = process.env.MASTRA_WORKERS;
		let workersOption;
		if (rawWorkersEnv === "false") workersOption = false;
		else {
			workersOption = config?.workers;
			if (rawWorkersEnv && rawWorkersEnv !== "false") {
				const names = rawWorkersEnv.split(",").map((s) => s.trim()).filter(Boolean);
				if (names.length > 0) this.#workerFilter = new Set(names);
			}
		}
		if (workersOption === false) this.#workersDisabled = true;
		else {
			const pubsubModes = this.#pubsub.supportedModes ?? ["pull"];
			const defaultWorkers = [];
			if (pubsubModes.includes("pull")) defaultWorkers.push(new OrchestrationWorker());
			if (config?.backgroundTasks?.enabled) defaultWorkers.push(new BackgroundTaskWorker(config.backgroundTasks));
			const customWorkers = workersOption ?? [];
			const customNames = /* @__PURE__ */ new Set();
			for (const w of customWorkers) {
				if (customNames.has(w.name)) throw new Error(`Duplicate worker name "${w.name}" in the 'workers' option`);
				customNames.add(w.name);
			}
			this.#workers = [...defaultWorkers.filter((w) => !customNames.has(w.name)), ...customWorkers];
			for (const w of this.#workers) w.__registerMastra(this);
		}
		let logger;
		if (config?.logger === false) {
			logger = noopLogger;
			this.#loggerExplicit = true;
		} else if (config?.logger) {
			logger = config.logger;
			this.#loggerExplicit = true;
		} else {
			const levelOnEnv = process.env.NODE_ENV === "production" && process.env.MASTRA_DEV !== "true" ? LogLevel.WARN : LogLevel.INFO;
			logger = new ConsoleLogger({
				name: "Mastra",
				level: levelOnEnv
			});
		}
		this.#logger = logger;
		this.#idGenerator = config?.idGenerator;
		let storage;
		if (config?.storage) {
			storage = config.storage;
			this.#storageExplicit = true;
		} else {
			storage = new InMemoryStore();
			this.#storageFallbackWarningPending = true;
			queueMicrotask(() => {
				if (!this.#storageFallbackWarningPending) return;
				this.#storageFallbackWarningPending = false;
				this.#logger?.warn("No `storage` configured on Mastra — falling back to an in-memory store. In-memory storage is not durable: all data is lost on restart, and it is not safe for production. Configure a persistent storage adapter (e.g. @mastra/libsql, @mastra/pg, @mastra/cloudflare). See https://mastra.ai/docs/storage");
			});
		}
		this.#storageSource = getStorageSource(storage);
		storage = augmentWithInit(storage);
		if (storage.stores) {
			if (!storage.stores.workflows || !storage.stores.backgroundTasks) {
				const fallbackDb = new InMemoryDB();
				if (!storage.stores.workflows) storage.stores.workflows = new WorkflowsInMemory({ db: fallbackDb });
				if (!storage.stores.backgroundTasks) storage.stores.backgroundTasks = new BackgroundTasksInMemory({ db: fallbackDb });
			}
		}
		if (config?.observability) {
			this.#observabilityExplicit = true;
			if (typeof config.observability.getDefaultInstance === "function") {
				this.#observability = config.observability;
				this.#observability.setLogger({ logger: this.#observabilitySafeLogger() });
			} else {
				this.#logger?.warn("Observability configuration error: Expected an Observability instance, but received a config object. Import and instantiate: import { Observability, MastraStorageExporter } from \"@mastra/observability\"; then pass: observability: new Observability({ configs: { default: { serviceName: \"mastra\", exporters: [new MastraStorageExporter()] } } }). Observability has been disabled.");
				this.#observability = new NoOpObservability();
			}
		} else this.#observability = new NoOpObservability();
		this.#loggerAdapterOptions = {
			correlation: config?.loggerOptions?.correlation ?? true,
			export: config?.loggerOptions?.export ?? true
		};
		this.#logger = this.#wireLoggerObservability(this.#logger);
		this.#vectors = {};
		this.#mcpServers = {};
		this.#tts = {};
		this.#agents = {};
		this.#scorers = {};
		this.#classifiers = {};
		this.#tools = {};
		this.#processors = {};
		this.#memory = {};
		this.#knowledge = {};
		this.#workflows = {};
		this.#gateways = {};
		this.#storage = storage;
		storage?.__registerMastra?.(this);
		if (this.#editor && typeof this.#editor.registerWithMastra === "function") this.#editor.registerWithMastra(this);
		if (process.env.MASTRA_LICENSE_KEY || process.env.MASTRA_EE_LICENSE) LicenseClient.getInstance(this.#logger).validate().catch(() => {});
		this.#backgroundTaskConfig = config?.backgroundTasks;
		const bgWorkerFiltered = this.#workerFilter && !this.#workerFilter.has("backgroundTasks");
		this.#ensureBackgroundTaskManager(workersOption === false || bgWorkerFiltered ? "producer" : void 0);
		this.#schedulerConfig = config?.scheduler;
		this.#notificationDispatchConfig = config?.notifications?.dispatch;
		this.#schedulesConfig = config?.schedules;
		if (config?.tools) Object.entries(config.tools).forEach(([key, tool]) => {
			if (tool != null) this.addTool(tool, key);
		});
		if (config?.processors) Object.entries(config.processors).forEach(([key, processor]) => {
			if (processor != null) this.addProcessor(processor, key);
		});
		if (config?.classifiers) Object.entries(config.classifiers).forEach(([key, classifier]) => {
			if (classifier != null) this.addClassifier(classifier, key);
		});
		if (config?.memory) Object.entries(config.memory).forEach(([key, memory]) => {
			if (memory != null) this.addMemory(memory, key);
		});
		if (config?.knowledge) Object.entries(config.knowledge).forEach(([key, knowledge]) => {
			if (knowledge != null) this.addKnowledge(knowledge, key);
		});
		if (config?.vectors) Object.entries(config.vectors).forEach(([key, vector]) => {
			if (vector != null) this.addVector(vector, key);
		});
		if (config?.workspace) {
			this.#workspace = config.workspace;
			this.addWorkspace(config.workspace, void 0, { source: "mastra" });
		}
		if (config?.scorers) Object.entries(config.scorers).forEach(([key, scorer]) => {
			if (scorer != null) this.addScorer(scorer, key, { source: "code" });
		});
		if (this.#notificationDispatchConfig?.enabled !== false) {
			const workflow = createNotificationDispatchWorkflow(this.#notificationDispatchConfig);
			this.addWorkflow(workflow, workflow.id);
			this.#hiddenWorkflowKeys.add(workflow.id);
		}
		if (config?.workflows) Object.entries(config.workflows).forEach(([key, workflow]) => {
			if (workflow != null) this.addWorkflow(workflow, key);
		});
		if (config?.gateways) Object.entries(config.gateways).forEach(([key, gateway]) => {
			if (gateway != null) this.addGateway(gateway, key);
		});
		for (const gateway of defaultGateways) {
			const key = getGatewayId(gateway);
			if (!Object.values(this.#gateways).some((existingGateway) => existingGateway != null && getGatewayId(existingGateway) === key)) this.#gateways[key] = gateway;
		}
		if (config?.mcpServers) Object.entries(config.mcpServers).forEach(([key, server]) => {
			if (server != null) this.addMCPServer(server, key);
		});
		if (config?.tts) Object.entries(config.tts).forEach(([key, tts]) => {
			if (tts != null) this.#tts[key] = tts;
		});
		if (config?.server) {
			this.#server = normalizeServerConfig(config.server);
			this.#serverExplicit = true;
		}
		if (config?.studio) {
			this.#studio = config.studio;
			this.#studioExplicit = true;
		}
		if (config?.channels) {
			const channelRoutes = [];
			if (typeof config.channels === "function") {
				this.#channelsResolver = config.channels;
				channelRoutes.push(...config.channels.getRoutes());
			} else {
				this.#channels = config.channels;
				for (const [, channel] of Object.entries(config.channels)) {
					if (channel == null) continue;
					if (channel.__attach) channel.__attach(this);
					const routes = channel.getRoutes();
					channelRoutes.push(...routes);
				}
			}
			if (channelRoutes.length > 0) {
				const existingRoutes = this.#server?.apiRoutes ?? [];
				this.#server = {
					...this.#server,
					apiRoutes: [...existingRoutes, ...channelRoutes]
				};
			}
		}
		if (config?.agents) Object.entries(config.agents).forEach(([key, agent]) => {
			if (agent != null) this.addAgent(agent, key);
		});
		const agentControllerEntries = {
			...config?.harnesses ?? {},
			...config?.agentControllers ?? {}
		};
		for (const [key, agentController] of Object.entries(agentControllerEntries)) {
			this.#harnesses[key] = agentController;
			agentController.__registerMastra(this);
			const controllerChannels = agentController.getChannels();
			if (controllerChannels) {
				controllerChannels.__setLogger(this.#logger);
				const channelRoutes = controllerChannels.getWebhookRoutes();
				if (channelRoutes.length > 0) this.#server = {
					...this.#server,
					apiRoutes: [...this.#server?.apiRoutes ?? [], ...channelRoutes]
				};
				controllerChannels.initialize(this).catch((err) => {
					this.#logger?.error(`Failed to initialize channels for agent controller ${key}:`, err);
				});
			}
		}
		if (!config?.__ephemeral) {
			this.#onScorerHook = createOnScorerHook(this);
			registerHook("onScorerRun", this.#onScorerHook);
		}
		this.#observability.setMastraContext({ mastra: this });
		this.setLogger({ logger });
		if (this.#channelsResolver) this.resolveChannels().catch((err) => {
			this.#logger?.warn(`[Mastra] Initial channels resolution failed (will retry on next access):`, err);
		});
		if (this.#channels) Promise.resolve().then(async () => {
			for (const [key, channel] of Object.entries(this.#channels ?? {})) if (channel.initialize) try {
				await channel.initialize();
			} catch (err) {
				console.error(`[Mastra] Failed to initialize channel "${key}":`, err);
			}
		});
	}
	#ensureBackgroundTaskManager(modeOverride) {
		if (!this.#backgroundTaskConfig?.enabled || !this.#storage || this.#backgroundTaskManager) return;
		const effectiveMode = modeOverride ?? (this.#workersDisabled || this.#workerFilter && !this.#workerFilter.has("backgroundTasks") ? "producer" : void 0);
		const managerConfig = effectiveMode ? {
			...this.#backgroundTaskConfig,
			mode: effectiveMode
		} : this.#backgroundTaskConfig;
		const bgManager = new BackgroundTaskManager(managerConfig);
		bgManager.__registerMastra(this);
		this.#backgroundTaskManager = bgManager;
		const tools = this.#tools;
		if (tools) for (const [name, tool] of Object.entries(tools)) this.#registerToolWithBackgroundManager(name, tool);
		bgManager.init(this.#pubsub).catch((error) => {
			this.#logger?.error("Failed to initialize background task manager", error);
		});
	}
	/**
	* Build a `ToolExecutor` adapter for a Mastra-registered tool and stash it
	* on the background task manager's static registry. Skipped if the tool has
	* no `execute` (declarative-only tools, e.g. MCP descriptors).
	*/
	#registerToolWithBackgroundManager(name, tool) {
		if (!this.#backgroundTaskManager) return;
		if (typeof tool.execute !== "function") return;
		const execute = tool.execute.bind(tool);
		this.#backgroundTaskManager.registerStaticExecutor(name, { execute: async (args, options) => {
			return execute(args, {
				toolCallId: "",
				messages: [],
				abortSignal: options?.abortSignal
			});
		} });
	}
	/**
	* Returns the flat list of declarative schedules sourced from currently
	* registered workflows. Single-schedule workflows yield one entry keyed by
	* `wf_<encoded(workflowId)>`. Array-form workflows yield one entry per array
	* entry keyed by `wf_<encoded(workflowId)>__<encoded(scheduleId)>` so the
	* prefix uniquely identifies "all rows owned by this workflow's declarative
	* config" even when ids contain `__` or other delimiter-like characters.
	*/
	#collectDeclarativeSchedules() {
		const out = [];
		const workflows = this.#workflows;
		for (const workflow of Object.values(workflows ?? {})) {
			const configs = collectWorkflowScheduleConfigs(workflow);
			if (configs.length === 0) continue;
			const isArrayForm = configs.length > 1 || configs.length === 1 && configs[0].id !== void 0;
			for (const cfg of configs) {
				const scheduleId = isArrayForm ? declarativeScheduleRowId(workflow.id, cfg.id) : declarativeScheduleRowId(workflow.id);
				const legacyScheduleId = isArrayForm ? legacyDeclarativeScheduleRowId(workflow.id, cfg.id) : legacyDeclarativeScheduleRowId(workflow.id);
				out.push({
					scheduleId,
					legacyScheduleId,
					workflowId: workflow.id,
					cfg
				});
			}
		}
		return out;
	}
	/**
	* Resolve the handler for a handler-mode file-based schedule. Handlers are
	* functions and therefore cannot be persisted on the JSON schedule row, so
	* the agent-schedule worker looks them up in-process by row id at fire time.
	*
	* @internal — public so the agent-schedule worker can call it.
	*/
	__getFsAgentScheduleHandler(scheduleId) {
		return findFsAgentScheduleHandler(this.#agents, scheduleId);
	}
	/**
	* True when the app opted out of the scheduler for the whole instance,
	* either with `workers: false` or with `scheduler: { enabled: false }`.
	*
	* `workers: false` disables all event processing in this instance, so never
	* auto-inject scheduler / agent-schedule workers (even when a schedule is
	* created at runtime). Standalone workers run the scheduler separately.
	*
	* Nothing can start the scheduler while this is true, so callers must also
	* skip the storage reads that only exist to request it (see #20550).
	*/
	#schedulerDisabled() {
		return this.#workersDisabled || this.#schedulerConfig?.enabled === false;
	}
	#shouldEnableScheduler() {
		if (this.#schedulerDisabled()) return false;
		if (this.#schedulerConfig?.enabled === true) return true;
		return this.#hasScheduledWorkflow || this.#schedulerRequested || hasFsAgentSchedule(this.#agents);
	}
	/**
	* Find the SchedulerWorker from the workers list (if present).
	*/
	#findSchedulerWorker() {
		return this.#workers.find((w) => w.name === "scheduler");
	}
	/**
	* Find the AgentScheduleWorker from the workers list (if present).
	*/
	#findAgentScheduleWorker() {
		return this.#workers.find((w) => w.name === "agent-schedule");
	}
	/**
	* Sync code-declared schedule configs to the database. Called by
	* SchedulerWorker during init and by addWorkflow() for late registrations.
	*
	* @internal — public so SchedulerWorker can call it, not part of the user API.
	*/
	async registerDeclarativeSchedules(schedulesStore) {
		const allRows = await schedulesStore.listSchedules();
		const rowsById = new Map(allRows.map((row) => [row.id, row]));
		const declared = this.#collectDeclarativeSchedules().map((entry) => {
			const legacyRow = rowsById.get(entry.legacyScheduleId);
			if (entry.legacyScheduleId !== entry.scheduleId && legacyRow?.target.type === "workflow" && legacyRow.target.workflowId === entry.workflowId) return {
				...entry,
				scheduleId: entry.legacyScheduleId
			};
			return entry;
		});
		const declaredIds = new Set(declared.map((d) => d.scheduleId));
		const declaredIdsByWorkflow = /* @__PURE__ */ new Map();
		const workflows = this.#workflows;
		const workflowsById = /* @__PURE__ */ new Map();
		for (const workflow of Object.values(workflows ?? {})) {
			declaredIdsByWorkflow.set(workflow.id, /* @__PURE__ */ new Set());
			workflowsById.set(workflow.id, workflow);
		}
		for (const { workflowId, scheduleId } of declared) {
			if (!declaredIdsByWorkflow.has(workflowId)) declaredIdsByWorkflow.set(workflowId, /* @__PURE__ */ new Set());
			declaredIdsByWorkflow.get(workflowId).add(scheduleId);
		}
		for (const { scheduleId, workflowId, cfg } of declared) try {
			const existing = rowsById.get(scheduleId);
			const now = Date.now();
			const target = {
				type: "workflow",
				workflowId,
				inputData: cfg.inputData,
				initialState: cfg.initialState,
				requestContext: cfg.requestContext
			};
			const definitionHash = computeScheduleDefinitionHash(workflowsById.get(workflowId)?.serializedStepGraph);
			if (definitionHash) target.definitionHash = definitionHash;
			const runAt = cfg.runAt !== void 0 ? toEpochMs(cfg.runAt) : void 0;
			const endAt = cfg.endAt !== void 0 ? toEpochMs(cfg.endAt) : void 0;
			const cron = cfg.cron ?? "";
			const computeTiming = () => {
				if (runAt !== void 0) return {
					nextFireAt: runAt,
					status: runAt > now ? "active" : "completed"
				};
				const next = computeNextFire({
					cron,
					timezone: cfg.timezone,
					endAt,
					nextFireAt: now
				}, now);
				return {
					nextFireAt: next.nextFireAt,
					status: next.completed ? "completed" : "active"
				};
			};
			if (!existing) {
				const timing = computeTiming();
				await schedulesStore.createSchedule({
					id: scheduleId,
					target,
					cron,
					timezone: cfg.timezone,
					...runAt !== void 0 ? { runAt } : {},
					...endAt !== void 0 ? { endAt } : {},
					status: timing.status,
					nextFireAt: timing.nextFireAt,
					createdAt: now,
					updatedAt: now,
					metadata: cfg.metadata
				});
				continue;
			}
			const patch = {};
			const cronChanged = existing.cron !== cron;
			const timezoneChanged = (existing.timezone ?? void 0) !== (cfg.timezone ?? void 0);
			const runAtChanged = (existing.runAt ?? void 0) !== runAt;
			const endAtChanged = (existing.endAt ?? void 0) !== endAt;
			if (cronChanged) patch.cron = cron;
			if (timezoneChanged) patch.timezone = cfg.timezone;
			if (runAtChanged) patch.runAt = runAt;
			if (endAtChanged) patch.endAt = endAt;
			if (!targetsEqual(existing.target, target)) patch.target = target;
			if (!metadataEqual(existing.metadata, cfg.metadata)) patch.metadata = cfg.metadata;
			if (cronChanged || timezoneChanged || runAtChanged || endAtChanged) {
				const timing = computeTiming();
				patch.nextFireAt = timing.nextFireAt;
				if (timing.status === "completed") patch.status = "completed";
				else if (existing.status === "completed") patch.status = "active";
			}
			if (Object.keys(patch).length > 0) await schedulesStore.updateSchedule(scheduleId, patch);
		} catch (error) {
			this.#logger?.error("Failed to register declarative schedule", {
				scheduleId,
				workflowId,
				error
			});
		}
		for (const row of allRows) {
			if (declaredIds.has(row.id)) continue;
			if (!row.id.startsWith("wf_")) continue;
			const targetWorkflowId = row.target.type === "workflow" ? row.target.workflowId : void 0;
			const failedOwnerId = targetWorkflowId && this.#failedDynamicWorkflowIds.has(targetWorkflowId) ? targetWorkflowId : ownerWorkflowIdForRow(row.id, this.#failedDynamicWorkflowIds);
			if (failedOwnerId !== void 0) {
				this.#logger?.warn?.(`Keeping declarative schedule "${row.id}": dynamic workflow "${failedOwnerId}" failed to load this boot.`);
				continue;
			}
			const ownerWorkflowId = targetWorkflowId ?? ownerWorkflowIdForRow(row.id, declaredIdsByWorkflow.keys()) ?? ownerWorkflowIdFromRowId(row.id);
			if (!ownerWorkflowId) continue;
			try {
				await schedulesStore.deleteSchedule(row.id);
			} catch (error) {
				this.#logger?.error("Failed to delete orphaned declarative schedule", {
					scheduleId: row.id,
					workflowId: ownerWorkflowId,
					error
				});
			}
		}
		await this.#registerFsAgentSchedules(schedulesStore, allRows);
		this.#findSchedulerWorker()?.scheduler?.wake();
	}
	/**
	* Sync schedules declared by file-based agents' `schedules/` directories into
	* schedule storage. Runs as part of {@link registerDeclarativeSchedules}, so
	* it happens on scheduler init and on late agent registration.
	*
	* The sync itself lives in `mastra/fs-agent-schedules.ts` — it needs only the
	* agent map, the store and a logger, so keeping it out of this file keeps the
	* upsert/diff/sweep policy readable on its own. Row equality goes through the
	* same `schedules/row-diff` comparators as the workflow sync above.
	*/
	async #registerFsAgentSchedules(schedulesStore, knownRows) {
		await syncFsAgentSchedules({
			agents: this.#agents,
			store: schedulesStore,
			logger: this.#logger,
			knownRows
		});
	}
	/**
	* Auto-enables the background task manager when an agent with sub-agents is
	* registered. Sub-agent delegation runs in the background by default so the
	* parent stream stays responsive; that requires the manager to be available.
	* No-op when the user explicitly opted out via `backgroundTasks.enabled: false`.
	*
	* Eligible agents: any agent whose `agents` field is either a static record
	* with at least one entry OR a dynamic (function-based) resolver. Function
	* resolvers are evaluated per request, so we can't inspect their contents
	* here — but if the caller bothered to wire one up, we enable defensively
	* so those resolved sub-agents also dispatch in the background.
	*/
	#maybeEnableBackgroundTasksForAgent(agent) {
		if (this.#backgroundTaskManager) return;
		if (this.#backgroundTaskConfig?.enabled === false) return;
		if (!agent.__hasSubAgentsConfigured?.()) return;
		this.#backgroundTaskConfig = {
			...this.#backgroundTaskConfig ?? {},
			enabled: true
		};
		this.#ensureBackgroundTaskManager();
	}
	getAgent(name, version) {
		const agent = this.#agents?.[name];
		if (!agent) {
			const error = new MastraError({
				id: "MASTRA_GET_AGENT_BY_NAME_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Agent with name ${String(name)} not found`,
				details: {
					status: 404,
					agentName: String(name),
					agents: Object.keys(this.#agents ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		if (!version) return this.#agents[name];
		return this.resolveVersionedAgent(agent, version);
	}
	/**
	* Returns the `AgentChannels` instances for all registered agents and
	* agent controllers. Keys are agent / agent controller registration keys.
	* A controller's channels — also attached to its mode agents — are
	* reported once, under the controller's key.
	*/
	getChannels() {
		const result = {};
		const controllerEntries = [];
		const controllerOwned = /* @__PURE__ */ new Set();
		for (const [controllerKey, controller] of Object.entries(this.#harnesses ?? {})) {
			const controllerChannels = controller.getChannels();
			if (controllerChannels) {
				controllerEntries.push([controllerKey, controllerChannels]);
				controllerOwned.add(controllerChannels);
			}
		}
		for (const [agentKey, agent] of Object.entries(this.#agents ?? {})) {
			const agentChannels = agent.getChannels();
			if (agentChannels instanceof AgentChannels && !controllerOwned.has(agentChannels)) result[agentKey] = agentChannels;
		}
		for (const [controllerKey, controllerChannels] of controllerEntries) {
			if (result[controllerKey]) this.#logger?.warn(`Channels key collision: an agent and an agent controller are both registered under '${controllerKey}'; reporting the controller's channels.`);
			result[controllerKey] = controllerChannels;
		}
		return result;
	}
	getAgentById(id, version) {
		let agent = Object.values(this.#agents).find((a) => a.id === id);
		if (!agent) try {
			agent = this.getAgent(id);
		} catch {}
		if (!agent) {
			const error = new MastraError({
				id: "MASTRA_GET_AGENT_BY_AGENT_ID_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Agent with id ${String(id)} not found`,
				details: {
					status: 404,
					agentId: String(id),
					agents: Object.keys(this.#agents ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		if (!version) return agent;
		return this.resolveVersionedAgent(agent, version);
	}
	/**
	* Resolve a versioned variant of an agent by applying stored overrides from the editor.
	*
	* Looking up a specific `versionId` requires the editor package to be
	* configured — throws `MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP` if
	* it is not. A `status` selector is a default rather than a request for a
	* specific stored version (the server stamps one on every agent request), so
	* without the editor there are no stored versions and the code-defined agent
	* is returned as-is.
	*
	* @param agent - The code-defined agent to resolve a version for.
	* @param version - Selects a version by ID or publication status.
	* @returns The code-defined agent for a status selector without an editor, otherwise a forked
	*   agent instance with the stored overrides applied.
	*/
	async resolveVersionedAgent(agent, version) {
		const editor = this.getEditor();
		if (!editor && !("versionId" in version)) return agent;
		if (!editor) {
			const error = new MastraError({
				id: "MASTRA_EDITOR_REQUIRED_FOR_VERSIONED_AGENT_LOOKUP",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: "Versioned agent lookup requires the editor package to be configured",
				details: {
					status: 400,
					agentId: agent.id,
					...version && "versionId" in version ? { versionId: version.versionId } : {},
					...version && "status" in version && version.status ? { versionStatus: version.status } : {}
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		const resolved = await editor.agent.applyStoredOverrides(agent, "versionId" in version ? version : { status: version.status ?? "published" });
		if (resolved !== agent) resolved.__markStoredVersionApplied();
		return resolved;
	}
	/**
	* Returns all registered agents as a record keyed by their names.
	*
	* This method provides access to the complete registry of agents, allowing you to
	* iterate over them, check what agents are available, or perform bulk operations.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   agents: {
	*     weatherAgent: new Agent({ id: 'weather-agent', name: 'weather', model: 'openai/gpt-4o' }),
	*     supportAgent: new Agent({ id: 'support-agent', name: 'support', model: 'openai/gpt-4o' })
	*   }
	* });
	*
	* const allAgents = mastra.listAgents();
	* console.log(Object.keys(allAgents)); // ['weatherAgent', 'supportAgent']
	* ```
	*/
	listAgents() {
		return this.#agents;
	}
	/**
	* Get an AgentController hosted on this Mastra instance by its registration
	* key (the key it was registered under in `new Mastra({ agentControllers })`).
	* Returns `undefined` when none is registered under that key. Server route
	* handlers use this to create and drive sessions over HTTP.
	*
	* @example
	* ```typescript
	* const code = new AgentController({ id: 'code-controller', modes });
	* const mastra = new Mastra({ agentControllers: { code } });
	*
	* mastra.getAgentController('code'); // → the AgentController (by key)
	* ```
	*/
	getAgentController(key) {
		return this.#harnesses[key];
	}
	/**
	* Get an AgentController hosted on this Mastra instance by its unique `id`
	* (the `id` passed to the `AgentController` constructor). Falls back to a
	* registration-key lookup when none matches by id, mirroring
	* {@link getAgentById}. Returns `undefined` when none is found.
	*
	* @example
	* ```typescript
	* const code = new AgentController({ id: 'code-controller', modes });
	* const mastra = new Mastra({ agentControllers: { code } });
	*
	* mastra.getAgentControllerById('code-controller'); // → by id
	* ```
	*/
	getAgentControllerById(id) {
		return Object.values(this.#harnesses).find((controller) => controller.id === id) ?? this.#harnesses[id];
	}
	/**
	* List all AgentControllers hosted on this Mastra instance, keyed by their
	* registration key.
	*/
	listAgentControllers() {
		return this.#harnesses;
	}
	/**
	* Get a Harness hosted on this Mastra instance by its registration key.
	*
	* @deprecated Use {@link Mastra.getAgentController} instead.
	*/
	getHarness(key) {
		return this.getAgentController(key);
	}
	/**
	* Get a Harness hosted on this Mastra instance by its unique `id`.
	*
	* @deprecated Use {@link Mastra.getAgentControllerById} instead.
	*/
	getHarnessById(id) {
		return this.getAgentControllerById(id);
	}
	/**
	* List all Harnesses hosted on this Mastra instance, keyed by their
	* registration key.
	*
	* @deprecated Use {@link Mastra.listAgentControllers} instead.
	*/
	listHarnesses() {
		return this.listAgentControllers();
	}
	/**
	* Adds a new agent to the Mastra instance.
	*
	* This method allows dynamic registration of agents after the Mastra instance
	* has been created. The agent will be initialized with the current logger.
	* Re-registering the same instance under the same key is a no-op. Rehydrating
	* a stored agent under an existing stored-agent key also leaves the original
	* registration unchanged.
	*
	* @throws {MastraError} When a different agent with the same key already exists,
	*   except when both registrations have source 'stored'
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const newAgent = new Agent({
	*   id: 'chat-agent',
	*   name: 'Chat Assistant',
	*   model: 'openai/gpt-4o'
	* });
	* mastra.addAgent(newAgent); // Uses agent.id as key
	* // or
	* mastra.addAgent(newAgent, 'customKey'); // Uses custom key
	*
	* // Durable agents (e.g., InngestAgent) are also supported:
	* const durableAgent = createInngestAgent({ agent: newAgent, inngest });
	* mastra.addAgent(durableAgent); // Auto-registers required workflows
	* ```
	*/
	addAgent(agent, key, options) {
		if (!agent) throw createUndefinedPrimitiveError("agent", agent, key);
		if (isDurableAgentLike(agent)) {
			const durableAgent = agent;
			const underlyingAgent = durableAgent.agent;
			const agentKey = key || durableAgent.id;
			const agents = this.#agents;
			if (agents[agentKey]) {
				if (Object.is(agents[agentKey], durableAgent)) return;
				throw new MastraError({
					id: "MASTRA_ADD_AGENT_DUPLICATE_KEY",
					domain: ErrorDomain.MASTRA,
					category: ErrorCategory.USER,
					text: `Agent with key ${agentKey} already exists`,
					details: {
						status: 409,
						key: agentKey
					}
				});
			}
			durableAgent.__setMastra?.(this);
			if (options?.source) {
				durableAgent.source = options.source;
				underlyingAgent.source = options.source;
			}
			underlyingAgent.__setLogger(this.#logger);
			underlyingAgent.__registerMastra(this);
			underlyingAgent.__registerPrimitives({
				logger: this.getLogger(),
				storage: this.getStorage(),
				agents,
				tts: this.#tts,
				vectors: this.#vectors
			});
			agents[agentKey] = durableAgent;
			const durableWorkflows = durableAgent.getDurableWorkflows?.() ?? [];
			for (const workflow of durableWorkflows) {
				this.addWorkflow(workflow, workflow.id);
				if (this.#workflows[workflow.id] === workflow) this.#hiddenWorkflowKeys.add(workflow.id);
			}
			underlyingAgent.getConfiguredProcessorWorkflows().then((processorWorkflows) => {
				for (const workflow of processorWorkflows) this.addWorkflow(workflow, workflow.id);
			}).catch((err) => {
				this.#logger?.debug(`Failed to register processor workflows for durable agent ${agentKey}:`, err);
			});
			if (underlyingAgent.hasOwnWorkspace?.()) Promise.resolve(underlyingAgent.getWorkspace?.()).then((workspace) => {
				if (workspace) this.addWorkspace(workspace, void 0, {
					source: "agent",
					agentId: durableAgent.id ?? agentKey,
					agentName: durableAgent.name,
					agentSource: underlyingAgent.source
				});
			}).catch((err) => {
				this.#logger?.debug(`Failed to register workspace for durable agent ${agentKey}:`, err);
			});
			underlyingAgent.listScorers().then((scorers) => {
				for (const [, entry] of Object.entries(scorers || {})) this.addScorer(entry.scorer, void 0, { source: "code" });
			}).catch((err) => {
				this.#logger?.debug(`Failed to register scorers from durable agent ${agentKey}:`, err);
			});
			if (this.#backgroundTaskManager) {
				const durableAgentId = durableAgent.id ?? agentKey;
				Promise.resolve(underlyingAgent.listTools()).then((agentTools) => {
					for (const [toolKey, tool] of Object.entries(agentTools || {})) if (tool && typeof tool.execute === "function") this.#registerToolWithBackgroundManager(`${durableAgentId}:${toolKey}`, tool);
				}).catch((err) => {
					this.#logger?.debug(`Failed to register durable agent tools for background tasks (agent ${agentKey}):`, err);
				});
			}
			const agentChannelsInstance = underlyingAgent.getChannels();
			if (agentChannelsInstance) {
				agentChannelsInstance.__setLogger(this.#logger);
				const channelRoutes = agentChannelsInstance.getWebhookRoutes();
				if (channelRoutes.length > 0) this.#server = {
					...this.#server,
					apiRoutes: [...this.#server?.apiRoutes ?? [], ...channelRoutes]
				};
				agentChannelsInstance.initialize(this).catch((err) => {
					this.#logger?.error(`Failed to initialize channels for durable agent ${agentKey}:`, err);
				});
			}
			this.#registerSignalProviderRoutes(underlyingAgent);
			this.#syncLateRegisteredAgentSchedules(underlyingAgent);
			return;
		}
		let mastraAgent;
		const toolLoopInput = isToolLoopAgentLike(agent) ? agent : void 0;
		if (toolLoopInput) mastraAgent = toolLoopAgentToMastraAgent(toolLoopInput, { fallbackName: key });
		else mastraAgent = agent;
		const agentKey = key || mastraAgent.id;
		const agents = this.#agents;
		if (agents[agentKey]) {
			if (agents[agentKey] === mastraAgent || toolLoopInput && this.#toolLoopRegistrations.get(toolLoopInput)?.get(agentKey) === agents[agentKey] || agents[agentKey].source === "stored" && options?.source === "stored") return;
			throw new MastraError({
				id: "MASTRA_ADD_AGENT_DUPLICATE_KEY",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Agent with key ${agentKey} already exists`,
				details: {
					status: 409,
					key: agentKey
				}
			});
		}
		if (options?.source) mastraAgent.source = options.source;
		mastraAgent.__setLogger(this.#logger);
		mastraAgent.__registerMastra(this);
		mastraAgent.__registerPrimitives({
			logger: this.getLogger(),
			storage: this.getStorage(),
			agents,
			tts: this.#tts,
			vectors: this.#vectors
		});
		agents[agentKey] = mastraAgent;
		if (toolLoopInput) {
			let registrations = this.#toolLoopRegistrations.get(toolLoopInput);
			if (!registrations) {
				registrations = /* @__PURE__ */ new Map();
				this.#toolLoopRegistrations.set(toolLoopInput, registrations);
			}
			registrations.set(agentKey, mastraAgent);
		}
		mastraAgent.getConfiguredProcessorWorkflows().then((processorWorkflows) => {
			for (const workflow of processorWorkflows) this.addWorkflow(workflow, workflow.id);
		}).catch((err) => {
			this.#logger?.debug(`Failed to register processor workflows for agent ${agentKey}:`, err);
		});
		if (mastraAgent.hasOwnWorkspace?.()) Promise.resolve(mastraAgent.getWorkspace?.()).then((workspace) => {
			if (workspace) this.addWorkspace(workspace, void 0, {
				source: "agent",
				agentId: mastraAgent.id ?? agentKey,
				agentName: mastraAgent.name,
				agentSource: mastraAgent.source
			});
		}).catch((err) => {
			this.#logger?.debug(`Failed to register workspace for agent ${agentKey}:`, err);
		});
		mastraAgent.listScorers().then((scorers) => {
			for (const [, entry] of Object.entries(scorers || {})) this.addScorer(entry.scorer, void 0, { source: "code" });
		}).catch((err) => {
			this.#logger?.debug(`Failed to register scorers from agent ${agentKey}:`, err);
		});
		if (this.#backgroundTaskManager) {
			const agentId = mastraAgent.id ?? agentKey;
			Promise.resolve(mastraAgent.listTools()).then((agentTools) => {
				for (const [toolKey, tool] of Object.entries(agentTools || {})) if (tool && typeof tool.execute === "function") this.#registerToolWithBackgroundManager(`${agentId}:${toolKey}`, tool);
			}).catch((err) => {
				this.#logger?.debug(`Failed to register agent tools for background tasks (agent ${agentKey}):`, err);
			});
		}
		const agentChannelsInstance = mastraAgent.getChannels();
		if (agentChannelsInstance) {
			agentChannelsInstance.__setLogger(this.#logger);
			const channelRoutes = agentChannelsInstance.getWebhookRoutes();
			if (channelRoutes.length > 0) this.#server = {
				...this.#server,
				apiRoutes: [...this.#server?.apiRoutes ?? [], ...channelRoutes]
			};
			agentChannelsInstance.initialize(this).catch((err) => {
				this.#logger?.error(`Failed to initialize channels for agent ${agentKey}:`, err);
			});
		}
		this.#registerSignalProviderRoutes(mastraAgent);
		this.#syncLateRegisteredAgentSchedules(mastraAgent);
	}
	/**
	* Merge routes from the agent's signal providers into `server.apiRoutes`.
	* Skips routes whose method and path are already registered, so a provider
	* shared by several agents only mounts its routes once and existing routes
	* win. Logs a warning when a route is skipped because something other than
	* the same provider already holds that method and path.
	*/
	#registerSignalProviderRoutes(agent) {
		const existingRoutes = this.#server?.apiRoutes ?? [];
		const newRoutes = [];
		for (const provider of agent.listSignalProviders?.() ?? []) for (const route of provider.getRoutes?.() ?? []) {
			const registered = [...existingRoutes, ...newRoutes].find((existing) => existing.path === route.path && existing.method === route.method);
			if (!registered) {
				newRoutes.push(route);
				this.#signalProviderRouteOwners.set(route, provider);
				continue;
			}
			if (this.#signalProviderRouteOwners.get(registered) !== provider) this.getLogger().warn(`Signal provider "${provider.id}" on agent "${agent.id}" declares ${route.method} ${route.path}, but that route is already registered. Skipping the provider route.`);
		}
		if (newRoutes.length > 0) this.#server = {
			...this.#server,
			apiRoutes: [...existingRoutes, ...newRoutes]
		};
	}
	/**
	* Remove routes added by a removed agent's signal providers, unless another
	* registered agent still uses the same provider instance.
	*/
	#unregisterSignalProviderRoutes(removedAgent) {
		const routes = this.#server?.apiRoutes;
		const removedProviders = new Set(this.#listAgentSignalProviders(removedAgent));
		if (!routes || removedProviders.size === 0) return;
		const providersInUse = new Set(Object.values(this.#agents).flatMap((agent) => this.#listAgentSignalProviders(agent)));
		const keptRoutes = routes.filter((route) => {
			const provider = this.#signalProviderRouteOwners.get(route);
			return !provider || !removedProviders.has(provider) || providersInUse.has(provider);
		});
		if (keptRoutes.length !== routes.length) this.#server = {
			...this.#server,
			apiRoutes: keptRoutes
		};
	}
	#listAgentSignalProviders(agent) {
		return (agent && isDurableAgentLike(agent) ? agent.agent : agent)?.listSignalProviders?.() ?? [];
	}
	/**
	* Push an agent's declared schedules into an already-running scheduler.
	*
	* Agents registered before `startWorkers()` are picked up by
	* `SchedulerWorker.init()`, which calls {@link registerDeclarativeSchedules}.
	* An agent added afterwards would otherwise never have its rows written, so
	* mirror what `addWorkflow` does for declarative workflow schedules.
	*
	* The sync covers every registered agent, so registering a batch (e.g.
	* `__registerFsAgents`) coalesces into a single sweep instead of one full
	* `listSchedules()` pass per agent.
	*/
	#syncLateRegisteredAgentSchedules(agent) {
		if (declaredSchedulesOf(agent).length === 0) return;
		if (!this.#findSchedulerWorker()?.scheduler) return;
		if (this.#fsScheduleSyncPending) {
			this.#fsScheduleSyncRerun = true;
			return;
		}
		this.#fsScheduleSyncPending = true;
		(async () => {
			try {
				do {
					this.#fsScheduleSyncRerun = false;
					await Promise.resolve();
					const schedulesStore = await this.#storage?.getStore("schedules");
					if (!schedulesStore) return;
					await this.registerDeclarativeSchedules(schedulesStore);
				} while (this.#fsScheduleSyncRerun);
			} catch (error) {
				this.#logger?.error("Failed to register schedules for late-registered agent", {
					agentId: agent.id,
					error
				});
			} finally {
				this.#fsScheduleSyncPending = false;
				this.#fsScheduleSyncRerun = false;
			}
		})();
	}
	/**
	* Registers a map of file-system routed agents (discovered from
	* `agents/<name>/` directories) into this Mastra instance.
	*
	* Code-registered agents win on name collisions: if an agent with the same
	* key already exists, the file-system agent is skipped and a warning is
	* logged. Otherwise each agent is added via {@link addAgent} with
	* `source: 'fs'`.
	*
	* Intended to be called by the bundler/dev generated entry, not by user code.
	*
	* @internal
	*/
	__registerFsAgents(fsAgents) {
		if (!fsAgents) return;
		const agents = this.#agents;
		let registeredCount = 0;
		for (const [key, agent] of Object.entries(fsAgents)) {
			if (agent == null) continue;
			if (agents[key]) {
				this.getLogger().warn(`File-system routed agent "${key}" conflicts with a code-registered agent of the same name. Keeping the code-registered agent.`);
				continue;
			}
			this.addAgent(agent, key, { source: "fs" });
			registeredCount++;
		}
		if (registeredCount > 0 && !this.#fsAgentUsageTracked) {
			this.#fsAgentUsageTracked = true;
			trackFeatureUsage("file_based_agents", { fs_agent_count: registeredCount });
		}
	}
	/**
	* Registers a map of file-system routed workflows (discovered from
	* `workflows/*.ts` files) into this Mastra instance.
	*
	* Code-registered workflows win on name collisions: if a workflow with the
	* same key already exists, the file-system workflow is skipped and a warning
	* is logged. Otherwise each workflow is added via {@link addWorkflow} with
	* its key.
	*
	* Intended to be called by the bundler/dev generated entry, not by user code.
	*
	* @internal
	*/
	__registerFsWorkflows(fsWorkflows) {
		if (!fsWorkflows) return;
		const workflows = this.#workflows;
		for (const [key, workflow] of Object.entries(fsWorkflows)) {
			if (workflow == null) continue;
			if (workflows[key]) {
				this.getLogger().warn(`File-system routed workflow "${key}" conflicts with a code-registered workflow of the same name. Keeping the code-registered workflow.`);
				continue;
			}
			this.addWorkflow(workflow, key);
		}
	}
	/**
	* Registers a file-system routed logger (discovered from `logger.ts`) into
	* this Mastra instance.
	*
	* Code-registered loggers win: if the user already passed `logger` to the
	* `new Mastra({logger})` constructor (including `logger: false`), the
	* file-system logger is skipped and a warning is logged. Otherwise the
	* fs-provided logger replaces the default ConsoleLogger via {@link setLogger}.
	*
	* Intended to be called by the bundler/dev generated entry, not by user code.
	*
	* @internal
	*/
	__registerFsLogger(fsLogger) {
		if (!fsLogger) return;
		if (this.#loggerExplicit) {
			this.getLogger().warn(`File-system routed logger conflicts with a code-registered logger. Keeping the code-registered logger.`);
			return;
		}
		this.setLogger({ logger: fsLogger });
	}
	/**
	* Registers a file-system routed storage instance (discovered from
	* `storage.ts`) into this Mastra instance.
	*
	* Code-registered storage wins: if the user already passed `storage` to the
	* `new Mastra({storage})` constructor, the file-system storage is skipped
	* and a warning is logged. Otherwise the fs-provided storage replaces the
	* default InMemoryStore via {@link setStorage}.
	*
	* Intended to be called by the bundler/dev generated entry, not by user code.
	*
	* @internal
	*/
	__registerFsStorage(fsStorage) {
		if (!fsStorage) return;
		if (this.#storageExplicit) {
			this.getLogger().warn(`File-system routed storage conflicts with a code-registered storage. Keeping the code-registered storage.`);
			return;
		}
		this.setStorage(fsStorage);
	}
	/**
	* Registers a file-system routed observability instance (discovered from
	* `observability.ts`) into this Mastra instance.
	*
	* Code-registered observability wins: if the user already passed
	* `observability` to the `new Mastra({observability})` constructor, the
	* file-system instance is skipped with a warning.
	*
	* @internal
	*/
	__registerFsObservability(fsObservability) {
		if (!fsObservability) return;
		if (this.#observabilityExplicit) {
			this.getLogger().warn(`File-system routed observability conflicts with a code-registered observability. Keeping the code-registered observability.`);
			return;
		}
		if (typeof fsObservability.getDefaultInstance !== "function") {
			this.getLogger().warn(`File-system routed observability.ts did not export a valid ObservabilityEntrypoint. Ignoring.`);
			return;
		}
		this.#observability = fsObservability;
		this.#observability.setLogger({ logger: this.#observabilitySafeLogger() });
		this.#observability.setMastraContext({ mastra: this });
	}
	/**
	* Registers a file-system routed server config (discovered from
	* `server.ts`) into this Mastra instance.
	*
	* Code-registered server config wins on collision.
	*
	* @internal
	*/
	__registerFsServer(fsServer) {
		if (!fsServer) return;
		if (this.#serverExplicit) {
			this.getLogger().warn(`File-system routed server config conflicts with a code-registered server config. Keeping the code-registered server config.`);
			return;
		}
		const fsRoutes = fsServer.apiRoutes ?? [];
		const mergedRoutes = [...(this.#server?.apiRoutes ?? []).filter((route) => {
			const provider = this.#signalProviderRouteOwners.get(route);
			if (!provider) return true;
			const overridden = fsRoutes.some((fsRoute) => fsRoute.path === route.path && fsRoute.method === route.method);
			if (overridden) this.getLogger().warn(`Signal provider "${provider.id}" route ${route.method} ${route.path} is overridden by a file-system route.`);
			return !overridden;
		}), ...fsRoutes];
		this.setServer({
			...fsServer,
			...mergedRoutes.length > 0 ? { apiRoutes: mergedRoutes } : {}
		});
	}
	/**
	* Registers a file-system routed studio config (discovered from
	* `studio.ts`) into this Mastra instance.
	*
	* Code-registered studio config wins on collision.
	*
	* @internal
	*/
	__registerFsStudio(fsStudio) {
		if (!fsStudio) return;
		if (this.#studioExplicit) {
			this.getLogger().warn(`File-system routed studio config conflicts with a code-registered studio config. Keeping the code-registered studio config.`);
			return;
		}
		this.setStudio(fsStudio);
	}
	/** Drops an agent's processor configurations; registering the agent again re-adds them. */
	#removeProcessorConfigurations(agentId) {
		for (const [processorId, configs] of this.#processorConfigurations) {
			const remaining = configs.filter((c) => c.agentId !== agentId);
			if (remaining.length === 0) this.#processorConfigurations.delete(processorId);
			else if (remaining.length !== configs.length) this.#processorConfigurations.set(processorId, remaining);
		}
	}
	/**
	* Removes an agent from the Mastra instance by its key or ID.
	* Used when stored agents are updated/deleted to allow fresh data to be loaded.
	*
	* @param keyOrId - The agent key or ID to remove
	* @returns true if an agent was removed, false if no agent was found
	*
	* @example
	* ```typescript
	* // Remove by key
	* mastra.removeAgent('myAgent');
	*
	* // Remove by ID
	* mastra.removeAgent('agent-123');
	* ```
	*/
	removeAgent(keyOrId) {
		const agents = this.#agents;
		if (agents[keyOrId]) {
			const removedAgent = agents[keyOrId];
			const agentId = removedAgent?.id;
			delete agents[keyOrId];
			this.#unregisterSignalProviderRoutes(removedAgent);
			if (agentId) {
				this.#storedAgentsCache.delete(agentId);
				this.#removeProcessorConfigurations(agentId);
			}
			return true;
		}
		const key = Object.keys(agents).find((k) => agents[k]?.id === keyOrId);
		if (key) {
			const removedAgent = agents[key];
			const agentId = removedAgent?.id;
			delete agents[key];
			this.#unregisterSignalProviderRoutes(removedAgent);
			if (agentId) {
				this.#storedAgentsCache.delete(agentId);
				this.#removeProcessorConfigurations(agentId);
			}
			return true;
		}
		this.#removeProcessorConfigurations(keyOrId);
		return false;
	}
	/**
	* Retrieves a registered vector store by its name.
	*
	* @template TVectorName - The specific vector store name type from the registered vectors
	* @throws {MastraError} When the vector store with the specified name is not found
	*
	* @example Using a vector store for semantic search
	* ```typescript
	* import { PineconeVector } from '@mastra/pinecone';
	* import { OpenAIEmbedder } from '@mastra/embedders';
	*
	* const mastra = new Mastra({
	*   vectors: {
	*     knowledge: new PineconeVector({
	*       apiKey: process.env.PINECONE_API_KEY,
	*       indexName: 'knowledge-base',
	*       embedder: new OpenAIEmbedder({
	*         apiKey: process.env.OPENAI_API_KEY,
	*         model: 'text-embedding-3-small'
	*       })
	*     }),
	*     products: new PineconeVector({
	*       apiKey: process.env.PINECONE_API_KEY,
	*       indexName: 'product-catalog'
	*     })
	*   }
	* });
	*
	* // Get a vector store and perform semantic search
	* const knowledgeBase = mastra.getVector('knowledge');
	* const results = await knowledgeBase.query({
	*   query: 'How to reset password?',
	*   topK: 5
	* });
	*
	* console.log('Relevant documents:', results);
	* ```
	*/
	getVector(name) {
		const vector = this.#vectors?.[name];
		if (!vector) {
			const error = new MastraError({
				id: "MASTRA_GET_VECTOR_BY_NAME_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Vector with name ${String(name)} not found`,
				details: {
					status: 404,
					vectorName: String(name),
					vectors: Object.keys(this.#vectors ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return vector;
	}
	/**
	* Retrieves a specific vector store instance by its ID.
	*
	* This method searches for a vector store by its internal ID property.
	* If not found by ID, it falls back to searching by registration key.
	*
	* @throws {MastraError} When the specified vector store is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   vectors: {
	*     embeddings: chromaVector
	*   }
	* });
	*
	* const vectorStore = mastra.getVectorById('chroma-123');
	* ```
	*/
	getVectorById(id) {
		const allVectors = this.#vectors ?? {};
		for (const vector of Object.values(allVectors)) if (vector.id === id) return vector;
		const vectorByKey = allVectors[id];
		if (vectorByKey) return vectorByKey;
		const error = new MastraError({
			id: "MASTRA_GET_VECTOR_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Vector store with id ${id} not found`,
			details: {
				status: 404,
				vectorId: String(id),
				vectors: Object.keys(allVectors).join(", ")
			}
		});
		this.#logger?.trackException(error);
		throw error;
	}
	/**
	* Returns all registered vector stores as a record keyed by their names.
	*
	* @example Listing all vector stores
	* ```typescript
	* const mastra = new Mastra({
	*   vectors: {
	*     documents: new PineconeVector({ indexName: 'docs' }),
	*     images: new PineconeVector({ indexName: 'images' }),
	*     products: new ChromaVector({ collectionName: 'products' })
	*   }
	* });
	*
	* const allVectors = mastra.getVectors();
	* console.log(Object.keys(allVectors)); // ['documents', 'images', 'products']
	*
	* // Check vector store types and configurations
	* for (const [name, vectorStore] of Object.entries(allVectors)) {
	*   console.log(`Vector store ${name}:`, vectorStore.constructor.name);
	* }
	* ```
	*/
	listVectors() {
		return this.#vectors;
	}
	/**
	* Adds a new vector store to the Mastra instance.
	*
	* This method allows dynamic registration of vector stores after the Mastra instance
	* has been created. The vector store will be initialized with the current logger.
	*
	* @throws {MastraError} When a vector store with the same key already exists
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const newVector = new ChromaVector({ id: 'chroma-embeddings' });
	* mastra.addVector(newVector); // Uses vector.id as key
	* // or
	* mastra.addVector(newVector, 'customKey'); // Uses custom key
	* ```
	*/
	addVector(vector, key) {
		if (!vector) throw createUndefinedPrimitiveError("vector", vector, key);
		const vectorKey = key || vector.id;
		const vectors = this.#vectors;
		if (vectors[vectorKey]) return;
		vector.__setLogger(this.#logger || this.getLogger());
		vectors[vectorKey] = vector;
	}
	/**
	* @deprecated Use listVectors() instead
	*/
	getVectors() {
		console.warn("getVectors() is deprecated. Use listVectors() instead.");
		return this.listVectors();
	}
	/**
	* Gets the currently configured deployment provider.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   deployer: new VercelDeployer({
	*     token: process.env.VERCEL_TOKEN,
	*     projectId: process.env.VERCEL_PROJECT_ID
	*   })
	* });
	*
	* const deployer = mastra.getDeployer();
	* if (deployer) {
	*   await deployer.deploy({
	*     name: 'my-mastra-app',
	*     environment: 'production'
	*   });
	* }
	* ```
	*/
	getDeployer() {
		return this.#deployer;
	}
	/**
	* Gets the global workspace instance.
	* Workspace provides file storage, skills, and code execution capabilities.
	* Agents inherit this workspace unless they have their own configured.
	*
	* @example
	* ```typescript
	* const workspace = mastra.getWorkspace();
	* if (workspace?.skills) {
	*   const skills = await workspace.skills.list();
	* }
	* ```
	*/
	getWorkspace() {
		return this.#workspace;
	}
	/**
	* Retrieves a registered workspace by its ID.
	*
	* @throws {MastraError} When the workspace with the specified ID is not found
	*
	* @example
	* ```typescript
	* const workspace = mastra.getWorkspaceById('workspace-123');
	* const files = await workspace.filesystem.readdir('/');
	* ```
	*/
	getWorkspaceById(id) {
		const entry = this.#workspaces[id];
		if (!entry) {
			const error = new MastraError({
				id: "MASTRA_GET_WORKSPACE_BY_ID_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Workspace with id ${id} not found`,
				details: {
					status: 404,
					workspaceId: id,
					availableIds: Object.keys(this.#workspaces).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return entry.workspace;
	}
	/**
	* Returns all registered workspaces as a record keyed by their IDs.
	*
	* @example
	* ```typescript
	* const workspaces = mastra.listWorkspaces();
	* for (const [id, entry] of Object.entries(workspaces)) {
	*   console.log(`Workspace ${id}: ${entry.workspace.name} (source: ${entry.source})`);
	* }
	* ```
	*/
	listWorkspaces() {
		return { ...this.#workspaces };
	}
	/**
	* Adds a new workspace to the Mastra instance.
	*
	* This method allows dynamic registration of workspaces after the Mastra instance
	* has been created. Workspaces are keyed by their ID.
	*
	* @example
	* ```typescript
	* const workspace = new Workspace({
	*   id: 'project-workspace',
	*   name: 'Project Workspace',
	*   filesystem: new LocalFilesystem({ rootPath: './workspace' })
	* });
	* mastra.addWorkspace(workspace);
	* ```
	*/
	addWorkspace(workspace, key, metadata) {
		if (!workspace) throw createUndefinedPrimitiveError("workspace", workspace, key);
		const source = metadata?.source ?? (metadata?.agentId || metadata?.agentName ? "agent" : "mastra");
		if (source === "agent" && (!metadata?.agentId || !metadata?.agentName)) throw new MastraError({
			id: "MASTRA_ADD_WORKSPACE_MISSING_AGENT_METADATA",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: "Agent workspaces must include agentId and agentName.",
			details: {
				status: 400,
				workspaceId: key || workspace.id
			}
		});
		const workspaceKey = key || workspace.id;
		if (this.#workspaces[workspaceKey]) return;
		this.#workspaces[workspaceKey] = {
			workspace,
			source,
			...metadata?.agentId ? { agentId: metadata.agentId } : {},
			...metadata?.agentName ? { agentName: metadata.agentName } : {},
			...source === "agent" && metadata?.agentSource ? { agentSource: metadata.agentSource } : {}
		};
	}
	/**
	* Removes a registered workspace by its ID.
	*
	* When `destroy` is true, the workspace is destroyed before it is removed from
	* the registry. If destruction fails, the workspace remains registered and the
	* error is rethrown.
	*
	* @example
	* ```typescript
	* await mastra.removeWorkspace('workspace-123', { destroy: true });
	* ```
	*/
	async removeWorkspace(id, options) {
		const entry = this.#workspaces[id];
		if (!entry) return false;
		if (options?.destroy) await entry.workspace.destroy();
		delete this.#workspaces[id];
		if (this.#workspace === entry.workspace) this.#workspace = void 0;
		return true;
	}
	/**
	* Retrieves a registered workflow by its ID.
	*
	* @template TWorkflowId - The specific workflow ID type from the registered workflows
	* @throws {MastraError} When the workflow with the specified ID is not found
	*
	* @example Getting and executing a workflow
	* ```typescript
	* import { createWorkflow, createStep } from '@mastra/core/workflows';
	* import { z } from 'zod/v4';
	*
	* const processDataWorkflow = createWorkflow({
	*   name: 'process-data',
	*   triggerSchema: z.object({ input: z.string() })
	* })
	*   .then(validateStep)
	*   .then(transformStep)
	*   .then(saveStep)
	*   .commit();
	*
	* const mastra = new Mastra({
	*   workflows: {
	*     dataProcessor: processDataWorkflow
	*   }
	* });
	* ```
	*/
	getWorkflow(id, { serialized } = {}) {
		const workflow = this.#workflows?.[id];
		if (!workflow) {
			const error = new MastraError({
				id: "MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Workflow with ID ${String(id)} not found`,
				details: {
					status: 404,
					workflowId: String(id),
					workflows: Object.keys(this.#workflows ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		if (serialized) return { name: workflow.name };
		return workflow;
	}
	/**
	* Track an in-flight evented workflow run owned by this instance so
	* {@link shutdown} can let it settle before tearing down pubsub. Returns a
	* release function the caller must invoke once the run has settled.
	*
	* @internal
	*/
	__trackEventedRun(execution) {
		execution.catch(() => {});
		this.#activeEventedRuns.add(execution);
		return () => {
			this.#activeEventedRuns.delete(execution);
		};
	}
	/**
	* Register a workflow under an internal-only registry.
	*
	* - Without `runId`: stored at the bare `${id}` slot. Used by single-instance
	*   internal workflows (background tasks, score-traces) that are looked up
	*   without a runId.
	* - With `runId`: stored *only* at `${id}:${runId}`. Concurrent or nested
	*   invocations that share a workflow id (e.g. a parent and a sub-agent both
	*   registering their `agentic-loop`) each get their own closure-bound
	*   instance keyed by run, and the bare `${id}` slot is never overwritten by
	*   a run-scoped registration — so a run-scoped lookup can never resolve a
	*   *different* run's instance via an id scan.
	*
	* Pass `{ distributed: true }` (unscoped only) when every process registers
	* the workflow identically, so any process's workers can execute its runs.
	* Its events then travel through the shared pubsub instead of being kept
	* local to the publishing process.
	*/
	__registerInternalWorkflow(workflow, runId, options) {
		workflow.__markInternal();
		workflow.__registerMastra(this);
		workflow.__registerPrimitives({ logger: this.getLogger() });
		if (runId) {
			const key = `${workflow.id}:${runId}`;
			const isNewRegistration = !this.#internalMastraWorkflows[key];
			this.#internalMastraWorkflows[key] = workflow;
			this.#runScopedWorkflowTimestamps.set(key, {
				lastActivityAt: Date.now(),
				runId
			});
			if (isNewRegistration) {
				this.#runScopeRefcounts.set(runId, (this.#runScopeRefcounts.get(runId) ?? 0) + 1);
				if (!this.#runScopes.has(runId)) this.#runScopes.set(runId, createRunScope());
			}
			this.#sweepStaleRunScopedWorkflows();
		} else {
			this.#internalMastraWorkflows[workflow.id] = workflow;
			if (options?.distributed) this.#distributedInternalWorkflowIds.add(workflow.id);
			else this.#distributedInternalWorkflowIds.delete(workflow.id);
		}
	}
	/**
	* Remove a runId-scoped registration. The unscoped `${id}` entry is left intact
	* so single-instance callers (background tasks, score-traces) continue to resolve.
	*
	* Decrements the refcount for the runScope tied to this runId; when the
	* count hits zero the scope is dropped along with every reference it held.
	*/
	__unregisterInternalWorkflow(id, runId) {
		const key = `${id}:${runId}`;
		const wasRegistered = !!this.#internalMastraWorkflows[key];
		delete this.#internalMastraWorkflows[key];
		this.#runScopedWorkflowTimestamps.delete(key);
		if (wasRegistered) this.#releaseRunScope(runId);
	}
	/**
	* Get the existing runScope for a runId without creating one.
	* Returns undefined when no internal workflow has been registered against
	* the runId — callers should treat this as the run not yet being bootstrapped.
	*/
	__getRunScope(runId) {
		return this.#runScopes.get(runId);
	}
	/**
	* Idempotently allocate a runScope for a runId. Used by call sites (like
	* `loop()`) that need to populate the scope *before* the internal workflow
	* registration lands. The scope is held until the matching internal-workflow
	* registration is released or the TTL sweep evicts it.
	*
	* Bumps the refcount so the scope cannot be freed before the caller is done
	* with it; callers MUST pair this with `__releaseRunScope(runId)`.
	*/
	__createRunScope(runId) {
		let scope = this.#runScopes.get(runId);
		if (!scope) {
			scope = createRunScope();
			this.#runScopes.set(runId, scope);
		}
		this.#runScopeRefcounts.set(runId, (this.#runScopeRefcounts.get(runId) ?? 0) + 1);
		return scope;
	}
	/**
	* Decrement the runScope refcount; drops the scope when the count reaches
	* zero. Public so callers that called `__createRunScope` directly (e.g.,
	* `loop()` hydration) can release their hold without unregistering a
	* workflow.
	*/
	__releaseRunScope(runId) {
		this.#releaseRunScope(runId);
	}
	#releaseRunScope(runId) {
		const next = (this.#runScopeRefcounts.get(runId) ?? 0) - 1;
		if (next <= 0) {
			this.#runScopeRefcounts.delete(runId);
			this.#runScopes.delete(runId);
		} else this.#runScopeRefcounts.set(runId, next);
	}
	/**
	* Whether this process consumes workflow-execution events itself, i.e.
	* whether a `workflow.start` published here would be handled here.
	*
	* True when a local OrchestrationWorker is pulling the `workflows` topic,
	* or when a push-only pubsub has `handleWorkflowEvent` wired directly
	* (`#wirePushWorkflowSubscription`).
	*
	* The scheduler uses this to keep a scheduled fire on the instance that
	* claimed it (#19169). Scheduler and execution workers start through
	* separate paths (`#startSchedulingWorkers` / `#startExecutionWorkers`),
	* so a scheduler-only process is a supported topology and must keep
	* publishing to the shared topic instead of stranding the fire locally.
	*
	* @internal
	*/
	__hasLocalWorkflowExecution() {
		if (this.#pushSubscription) return true;
		return !!this.#workers.find((w) => w.name === "orchestration")?.isRunning;
	}
	__hasInternalWorkflow(id, runId) {
		if (runId) {
			if (this.#internalMastraWorkflows[`${id}:${runId}`]) {
				this.#touchRunScopedWorkflow(id, runId);
				return true;
			}
			return !!this.#internalMastraWorkflows[id];
		}
		return !!this.#internalMastraWorkflows[id];
	}
	/**
	* Whether this internal workflow event must stay in this process. A
	* run-scoped registration always qualifies; an unscoped one does unless it
	* was registered `distributed`. A distributed workflow's `workflows` events
	* stay local on stores without atomic occurrence guards. Guarded stores
	* allow workers to publish reclaimable continuations through the broker.
	* Its `workflows-finish` events always cross, since
	* the process waiting for the result may not be the one that ran it.
	*/
	#isProcessLocalInternalWorkflow(id, runId, topic, guarded) {
		if (!this.__hasInternalWorkflow(id, runId)) return false;
		if (this.#internalMastraWorkflows[`${id}:${runId}`]) return true;
		if (!this.#distributedInternalWorkflowIds.has(id)) return true;
		return topic === "workflows" && !guarded && this.__hasLocalWorkflowExecution();
	}
	/**
	* Mark a run-scoped registration as active so the lazy TTL sweep measures
	* idle time rather than total run duration. Only refreshes an entry that
	* already exists at the exact `${id}:${runId}` key — resolving the bare
	* unscoped `${id}` slot says nothing about a run's liveness, and this must
	* never create an entry.
	*/
	#touchRunScopedWorkflow(id, runId) {
		const entry = this.#runScopedWorkflowTimestamps.get(`${id}:${runId}`);
		if (entry) entry.lastActivityAt = Date.now();
	}
	/**
	* Returns `true` when this Mastra instance can resolve the workflow
	* identified by `workflowId` + `runId`.  Mirrors the resolution order in
	* the WEP's `#dispatch` — internal registry → nested (parentWorkflow
	* present) → public registry — without side-effects.
	*
	* Used by the push-subscription guard in {@link startWorkers} to drop
	* cross-process events for internal workflows that belong to another
	* process.
	*/
	#ownsWorkflow(workflowId, runId, parentWorkflow) {
		if (this.__hasInternalWorkflow(workflowId, runId)) return true;
		if (parentWorkflow) {
			let root = parentWorkflow;
			while (root.parentWorkflow) root = root.parentWorkflow;
			const rootId = root.workflowId;
			const rootRunId = root.runId;
			if (rootId && rootRunId) return this.#ownsWorkflow(rootId, rootRunId, void 0);
		}
		const workflows = this.#workflows;
		if (workflows?.[workflowId]) return true;
		return Object.values(workflows ?? {}).some((w) => w.id === workflowId);
	}
	__getInternalWorkflow(id, runId) {
		let workflow;
		if (runId) {
			workflow = this.#internalMastraWorkflows[`${id}:${runId}`];
			if (workflow) this.#touchRunScopedWorkflow(id, runId);
			else workflow = this.#internalMastraWorkflows[id];
		} else workflow = this.#internalMastraWorkflows[id];
		if (!workflow) throw new MastraError({
			id: "MASTRA_GET_INTERNAL_WORKFLOW_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.SYSTEM,
			text: `Workflow with id ${String(id)} not found`,
			details: {
				status: 404,
				workflowId: String(id)
			}
		});
		return workflow;
	}
	/**
	* @internal Records the tracing context for an evented workflow run so the
	* event processor can nest step spans under the run's parent span. The
	* `currentSpan` is non-serializable, so it is held here rather than passed
	* through the engine's pubsub events.
	*/
	__registerRunTracingContext(runId, tracingContext) {
		this.#runTracingContexts.set(runId, tracingContext);
	}
	/** @internal Returns the tracing context recorded for an evented workflow run. */
	__getRunTracingContext(runId) {
		return this.#runTracingContexts.get(runId);
	}
	/** @internal Clears the tracing context once an evented workflow run finishes. */
	__unregisterRunTracingContext(runId) {
		this.#runTracingContexts.delete(runId);
	}
	/**
	* Lazily evict run-scoped internal workflow entries that have been *idle*
	* longer than {@link Mastra.INTERNAL_WORKFLOW_TTL_MS}. Called on every new
	* run-scoped registration so cleanup is proportional to activity — zero
	* overhead when the system is idle.
	*
	* Idleness, not age: every lookup a run makes against its own registration
	* refreshes `lastActivityAt` (see `#touchRunScopedWorkflow`), so a run that
	* executes for longer than the TTL is never evicted mid-flight. Only a run
	* that has stopped touching its registration — suspended and never resumed,
	* or abandoned — ages out. This matches how the agent thread-stream runtime
	* treats the shared `MASTRA_SUSPENDED_RUN_TTL_MS` bound, which only expires
	* records that are actually parked.
	*/
	#sweepStaleRunScopedWorkflows() {
		const now = Date.now();
		for (const [key, entry] of this.#runScopedWorkflowTimestamps) if (now - entry.lastActivityAt > Mastra.INTERNAL_WORKFLOW_TTL_MS) {
			delete this.#internalMastraWorkflows[key];
			this.#runScopedWorkflowTimestamps.delete(key);
			this.#releaseRunScope(entry.runId);
			this.#logger.warn("Evicted stale run-scoped workflow after TTL expired", {
				runId: entry.runId,
				idleMs: now - entry.lastActivityAt,
				ttlMs: Mastra.INTERNAL_WORKFLOW_TTL_MS
			});
		}
	}
	/**
	* Retrieves a registered workflow by its unique ID.
	*
	* This method searches for a workflow using its internal ID property. If no workflow
	* is found with the given ID, it also attempts to find a workflow using the ID as
	* a name.
	*
	* @throws {MastraError} When no workflow is found with the specified ID
	*
	* @example Finding a workflow by ID
	* ```typescript
	* const mastra = new Mastra({
	*   workflows: {
	*     dataProcessor: createWorkflow({
	*       name: 'process-data',
	*       triggerSchema: z.object({ input: z.string() })
	*     }).commit()
	*   }
	* });
	*
	* // Get the workflow's ID
	* const workflow = mastra.getWorkflow('dataProcessor');
	* const workflowId = workflow.id;
	*
	* // Later, retrieve the workflow by ID
	* const sameWorkflow = mastra.getWorkflowById(workflowId);
	* console.log(sameWorkflow.name); // "process-data"
	* ```
	*/
	getWorkflowById(id) {
		let workflow = Object.values(this.#workflows).find((a) => a.id === id);
		if (!workflow) try {
			workflow = this.getWorkflow(id);
		} catch {}
		if (!workflow) {
			const error = new MastraError({
				id: "MASTRA_GET_WORKFLOW_BY_ID_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Workflow with id ${String(id)} not found`,
				details: {
					status: 404,
					workflowId: String(id),
					workflows: Object.keys(this.#workflows ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return workflow;
	}
	/**
	* Every RUNNING/WAITING run of the workflows recovery restarts, with full snapshots, read in one
	* call per workflow and status. `restartAllActiveWorkflowRuns()` lists summaries instead.
	*/
	async listActiveWorkflowRuns() {
		if (!this.#storage) {
			this.#logger.debug("Cannot get active workflow runs. Mastra storage is not initialized");
			return {
				runs: [],
				total: 0
			};
		}
		const activeRunsByWorkflow = await Promise.all(this.#restartableWorkflows().map((workflow) => workflow.listActiveWorkflowRuns()));
		return {
			runs: activeRunsByWorkflow.flatMap((activeRuns) => activeRuns.runs),
			total: activeRunsByWorkflow.reduce((total, activeRuns) => total + activeRuns.total, 0)
		};
	}
	/**
	* The workflows whose active runs the recovery sweep restarts (see {@link isRecoveryRestartable}).
	* Filtered before listing, so opted-out workflows cost no storage queries.
	*/
	#restartableWorkflows() {
		return Object.values(this.#workflows).filter((workflow) => isRecoveryRestartable(workflow));
	}
	/**
	* Whether the pubsub's broker recovers run `runId` of `workflow`, so recovery never lists, reads
	* or restarts it: an evented run whose events reach a broker that redelivers a dead worker's
	* unacked message to another worker. A scheduled run whose events stay in the publishing process
	* (see {@link isProcessLocalScheduledRunId}) has no message at the broker, so it is not one.
	*/
	#brokerOwnsRun(workflow, runId) {
		return workflow.engineType === "evented" && this.#pubsub.__rawBus().redeliversUnacked && !isProcessLocalScheduledRunId(runId);
	}
	/**
	* Restarts the RUNNING/WAITING runs of the registered workflows that no process runs any more,
	* `recovery.workflowConcurrency` at a time (default 5).
	*
	* A default-engine run counts as stopped once no instance holds its run lease and
	* `recovery.workflowGraceMs` passed since it or its lease last changed. A run still live or in
	* its grace period is left to the recovery loop (see {@link Mastra.startWorkers}); this call
	* doesn't look at it again. Without run fencing in the store, every active default-engine run is
	* restarted.
	*
	* An evented run on a pubsub whose broker redelivers unacked messages
	* (`PubSub.redeliversUnacked`) is left to the broker and never read, except a scheduled run
	* whose events stay in the process. Every other evented run is restarted at once, by this call
	* only: the recovery loop never restarts evented runs.
	*
	* Resolves once every restart its pass queued finished. Runs an earlier pass already queued are
	* skipped and not awaited. A call made while a default-engine pass is still handing out restarts
	* joins it. Failures are logged per run and never reject. Once `shutdown()` starts, no further
	* runs are restarted.
	*/
	async restartAllActiveWorkflowRuns() {
		let workflowsStore;
		try {
			workflowsStore = await this.#storage?.getStore("workflows");
		} catch (error) {
			this.#logger.error("Failed to recover stopped workflow runs", { error });
			return;
		}
		if (!workflowsStore) {
			this.#logger.debug("Cannot restart active workflow runs. Mastra storage is not initialized");
			return;
		}
		const runFencing = await this.#supportsRunFencing(workflowsStore);
		const passes = await Promise.all([this.#trackDurableRecovery(this.#runRecoveryPass({
			workflowsStore,
			runFencing,
			engine: "evented"
		})), this.#recoverStoppedRuns(workflowsStore, runFencing)]);
		await Promise.all(passes.map((pass) => pass.settled));
	}
	/** The default-engine recovery pass still handing out restarts, which overlapping callers share, or a new one. */
	#recoverStoppedRuns(workflowsStore, runFencing) {
		if (!this.#recoveryPass) {
			const pass = this.#runRecoveryPass({
				workflowsStore,
				runFencing,
				engine: "default"
			});
			this.#recoveryPass = pass;
			pass.finally(() => {
				if (this.#recoveryPass === pass) this.#recoveryPass = void 0;
			});
		}
		return this.#recoveryPass;
	}
	/**
	* One recovery pass over the run summaries of `engine`'s workflows and their run leases (see
	* {@link recoveryVerdict}); never rejects.
	*/
	async #runRecoveryPass({ workflowsStore, runFencing, engine }) {
		const restarts = [];
		const failedRestarts = this.#failedRecoveryRestarts[engine];
		let earliestDueAt;
		try {
			const listed = await this.#listActiveRunSummaries(workflowsStore, engine);
			const listedKeys = new Set(listed.map(({ run }) => recoveryRunKey(run.workflowName, run.runId)));
			for (const key of failedRestarts) if (!listedKeys.has(key)) failedRestarts.delete(key);
			const candidates = await this.#recoveryCandidates(workflowsStore, listed);
			const graceMs = this.#workflowGraceMs();
			for (let start = 0; start < candidates.length; start += RECOVERY_OWNERSHIP_BATCH_SIZE) {
				if (this.#shuttingDown) break;
				const batch = candidates.slice(start, start + RECOVERY_OWNERSHIP_BATCH_SIZE).filter(({ run }) => !this.#queuedRecoveryRestarts.has(recoveryRunKey(run.workflowName, run.runId)));
				const leased = runFencing ? batch.filter(({ workflow }) => usesRunLease(workflow)) : [];
				const owners = leased.length > 0 ? await this.#readRunOwners(workflowsStore, leased) : void 0;
				const now = Date.now();
				for (const candidate of batch) {
					if (this.#shuttingDown) break;
					const { workflow, run } = candidate;
					let verdict;
					if (!runFencing || !usesRunLease(workflow)) verdict = { restart: true };
					else if (!owners) verdict = {
						restart: false,
						live: true,
						dueAt: now + graceMs
					};
					else verdict = recoveryVerdict({
						owner: owners.get(run.runId),
						updatedAt: run.updatedAt,
						graceMs,
						now
					});
					if (verdict.restart) {
						const key = recoveryRunKey(run.workflowName, run.runId);
						const restart = this.#queueRecoveryRestart({
							workflow,
							run,
							workflowsStore,
							runFencing
						}).then(() => void failedRestarts.delete(key), (error) => {
							const context = {
								workflow: workflow.id,
								runId: run.runId,
								error
							};
							if (failedRestarts.has(key)) this.#logger.debug("Failed to restart workflow run again", context);
							else {
								failedRestarts.add(key);
								this.#logger.error("Failed to restart workflow run", context);
							}
						});
						restarts.push(restart);
						continue;
					}
					if (!verdict.live) earliestDueAt = Math.min(earliestDueAt ?? Infinity, verdict.dueAt);
				}
			}
		} catch (error) {
			this.#logger.error("Failed to recover stopped workflow runs", { error });
		}
		return {
			earliestDueAt,
			settled: Promise.all(restarts).then(() => {})
		};
	}
	/**
	* Restarts a run the recovery pass picked once `#recoveryRestarts` has a free slot, and rejects when
	* the restart fails. The run counts as queued meanwhile, so recovery leaves it to this restart, and a
	* run that is already queued resolves at once without a second restart.
	*
	* A default-engine run's verdict is from a lease read before the run was queued. While it waited for a
	* slot, another instance can have restarted the run and stopped again; `restart()` alone would not see
	* that, as it ignores the grace period. So the lease is read once more first.
	*/
	#queueRecoveryRestart({ workflow, run, workflowsStore, runFencing }) {
		const restartIfStopped = async () => {
			if (this.#shuttingDown) return;
			if (runFencing && usesRunLease(workflow)) {
				let owners;
				try {
					owners = await workflowsStore.getRunOwnerships({ runIds: [run.runId] });
				} catch (error) {
					this.#logger.warn("Failed to read workflow run lease before restarting", {
						workflow: workflow.id,
						runId: run.runId,
						error
					});
					return;
				}
				if (!recoveryVerdict({
					owner: owners.get(run.runId),
					updatedAt: run.updatedAt,
					graceMs: this.#workflowGraceMs(),
					now: Date.now()
				}).restart) return;
			}
			await this.#restartWorkflowRun(workflow, run.runId);
		};
		const key = recoveryRunKey(run.workflowName, run.runId);
		if (this.#queuedRecoveryRestarts.has(key)) return Promise.resolve();
		this.#queuedRecoveryRestarts.add(key);
		return this.#recoveryRestarts.run(() => this.#trackDurableRecovery(restartIfStopped())).finally(() => this.#queuedRecoveryRestarts.delete(key));
	}
	/** The grace period of the recovery rule (`recovery.workflowGraceMs`). */
	#workflowGraceMs() {
		return this.#recoveryConfig.workflowGraceMs ?? DEFAULT_WORKFLOW_GRACE_MS;
	}
	/**
	* Whether the pass can read run leases. A failed probe counts as no, which restarts every active
	* run as a store without leases does: `restart()` probes again and refuses a run another process
	* still holds.
	*/
	async #supportsRunFencing(workflowsStore) {
		try {
			return await workflowsStore.supportsRunFencing();
		} catch (error) {
			this.#logger.warn("Failed to check run fencing support before restarting workflow runs", { error });
			return false;
		}
	}
	/**
	* Every RUNNING/WAITING run of the restartable workflows on `engine` that recovery may restart, as
	* summaries without step results. Runs the broker recovers (see `#brokerOwnsRun`) are left out.
	*/
	async #listActiveRunSummaries(workflowsStore, engine) {
		const redelivers = this.#pubsub.__rawBus().redeliversUnacked;
		const workflows = this.#restartableWorkflows().filter((workflow) => workflow.engineType === engine);
		return (await Promise.all(workflows.map(async (workflow) => {
			if (workflow.engineType === "evented" && redelivers && collectWorkflowScheduleConfigs(workflow).length === 0) return [];
			try {
				const runs = /* @__PURE__ */ new Map();
				for (const status of ACTIVE_RUN_STATUSES) {
					const { runs: listedRuns } = await this.#recoveryListings.run(() => workflowsStore.listWorkflowRuns({
						workflowName: workflow.id,
						status,
						perPage: false,
						summary: true
					}));
					for (const run of listedRuns) if (!runs.has(run.runId) && !this.#brokerOwnsRun(workflow, run.runId)) runs.set(run.runId, run);
				}
				return [...runs.values()].map((run) => ({
					workflow,
					run
				}));
			} catch (error) {
				this.#logger.error("Failed to list active workflow runs for recovery", {
					workflow: workflow.id,
					error
				});
				return [];
			}
		}))).flat();
	}
	/** The listed runs the recovery rule applies to, after nested runs are left to or canceled by their parents. */
	async #recoveryCandidates(workflowsStore, listed) {
		const activeRuns = new Set(listed.map(({ run }) => recoveryRunKey(run.workflowName, run.runId)));
		const parentStatusOf = createNestedRunParentStatusLookup({ store: workflowsStore });
		const candidates = [];
		for (const candidate of listed) {
			const { run } = candidate;
			const parent = nestedRunParentOf(run.snapshot);
			if (!parent) {
				candidates.push(candidate);
				continue;
			}
			if (activeRuns.has(recoveryRunKey(parent.workflowName, parent.runId))) continue;
			try {
				const parentStatus = await parentStatusOf(parent);
				const recovery = nestedRunRecoveryAction(parentStatus);
				if (recovery === "restart") candidates.push(candidate);
				else if (recovery === "cancel") await cancelNestedRun({
					store: workflowsStore,
					workflowName: run.workflowName,
					runId: run.runId,
					expectedStatus: nestedRunStatusOf(run.snapshot),
					logger: this.#logger
				});
				else this.#logger.debug("Left a nested workflow run for its parent to drive", {
					workflow: run.workflowName,
					runId: run.runId,
					parentWorkflow: parent.workflowName,
					parentRunId: parent.runId,
					parentStatus
				});
			} catch (error) {
				this.#logger.error("Failed to recover nested workflow run", {
					workflow: run.workflowName,
					runId: run.runId,
					error
				});
			}
		}
		return candidates;
	}
	/** The run leases of one batch of default-engine runs, read in one call; `undefined` when the read fails. */
	async #readRunOwners(workflowsStore, batch) {
		try {
			return await workflowsStore.getRunOwnerships({ runIds: batch.map(({ run }) => run.runId) });
		} catch (error) {
			this.#logger.warn("Failed to read workflow run leases before restarting", {
				runs: batch.length,
				error
			});
			return;
		}
	}
	/**
	* Restarts one run the recovery pass picked. When another process won a default-engine run in
	* the meantime, `restart()` refuses with `WORKFLOW_RESTART_RUN_OWNED` and the run is left to the
	* recovery loop's next pass. Other failures reject, for the caller to log or retry. The restart
	* holds its slot until the run ends.
	*/
	async #restartWorkflowRun(workflow, runId) {
		if (this.#shuttingDown) return;
		const run = await workflow.createRun({ runId });
		try {
			await run.restart();
		} catch (error) {
			if (!(error instanceof MastraError && error.id === "WORKFLOW_RESTART_RUN_OWNED")) throw error;
			this.#logger.debug("Skipped restarting workflow run owned by a live process", {
				workflow: workflow.id,
				runId
			});
			return;
		}
		this.#logger.debug("Restarted workflow run", {
			workflow: workflow.id,
			runId
		});
	}
	/**
	* Whether this instance is the recovery leader: it holds the `::recovery-leader` run-owners row,
	* or takes it now when no other instance holds it live. A taken row is renewed until
	* `#releaseRecoveryLeader()`, so the leader keeps it across passes; when this instance dies the
	* row lapses after the lease TTL and the next instance to try takes it. Only the loop's ticks call
	* this, one at a time. Rejects when the store fails the claim.
	*/
	#leadWorkflowRecovery(workflowsStore) {
		if (this.#recoveryLeader) return Promise.resolve(true);
		this.#recoveryLeaderClaim = this.#claimRecoveryLeader(workflowsStore).finally(() => {
			this.#recoveryLeaderClaim = void 0;
		});
		return this.#recoveryLeaderClaim;
	}
	/** One non-forced claim of the recovery leader row; see `#leadWorkflowRecovery`. */
	async #claimRecoveryLeader(workflowsStore) {
		const claim = await workflowsStore.claimRunOwnership({
			runId: RECOVERY_LEADER_KEY,
			ownerId: crypto.randomUUID(),
			leaseMs: WORKFLOW_RUN_LEASE_TTL_MS,
			force: false
		});
		if (!claim.acquired) return false;
		const fence = {
			runId: RECOVERY_LEADER_KEY,
			generation: claim.record.generation,
			ownerId: claim.record.ownerId
		};
		const leader = {
			store: workflowsStore,
			fence,
			stopRenewing: () => {}
		};
		leader.stopRenewing = runOutsideRunFenceScope(() => renewWorkflowLease({
			store: workflowsStore,
			fence,
			onLost: (owner) => {
				if (this.#recoveryLeader === leader) this.#recoveryLeader = void 0;
				this.#logger.warn("Lost the workflow recovery leader lease; another instance may lead recovery now", { owner: owner?.ownerId });
			},
			onError: (error) => this.#logger.warn("Failed to renew the workflow recovery leader lease", { error })
		}));
		this.#recoveryLeader = leader;
		return true;
	}
	/** Hands the recovery leader row back, if this instance holds it, so another instance can take it at once. */
	async #releaseRecoveryLeader() {
		await this.#recoveryLeaderClaim?.catch(() => {});
		const leader = this.#recoveryLeader;
		if (!leader) return;
		this.#recoveryLeader = void 0;
		leader.stopRenewing();
		try {
			await leader.store.releaseRunOwnership(leader.fence);
		} catch (error) {
			this.#logger.warn("Failed to release the workflow recovery leader lease", { error });
		}
	}
	/**
	* Starts the recovery loop unless it runs, recovery is off, or this instance has no storage or
	* workers; the caller checks that this instance handles workflow events.
	*
	* Each tick tries to lead (see `#leadWorkflowRecovery`); only the leader runs a pass, over
	* default-engine runs only. The first tick runs now; a `restartAllActiveWorkflowRuns()` call made
	* while this instance's pass runs, such as the server's at boot, joins it. Each later tick runs a scan
	* interval after the previous one handed out its restarts, or sooner when a run that pass found
	* in its grace period comes due first (see {@link nextWorkflowScanDelay}). The loop stops for
	* good on a store without run fencing, where nothing tells a live run from a stopped one.
	*/
	#startWorkflowRecoveryLoop() {
		if (this.#stopWorkflowRecoveryLoop || this.#recoveryConfig.workflows === "off" || !this.#storage || this.#workersDisabled) return;
		let stopChain;
		const stop = () => {
			stopChain?.();
			if (this.#stopWorkflowRecoveryLoop === stop) this.#stopWorkflowRecoveryLoop = void 0;
		};
		this.#stopWorkflowRecoveryLoop = stop;
		let dueAt;
		const tick = async () => {
			dueAt = void 0;
			if (!this.#restartableWorkflows().some(usesRunLease)) return;
			try {
				const workflowsStore = await this.#storage?.getStore("workflows");
				if (!workflowsStore) return;
				if (!await workflowsStore.supportsRunFencing()) {
					stop();
					return;
				}
				if (this.#stopWorkflowRecoveryLoop !== stop) return;
				if (!await this.#leadWorkflowRecovery(workflowsStore)) return;
				if (this.#stopWorkflowRecoveryLoop !== stop) return;
				dueAt = (await this.#recoverStoppedRuns(workflowsStore, true)).earliestDueAt;
			} catch (error) {
				this.#logger.warn("Workflow recovery loop skipped a pass", { error });
			}
		};
		stopChain = runOutsideRunFenceScope(() => repeatAfterSettled(tick, () => nextWorkflowScanDelay(this.#recoveryConfig.workflowScanIntervalMs, dueAt), { immediately: true }));
	}
	/**
	* The resolved boot-time recovery configuration for this Mastra instance.
	* See {@link Config.recovery}.
	*/
	get recoveryConfig() {
		return this.#recoveryConfig;
	}
	/**
	* True once `shutdown()` has started. Durable agents use it to checkpoint
	* in-flight runs so they can be recovered after the process exits.
	* @internal
	*/
	get __shuttingDown() {
		return this.#shuttingDown;
	}
	/**
	* Re-drive every orphaned RUNNING durable-agent run across every registered
	* `DurableAgent`. Delegates to `DurableAgent.recoverActiveRuns()` on each
	* agent that supports it (default-engine durable agents only — Inngest and
	* other externally-executed durable wrappers run their own recovery).
	*
	* Intended to be called once on server boot, concurrently with
	* `restartAllActiveWorkflowRuns()`. The deployer wires this up automatically
	* when `recovery.durableAgents` is set to `'auto'` in the Mastra config; you
	* can also call it directly if you need finer control (e.g. running it in a
	* cron, or gating it behind a leader election).
	*
	* Runs another instance still drives are skipped, not taken over, and
	* counted in `skipped`. Each is re-checked once that instance's claim could
	* have lapsed, so a run whose instance crashed is recovered without another
	* call. `shutdown()` cancels pending re-checks.
	*
	* Requires persistent storage — with an in-memory store there is nothing to
	* recover after a process restart, so this is a no-op and returns zeroed
	* counts.
	*/
	async recoverAllDurableAgents() {
		if (!this.#storage) {
			this.#logger.debug("Cannot recover durable agents. Mastra storage is not initialized");
			return {
				agents: 0,
				recovered: 0,
				succeeded: 0,
				failed: 0,
				skipped: 0
			};
		}
		const durableAgents = [];
		for (const agent of Object.values(this.#agents ?? {})) if (agent && isDurableAgentLike(agent)) durableAgents.push(agent);
		if (durableAgents.length === 0) return {
			agents: 0,
			recovered: 0,
			succeeded: 0,
			failed: 0,
			skipped: 0
		};
		this.#logger.debug(`Recovering active durable-agent runs across ${durableAgents.length} agent${durableAgents.length > 1 ? "s" : ""}`);
		return this.#trackDurableRecovery((async () => {
			let recovered = 0;
			let succeeded = 0;
			let failed = 0;
			let skipped = 0;
			await runWithConcurrency(durableAgents, 5, async (agent) => {
				if (this.#shuttingDown) return;
				try {
					const result = await agent.recoverActiveRuns();
					for (const run of result.recovered) if (run.status === "skipped") {
						skipped++;
						this.#scheduleDurableRecoveryRecheck(agent, run);
					} else recovered++;
					succeeded += result.succeeded;
					failed += result.failed;
				} catch (error) {
					this.#logger.error("Failed to recover active runs for durable agent", {
						agentId: agent.id,
						error
					});
				}
			});
			return {
				agents: durableAgents.length,
				recovered,
				succeeded,
				failed,
				skipped
			};
		})());
	}
	#trackDurableRecovery(promise) {
		this.#durableRecoveryRechecksInFlight.add(promise);
		const remove = () => this.#durableRecoveryRechecksInFlight.delete(promise);
		promise.then(remove, remove);
		return promise;
	}
	/** @internal Bound waiting, not execution; shutdown must still drain the original attempt. */
	__awaitDurableRecoveryAttempt(promise, description) {
		return this.#awaitBounded(this.#trackDurableRecovery(promise).then((value) => ({ value })), DURABLE_RECOVERY_ATTEMPT_TIMEOUT_MS, description, `Durable recovery timed out after ${DURABLE_RECOVERY_ATTEMPT_TIMEOUT_MS}ms waiting for ${description}; the attempt continues in the background`);
	}
	/**
	* Re-check skipped runs after a foreign claim could have lapsed or a
	* recovery wait timed out. Timed-out originals keep their ownership and
	* defer rechecks until settlement without starting duplicate executions.
	* A re-check that throws is retried with backoff; `failures` counts the
	* consecutive ones.
	*/
	#scheduleDurableRecoveryRecheck(agent, run, failures = 0) {
		if (run.retryAt === void 0 || this.#shuttingDown) return;
		const key = JSON.stringify([agent.id, run.runId]);
		clearTimeout(this.#durableRecoveryRechecks.get(key));
		const delay = Math.max(0, run.retryAt - Date.now()) + Math.random() * DURABLE_RECOVERY_RECHECK_JITTER_MS;
		const timer = setTimeout(() => {
			this.#durableRecoveryRechecks.delete(key);
			const recheck = agent.recoverActiveRuns({ runId: run.runId }).then((result) => {
				for (const next of result.recovered) if (next.status === "skipped") this.#scheduleDurableRecoveryRecheck(agent, next);
			}).catch((error) => {
				const context = {
					agentId: agent.id,
					runId: run.runId,
					error
				};
				if (failures >= DURABLE_RECOVERY_RECHECK_MAX_RETRIES) {
					this.#logger.error("Failed to re-check durable agent run for recovery; leaving it for the next boot or a manual recover()", context);
					return;
				}
				this.#logger.warn("Failed to re-check durable agent run for recovery; retrying", context);
				this.#scheduleDurableRecoveryRecheck(agent, {
					runId: run.runId,
					retryAt: Date.now() + DURABLE_RECOVERY_RECHECK_RETRY_BASE_MS * 2 ** failures
				}, failures + 1);
			}).finally(() => this.#durableRecoveryRechecksInFlight.delete(recheck));
			this.#durableRecoveryRechecksInFlight.add(recheck);
		}, delay);
		timer.unref?.();
		this.#durableRecoveryRechecks.set(key, timer);
	}
	/**
	* Returns all registered scorers as a record keyed by their IDs.
	*
	* @example Listing all scorers
	* ```typescript
	* import { HelpfulnessScorer, AccuracyScorer, RelevanceScorer } from '@mastra/scorers';
	*
	* const mastra = new Mastra({
	*   scorers: {
	*     helpfulness: new HelpfulnessScorer(),
	*     accuracy: new AccuracyScorer(),
	*     relevance: new RelevanceScorer()
	*   }
	* });
	*
	* const allScorers = mastra.listScorers();
	* console.log(Object.keys(allScorers)); // ['helpfulness', 'accuracy', 'relevance']
	*
	* // Check scorer configurations
	* for (const [id, scorer] of Object.entries(allScorers)) {
	*   console.log(`Scorer ${id}:`, scorer.id, scorer.name, scorer.description);
	* }
	* ```
	*/
	listScorers() {
		return this.#scorers;
	}
	/**
	* Adds a new scorer to the Mastra instance.
	*
	* This method allows dynamic registration of scorers after the Mastra instance
	* has been created.
	*
	* If a scorer with the same key already exists, this method leaves the existing
	* scorer registered and returns.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const newScorer = new MastraScorer({
	*   id: 'quality-scorer',
	*   name: 'Quality Scorer'
	* });
	* mastra.addScorer(newScorer); // Uses scorer.id as key
	* // or
	* mastra.addScorer(newScorer, 'customKey'); // Uses custom key
	* ```
	*/
	addScorer(scorer, key, options) {
		if (!scorer) throw createUndefinedPrimitiveError("scorer", scorer, key);
		const scorerKey = key || scorer.id;
		const scorers = this.#scorers;
		if (scorers[scorerKey]) return;
		scorer.__registerMastra(this);
		if (options?.source) scorer.source = options.source;
		scorers[scorerKey] = scorer;
	}
	/**
	* Retrieves a registered scorer by its key.
	*
	* @template TScorerKey - The specific scorer key type from the registered scorers
	* @throws {MastraError} When the scorer with the specified key is not found
	*
	* @example Getting and using a scorer
	* ```typescript
	* import { HelpfulnessScorer, AccuracyScorer } from '@mastra/scorers';
	*
	* const mastra = new Mastra({
	*   scorers: {
	*     helpfulness: new HelpfulnessScorer({
	*       model: 'openai/gpt-4o',
	*       criteria: 'Rate how helpful this response is'
	*     }),
	*     accuracy: new AccuracyScorer({
	*       model: 'openai/gpt-5'
	*     })
	*   }
	* });
	*
	* // Get a specific scorer
	* const helpfulnessScorer = mastra.getScorer('helpfulness');
	* const score = await helpfulnessScorer.score({
	*   input: 'How do I reset my password?',
	*   output: 'You can reset your password by clicking the forgot password link.',
	*   expected: 'Detailed password reset instructions'
	* });
	*
	* console.log('Helpfulness score:', score);
	* ```
	*/
	getScorer(key) {
		const scorer = this.#scorers?.[key];
		if (!scorer) {
			const error = new MastraError({
				id: "MASTRA_GET_SCORER_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Scorer with ${String(key)} not found`
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return scorer;
	}
	/**
	* Retrieves a registered scorer by its name.
	*
	* This method searches through all registered scorers to find one with the specified name.
	* Unlike `getScorer()` which uses the registration key, this method uses the scorer's
	* internal name property.
	*
	* @throws {MastraError} When no scorer is found with the specified name
	*
	* @example Finding a scorer by name
	* ```typescript
	* import { HelpfulnessScorer } from '@mastra/scorers';
	*
	* const mastra = new Mastra({
	*   scorers: {
	*     myHelpfulnessScorer: new HelpfulnessScorer({
	*       name: 'helpfulness-evaluator',
	*       model: 'openai/gpt-5'
	*     })
	*   }
	* });
	*
	* // Find scorer by its internal name, not the registration key
	* const scorer = mastra.getScorerById('helpfulness-evaluator');
	* const score = await scorer.score({
	*   input: 'question',
	*   output: 'answer'
	* });
	* ```
	*/
	getScorerById(id) {
		for (const [_key, value] of Object.entries(this.#scorers ?? {})) if (value.id === id || value?.name === id) return value;
		const error = new MastraError({
			id: "MASTRA_GET_SCORER_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Scorer with id ${String(id)} not found`
		});
		this.#logger?.trackException(error);
		throw error;
	}
	/**
	* Removes a scorer from the Mastra instance by its key or ID.
	*
	* @param keyOrId - The scorer key or ID to remove
	* @returns true if a scorer was removed, false if no scorer was found
	*/
	removeScorer(keyOrId) {
		const scorers = this.#scorers;
		if (!scorers) return false;
		if (scorers[keyOrId]) {
			const scorerId = scorers[keyOrId]?.id;
			delete scorers[keyOrId];
			if (scorerId) this.#storedScorersCache.delete(scorerId);
			return true;
		}
		const key = Object.keys(scorers).find((k) => scorers[k]?.id === keyOrId || scorers[k]?.name === keyOrId);
		if (key) {
			const scorerId = scorers[key]?.id;
			delete scorers[key];
			if (scorerId) this.#storedScorersCache.delete(scorerId);
			return true;
		}
		return false;
	}
	/**
	* Returns all registered classifiers keyed by their registration key.
	*/
	listClassifiers() {
		return this.#classifiers;
	}
	/**
	* Adds a classifier to the Mastra instance.
	*
	* If a classifier with the same key already exists, this method leaves the existing
	* classifier registered and returns.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* mastra.addClassifier(new Classifier({ id: 'safety', model })); // Uses classifier.id as key
	* mastra.addClassifier(new Classifier({ id: 'safety', model }), 'customKey');
	* ```
	*/
	addClassifier(classifier, key) {
		if (!classifier) throw createUndefinedPrimitiveError("classifier", classifier, key);
		const classifierKey = key || classifier.id;
		const classifiers = this.#classifiers;
		if (classifiers[classifierKey]) return;
		classifier.__registerMastra(this);
		classifiers[classifierKey] = classifier;
	}
	/**
	* Retrieves a registered classifier by its registration key.
	*
	* @throws {MastraError} When the classifier with the specified key is not found
	*/
	getClassifier(key) {
		const classifier = this.#classifiers?.[key];
		if (!classifier) {
			const error = new MastraError({
				id: "MASTRA_GET_CLASSIFIER_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Classifier with ${String(key)} not found`,
				details: { status: 404 }
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return classifier;
	}
	/**
	* Retrieves a registered classifier by its `id`, falling back to the registration key.
	*
	* @throws {MastraError} When no classifier is found with the specified id
	*/
	getClassifierById(id) {
		for (const [key, value] of Object.entries(this.#classifiers ?? {})) if (value.id === id || key === id) return value;
		const error = new MastraError({
			id: "MASTRA_GET_CLASSIFIER_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Classifier with id ${String(id)} not found`,
			details: { status: 404 }
		});
		this.#logger?.trackException(error);
		throw error;
	}
	/**
	* Removes a classifier from the Mastra instance by its key or id.
	*
	* @returns true if a classifier was removed, false if no classifier was found
	*/
	removeClassifier(keyOrId) {
		const classifiers = this.#classifiers;
		if (!classifiers) return false;
		if (classifiers[keyOrId]) {
			delete classifiers[keyOrId];
			return true;
		}
		const key = Object.keys(classifiers).find((k) => classifiers[k]?.id === keyOrId);
		if (key) {
			delete classifiers[key];
			return true;
		}
		return false;
	}
	/**
	* Returns all registered prompt blocks.
	*/
	listPromptBlocks() {
		return this.#promptBlocks;
	}
	/**
	* Registers a prompt block in the Mastra instance's runtime registry.
	*
	* @param promptBlock - The resolved prompt block to register
	* @param key - Optional registration key (defaults to promptBlock.id)
	*/
	addPromptBlock(promptBlock, key) {
		const blockKey = key || promptBlock.id;
		if (this.#promptBlocks[blockKey]) return;
		this.#promptBlocks[blockKey] = promptBlock;
	}
	/**
	* Retrieves a registered prompt block by its key.
	*
	* @throws {MastraError} When the prompt block with the specified key is not found
	*/
	getPromptBlock(key) {
		const block = this.#promptBlocks[key];
		if (!block) throw new MastraError({
			id: "MASTRA_GET_PROMPT_BLOCK_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Prompt block with key ${key} not found`
		});
		return block;
	}
	/**
	* Retrieves a registered prompt block by its ID.
	*
	* @throws {MastraError} When no prompt block is found with the specified ID
	*/
	getPromptBlockById(id) {
		for (const [, block] of Object.entries(this.#promptBlocks)) if (block.id === id) return block;
		throw new MastraError({
			id: "MASTRA_GET_PROMPT_BLOCK_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Prompt block with id ${id} not found`
		});
	}
	/**
	* Removes a prompt block from the Mastra instance by its key or ID.
	*
	* @param keyOrId - The prompt block key or ID to remove
	* @returns true if a prompt block was removed, false if not found
	*/
	removePromptBlock(keyOrId) {
		if (this.#promptBlocks[keyOrId]) {
			delete this.#promptBlocks[keyOrId];
			return true;
		}
		const key = Object.keys(this.#promptBlocks).find((k) => this.#promptBlocks[k]?.id === keyOrId);
		if (key) {
			delete this.#promptBlocks[key];
			return true;
		}
		return false;
	}
	/**
	* Retrieves a specific tool by registration key.
	*
	* @throws {MastraError} When the specified tool is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   tools: {
	*     calculator: calculatorTool,
	*     weather: weatherTool
	*   }
	* });
	*
	* const tool = mastra.getTool('calculator');
	* ```
	*/
	getTool(name) {
		if (!this.#tools || !this.#tools[name]) {
			const error = new MastraError({
				id: "MASTRA_GET_TOOL_BY_NAME_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Tool with name ${String(name)} not found`,
				details: {
					status: 404,
					toolName: String(name),
					tools: Object.keys(this.#tools ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return this.#tools[name];
	}
	/**
	* Retrieves a specific tool by its ID.
	*
	* @throws {MastraError} When the specified tool is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   tools: {
	*     calculator: calculatorTool
	*   }
	* });
	*
	* const tool = mastra.getToolById('calculator-tool-id');
	* ```
	*/
	getToolById(id) {
		const allTools = this.#tools;
		if (!allTools) throw new MastraError({
			id: "MASTRA_GET_TOOL_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Tool with id ${id} not found`
		});
		for (const tool of Object.values(allTools)) if (tool.id === id) return tool;
		const toolByKey = allTools[id];
		if (toolByKey) return toolByKey;
		const error = new MastraError({
			id: "MASTRA_GET_TOOL_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Tool with id ${id} not found`,
			details: {
				status: 404,
				toolId: String(id),
				tools: Object.keys(allTools).join(", ")
			}
		});
		this.#logger?.trackException(error);
		throw error;
	}
	/**
	* Lists all configured tools.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   tools: {
	*     calculator: calculatorTool,
	*     weather: weatherTool
	*   }
	* });
	*
	* const tools = mastra.listTools();
	* Object.entries(tools || {}).forEach(([name, tool]) => {
	*   console.log(`Tool "${name}":`, tool.id);
	* });
	* ```
	*/
	listTools() {
		return this.#tools;
	}
	/**
	* Adds a new tool to the Mastra instance.
	*
	* This method allows dynamic registration of tools after the Mastra instance
	* has been created.
	*
	* If a tool with the same key already exists, this method leaves the existing
	* tool registered and returns without an error. The new tool is not added.
	*
	* @throws {MastraError} When the tool is undefined
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const newTool = createTool({
	*   id: 'calculator-tool',
	*   description: 'Performs calculations'
	* });
	* mastra.addTool(newTool); // Uses tool.id as key
	* // or
	* mastra.addTool(newTool, 'customKey'); // Uses custom key
	* ```
	*/
	addTool(tool, key) {
		if (!tool) throw createUndefinedPrimitiveError("tool", tool, key);
		const toolKey = key || tool.id;
		const tools = this.#tools;
		if (tools[toolKey]) return;
		tools[toolKey] = tool;
		if (this.#backgroundTaskManager) this.#registerToolWithBackgroundManager(toolKey, tool);
	}
	/**
	* Removes a tool from the Mastra instance by its registration key.
	*
	* Also unregisters the tool's static executor from the background task
	* manager, if one was registered.
	*
	* @returns `true` if a tool was removed, `false` if no tool was registered under the key
	*
	* @example
	* ```typescript
	* mastra.removeTool('calculator-tool');
	* ```
	*/
	removeTool(key) {
		const tools = this.#tools;
		if (!tools[key]) return false;
		delete tools[key];
		this.#backgroundTaskManager?.unregisterStaticExecutor(key);
		return true;
	}
	/**
	* Retrieves a specific processor by registration key.
	*
	* @throws {MastraError} When the specified processor is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   processors: {
	*     validator: validatorProcessor,
	*     transformer: transformerProcessor
	*   }
	* });
	*
	* const processor = mastra.getProcessor('validator');
	* ```
	*/
	getProcessor(name) {
		if (!this.#processors || !this.#processors[name]) {
			const error = new MastraError({
				id: "MASTRA_GET_PROCESSOR_BY_NAME_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Processor with name ${String(name)} not found`,
				details: {
					status: 404,
					processorName: String(name),
					processors: Object.keys(this.#processors ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return this.#processors[name];
	}
	/**
	* Retrieves a specific processor by its ID.
	*
	* @throws {MastraError} When the specified processor is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   processors: {
	*     validator: validatorProcessor
	*   }
	* });
	*
	* const processor = mastra.getProcessorById('validator-processor-id');
	* ```
	*/
	getProcessorById(id) {
		const allProcessors = this.#processors;
		if (!allProcessors) throw new MastraError({
			id: "MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Processor with id ${id} not found`
		});
		for (const processor of Object.values(allProcessors)) if (processor.id === id) return processor;
		const processorByKey = allProcessors[id];
		if (processorByKey) return processorByKey;
		const error = new MastraError({
			id: "MASTRA_GET_PROCESSOR_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Processor with id ${id} not found`,
			details: {
				status: 404,
				processorId: String(id),
				processors: Object.keys(allProcessors).join(", ")
			}
		});
		this.#logger?.trackException(error);
		throw error;
	}
	/**
	* Lists all configured processors.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   processors: {
	*     validator: validatorProcessor,
	*     transformer: transformerProcessor
	*   }
	* });
	*
	* const processors = mastra.listProcessors();
	* Object.entries(processors || {}).forEach(([name, processor]) => {
	*   console.log(`Processor "${name}":`, processor.id);
	* });
	* ```
	*/
	listProcessors() {
		return this.#processors;
	}
	/**
	* Adds a new processor to the Mastra instance.
	*
	* This method allows dynamic registration of processors after the Mastra instance
	* has been created.
	*
	* @throws {MastraError} When a processor with the same key already exists
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const newProcessor = {
	*   id: 'text-processor',
	*   processInput: async (messages) => messages
	* };
	* mastra.addProcessor(newProcessor); // Uses processor.id as key
	* // or
	* mastra.addProcessor(newProcessor, 'customKey'); // Uses custom key
	* ```
	*/
	addProcessor(processor, key) {
		if (!processor) throw createUndefinedPrimitiveError("processor", processor, key);
		if (typeof processor.__registerMastra === "function") processor.__registerMastra(this);
		const processorKey = key || processor.id;
		const processors = this.#processors;
		if (processors[processorKey]) return;
		processors[processorKey] = processor;
	}
	/**
	* Registers a processor configuration with agent context.
	* This tracks which agents use which processors with what configuration.
	*
	* @param processor - The processor instance
	* @param agentId - The ID of the agent that uses this processor
	* @param type - Whether this is an input or output processor
	* @param source - Where the agent is defined. Configurations of stored agents stay marked as stored, so they can
	*   be told apart from code agents' configurations after the stored agent is gone.
	*/
	addProcessorConfiguration(processor, agentId, type, source) {
		const processorId = processor.id;
		if (!this.#processorConfigurations.has(processorId)) this.#processorConfigurations.set(processorId, []);
		const configs = this.#processorConfigurations.get(processorId);
		const existing = configs.find((c) => c.agentId === agentId && c.type === type);
		if (!existing) configs.push({
			processor,
			agentId,
			type,
			...source && { source }
		});
		else if (source === "stored") existing.source = "stored";
	}
	/**
	* Gets all processor configurations for a specific processor ID.
	*
	* @param processorId - The ID of the processor
	* @returns Array of configurations with agent context
	*/
	getProcessorConfigurations(processorId) {
		return this.#processorConfigurations.get(processorId) || [];
	}
	/**
	* Gets all processor configurations.
	*
	* @returns Map of processor IDs to their configurations
	*/
	listProcessorConfigurations() {
		return this.#processorConfigurations;
	}
	/** Retrieves a registered Knowledge instance by its application key. */
	getKnowledge(key) {
		const knowledge = this.#knowledge[key];
		if (!knowledge) {
			const error = new MastraError({
				id: "MASTRA_GET_KNOWLEDGE_BY_KEY_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Knowledge with key ${String(key)} not found`,
				details: {
					status: 404,
					knowledgeKey: String(key),
					availableKeys: Object.keys(this.#knowledge).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return knowledge;
	}
	/** Returns all registered Knowledge instances keyed by application key. */
	listKnowledge() {
		return { ...this.#knowledge };
	}
	/** Registers a Knowledge instance without initializing its storage. */
	addKnowledge(knowledge, key) {
		if (!knowledge) throw createUndefinedPrimitiveError("knowledge", knowledge, key);
		const knowledgeKey = key ?? knowledge.id;
		const registry = this.#knowledge;
		if (registry[knowledgeKey]) throw new MastraError({
			id: "MASTRA_ADD_KNOWLEDGE_DUPLICATE_KEY",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Knowledge with key ${knowledgeKey} is already registered`,
			details: {
				status: 409,
				knowledgeKey
			}
		});
		if (Object.values(registry).some((instance) => !knowledge.hasOwnStorage && !instance.hasOwnStorage || knowledge.__sharesStorageWith(instance) || !knowledge.hasOwnStorage && this.#storageSource !== void 0 && instance.__usesStorage(this.#storageSource))) throw new MastraError({
			id: "MASTRA_ADD_KNOWLEDGE_SHARED_STORAGE",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: "Knowledge instances cannot share a storage backend. Configure separate storage on named instances to preserve isolation.",
			details: {
				status: 409,
				knowledgeKey
			}
		});
		knowledge.__setLogger(this.#logger);
		knowledge.__registerMastra(this);
		if (!knowledge.hasOwnStorage && this.#storage) knowledge.setStorage(this.#storage, this.#storageSource);
		registry[knowledgeKey] = knowledge;
	}
	/**
	* Retrieves a registered memory instance by its registration key.
	*
	* @throws {MastraError} When the memory instance with the specified key is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   memory: {
	*     chat: new Memory({ storage })
	*   }
	* });
	*
	* const chatMemory = mastra.getMemory('chat');
	* ```
	*/
	getMemory(name) {
		if (!this.#memory || !this.#memory[name]) {
			const error = new MastraError({
				id: "MASTRA_GET_MEMORY_BY_KEY_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Memory with key ${String(name)} not found`,
				details: {
					status: 404,
					memoryKey: String(name),
					memory: Object.keys(this.#memory ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return this.#memory[name];
	}
	/**
	* Retrieves a registered memory instance by its ID.
	*
	* Searches through all registered memory instances and returns the one whose ID matches.
	*
	* @throws {MastraError} When no memory instance with the specified ID is found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   memory: {
	*     chat: new Memory({ id: 'chat-memory', storage })
	*   }
	* });
	*
	* const memory = mastra.getMemoryById('chat-memory');
	* ```
	*/
	getMemoryById(id) {
		const allMemory = this.#memory;
		if (allMemory) {
			for (const [, memory] of Object.entries(allMemory)) if (memory.id === id) return memory;
		}
		const error = new MastraError({
			id: "MASTRA_GET_MEMORY_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Memory with id ${id} not found`,
			details: {
				status: 404,
				memoryId: id,
				availableIds: Object.values(allMemory ?? {}).map((m) => m.id).join(", ")
			}
		});
		this.#logger?.trackException(error);
		throw error;
	}
	/**
	* Returns all registered memory instances as a record keyed by their names.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   memory: {
	*     chat: new Memory({ storage }),
	*     longTerm: new Memory({ storage })
	*   }
	* });
	*
	* const allMemory = mastra.listMemory();
	* console.log(Object.keys(allMemory)); // ['chat', 'longTerm']
	* ```
	*/
	listMemory() {
		return this.#memory;
	}
	/**
	* Adds a new memory instance to the Mastra instance.
	*
	* This method allows dynamic registration of memory instances after the Mastra instance
	* has been created.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const chatMemory = new Memory({
	*   id: 'chat-memory',
	*   storage: mastra.getStorage()
	* });
	* mastra.addMemory(chatMemory); // Uses memory.id as key
	* // or
	* mastra.addMemory(chatMemory, 'customKey'); // Uses custom key
	* ```
	*/
	addMemory(memory, key) {
		if (!memory) throw createUndefinedPrimitiveError("memory", memory, key);
		const memoryKey = key || memory.id;
		const memoryRegistry = this.#memory;
		if (memoryRegistry[memoryKey]) return;
		memory.__registerMastra(this);
		if (!memory.hasOwnStorage) {
			const storage = this.getStorage();
			if (storage) memory.setStorage(storage);
		}
		memoryRegistry[memoryKey] = memory;
	}
	/**
	* Returns all registered workflows as a record keyed by their IDs.
	*
	* @example Listing all workflows
	* ```typescript
	* const mastra = new Mastra({
	*   workflows: {
	*     dataProcessor: createWorkflow({...}).commit(),
	*     emailSender: createWorkflow({...}).commit(),
	*     reportGenerator: createWorkflow({...}).commit()
	*   }
	* });
	*
	* const allWorkflows = mastra.listWorkflows();
	* console.log(Object.keys(allWorkflows)); // ['dataProcessor', 'emailSender', 'reportGenerator']
	*
	* // Execute all workflows with sample data
	* for (const [id, workflow] of Object.entries(allWorkflows)) {
	*   console.log(`Workflow ${id}:`, workflow.name);
	*   // const result = await workflow.execute(sampleData);
	* }
	* ```
	*/
	listWorkflows(props = {}) {
		const workflows = Object.fromEntries(Object.entries(this.#workflows).filter(([key]) => !this.#hiddenWorkflowKeys.has(key)));
		if (props.serialized) return Object.entries(workflows).reduce((acc, [k, v]) => {
			return {
				...acc,
				[k]: { name: v.name }
			};
		}, {});
		return workflows;
	}
	/**
	* Removes a workflow from the Mastra instance by its key or ID.
	* Used when dynamic workflows are updated/deleted so subsequent saves can
	* re-register the same id cleanly.
	*
	* Note: this only clears the live in-process registration. In-flight runs
	* are unaffected (they capture stepFlow at start time). Static workflow
	* scorers stay registered (matching removeAgent/removeTool behavior).
	*
	* @param keyOrId - The workflow key or ID to remove
	* @returns true if a workflow was removed, false if no workflow was found
	*
	* @example
	* ```typescript
	* // Remove by key
	* mastra.removeWorkflow('myWorkflow');
	*
	* // Remove by ID
	* mastra.removeWorkflow('workflow-123');
	* ```
	*/
	removeWorkflow(keyOrId) {
		const workflows = this.#workflows;
		if (workflows[keyOrId]) {
			delete workflows[keyOrId];
			this.#hiddenWorkflowKeys.delete(keyOrId);
			return true;
		}
		const key = Object.keys(workflows).find((k) => workflows[k]?.id === keyOrId);
		if (key) {
			delete workflows[key];
			this.#hiddenWorkflowKeys.delete(key);
			return true;
		}
		return false;
	}
	/**
	* Returns how a workflow was registered — `'code'` for statically declared
	* or `addWorkflow()`-added workflows, `'dynamic'` for anything added via
	* `addDynamicWorkflow()` (either at boot or through the HTTP/SDK surface).
	* Returns `undefined` if no workflow is registered under that key/id.
	*
	* Reads `workflow.origin`, which is set to `'dynamic'` by `rehydrateWorkflow`
	* at construction time and defaults to `'code'` otherwise. Used by the HTTP
	* layer to surface a visual distinction (e.g. a "Dynamic" badge in Studio).
	*/
	getWorkflowOrigin(keyOrId) {
		const workflows = this.#workflows;
		return (workflows[keyOrId] ?? Object.values(workflows).find((wf) => wf?.id === keyOrId))?.origin;
	}
	/**
	* Adds a new workflow to the Mastra instance.
	*
	* This method allows dynamic registration of workflows after the Mastra instance
	* has been created. The workflow will be initialized with Mastra and primitives.
	*
	* @throws {MastraError} When a workflow with the same key already exists
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const newWorkflow = createWorkflow({
	*   id: 'data-pipeline',
	*   name: 'Data Pipeline'
	* }).commit();
	* mastra.addWorkflow(newWorkflow); // Uses workflow.id as key
	* // or
	* mastra.addWorkflow(newWorkflow, 'customKey'); // Uses custom key
	* ```
	*/
	addWorkflow(workflow, key) {
		if (!workflow) throw createUndefinedPrimitiveError("workflow", workflow, key);
		const workflowKey = key || workflow.id;
		const workflows = this.#workflows;
		if (workflows[workflowKey]) return;
		const hasSchedule = collectWorkflowScheduleConfigs(workflow).length > 0;
		if (!runsOnMastraScheduler(workflow) && readWorkflowScheduleConfigs(workflow).length > 0) this.#logger?.warn(`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\`).`, {
			workflowId: workflow.id,
			engineType: workflow.engineType
		});
		workflow.__registerMastra(this);
		workflow.__registerPrimitives({
			logger: this.getLogger(),
			storage: this.getStorage()
		});
		if (!workflow.committed) workflow.commit();
		workflows[workflowKey] = workflow;
		this.registerStaticWorkflowScorers(workflow);
		if (hasSchedule) {
			this.#hasScheduledWorkflow = true;
			if (this.#findSchedulerWorker()?.scheduler) (async () => {
				try {
					const schedulesStore = await this.#storage?.getStore("schedules");
					if (!schedulesStore) return;
					await this.registerDeclarativeSchedules(schedulesStore);
				} catch (error) {
					this.#logger?.error("Failed to register declarative schedule for workflow", {
						workflowId: workflow.id,
						error
					});
				}
			})();
		}
	}
	#replaceDynamicWorkflow(workflow, key) {
		workflow.__registerMastra(this);
		workflow.__registerPrimitives({
			logger: this.getLogger(),
			storage: this.getStorage()
		});
		if (!workflow.committed) workflow.commit();
		this.#workflows[key] = workflow;
		this.#hiddenWorkflowKeys.delete(key);
		this.registerStaticWorkflowScorers(workflow);
		if (collectWorkflowScheduleConfigs(workflow).length > 0) this.#hasScheduledWorkflow = true;
	}
	/**
	* Flattens this instance's registries into the index the dynamic-workflow
	* validation core resolves references and schemas against. Registered keys
	* and canonical ids both count as valid references. Schemas are converted
	* best-effort — an unconvertible schema degrades to "unknown", never to a
	* false incompatibility. Agents stay presence-only: their `{ prompt }`
	* input default lives in schema-flow itself.
	*/
	#buildWorkflowRegistryIndex() {
		const agents = {};
		for (const [key, agent] of Object.entries(this.listAgents() ?? {})) {
			agents[key] = {};
			agents[agent.id] = {};
		}
		const tools = {};
		for (const [key, tool] of Object.entries(this.listTools() ?? {})) {
			const schemas = {
				inputSchema: toJsonSchemaOrUndefined(tool.inputSchema),
				outputSchema: toJsonSchemaOrUndefined(tool.outputSchema)
			};
			tools[key] = schemas;
			tools[tool.id] = schemas;
		}
		const classifiers = {};
		const refusedAnswerDescription = "When the model refuses the question, the answer is { type: 'refusal' } with no choice, score, probability, or probabilities.";
		for (const [key, classifier] of Object.entries(this.listClassifiers() ?? {})) {
			const questions = classifier.questions ? Object.fromEntries(Object.entries(classifier.questions).map(([questionId, question]) => [questionId, question.type === "choice" ? {
				type: "choice",
				choices: Object.keys(question.criteria)
			} : question.type === "score" ? {
				type: "score",
				min: 0,
				max: question.criteria.length - 1
			} : { type: "boolean" }])) : void 0;
			const answerProperties = questions ? Object.fromEntries(Object.entries(questions).map(([questionId, question]) => [questionId, question.type === "choice" ? {
				type: "object",
				properties: {
					type: {
						type: "string",
						enum: ["choice", "refusal"]
					},
					choice: {
						type: "string",
						enum: question.choices
					},
					probabilities: {
						type: "object",
						properties: Object.fromEntries(question.choices.map((choice) => [choice, { type: "number" }])),
						additionalProperties: false
					}
				},
				required: ["type"],
				description: refusedAnswerDescription
			} : question.type === "score" ? {
				type: "object",
				properties: {
					type: {
						type: "string",
						enum: ["score", "refusal"]
					},
					score: {
						type: "number",
						minimum: question.min,
						maximum: question.max
					},
					probabilities: {
						type: "object",
						properties: Object.fromEntries(Array.from({ length: question.max - question.min + 1 }, (_, index) => [String(question.min + index), { type: "number" }])),
						additionalProperties: false
					}
				},
				required: ["type"],
				description: refusedAnswerDescription
			} : {
				type: "object",
				properties: {
					type: {
						type: "string",
						enum: ["boolean", "refusal"]
					},
					probability: {
						type: "number",
						minimum: 0,
						maximum: 1
					}
				},
				required: ["type"],
				description: refusedAnswerDescription
			}])) : {};
			const schemas = {
				inputSchema: {},
				outputSchema: {
					type: "object",
					properties: {
						answers: {
							type: "object",
							properties: answerProperties,
							required: Object.keys(answerProperties)
						},
						usage: { type: "object" }
					},
					required: ["answers", "usage"]
				},
				questions
			};
			classifiers[key] = schemas;
			classifiers[classifier.id] = schemas;
		}
		const workflows = {};
		for (const [key, workflow] of Object.entries(this.#workflows)) {
			const schemas = {
				inputSchema: toJsonSchemaOrUndefined(workflow.inputSchema),
				outputSchema: toJsonSchemaOrUndefined(workflow.outputSchema)
			};
			workflows[key] = schemas;
			workflows[workflow.id] = schemas;
		}
		return {
			agents,
			tools,
			classifiers,
			workflows
		};
	}
	/**
	* Persist a static workflow definition to storage and live-register it on
	* this Mastra instance so it becomes immediately runnable. The same path is
	* used by `loadDynamicWorkflows()` at boot to re-materialize previously saved
	* workflows.
	*
	* @example
	* ```typescript
	* await mastra.addDynamicWorkflow({
	*   id: 'cli-weather-v1',
	*   inputSchema:  { type: 'object', properties: { location: { type: 'string' } }, required: ['location'] },
	*   outputSchema: { type: 'object', properties: { report:   { type: 'string' } }, required: ['report'] },
	*   graph: [...],
	* });
	*
	* const run = await mastra.getWorkflow('cli-weather-v1').createRun();
	* await run.start({ inputData: { location: 'Helsinki' } });
	* ```
	*/
	async addDynamicWorkflow(def) {
		await this.addDynamicWorkflows([def]);
	}
	/**
	* Persist and live-register a set of dynamic workflow definitions that depend
	* on each other — typically a root workflow plus the helper workflows it
	* nests, none of which exist yet.
	*
	* The bundle is validated as a unit: references resolve against this
	* instance's registries UNION the bundle's own ids, so a root may nest a
	* helper being introduced in the same call. Members are then hydrated in
	* dependency order, since hydration resolves nested workflows through the
	* live registry.
	*
	* Failure semantics — a rejected bundle registers nothing:
	* - Duplicate ids, invalid members, and dependency cycles are all detected
	*   before anything is mutated.
	* - If hydration or persistence fails partway, the in-memory registry is
	*   restored to its prior state.
	* - Storage writes happen last. A storage-level failure mid-bundle is the
	*   one residual window where rows can be partially written; the registry is
	*   still rolled back, and the orphaned rows are inert until the next boot.
	*
	* `addDynamicWorkflow()` is the single-member case.
	*
	* @example
	* ```typescript
	* await mastra.addDynamicWorkflows([
	*   { id: 'lookup-first-customer', ... },  // helper — order is derived, not assumed
	*   { id: 'parallel-customer-lookup', ... }, // root, nests the helper above
	* ]);
	* ```
	*/
	async addDynamicWorkflows(defs) {
		if (defs.length === 0) return;
		const seen = /* @__PURE__ */ new Set();
		for (const def of defs) {
			if (seen.has(def.id)) throw new Error(`Dynamic workflow bundle contains more than one definition with id "${def.id}". Ids must be unique within a bundle.`);
			seen.add(def.id);
		}
		const members = defs.map((def) => ({ normalized: normalizeWorkflowBuilderDefinition({
			id: def.id,
			description: def.description,
			metadata: def.metadata,
			inputSchema: def.inputSchema,
			outputSchema: def.outputSchema,
			stateSchema: def.stateSchema,
			requestContextSchema: def.requestContextSchema,
			graph: def.graph,
			schedule: def.schedule
		}) }));
		const index = this.#buildWorkflowRegistryIndex();
		const bundleIds = new Set(members.map((member) => member.normalized.id));
		for (const { normalized } of members) (index.workflows ??= {})[normalized.id] = {
			inputSchema: normalized.inputSchema,
			outputSchema: normalized.outputSchema
		};
		for (const { normalized } of members) assertValidDynamicWorkflow(normalized, index);
		const ordered = [];
		const remaining = new Map(members.map((member) => [member.normalized.id, member]));
		const hydrated = /* @__PURE__ */ new Set();
		let progress = true;
		while (remaining.size > 0 && progress) {
			progress = false;
			for (const [id, member] of Array.from(remaining)) {
				if (Array.from(collectNestedWorkflowIds(member.normalized.graph)).filter((dependency) => dependency !== id && bundleIds.has(dependency) && !hydrated.has(dependency)).length > 0) continue;
				remaining.delete(id);
				hydrated.add(id);
				ordered.push(member);
				progress = true;
			}
		}
		if (remaining.size > 0) throw new Error(`Dynamic workflow bundle has a circular nested-workflow dependency among: ${Array.from(remaining.keys()).sort().join(", ")}.`);
		const registry = this.#workflows;
		const priorWorkflows = /* @__PURE__ */ new Map();
		const priorHiddenKeys = /* @__PURE__ */ new Set();
		for (const { normalized } of ordered) {
			priorWorkflows.set(normalized.id, registry[normalized.id]);
			if (this.#hiddenWorkflowKeys.has(normalized.id)) priorHiddenKeys.add(normalized.id);
		}
		const restoreRegistry = () => {
			for (const [id, prior] of priorWorkflows) {
				if (prior) registry[id] = prior;
				else delete registry[id];
				if (priorHiddenKeys.has(id)) this.#hiddenWorkflowKeys.add(id);
			}
		};
		try {
			for (const { normalized } of ordered) {
				const { workflow } = await rehydrateWorkflow(normalized, this);
				this.#replaceDynamicWorkflow(workflow, normalized.id);
			}
			const store = await this.#storage?.getStore("workflowDefinitions");
			if (store) for (const { normalized } of ordered) await store.upsert({
				id: normalized.id,
				description: normalized.description,
				metadata: normalized.metadata,
				inputSchema: normalized.inputSchema,
				outputSchema: normalized.outputSchema,
				stateSchema: normalized.stateSchema,
				requestContextSchema: normalized.requestContextSchema,
				graph: normalized.graph,
				schedule: normalized.schedule
			});
		} catch (error) {
			restoreRegistry();
			throw error;
		}
		if (this.#findSchedulerWorker()?.scheduler) try {
			const schedulesStore = await this.#storage?.getStore("schedules");
			if (schedulesStore) await this.registerDeclarativeSchedules(schedulesStore);
		} catch (error) {
			this.#logger?.error("Failed to synchronize declarative schedules after dynamic workflow registration", {
				workflowIds: ordered.map(({ normalized }) => normalized.id),
				error
			});
		}
	}
	/**
	* Load any previously persisted workflow definitions from storage and
	* live-register each one. Called by `startWorkers()` after storage init.
	* Bad rows are logged and skipped — one corrupt definition shouldn't sink
	* the rest.
	* @internal
	*/
	async #loadDynamicWorkflows() {
		const store = await this.#storage?.getStore("workflowDefinitions");
		if (!store) return;
		const { definitions } = await store.list({ status: "active" });
		this.#failedDynamicWorkflowIds.clear();
		const pending = definitions.filter((d) => !this.#workflows[d.id]);
		const pendingIds = new Set(pending.map((d) => d.id));
		const deps = /* @__PURE__ */ new Map();
		for (const def of pending) {
			const all = collectNestedWorkflowIds(def.graph);
			const pendingDeps = /* @__PURE__ */ new Set();
			for (const id of all) if (pendingIds.has(id) && id !== def.id) pendingDeps.add(id);
			deps.set(def.id, pendingDeps);
		}
		const remaining = new Map(pending.map((d) => [d.id, d]));
		const loaded = /* @__PURE__ */ new Set();
		let progress = true;
		while (remaining.size > 0 && progress) {
			progress = false;
			for (const [id, def] of Array.from(remaining)) {
				if (Array.from(deps.get(id) ?? []).filter((d) => !loaded.has(d)).length > 0) continue;
				remaining.delete(id);
				progress = true;
				try {
					const { workflow } = await rehydrateWorkflow({
						id: def.id,
						description: def.description,
						metadata: def.metadata,
						inputSchema: def.inputSchema,
						outputSchema: def.outputSchema,
						stateSchema: def.stateSchema,
						requestContextSchema: def.requestContextSchema,
						graph: def.graph,
						schedule: def.schedule
					}, this, {
						onUnsupportedSchema: "warn",
						onUnsupported: (message) => this.#logger?.warn?.(`Dynamic workflow "${def.id}": ${message}`)
					});
					this.addWorkflow(workflow, def.id);
					loaded.add(def.id);
				} catch (error) {
					this.#failedDynamicWorkflowIds.add(def.id);
					this.#logger?.error?.(`Failed to load dynamic workflow "${def.id}"`, { error });
				}
			}
		}
		if (remaining.size > 0) {
			for (const id of remaining.keys()) this.#failedDynamicWorkflowIds.add(id);
			const stuck = Array.from(remaining.keys()).join(", ");
			this.#logger?.error?.(`Failed to load dynamic workflows (cycle or unresolved nested-workflow reference): ${stuck}`);
		}
	}
	/**
	* Signal that a schedule has been registered imperatively at runtime
	* (e.g. `mastra.schedules.create()` after `startWorkers()`). Flips the
	* scheduler-requested flag and, if workers are already running,
	* lazily injects + starts both the scheduler and agent-schedule workers.
	*
	* @internal
	*/
	async __ensureScheduleRuntimeReady() {
		this.#schedulerRequested = true;
		if (this.#workersStarted) await this.#ensureSchedulingWorkersStarted();
	}
	/**
	* Publish a best-effort cross-process wake after the schedule row is durable.
	* This also runs in producer-only (`workers: false`) processes.
	*
	* @internal
	*/
	async __publishSchedulerWake(scheduleId) {
		try {
			await this.#pubsub.publish(SCHEDULER_WAKE_TOPIC, {
				type: SCHEDULER_WAKE_EVENT,
				runId: scheduleId,
				data: {}
			});
		} catch (err) {
			this.#logger?.warn?.("Failed to publish scheduler wake event", err);
		}
	}
	/** Subscribe for cross-process scheduler wakes. Idempotent. */
	async #wireSchedulerWakeSubscription() {
		if (this.#schedulerWakeSubscription) return;
		const cb = async (event, ack, nack) => {
			try {
				if (event.type !== SCHEDULER_WAKE_EVENT) {
					await ack?.();
					return;
				}
				this.#schedulerRequested = true;
				if (this.#workersStarted) {
					await this.#ensureSchedulingWorkersStarted();
					this.#findSchedulerWorker()?.scheduler?.wake();
				}
				await ack?.();
			} catch (err) {
				await nack?.();
				this.#logger?.warn?.("Failed to start scheduling workers from wake event", err);
			}
		};
		this.#schedulerWakeSubscription = cb;
		try {
			await this.#pubsub.subscribe(SCHEDULER_WAKE_TOPIC, cb, { startFrom: "latest" });
		} catch (err) {
			if (this.#schedulerWakeSubscription === cb) this.#schedulerWakeSubscription = void 0;
			throw err;
		}
	}
	async #unwireSchedulerWakeSubscription() {
		const cb = this.#schedulerWakeSubscription;
		if (!cb) return;
		this.#schedulerWakeSubscription = void 0;
		await this.#pubsub.unsubscribe(SCHEDULER_WAKE_TOPIC, cb);
	}
	/**
	* One-shot boot probe for persisted agent, workflow, or notification-dispatch
	* schedules. Runtime discovery uses the wake subscription instead.
	*/
	async #detectPersistedSchedulerWork() {
		if (!this.#storage) return;
		try {
			const schedulesStore = await this.#storage.getStore("schedules");
			if (!schedulesStore) return;
			const rows = await schedulesStore.listSchedules();
			let hasWork = rows.some((row) => row.id !== NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);
			const dispatchEnabled = this.#notificationDispatchConfig?.enabled !== false;
			if (!hasWork && dispatchEnabled && rows.some((row) => row.id === "__mastra_notification_dispatch")) {
				const notifications = await this.#storage.getStore("notifications");
				hasWork = notifications ? await hasPendingDeferredNotifications(notifications) : false;
			}
			if (hasWork) this.#schedulerRequested = true;
		} catch (err) {
			this.#logger?.warn?.("Failed to detect persisted scheduler work on boot", err);
		}
	}
	/**
	* Signal that a deferred notification exists and the dispatcher schedule is
	* needed. Lazily upserts the dispatcher schedule row (imperative, non-`wf_`
	* id so declarative orphan-cleanup leaves it alone) and requests the
	* scheduler — mirroring `__ensureScheduleRuntimeReady()`. This also supports
	* processes that publish notifications without running workers locally.
	*
	* The row is read on every call rather than memoized: the dispatcher deletes
	* it once nothing is pending (`__releaseNotificationDispatchIfIdle()`),
	* possibly from another process, and the next deferral must re-arm it.
	*
	* @internal
	*/
	async __ensureNotificationDispatchReady() {
		if (this.#notificationDispatchConfig?.enabled === false) return;
		if (!this.#storage) return;
		let created = false;
		try {
			const schedulesStore = await this.#storage.getStore("schedules");
			if (!schedulesStore) return;
			const desired = buildNotificationDispatchSchedule(this.#notificationDispatchConfig);
			const existing = await schedulesStore.getSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);
			if (!existing) try {
				await schedulesStore.createSchedule(desired);
				created = true;
			} catch (err) {
				if (!await schedulesStore.getSchedule("__mastra_notification_dispatch")) throw err;
			}
			else {
				const patch = {};
				if (existing.cron !== desired.cron) {
					patch.cron = desired.cron;
					patch.nextFireAt = desired.nextFireAt;
				}
				if (!targetsEqual(existing.target, desired.target)) patch.target = desired.target;
				if (Object.keys(patch).length > 0) await schedulesStore.updateSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID, patch);
			}
		} catch (err) {
			this.#logger?.warn?.("Failed to ensure notification dispatch schedule", err);
			return;
		}
		if (this.#notificationDispatchReady && !created) return;
		this.#notificationDispatchReady = true;
		this.#schedulerRequested = true;
		if (this.#workersStarted) await this.#ensureSchedulingWorkersStarted();
		await this.__publishSchedulerWake(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);
	}
	/**
	* Called by the dispatcher after each pass. When no deferred notification is
	* pending, deletes the dispatcher schedule row so its cron stops firing and
	* an idle app stops polling storage. The next deferral re-creates it.
	*
	* @internal
	*/
	async __releaseNotificationDispatchIfIdle() {
		if (!this.#storage) return;
		try {
			const [schedulesStore, notifications] = await Promise.all([this.#storage.getStore("schedules"), this.#storage.getStore("notifications")]);
			if (!schedulesStore || !notifications) return;
			if (await hasPendingDeferredNotifications(notifications)) return;
			await schedulesStore.deleteSchedule(NOTIFICATION_DISPATCH_SCHEDULE_ROW_ID);
			this.#notificationDispatchReady = false;
			if (await hasPendingDeferredNotifications(notifications)) await this.__ensureNotificationDispatchReady();
		} catch (err) {
			this.#logger?.warn?.("Failed to release idle notification dispatch schedule", err);
		}
	}
	/**
	* Lazily inject and start the SchedulerWorker (and AgentScheduleWorker when
	* needed) after `startWorkers()` has already run. Used by features that
	* surface a need for the scheduler at runtime (e.g.
	* `mastra.schedules.create()`). No-op when the scheduler is disabled, no
	* storage is configured, or the workers are already present.
	*
	* @internal
	*/
	async #ensureSchedulingWorkersStarted() {
		if (!this.#schedulingWorkersStartPromise) this.#schedulingWorkersStartPromise = this.#startSchedulingWorkers().finally(() => {
			this.#schedulingWorkersStartPromise = void 0;
		});
		await this.#schedulingWorkersStartPromise;
	}
	async #startSchedulingWorkers() {
		if (this.#workerFilter && !this.#workerFilter.has("scheduler")) return;
		if (!this.#shouldEnableScheduler()) return;
		if (!this.#storage) return;
		const deps = {
			pubsub: this.#pubsub,
			storage: this.#storage,
			logger: this.#logger,
			mastra: this
		};
		let schedulerWorker = this.#findSchedulerWorker();
		if (!schedulerWorker) {
			schedulerWorker = new SchedulerWorker(this.#schedulerConfig);
			schedulerWorker.__registerMastra(this);
			this.#workers.push(schedulerWorker);
		}
		if (!schedulerWorker.isRunning) {
			await schedulerWorker.init(deps);
			await schedulerWorker.start();
		}
		if (!this.#workerFilter || this.#workerFilter.has("agent-schedule")) {
			let agentScheduleWorker = this.#findAgentScheduleWorker();
			if (!agentScheduleWorker) {
				const { AgentScheduleWorker } = await import("./worker-OXyX9B5Z.js");
				agentScheduleWorker = new AgentScheduleWorker();
				agentScheduleWorker.__registerMastra(this);
				this.#workers.push(agentScheduleWorker);
			}
			if (!agentScheduleWorker.isRunning) {
				await agentScheduleWorker.init(deps);
				await agentScheduleWorker.start();
			}
		}
	}
	registerStaticWorkflowScorers(workflow) {
		for (const step of Object.values(workflow.steps ?? {})) {
			const scorers = step.scorers;
			if (!scorers || typeof scorers === "function") continue;
			for (const [, entry] of Object.entries(scorers)) this.addScorer(entry.scorer, void 0, { source: "code" });
		}
	}
	/**
	* Sets the storage provider for the Mastra instance.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	*
	* // Set PostgreSQL storage
	* mastra.setStorage(new PostgresStore({
	*   connectionString: process.env.DATABASE_URL
	* }));
	*
	* // Now agents can use memory with the storage
	* const agent = new Agent({
	*   id: 'assistant',
	*   name: 'assistant',
	*   memory: new Memory({ storage: mastra.getStorage() })
	* });
	* ```
	*/
	setStorage(storage) {
		const knowledgeInstances = Object.values(this.#knowledge);
		if (knowledgeInstances.some((instance) => !instance.hasOwnStorage) && knowledgeInstances.some((instance) => instance.hasOwnStorage && instance.__usesStorage(storage))) throw new MastraError({
			id: "MASTRA_SET_STORAGE_KNOWLEDGE_CONFLICT",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: "Cannot set Mastra storage because a named Knowledge instance already uses that backend.",
			details: { status: 409 }
		});
		this.#storageFallbackWarningPending = false;
		this.#storageSource = getStorageSource(storage);
		this.#storage = augmentWithInit(storage);
		this.#storage?.__registerMastra?.(this);
		this.#storage.__setLogger(this.#logger);
		for (const knowledge of Object.values(this.#knowledge)) if (!knowledge.hasOwnStorage) knowledge.setStorage(this.#storage, this.#storageSource);
		this.#ensureBackgroundTaskManager();
	}
	/**
	* Wire a logger into observability. Adaptable loggers get trace
	* correlation + export attached in place (native record path); other
	* loggers are wrapped in the deprecated DualLogger fallback.
	*/
	#wireLoggerObservability(logger) {
		const inner = logger;
		if (isAdaptableLogger(inner)) {
			if (this.#wiredLoggers.has(inner)) return logger;
			this.#wiredLoggers.add(inner);
			const ownershipKey = inner.__observabilityAttachmentKey?.() ?? inner;
			const previousOwner = attachedLoggerOwners.get(ownershipKey);
			if (previousOwner && previousOwner !== this && this.#loggerAdapterOptions.export) try {
				inner.warn("This logger instance is already wired to another Mastra instance; re-attaching. Its observability export now targets the newest Mastra. Create a separate logger per Mastra instance to keep exports isolated.");
			} catch {}
			attachedLoggerOwners.set(ownershipKey, this);
			inner.__attachObservability({
				resolveTraceFields,
				getLogSink: () => {
					if (!this.#loggerAdapterOptions.export || isObservabilityExportSuppressed()) return void 0;
					const span = resolveCurrentSpan();
					return span?.observabilityInstance?.getLoggerContext?.(span) ?? this.#observability.getDefaultInstance()?.getLoggerContext?.();
				},
				options: this.#loggerAdapterOptions
			});
			return logger;
		}
		if (inner instanceof DualLogger) return this.#wireLoggerObservability(inner.baseLogger);
		const existing = this.#fallbackWrappers.get(inner);
		if (existing) return existing;
		try {
			inner.debug?.("Configured logger does not support observability adapters; falling back to DualLogger (deprecated). Implement __attachObservability() on your logger to get trace-correlated stdout.");
		} catch {}
		const wrapper = new DualLogger(inner, this.#loggerAdapterOptions.export ? () => this.#observability.getDefaultInstance()?.getLoggerContext?.() : void 0);
		this.#fallbackWrappers.set(inner, wrapper);
		return wrapper;
	}
	setLogger({ logger }) {
		this.#logger = this.#wireLoggerObservability(logger);
		if (this.#agents) Object.keys(this.#agents).forEach((key) => {
			this.#agents?.[key]?.__setLogger(this.#logger);
			this.#agents?.[key]?.getChannels()?.__setLogger(this.#logger);
		});
		Object.values(this.#harnesses ?? {}).forEach((controller) => controller.getChannels()?.__setLogger(this.#logger));
		if (this.#deployer) this.#deployer.__setLogger(this.#logger);
		if (this.#tts) Object.keys(this.#tts).forEach((key) => {
			this.#tts?.[key]?.__setLogger(this.#logger);
		});
		if (this.#storage) this.#storage.__setLogger(this.#logger);
		if (this.#vectors) Object.keys(this.#vectors).forEach((key) => {
			this.#vectors?.[key]?.__setLogger(this.#logger);
		});
		if (this.#mcpServers) Object.keys(this.#mcpServers).forEach((key) => {
			this.#mcpServers?.[key]?.__setLogger(this.#logger);
		});
		if (this.#workflows) Object.keys(this.#workflows).forEach((key) => {
			this.#workflows?.[key]?.__setLogger(this.#logger);
		});
		Object.values(this.#knowledge).forEach((knowledge) => knowledge.__setLogger(this.#logger));
		if (this.#serverAdapter) this.#serverAdapter.__setLogger(this.#logger);
		if (this.#workspace) this.#workspace.__setLogger(this.#logger);
		if (this.#memory) Object.keys(this.#memory).forEach((key) => {
			this.#memory?.[key]?.__setLogger(this.#logger);
		});
		this.#observability.setLogger({ logger: this.#observabilitySafeLogger() });
	}
	/**
	* A view of the current logger safe to hand to observability internals:
	* unwraps the DualLogger fallback and suppresses observability export.
	*/
	#observabilitySafeLogger() {
		const inner = this.#logger instanceof DualLogger ? this.#logger.baseLogger : this.#logger;
		return createExportSuppressedLogger(inner);
	}
	/**
	* Gets all registered text-to-speech (TTS) providers.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   tts: {
	*     openai: new OpenAITTS({
	*       apiKey: process.env.OPENAI_API_KEY,
	*       voice: 'alloy'
	*     })
	*   }
	* });
	*
	* const ttsProviders = mastra.getTTS();
	* const openaiTTS = ttsProviders?.openai;
	* if (openaiTTS) {
	*   const audioBuffer = await openaiTTS.synthesize('Hello, world!');
	* }
	* ```
	*/
	getTTS() {
		return this.#tts;
	}
	/**
	* Gets the currently configured logger instance.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   logger: new PinoLogger({
	*     name: 'MyApp',
	*     level: 'info'
	*   })
	* });
	*
	* const logger = mastra.getLogger();
	* logger.info('Application started');
	* logger.error('An error occurred', { error: 'details' });
	* ```
	*/
	getLogger() {
		return this.#logger;
	}
	/**
	* Gets the currently configured storage provider.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./data.db' })
	* });
	*
	* // Use the storage in agent memory
	* const agent = new Agent({
	*   id: 'assistant',
	*   name: 'assistant',
	*   memory: new Memory({
	*     storage: mastra.getStorage()
	*   })
	* });
	* ```
	*/
	getStorage() {
		return this.#storage;
	}
	get observability() {
		return this.#observability;
	}
	/**
	* Structured logging API for observability.
	* Logs emitted via this API will not have trace correlation when used outside a span.
	* Use for startup logs, background jobs, or other non-traced scenarios.
	*
	* Note: For the infrastructure logger (IMastraLogger), use getLogger() instead.
	*/
	get loggerVNext() {
		return this.#observability.getDefaultInstance()?.getLoggerContext?.() ?? noOpLoggerContext;
	}
	/**
	* Direct metrics API for use outside trace context.
	* Metrics emitted via this API will not have auto correlation or cost context from spans.
	* Use for background jobs, startup metrics, or other non-traced scenarios.
	*/
	get metrics() {
		return this.#observability.getDefaultInstance()?.getMetricsContext?.() ?? noOpMetricsContext;
	}
	getServerMiddleware() {
		return this.#serverMiddleware;
	}
	getServerCache() {
		return this.#serverCache;
	}
	setServerMiddleware(serverMiddleware) {
		if (typeof serverMiddleware === "function") {
			this.#serverMiddleware = [{
				handler: serverMiddleware,
				path: "/api/*"
			}];
			return;
		}
		if (!Array.isArray(serverMiddleware)) {
			const error = new MastraError({
				id: "MASTRA_SET_SERVER_MIDDLEWARE_INVALID_TYPE",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Invalid middleware: expected a function or array, received ${typeof serverMiddleware}`
			});
			this.#logger?.trackException(error);
			throw error;
		}
		this.#serverMiddleware = serverMiddleware.map((m) => {
			if (typeof m === "function") return {
				handler: m,
				path: "/api/*"
			};
			return {
				handler: m.handler,
				path: m.path || "/api/*"
			};
		});
	}
	getServer() {
		return this.#server;
	}
	/**
	* Gets the Studio-specific authentication and authorization configuration.
	*
	* @returns The studio config, or undefined if not configured
	*
	* @example
	* ```typescript
	* const studioConfig = mastra.getStudio();
	* if (studioConfig?.auth) {
	*   // Studio has separate auth configured
	* }
	* ```
	*/
	getStudio() {
		return this.#studio;
	}
	/**
	* Sets the server adapter for this Mastra instance.
	*
	* The server adapter provides access to the underlying server app (e.g., Hono, Express)
	* and allows users to call routes directly via `app.fetch()` instead of making HTTP requests.
	*
	* This is typically called by `createHonoServer` or similar factory functions during
	* server initialization.
	*
	* @param adapter - The server adapter instance (e.g., MastraServer from @mastra/hono or @mastra/express)
	*
	* @example
	* ```typescript
	* const app = new Hono();
	* const adapter = new MastraServer({ app, mastra });
	* mastra.setMastraServer(adapter);
	* ```
	*/
	setMastraServer(adapter) {
		if (this.#serverAdapter) this.#logger?.debug("Replacing existing server adapter. Only one adapter should be registered per Mastra instance.");
		this.#serverAdapter = adapter;
		if (this.#logger) adapter.__setLogger(this.#logger);
	}
	/**
	* Gets the server adapter for this Mastra instance.
	*
	* @returns The server adapter, or undefined if not set
	*
	* @example
	* ```typescript
	* const adapter = mastra.getMastraServer();
	* if (adapter) {
	*   const app = adapter.getApp<Hono>();
	* }
	* ```
	*/
	getMastraServer() {
		return this.#serverAdapter;
	}
	/**
	* Gets the server app from the server adapter.
	*
	* This is a convenience method that calls `getMastraServer()?.getApp<T>()`.
	* Use this to access the underlying server framework's app instance (e.g., Hono, Express)
	* for direct operations like calling routes via `app.fetch()`.
	*
	* @template T - The expected type of the app (e.g., Hono, Express Application)
	* @returns The server app, or undefined if no adapter is set
	*
	* @example
	* ```typescript
	* // After createHonoServer() is called:
	* const app = mastra.getServerApp<Hono>();
	*
	* // Call routes directly without HTTP overhead
	* const response = await app?.fetch(new Request('http://localhost/health'));
	* const data = await response?.json();
	* ```
	*/
	getServerApp() {
		return this.#serverAdapter?.getApp();
	}
	getBundlerConfig() {
		return this.#bundler;
	}
	async listLogsByRunId({ runId, transportId, fromDate, toDate, logLevel, filters, page, perPage }) {
		if (!transportId) {
			const error = new MastraError({
				id: "MASTRA_LIST_LOGS_BY_RUN_ID_MISSING_TRANSPORT",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: "Transport ID is required",
				details: {
					runId,
					transportId
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		if (!this.#logger?.listLogsByRunId) {
			const error = new MastraError({
				id: "MASTRA_GET_LOGS_BY_RUN_ID_LOGGER_NOT_CONFIGURED",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.SYSTEM,
				text: "Logger is not configured or does not support listLogsByRunId operation",
				details: {
					runId,
					transportId
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return await this.#logger.listLogsByRunId({
			runId,
			transportId,
			fromDate,
			toDate,
			logLevel,
			filters,
			page,
			perPage
		});
	}
	async listLogs(transportId, params) {
		if (!transportId) {
			const error = new MastraError({
				id: "MASTRA_GET_LOGS_MISSING_TRANSPORT",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: "Transport ID is required",
				details: { transportId }
			});
			this.#logger?.trackException(error);
			throw error;
		}
		if (!this.#logger) throw new MastraError({
			id: "MASTRA_GET_LOGS_LOGGER_NOT_CONFIGURED",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.SYSTEM,
			text: "Logger is not set",
			details: { transportId }
		});
		return await this.#logger.listLogs(transportId, params);
	}
	/**
	* Gets all registered Model Context Protocol (MCP) server instances.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   mcpServers: {
	*     filesystem: new FileSystemMCPServer({
	*       rootPath: '/app/data'
	*     })
	*   }
	* });
	*
	* const mcpServers = mastra.getMCPServers();
	* if (mcpServers) {
	*   const fsServer = mcpServers.filesystem;
	*   const tools = await fsServer.listTools();
	* }
	* ```
	*/
	listMCPServers() {
		return this.#mcpServers;
	}
	/**
	* Adds a new MCP server to the Mastra instance.
	*
	* This method allows dynamic registration of MCP servers after the Mastra instance
	* has been created. The server will be initialized with ID, Mastra instance, and logger.
	*
	* @throws {MastraError} When an MCP server with the same key already exists
	*
	* @example
	* ```typescript
	* const mastra = new Mastra();
	* const newServer = new FileSystemMCPServer({
	*   rootPath: '/data'
	* });
	* mastra.addMCPServer(newServer); // Uses server.id as key
	* // or
	* mastra.addMCPServer(newServer, 'customKey'); // Uses custom key
	* ```
	*/
	addMCPServer(server, key) {
		if (!server) throw createUndefinedPrimitiveError("mcp-server", server, key);
		if (key) server.setId(key);
		const resolvedId = server.id;
		if (!resolvedId) {
			const error = new MastraError({
				id: "MASTRA_ADD_MCP_SERVER_MISSING_ID",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: "MCP server must expose an id or be registered under one",
				details: { status: 400 }
			});
			this.#logger?.trackException(error);
			throw error;
		}
		const serverKey = key ?? resolvedId;
		const servers = this.#mcpServers;
		if (servers[serverKey]) return;
		server.__registerMastra(this);
		server.__setLogger(this.getLogger());
		servers[serverKey] = server;
	}
	/**
	* Retrieves a specific MCP server instance by registration key.
	*
	* @throws {MastraError} When the specified MCP server is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   mcpServers: {
	*     filesystem: new FileSystemMCPServer({...})
	*   }
	* });
	*
	* const fsServer = mastra.getMCPServer('filesystem');
	* const tools = await fsServer.listTools();
	* ```
	*/
	getMCPServer(name) {
		if (!this.#mcpServers || !this.#mcpServers[name]) {
			this.#logger?.debug(`MCP server with name ${String(name)} not found`);
			return;
		}
		return this.#mcpServers[name];
	}
	/**
	* Retrieves a specific Model Context Protocol (MCP) server instance by its logical ID.
	*
	* This method searches for an MCP server using its logical ID. If a version is specified,
	* it returns the exact version match. If no version is provided, it returns the server
	* with the most recent release date.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   mcpServers: {
	*     filesystem: new FileSystemMCPServer({
	*       id: 'fs-server',
	*       version: '1.0.0',
	*       rootPath: '/app/data'
	*     })
	*   }
	* });
	*
	* const fsServer = mastra.getMCPServerById('fs-server');
	* if (fsServer) {
	*   const tools = await fsServer.listTools();
	* }
	* ```
	*/
	getMCPServerById(serverId, version) {
		if (!this.#mcpServers) return;
		const matchingLogicalIdServers = Object.values(this.#mcpServers || {}).filter((server) => server.id === serverId);
		if (matchingLogicalIdServers.length === 0) {
			this.#logger?.debug(`No MCP servers found with logical ID: ${serverId}`);
			return;
		}
		if (version) {
			const specificVersionServer = matchingLogicalIdServers.find((server) => server.version === version);
			if (!specificVersionServer) this.#logger?.debug(`MCP server with logical ID '${serverId}' found, but not version '${version}'.`);
			return specificVersionServer;
		}
		if (matchingLogicalIdServers.length === 1) return matchingLogicalIdServers[0];
		matchingLogicalIdServers.sort((a, b) => {
			const dateAVal = a.releaseDate && typeof a.releaseDate === "string" ? new Date(a.releaseDate).getTime() : NaN;
			const dateBVal = b.releaseDate && typeof b.releaseDate === "string" ? new Date(b.releaseDate).getTime() : NaN;
			if (isNaN(dateAVal) && isNaN(dateBVal)) return 0;
			if (isNaN(dateAVal)) return 1;
			if (isNaN(dateBVal)) return -1;
			return dateBVal - dateAVal;
		});
		if (matchingLogicalIdServers.length > 0) {
			const latestServer = matchingLogicalIdServers[0];
			if (latestServer && latestServer.releaseDate && typeof latestServer.releaseDate === "string" && !isNaN(new Date(latestServer.releaseDate).getTime())) return latestServer;
		}
		this.#logger?.warn(`Could not determine the latest server for logical ID '${serverId}' due to invalid or missing release dates, or no servers left after filtering.`);
	}
	/**
	* Wrap a user-provided topic listener so the delivery is acknowledged once
	* the listener resolves. User listeners take only the event, so nothing
	* would ever call `ack` for them — and on a durable transport (Redis
	* consumer groups) an unacknowledged delivery stays pending for the life of
	* the subscription. A throwing listener nacks instead so the transport can
	* redeliver rather than assume success.
	*
	* The wrapper is memoized per listener so `removeTopicListener` can
	* unsubscribe the exact callback `addTopicListener` registered.
	*/
	#ackingTopicListeners = /* @__PURE__ */ new WeakMap();
	#ackingTopicListener(listener) {
		const existing = this.#ackingTopicListeners.get(listener);
		if (existing) return existing;
		const wrapped = async (event, ack, nack) => {
			try {
				await listener(event);
			} catch (err) {
				this.#logger?.error?.("Error in topic listener; nacking event", {
					eventType: event.type,
					err: err instanceof Error ? err.message : err
				});
				await nack?.();
				return;
			}
			await ack?.();
		};
		this.#ackingTopicListeners.set(listener, wrapped);
		return wrapped;
	}
	async addTopicListener(topic, listener) {
		await this.#pubsub.subscribe(topic, this.#ackingTopicListener(listener));
	}
	async removeTopicListener(topic, listener) {
		await this.#pubsub.unsubscribe(topic, this.#ackingTopicListener(listener));
	}
	/**
	* Process a single workflow event. Shared entry point used by:
	* - pull-mode workers (OrchestrationWorker)
	* - in-process push pubsubs (EventEmitterPubSub) wired during startWorkers()
	* - HTTP push delivered to `POST /api/workers/events`
	*
	* Returns `{ ok: true }` on success; the caller should ack/return 2xx.
	* Returns `{ ok: false, retry: true }` on transient failure; the caller
	* should nack/return 5xx so the broker retries.
	*/
	async handleWorkflowEvent(event) {
		if (!this.#workflowEventProcessor) this.#workflowEventProcessor = new WorkflowEventProcessor({ mastra: this });
		return this.#workflowEventProcessor.handle(event);
	}
	/**
	* Initialize and start workers. If `name` is provided, starts only
	* that worker. Otherwise starts all registered workers and subscribes
	* user-defined event listeners.
	*
	* When the orchestration worker is among them, this also starts the
	* workflow recovery loop (unless `recovery.workflows` is `'off'`): every
	* `recovery.workflowScanIntervalMs` it restarts default-engine runs whose
	* instance stopped, by the rule of {@link Mastra.restartAllActiveWorkflowRuns}.
	* Instances sharing a store elect one leader through a run lease; the others'
	* ticks only try to take that role, which they get once the leader's
	* `stopWorkers()` releases it or its lease lapses. The leader's loop looks
	* only at the workflows it registers, and the runs it restarts execute on
	* it. The loop never restarts evented runs, and doesn't run on a store
	* without run fencing.
	*/
	async startWorkers(name) {
		if (this.#storage) await this.#storage.init();
		const schedulerSelected = !this.#schedulerDisabled() && (!this.#workerFilter || this.#workerFilter.has("scheduler"));
		const schedulerForcedByFilter = schedulerSelected && (this.#workerFilter?.has("scheduler") ?? false);
		if (!name && schedulerSelected && this.#storage && !this.#findSchedulerWorker()?.isRunning) try {
			await this.#wireSchedulerWakeSubscription();
		} catch (err) {
			this.#logger?.warn?.("Failed to subscribe to scheduler wake events; scheduler will not wake on demand", err);
		}
		if (!name && schedulerSelected && !this.#schedulerRequested && !schedulerForcedByFilter) await this.#detectPersistedSchedulerWork();
		if (!name && (this.#shouldEnableScheduler() || schedulerForcedByFilter) && this.#storage) {
			if (!this.#findSchedulerWorker()) {
				const sw = new SchedulerWorker(schedulerForcedByFilter ? {
					...this.#schedulerConfig,
					enabled: true
				} : this.#schedulerConfig);
				sw.__registerMastra(this);
				this.#workers.push(sw);
			}
			if (!this.#findAgentScheduleWorker()) {
				const { AgentScheduleWorker } = await import("./worker-OXyX9B5Z.js");
				const asw = new AgentScheduleWorker();
				asw.__registerMastra(this);
				this.#workers.push(asw);
			}
		}
		const deps = {
			pubsub: this.#pubsub,
			storage: this.#storage,
			logger: this.#logger,
			mastra: this
		};
		let targets;
		if (name) {
			targets = this.#workers.filter((w) => w.name === name);
			if (targets.length === 0) throw new Error(`Worker "${name}" not found. Available: ${this.#workers.map((w) => w.name).join(", ")}`);
		} else if (this.#workerFilter) {
			targets = this.#workers.filter((w) => this.#workerFilter.has(w.name));
			if (targets.length === 0) this.#logger?.warn?.(`MASTRA_WORKERS=${[...this.#workerFilter].join(",")} did not match any registered workers (have: ${this.#workers.map((w) => w.name).join(", ")})`);
		} else targets = this.#workers;
		if (this.#storage) await this.#loadDynamicWorkflows();
		if (name === "backgroundTasks" && this.#backgroundTaskManager && this.#backgroundTaskManager.config.mode === "producer") {
			await this.#backgroundTaskManager.shutdown();
			this.#backgroundTaskManager = void 0;
			this.#ensureBackgroundTaskManager("full");
		}
		for (const worker of targets) {
			await worker.init(deps);
			await worker.start();
		}
		if (!name) await this.#wirePushWorkflowSubscription();
		if (!name) for (const topic in this.#events) {
			if (!this.#events[topic]) continue;
			const listeners = Array.isArray(this.#events[topic]) ? this.#events[topic] : [this.#events[topic]];
			for (const listener of listeners) {
				const cb = this.#ackingTopicListener(listener);
				if (this.#userEventSubscriptions.some((sub) => sub.topic === topic && sub.cb === cb)) continue;
				await this.#pubsub.subscribe(topic, cb);
				this.#userEventSubscriptions.push({
					topic,
					cb
				});
			}
		}
		this.#workersStarted = true;
		if (!name && this.#schedulerRequested && !this.#findSchedulerWorker()) await this.#ensureSchedulingWorkersStarted();
		if (name ? name === "orchestration" : !this.#workerFilter || this.#workerFilter.has("orchestration")) this.#startWorkflowRecoveryLoop();
	}
	/**
	* Wire `handleWorkflowEvent` directly to the pubsub when it is push-only
	* (no pull mode for an OrchestrationWorker to drive). Idempotent — no-op
	* when the pubsub supports pull or the subscription already exists.
	* Shared by `startWorkers()` and `__ensureExecutionWorkersStarted()`.
	*/
	async #wirePushWorkflowSubscription() {
		const modes = this.#pubsub.supportedModes ?? ["pull"];
		if (modes.includes("push") && !modes.includes("pull") && !this.#pushSubscription) {
			const cb = (event, ack, nack) => {
				const data = event.data;
				const wfId = data?.workflowId;
				const rId = data?.runId;
				if (wfId && rId && !this.#ownsWorkflow(wfId, rId, data?.parentWorkflow)) {
					if (ack) ack().catch((err) => this.#logger?.error?.("Error acking skipped workflow event", err));
					return;
				}
				const inFlight = this.handleWorkflowEvent(event).then((result) => {
					if (result.ok) {
						if (ack) return ack().catch((err) => this.#logger?.error?.("Error acking workflow event in push subscription", err));
						return;
					}
					if (result.retry) {
						if (nack) return nack().catch((err) => this.#logger?.error?.("Error nacking workflow event in push subscription", err));
						this.#logger?.error?.("Retryable workflow event cannot be requeued because nack is unavailable", {
							type: event.type,
							runId: event.runId
						});
						return;
					}
					if (ack) return ack().catch((err) => this.#logger?.error?.("Error acking terminal workflow event in push subscription", err));
				}).catch((err) => this.#logger?.error?.("Unhandled error in workflow event push subscription", err));
				this.#inFlightPushEvents.add(inFlight);
				inFlight.finally(() => this.#inFlightPushEvents.delete(inFlight));
			};
			await this.#pubsub.subscribe("workflows", cb);
			this.#pushSubscription = {
				topic: "workflows",
				cb
			};
		}
	}
	/**
	* Ensure the execution-side machinery — the `orchestration` and
	* `backgroundTasks` workers, plus the push-mode workflow subscription —
	* is running. Called lazily by {@link BackgroundTaskManager} when a task
	* is dispatched or resumed, so background tasks execute in "library mode"
	* where nothing ever calls `startWorkers()` (no server, no `mastra dev`;
	* see #19339).
	*
	* Deliberately narrower than `startWorkers()`: it never injects or starts
	* the scheduler/agent-schedule workers and never subscribes user event
	* listeners — dispatching a background task must not boot cron machinery
	* as a side effect.
	*
	* Honors the same opt-outs as the rest of the worker lifecycle:
	* `workers: false` / `MASTRA_WORKERS=false` (standalone-worker topologies
	* run their own worker processes, so this instance must not start local
	* ones) and the `MASTRA_WORKERS` name filter.
	*
	* The fast path is its own `#executionWorkersStarted` flag, NOT
	* `#workersStarted` — the latter is set by any `startWorkers(name)` call,
	* including partial named starts (e.g. `startWorkers('backgroundTasks')`)
	* that never start the orchestration worker or push wiring, which would
	* leave dispatched tasks stuck again. The pass itself is idempotent
	* (per-worker `isRunning` checks, idempotent push wiring), so running it
	* once after a full `startWorkers()` boot is a cheap no-op.
	*
	* @internal
	*/
	async __ensureExecutionWorkersStarted() {
		if (this.#executionWorkersStarted) return;
		if (this.#workersDisabled) return;
		if (!this.#executionWorkersStartPromise) this.#executionWorkersStartPromise = runOutsideRunFenceScope(() => this.#startExecutionWorkers()).finally(() => {
			this.#executionWorkersStartPromise = void 0;
		});
		await this.#executionWorkersStartPromise;
	}
	async #startExecutionWorkers() {
		if (this.#storage) await this.#storage.init();
		const deps = {
			pubsub: this.#pubsub,
			storage: this.#storage,
			logger: this.#logger,
			mastra: this
		};
		for (const worker of this.#workers) {
			if (worker.name !== "orchestration" && worker.name !== "backgroundTasks") continue;
			if (this.#workerFilter && !this.#workerFilter.has(worker.name)) continue;
			if (worker.isRunning) continue;
			await worker.init(deps);
			await worker.start();
		}
		await this.#wirePushWorkflowSubscription();
		this.#executionWorkersStarted = true;
	}
	/**
	* Stop all running workers and unsubscribe event listeners.
	*
	* Workflow events already being processed are given up to
	* `options.drainTimeout` milliseconds (default 5000) to finish before the
	* pubsub is flushed.
	*/
	async stopWorkers(options) {
		const drainTimeout = assertDrainTimeout(options?.drainTimeout ?? waitMs(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS, 50), "stopWorkers");
		const deadline = Date.now() + drainTimeout;
		const remaining = () => Math.max(0, deadline - Date.now());
		this.#workersStarted = false;
		this.#stopWorkflowRecoveryLoop?.();
		await this.#releaseRecoveryLeader();
		while (this.#schedulingWorkersStartPromise) await this.#schedulingWorkersStartPromise.catch(() => {});
		while (this.#executionWorkersStartPromise) await this.#executionWorkersStartPromise.catch(() => {});
		for (const worker of [...this.#workers].reverse()) if (worker.isRunning) await worker.stop({ drainTimeout: remaining() });
		if (this.#pushSubscription) {
			await this.#pubsub.unsubscribe(this.#pushSubscription.topic, this.#pushSubscription.cb);
			this.#pushSubscription = void 0;
		}
		if (this.#inFlightPushEvents.size > 0) await this.#awaitBounded(Promise.allSettled([...this.#inFlightPushEvents]), remaining(), `${this.#inFlightPushEvents.size} in-flight workflow event(s)`);
		for (const { topic, cb } of this.#userEventSubscriptions) await this.#pubsub.unsubscribe(topic, cb);
		this.#userEventSubscriptions = [];
		await this.#unwireSchedulerWakeSubscription();
		await this.#pubsub.flush();
		this.#executionWorkersStarted = false;
		this.#warnedStrandedLocalWorkflowIds.clear();
	}
	/**
	* Hand back the thread runs this Mastra still holds once its durable executions are abandoned: announce each run's
	* end, stop its lease renewal and release its thread lease, so another process can take the thread right away.
	*/
	async #shutdownThreadRuns(deadline) {
		const pubsubs = /* @__PURE__ */ new Set([this.pubsub]);
		for (const agent of Object.values(this.#agents)) if (typeof agent?.getPubSub === "function") pubsubs.add(agent.getPubSub());
		const abortGraceMs = Math.max(SHUTDOWN_THREAD_RUN_ABORT_GRACE_MIN_MS, deadline - Date.now());
		const executesElsewhere = (runId) => isDurableAgentExecutionDetached(this, runId);
		(await this.#awaitBounded(Promise.allSettled([...pubsubs].map((pubsub) => agentThreadStreamRuntime.shutdown(pubsub, this, {
			abortGraceMs,
			executesElsewhere
		}))), abortGraceMs + 1e3, "thread run handback"))?.forEach((result) => {
			if (result.status === "rejected") this.#logger?.error("Handing back thread runs failed during shutdown", { error: result.reason });
		});
	}
	/**
	* Await an already-started promise for at most `timeoutMs`. Returns its value
	* when it settles in time, or `undefined` after logging a warning when the
	* budget is exhausted — the work keeps running in the background so teardown
	* stays best-effort but bounded.
	*/
	async #awaitBounded(promise, timeoutMs, description, timeoutMessage = `Shutdown drain timed out after ${timeoutMs}ms; abandoning ${description}`) {
		let timeoutHandle;
		try {
			const outcome = await Promise.race([promise.then((value) => ({
				timedOut: false,
				value
			})), new Promise((resolve) => {
				timeoutHandle = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
			})]);
			if (outcome.timedOut) {
				this.#logger?.warn(timeoutMessage);
				return;
			}
			return outcome.value;
		} finally {
			if (timeoutHandle) clearTimeout(timeoutHandle);
		}
	}
	/**
	* Release the module-level hooks this instance registered in its constructor.
	* The scorer hook is added to a shared emitter that never drops handlers on
	* its own, so short-lived internal/ephemeral Mastras must call this on teardown
	* or their handler keeps firing (and failing to resolve the scorer) on every
	* scorer run for the rest of the process. Idempotent.
	* @internal
	*/
	__unregisterHooks() {
		if (this.#onScorerHook) {
			deregisterHook("onScorerRun", this.#onScorerHook);
			this.#onScorerHook = void 0;
		}
	}
	/**
	* @deprecated Use {@link Mastra.startWorkers} instead. Will be removed in a
	* future release.
	*/
	async startEventEngine(name) {
		return this.startWorkers(name);
	}
	/**
	* @deprecated Use {@link Mastra.stopWorkers} instead. Will be removed in a
	* future release.
	*/
	async stopEventEngine() {
		return this.stopWorkers();
	}
	/**
	* Retrieves a registered gateway by its key.
	*
	* @throws {MastraError} When the gateway with the specified key is not found
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   gateways: {
	*     myGateway: new CustomGateway()
	*   }
	* });
	*
	* const gateway = mastra.getGateway('myGateway');
	* ```
	*/
	getGateway(key) {
		const gateway = this.#gateways?.[key];
		if (!gateway) {
			const error = new MastraError({
				id: "MASTRA_GET_GATEWAY_BY_KEY_NOT_FOUND",
				domain: ErrorDomain.MASTRA,
				category: ErrorCategory.USER,
				text: `Gateway with key ${key} not found`,
				details: {
					status: 404,
					gatewayKey: key,
					gateways: Object.keys(this.#gateways ?? {}).join(", ")
				}
			});
			this.#logger?.trackException(error);
			throw error;
		}
		return gateway;
	}
	/**
	* Retrieves a registered gateway by its ID.
	*
	* Searches through all registered gateways and returns the one whose ID matches.
	* If a gateway doesn't have an explicit ID, its name is used as the ID.
	*
	* @throws {MastraError} When no gateway with the specified ID is found
	*
	* @example
	* ```typescript
	* class CustomGateway extends MastraModelGateway {
	*   readonly id = 'custom-gateway-v1';
	*   readonly name = 'Custom Gateway';
	*   // ...
	* }
	*
	* const mastra = new Mastra({
	*   gateways: {
	*     myGateway: new CustomGateway()
	*   }
	* });
	*
	* const gateway = mastra.getGatewayById('custom-gateway-v1');
	* ```
	*/
	getGatewayById(id) {
		const gateways = this.#gateways ?? {};
		for (const gateway of Object.values(gateways)) if (getGatewayId(gateway) === id) return gateway;
		const error = new MastraError({
			id: "MASTRA_GET_GATEWAY_BY_ID_NOT_FOUND",
			domain: ErrorDomain.MASTRA,
			category: ErrorCategory.USER,
			text: `Gateway with ID ${id} not found`,
			details: {
				status: 404,
				gatewayId: id,
				availableIds: Object.values(gateways).map((g) => getGatewayId(g)).join(", ")
			}
		});
		this.#logger?.trackException(error);
		throw error;
	}
	/**
	* Returns all registered gateways as a record keyed by their registration keys.
	*
	* Gateways can be plain objects that satisfy `MastraModelGatewayInterface` or
	* classes that extend `MastraModelGateway`.
	*
	* @example
	* ```typescript
	* import { createOpenAICompatible } from '@ai-sdk/openai-compatible-v6';
	* import { MastraModelGateway, type MastraModelGatewayInterface } from '@mastra/core/llm';
	*
	* const plainGateway: MastraModelGatewayInterface = {
	*   id: 'plain-gateway',
	*   name: 'Plain Gateway',
	*   async fetchProviders() { return {}; },
	*   buildUrl() { return undefined; },
	*   async getApiKey() { return ''; },
	*   resolveLanguageModel(args) { return createOpenAICompatible({ name: args.providerId, apiKey: args.apiKey }).chatModel(args.modelId); },
	* };
	*
	* class ClassGateway extends MastraModelGateway {
	*   readonly id = 'class-gateway';
	*   readonly name = 'Class Gateway';
	*   // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.
	* }
	*
	* const mastra = new Mastra({
	*   gateways: {
	*     plain: plainGateway,
	*     class: new ClassGateway(),
	*   },
	* });
	*
	* const allGateways = mastra.listGateways();
	* console.log(Object.keys(allGateways ?? {})); // ['plain', 'class']
	* ```
	*/
	listGateways() {
		return this.#gateways;
	}
	/**
	* Adds a new gateway to the Mastra instance.
	*
	* This method allows dynamic registration of gateways after the Mastra instance
	* has been created. Gateways enable access to LLM providers through custom
	* authentication and routing logic.
	*
	* If no key is provided, the gateway's ID will be used as the key.
	*
	* @example Plain object gateway
	* ```typescript
	* import type { MastraModelGatewayInterface } from '@mastra/core/llm';
	*
	* const customGateway: MastraModelGatewayInterface = {
	*   id: 'custom-gateway-v1',
	*   name: 'Custom Gateway',
	*   async fetchProviders() {
	*     return {
	*       myProvider: {
	*         name: 'My Provider',
	*         models: ['model-1', 'model-2'],
	*         apiKeyEnvVar: 'MY_API_KEY',
	*         gateway: 'custom-gateway-v1',
	*       },
	*     };
	*   },
	*   buildUrl() {
	*     return 'https://api.myprovider.com/v1';
	*   },
	*   async getApiKey() {
	*     return process.env.MY_API_KEY || '';
	*   },
	*   async resolveLanguageModel({ modelId, providerId, apiKey }) {
	*     const provider = createOpenAICompatible({
	*       name: providerId,
	*       apiKey,
	*       baseURL: this.buildUrl(),
	*       supportsStructuredOutputs: true,
	*     });
	*     return provider.chatModel(modelId);
	*   },
	* };
	*
	* const mastra = new Mastra();
	* mastra.addGateway(customGateway);
	* ```
	*
	* @example Convenience base class
	* ```typescript
	* import { MastraModelGateway } from '@mastra/core/llm';
	*
	* class CustomGateway extends MastraModelGateway {
	*   readonly id = 'custom-gateway-v1';
	*   readonly name = 'Custom Gateway';
	*
	*   // Implement fetchProviders, buildUrl, getApiKey, and resolveLanguageModel.
	* }
	*
	* mastra.addGateway(new CustomGateway(), 'customKey');
	* ```
	*/
	addGateway(gateway, key) {
		if (!gateway) throw createUndefinedPrimitiveError("gateway", gateway, key);
		const gatewayKey = key || getGatewayId(gateway);
		const gateways = this.#gateways;
		if (gateways[gatewayKey]) return;
		gateways[gatewayKey] = gateway;
		this.#syncGatewayRegistry();
	}
	/**
	* Sync custom gateways with the GatewayRegistry for type generation
	* @private
	*/
	#syncGatewayRegistry() {
		try {
			if (process.env.MASTRA_DEV !== "true" && process.env.MASTRA_DEV !== "1") return;
			import("./provider-registry-DBfyKz2x.js").then((n) => n.d).then(async ({ GatewayRegistry }) => {
				const registry = GatewayRegistry.getInstance();
				const customGateways = Object.values(this.#gateways || {});
				registry.registerCustomGateways(customGateways);
				const logger = this.getLogger();
				logger.info("🔄 Syncing custom gateway types...");
				await registry.syncGateways(true);
				logger.info("✅ Custom gateway types synced! Restart your TypeScript server to see autocomplete.");
			}).catch((err) => {
				this.getLogger().debug("Gateway registry sync skipped:", err);
			});
		} catch (err) {
			this.getLogger().debug("Gateway registry sync failed:", err);
		}
	}
	/**
	* Gracefully shuts down the Mastra instance and cleans up all resources.
	*
	* This method performs a clean shutdown of all Mastra components, including:
	* - tracing registry and all tracing instances
	* - Event engine and pub/sub system
	* - registered workspaces (sandbox processes, filesystem handles, LSP, browser)
	* - All registered components and their resources
	*
	* It's important to call this method when your application is shutting down
	* to ensure proper cleanup and prevent resource leaks.
	*
	* @example
	* ```typescript
	* const mastra = new Mastra({
	*   agents: { myAgent },
	*   workflows: { myWorkflow }
	* });
	*
	* // Graceful shutdown on SIGINT
	* process.on('SIGINT', async () => {
	*   await mastra.shutdown();
	*   process.exit(0);
	* });
	* ```
	*
	* In-flight evented workflow runs (including durable agent runs) started
	* through this instance are given up to `drainTimeout` milliseconds
	* (default 5000) to reach a terminal or suspended state before workers and
	* pubsub subscriptions are torn down. Runs that do not settle within the
	* window are abandoned with a warning. Durable agent runs using the default
	* snapshot policy persist a `running` checkpoint at each step boundary they
	* reach during the drain. An abandoned durable agent run then stops without
	* writing and is released. It can be recovered only if a checkpoint was
	* persisted.
	*
	* Agent thread runs this instance still holds are then handed back. A run
	* still executing is aborted so it starts no further steps, and other
	* processes watching its thread see it end; its partial response is not
	* saved. A run parked on a tool approval or suspension stays parked and
	* resumable. Either way the thread lease is released right away instead of
	* at expiry, so another process can use the thread immediately. Release is
	* best-effort: if an aborted run doesn't stop in time (for example, a tool
	* call that ignores the abort), or the lease backend doesn't answer or
	* fails the release, the lease is kept until it expires. Handing runs back can take up to about 1.5 seconds past
	* `drainTimeout`.
	*/
	async shutdown(options) {
		const drainTimeout = assertDrainTimeout(options?.drainTimeout ?? waitMs(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS, 50), "shutdown");
		const deadline = Date.now() + drainTimeout;
		this.#shuttingDown = true;
		this.#durableRecoveryRechecks.forEach((timer) => clearTimeout(timer));
		this.#durableRecoveryRechecks.clear();
		this.#stopWorkflowRecoveryLoop?.();
		this.__unregisterHooks();
		const awaited = /* @__PURE__ */ new Set();
		for (;;) {
			const pendingRuns = [
				...this.#activeEventedRuns,
				...getActiveDurableAgentWorkflowExecutions(this),
				...this.#durableRecoveryRechecksInFlight,
				...this.#recoveryPass ? [this.#recoveryPass] : []
			].filter((run) => !awaited.has(run));
			if (pendingRuns.length === 0) break;
			pendingRuns.forEach((run) => awaited.add(run));
			const drained = await this.#awaitBounded(Promise.allSettled(pendingRuns), Math.max(0, deadline - Date.now()), `${pendingRuns.length} in-flight evented workflow run(s)`);
			if (!drained) break;
			drained.forEach((result) => {
				if (result.status === "rejected") this.#logger?.error("Evented workflow run failed during shutdown", { error: result.reason });
			});
		}
		await abandonDurableAgentExecutions(this);
		await this.#shutdownThreadRuns(deadline);
		if (this.#backgroundTaskManager) await this.#backgroundTaskManager.shutdown({ deadline });
		await this.stopWorkers({ drainTimeout: Math.max(0, deadline - Date.now()) });
		const workspaceIds = Object.keys(this.#workspaces);
		(await Promise.allSettled(workspaceIds.map(async (id) => {
			const entry = this.#workspaces[id];
			if (!entry) return;
			await entry.workspace.stop();
			await this.removeWorkspace(id);
		}))).forEach((result, index) => {
			if (result.status === "rejected") this.#logger?.error("Failed to tear down workspace during shutdown", {
				workspaceId: workspaceIds[index],
				error: result.reason
			});
		});
		const harnessKeys = Object.keys(this.#harnesses);
		(await Promise.allSettled(harnessKeys.map((key) => this.#harnesses[key].destroy()))).forEach((result, index) => {
			if (result.status === "rejected") this.#logger?.error("Failed to destroy harness during shutdown", {
				harnessKey: harnessKeys[index],
				error: result.reason
			});
		});
		const pubsub = this.#pubsub;
		if (typeof pubsub.close === "function") try {
			await pubsub.close();
		} catch (error) {
			this.#logger?.error("Failed to close pubsub during shutdown", { error });
		}
		await this.#observability.shutdown();
		if (this.#storage?.close) await this.#storage.close();
		this.#logger?.info("Mastra shutdown completed");
	}
	get serverCache() {
		return this.#serverCache;
	}
};
__registerMastraCtor(Mastra);
export { Mastra as t };

//# sourceMappingURL=mastra-BPT-un5h.js.map